From 12f1985439eeb2ad957d107d8765c6aaa00b942e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:04:56 +1300 Subject: [PATCH 001/199] ci: prove protected Pod admission in isolated runner --- .../protected-pod-admission-proof.yml | 293 ++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 .github/workflows/protected-pod-admission-proof.yml diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml new file mode 100644 index 0000000000..72d554360d --- /dev/null +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -0,0 +1,293 @@ +name: Temporary Protected Pod Admission Proof + +on: + pull_request: + paths: + - .github/workflows/protected-pod-admission-proof.yml + - .github/actions/load-workflow-tool-versions/** + - .github/actions/setup-kubectl/** + - .github/actions/setup-python/** + - config/workflow-tool-versions.env + - dev-tools/hosted/trust-bootstrap/** + - k8s/trust-bootstrap/deployment-admission.yaml + workflow_dispatch: + +permissions: + contents: read + +jobs: + admission-only: + if: ${{ github.repository == 'benhook1013/FireMUD' }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + steps: + - name: Check out approved immutable proof source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: 077829af77c89e4bff416f406ea4603290f64995 + persist-credentials: false + + - name: Set up repository-pinned Python and PyYAML + uses: ./.github/actions/setup-python + with: + requirements: yaml + + - name: Load repository-pinned workflow tools + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up repository-pinned kubectl + uses: ./.github/actions/setup-kubectl + + - name: Install checksum-verified kind + env: + KIND_VERSION: ${{ steps.workflow-tool-versions.outputs.kind-version }} + KIND_LINUX_AMD64_SHA256: ${{ steps.workflow-tool-versions.outputs.kind-linux-amd64-sha256 }} + run: | + set -euo pipefail + if [[ "${RUNNER_OS:-}" != Linux || "${RUNNER_ARCH:-}" != X64 || "$(uname -m)" != x86_64 ]]; then + echo "kind proof requires a GitHub-hosted Linux x64 runner" >&2 + exit 1 + fi + if [[ "${RUNNER_ENVIRONMENT:-}" != github-hosted ]]; then + echo "proof requires an ephemeral GitHub-hosted runner" >&2 + exit 1 + fi + install_directory="${RUNNER_TEMP:?}/firemud-pod-admission-tools" + mkdir -p -- "$install_directory" + chmod 0700 "$install_directory" + kind_binary="$install_directory/kind" + curl -fsSL --retry 3 --retry-delay 2 --retry-max-time 30 \ + --connect-timeout 10 --max-time 90 --max-filesize 134217728 \ + "https://kind.sigs.k8s.io/dl/v${KIND_VERSION:?}/kind-linux-amd64" \ + -o "$kind_binary" + binary_bytes="$(wc -c < "$kind_binary")" + if [[ "$binary_bytes" -le 0 || "$binary_bytes" -gt 134217728 ]]; then + echo "downloaded kind binary is outside the allowed size" >&2 + exit 1 + fi + printf '%s %s\n' "${KIND_LINUX_AMD64_SHA256:?}" "$kind_binary" | sha256sum --check --status + chmod 0755 "$kind_binary" + printf '%s\n' "$install_directory" >> "$GITHUB_PATH" + + - name: Derive run-local proof paths + env: + SOURCE_SHA: 077829af77c89e4bff416f406ea4603290f64995 + run: | + set -euo pipefail + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + KIND_CLUSTER_NAME="firemud-pod-admission-${GITHUB_RUN_ID:?}-${GITHUB_RUN_ATTEMPT:?}-${SOURCE_SHA:0:8}" + PROOF_DIR="${RUNNER_TEMP:?}/firemud-pod-admission-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + KUBECONFIG="$PROOF_DIR/kubeconfig" + printf 'KIND_CLUSTER_NAME=%s\nPROOF_DIR=%s\nKUBECONFIG=%s\n' \ + "$KIND_CLUSTER_NAME" "$PROOF_DIR" "$KUBECONFIG" >> "$GITHUB_ENV" + + - name: Create run-owned cluster and execute native admission probes + id: proof + env: + KIND_NODE_IMAGE: ${{ steps.workflow-tool-versions.outputs.kind-node-image }} + SOURCE_SHA: 077829af77c89e4bff416f406ea4603290f64995 + run: | + set -euo pipefail + if [[ -e "$PROOF_DIR" || -L "$PROOF_DIR" ]]; then + echo "run-specific proof directory already exists; refusing reuse" >&2 + exit 1 + fi + install -d -m 0700 -- "$PROOF_DIR" + evidence="$PROOF_DIR/admission-only.txt" + claim="$PROOF_DIR/cluster-ownership.claim" + + probe_resources() { + local label="$1" + printf 'resource_probe=%s\n' "$label" + printf 'logical_cpus=%s\n' "$(nproc)" + awk '/MemAvailable:/ { printf "available_memory_kib=%s\n", $2 }' /proc/meminfo + df -B1 --output=avail "$RUNNER_TEMP" | tail -n 1 | awk '{ printf "runner_temp_available_bytes=%s\n", $1 }' + docker stats --no-stream --format 'cluster_container={{.Name}} memory={{.MemUsage}} cpu={{.CPUPerc}}' \ + "${KIND_CLUSTER_NAME}-control-plane" 2>/dev/null || true + } + + elapsed() { + local label="$1" + local started="$2" + printf '%s_seconds=%s\n' "$label" "$(( $(date +%s) - started ))" + } + + owned_cleanup() { + local status=$? + trap - EXIT INT TERM + local node="${KIND_CLUSTER_NAME}-control-plane" + local expected_claim actual_claim + expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "$SOURCE_SHA")" + if [[ ! -f "$claim" || -L "$claim" ]]; then + printf 'cleanup=refused_unclaimed_cluster\n' + status=1 + elif ! actual_claim="$(cat "$claim")" || [[ "$actual_claim" != "$expected_claim" ]]; then + printf 'cleanup=refused_invalid_ownership_claim\n' + status=1 + elif docker inspect "$node" >/dev/null 2>&1; then + local owner_label + owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" + if [[ "$owner_label" == "$KIND_CLUSTER_NAME" ]]; then + kind delete cluster --name "$KIND_CLUSTER_NAME" --kubeconfig "$KUBECONFIG" || status=$? + else + printf 'cleanup=refused_unverified_node_identity node=%s label=%s\n' "$node" "$owner_label" + status=1 + fi + else + printf 'cleanup=no_owned_cluster_node_present\n' + fi + exit "$status" + } + + run_proof() { + trap owned_cleanup EXIT INT TERM + printf 'source_sha=%s\n' "$SOURCE_SHA" + printf 'cluster_name=%s\n' "$KIND_CLUSTER_NAME" + printf 'node_image=%s\n' "$KIND_NODE_IMAGE" + printf 'proof_scope=native_admission_only\n' + printf 'unproved=tls,cni,socket_routing,pod_process_attribution,replacement_races,shared_key_closure,promotion\n' + probe_resources before_cluster_creation + + if [[ ! "$KIND_CLUSTER_NAME" =~ ^firemud-pod-admission-[0-9]+-[0-9]+-[0-9a-f]{8}$ ]]; then + echo "run-owned cluster name did not match the expected unique form" >&2 + exit 1 + fi + if [[ -e "$KUBECONFIG" || -L "$KUBECONFIG" ]]; then + echo "run-specific kubeconfig already exists; refusing reuse" >&2 + exit 1 + fi + existing_clusters="$(kind get clusters)" + if grep -Fxq "$KIND_CLUSTER_NAME" <<< "$existing_clusters"; then + echo "run-specific kind cluster already exists; refusing reuse" >&2 + exit 1 + fi + + expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "$SOURCE_SHA")" + ( set -o noclobber; printf '%s\n' "$expected_claim" > "$claim" ) + + phase_started="$(date +%s)" + kind create cluster --name "$KIND_CLUSTER_NAME" --image "$KIND_NODE_IMAGE" \ + --kubeconfig "$KUBECONFIG" --wait 180s + expected_context="kind-${KIND_CLUSTER_NAME}" + actual_context="$(kubectl --kubeconfig "$KUBECONFIG" config current-context)" + [[ "$actual_context" == "$expected_context" ]] || { + echo "created kubeconfig did not select the exact run-owned context" >&2 + exit 1 + } + node_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' \ + "${KIND_CLUSTER_NAME}-control-plane")" + [[ "$node_label" == "$KIND_CLUSTER_NAME" ]] || { + echo "kind node ownership label did not match this run" >&2 + exit 1 + } + server_version="$(kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" version -o json \ + | jq -er '.serverVersion.gitVersion')" + expected_server_version="${KIND_NODE_IMAGE#*:v}" + expected_server_version="${expected_server_version%%@*}" + [[ "${server_version#v}" == "$expected_server_version"* ]] || { + echo "Kubernetes API version did not match the pinned kind node image" >&2 + exit 1 + } + printf 'kubernetes_context=%s\n' "$actual_context" + printf 'kubernetes_server_version=%s\n' "$server_version" + elapsed cluster_create_and_identity_check "$phase_started" + + namespace="$(kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" \ + get namespace dev --ignore-not-found -o name)" + [[ -z "$namespace" ]] || { + echo "fresh cluster unexpectedly already contains dev namespace" >&2 + exit 1 + } + + phase_started="$(date +%s)" + # The fixture image must already be present in this digest-pinned kind node. + # If its exact tag and immutable registry digest are unavailable, fail closed; + # never resolve or pull an unpinned image here. + pause_image="$(docker exec "${KIND_CLUSTER_NAME}-control-plane" crictl images --output=json \ + | jq -er '[.images[] | select(any(.repoTags[]?; . == "registry.k8s.io/pause:3.10")) \ + | .repoDigests[]? | select(test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] \ + | unique | if length == 1 then .[0] else error("pinned node has no unique immutable pause:3.10 digest") end')" + printf 'pause_image_from_pinned_node=%s\n' "$pause_image" + kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" \ + create -f k8s/trust-bootstrap/deployment-admission.yaml + sed "s|registry.k8s.io/pause:3.10|$pause_image|g" \ + dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml \ + | kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" create -f - + elapsed policy_and_fixture_creation "$phase_started" + + phase_started="$(date +%s)" + for app in account-service game-session-service; do + kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" -n dev \ + rollout status "deployment/$app" --timeout=180s + done + elapsed fixture_rollout "$phase_started" + + phase_started="$(date +%s)" + for app in account-service game-session-service; do + proof_pod="$(kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" -n dev \ + get pods -l "app=$app" -o json \ + | jq -er '.items | select(length == 1) | .[0].metadata.name')" + printf 'fixture_pod_%s=%s\n' "$app" "$proof_pod" + bash dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh \ + --context "$expected_context" --namespace dev --pod "$proof_pod" + done + elapsed server_dry_run_admission_probes "$phase_started" + probe_resources before_cleanup + printf 'result=admission_only_passed\n' + } + + run_proof 2>&1 | tee "$evidence" + grep -Fq 'PASS native admission only;' "$evidence" + grep -Fq 'UNPROVED:' "$evidence" + + - name: Tear down only this run-owned cluster + if: always() + run: | + set -euo pipefail + started="$(date +%s)" + if [[ -z "${KIND_CLUSTER_NAME:-}" || -z "${PROOF_DIR:-}" || -z "${KUBECONFIG:-}" ]]; then + echo "cleanup=not_claimed_paths_unavailable" + exit 0 + fi + node="${KIND_CLUSTER_NAME}-control-plane" + evidence="$PROOF_DIR/admission-only.txt" + claim="$PROOF_DIR/cluster-ownership.claim" + expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "077829af77c89e4bff416f406ea4603290f64995")" + if [[ ! -f "$claim" || -L "$claim" ]]; then + echo "cleanup=not_claimed_no_cluster_deletion" + exit 0 + fi + actual_claim="$(cat "$claim")" + if [[ "$actual_claim" != "$expected_claim" ]]; then + printf 'cleanup=refused_invalid_ownership_claim\n' | tee -a "$evidence" + exit 1 + fi + if docker inspect "$node" >/dev/null 2>&1; then + owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" + if [[ "$owner_label" != "$KIND_CLUSTER_NAME" ]]; then + printf 'cleanup=refused_unverified_node_identity node=%s label=%s\n' "$node" "$owner_label" \ + | tee -a "$evidence" + exit 1 + fi + kind delete cluster --name "$KIND_CLUSTER_NAME" --kubeconfig "$KUBECONFIG" + else + printf 'cleanup=no_owned_cluster_node_present\n' | tee -a "$evidence" + fi + if [[ -d "$PROOF_DIR" ]]; then + printf 'cleanup_seconds=%s\n' "$(( $(date +%s) - started ))" | tee -a "$evidence" + fi + + - name: Upload bounded admission-only evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: protected-pod-admission-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/firemud-pod-admission-${{ github.run_id }}-${{ github.run_attempt }}/admission-only.txt + if-no-files-found: warn + retention-days: 1 From 338e1e67a7515939f98b956261e39d37830e7b87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:10:13 +1300 Subject: [PATCH 002/199] ci: correct admission proof jq expression --- .github/workflows/protected-pod-admission-proof.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 72d554360d..bd16ed0636 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -209,8 +209,8 @@ jobs: # If its exact tag and immutable registry digest are unavailable, fail closed; # never resolve or pull an unpinned image here. pause_image="$(docker exec "${KIND_CLUSTER_NAME}-control-plane" crictl images --output=json \ - | jq -er '[.images[] | select(any(.repoTags[]?; . == "registry.k8s.io/pause:3.10")) \ - | .repoDigests[]? | select(test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] \ + | jq -er '[.images[] | select(any(.repoTags[]?; . == "registry.k8s.io/pause:3.10")) + | .repoDigests[]? | select(test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] | unique | if length == 1 then .[0] else error("pinned node has no unique immutable pause:3.10 digest") end')" printf 'pause_image_from_pinned_node=%s\n' "$pause_image" kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" \ From b70a4fe46abddef9ce6816ce6ca3d1c53bda9e2c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:16:35 +1300 Subject: [PATCH 003/199] ci: derive admission fixture from cached node digest --- .../protected-pod-admission-proof.yml | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index bd16ed0636..09844eb991 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -205,13 +205,39 @@ jobs: } phase_started="$(date +%s)" - # The fixture image must already be present in this digest-pinned kind node. - # If its exact tag and immutable registry digest are unavailable, fail closed; - # never resolve or pull an unpinned image here. - pause_image="$(docker exec "${KIND_CLUSTER_NAME}-control-plane" crictl images --output=json \ - | jq -er '[.images[] | select(any(.repoTags[]?; . == "registry.k8s.io/pause:3.10")) - | .repoDigests[]? | select(test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] - | unique | if length == 1 then .[0] else error("pinned node has no unique immutable pause:3.10 digest") end')" + # Derive the fixture image from cached pause tags in this digest-pinned kind node. + # Require one unique valid registry digest and never resolve or pull an unpinned image. + pause_image_cache_diagnostic() { + local inventory="$1" + local diagnostic + diagnostic="$(jq -c ' + [.images[]? + | select(any(.repoTags[]?; type == "string" and startswith("registry.k8s.io/pause:"))) + | { + repoTags: [.repoTags[]? | select(type == "string" and startswith("registry.k8s.io/pause:")) | .[0:160]][0:4], + repoDigests: [.repoDigests[]? | select(type == "string") | .[0:160]][0:4] + } + ][0:5] + ' <<< "$inventory" 2>/dev/null || printf '[]')" + printf 'pause_image_cache_diagnostic=%s\n' "$diagnostic" >&2 + } + if ! pause_image_inventory="$(docker exec "${KIND_CLUSTER_NAME}-control-plane" crictl images --output=json)"; then + pause_image_cache_diagnostic "${pause_image_inventory:-}" + echo "could not inspect cached pause images in the pinned kind node" >&2 + exit 1 + fi + if ! pause_image="$(jq -er ' + [.images[] + | select(any(.repoTags[]?; type == "string" and startswith("registry.k8s.io/pause:"))) + | .repoDigests[]? + | select(type == "string" and test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] + | unique + | if length == 1 then .[0] else error("cached pause tags do not identify one unique immutable registry digest") end + ' <<< "$pause_image_inventory")"; then + pause_image_cache_diagnostic "$pause_image_inventory" + echo "cached pause tags did not yield one unique immutable registry digest" >&2 + exit 1 + fi printf 'pause_image_from_pinned_node=%s\n' "$pause_image" kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" \ create -f k8s/trust-bootstrap/deployment-admission.yaml From 4afdbdfca0b96da0427a949bbeed8fdaf8a635ca Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:26:59 +1300 Subject: [PATCH 004/199] ci: pin verified publisher image for admission fixture --- .../protected-pod-admission-proof.yml | 37 ++----------------- 1 file changed, 3 insertions(+), 34 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 09844eb991..fdc24dc3b4 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -205,40 +205,9 @@ jobs: } phase_started="$(date +%s)" - # Derive the fixture image from cached pause tags in this digest-pinned kind node. - # Require one unique valid registry digest and never resolve or pull an unpinned image. - pause_image_cache_diagnostic() { - local inventory="$1" - local diagnostic - diagnostic="$(jq -c ' - [.images[]? - | select(any(.repoTags[]?; type == "string" and startswith("registry.k8s.io/pause:"))) - | { - repoTags: [.repoTags[]? | select(type == "string" and startswith("registry.k8s.io/pause:")) | .[0:160]][0:4], - repoDigests: [.repoDigests[]? | select(type == "string") | .[0:160]][0:4] - } - ][0:5] - ' <<< "$inventory" 2>/dev/null || printf '[]')" - printf 'pause_image_cache_diagnostic=%s\n' "$diagnostic" >&2 - } - if ! pause_image_inventory="$(docker exec "${KIND_CLUSTER_NAME}-control-plane" crictl images --output=json)"; then - pause_image_cache_diagnostic "${pause_image_inventory:-}" - echo "could not inspect cached pause images in the pinned kind node" >&2 - exit 1 - fi - if ! pause_image="$(jq -er ' - [.images[] - | select(any(.repoTags[]?; type == "string" and startswith("registry.k8s.io/pause:"))) - | .repoDigests[]? - | select(type == "string" and test("^registry\\.k8s\\.io/pause@sha256:[0-9a-f]{64}$"))] - | unique - | if length == 1 then .[0] else error("cached pause tags do not identify one unique immutable registry digest") end - ' <<< "$pause_image_inventory")"; then - pause_image_cache_diagnostic "$pause_image_inventory" - echo "cached pause tags did not yield one unique immutable registry digest" >&2 - exit 1 - fi - printf 'pause_image_from_pinned_node=%s\n' "$pause_image" + # Publisher's pause:3.10 linux/amd64 manifest was verified against response-byte SHA-256. + pause_image='registry.k8s.io/pause@sha256:7c38f24774e3cbd906d2d33c38354ccf787635581c122965132c9bd309754d4a' + printf 'pause_image_from_verified_publisher=%s\n' "$pause_image" kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" \ create -f k8s/trust-bootstrap/deployment-admission.yaml sed "s|registry.k8s.io/pause:3.10|$pause_image|g" \ From 7df8cd99e82966cd647bdbc87334c73c260f5364 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:53:36 +1300 Subject: [PATCH 005/199] Use bounded admission diagnostics in hosted proof --- .github/workflows/protected-pod-admission-proof.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index fdc24dc3b4..2f65e4a980 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -26,7 +26,7 @@ jobs: - name: Check out approved immutable proof source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: 077829af77c89e4bff416f406ea4603290f64995 + ref: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 persist-credentials: false - name: Set up repository-pinned Python and PyYAML @@ -74,7 +74,7 @@ jobs: - name: Derive run-local proof paths env: - SOURCE_SHA: 077829af77c89e4bff416f406ea4603290f64995 + SOURCE_SHA: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 run: | set -euo pipefail [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] @@ -88,7 +88,7 @@ jobs: id: proof env: KIND_NODE_IMAGE: ${{ steps.workflow-tool-versions.outputs.kind-node-image }} - SOURCE_SHA: 077829af77c89e4bff416f406ea4603290f64995 + SOURCE_SHA: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 run: | set -euo pipefail if [[ -e "$PROOF_DIR" || -L "$PROOF_DIR" ]]; then @@ -253,7 +253,7 @@ jobs: evidence="$PROOF_DIR/admission-only.txt" claim="$PROOF_DIR/cluster-ownership.claim" expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ - "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "077829af77c89e4bff416f406ea4603290f64995")" + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "72d6c8a11d933c7d1fedba6876bb1577a3cad051")" if [[ ! -f "$claim" || -L "$claim" ]]; then echo "cleanup=not_claimed_no_cluster_deletion" exit 0 From fcb20e188b8c32429c6e63200702c883f3f5ba50 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:19:22 +1300 Subject: [PATCH 006/199] Use schema-valid privileged Pod admission probe --- .github/workflows/protected-pod-admission-proof.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 2f65e4a980..3429e6fc44 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -26,7 +26,7 @@ jobs: - name: Check out approved immutable proof source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 + ref: 906fb30de00192d29d88513769cdd2bc3ec544f7 persist-credentials: false - name: Set up repository-pinned Python and PyYAML @@ -74,7 +74,7 @@ jobs: - name: Derive run-local proof paths env: - SOURCE_SHA: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 + SOURCE_SHA: 906fb30de00192d29d88513769cdd2bc3ec544f7 run: | set -euo pipefail [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] @@ -88,7 +88,7 @@ jobs: id: proof env: KIND_NODE_IMAGE: ${{ steps.workflow-tool-versions.outputs.kind-node-image }} - SOURCE_SHA: 72d6c8a11d933c7d1fedba6876bb1577a3cad051 + SOURCE_SHA: 906fb30de00192d29d88513769cdd2bc3ec544f7 run: | set -euo pipefail if [[ -e "$PROOF_DIR" || -L "$PROOF_DIR" ]]; then @@ -253,7 +253,7 @@ jobs: evidence="$PROOF_DIR/admission-only.txt" claim="$PROOF_DIR/cluster-ownership.claim" expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ - "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "72d6c8a11d933c7d1fedba6876bb1577a3cad051")" + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "906fb30de00192d29d88513769cdd2bc3ec544f7")" if [[ ! -f "$claim" || -L "$claim" ]]; then echo "cleanup=not_claimed_no_cluster_deletion" exit 0 From b24baa02d4b138ff97e4b8f4a68bb7da5811024f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:16:28 +1300 Subject: [PATCH 007/199] Use audited schema-valid admission probes --- .github/workflows/protected-pod-admission-proof.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 3429e6fc44..59e460e4e8 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -26,7 +26,7 @@ jobs: - name: Check out approved immutable proof source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: 906fb30de00192d29d88513769cdd2bc3ec544f7 + ref: 60c507243987705094a3028e0b46f3bccd5d9504 persist-credentials: false - name: Set up repository-pinned Python and PyYAML @@ -74,7 +74,7 @@ jobs: - name: Derive run-local proof paths env: - SOURCE_SHA: 906fb30de00192d29d88513769cdd2bc3ec544f7 + SOURCE_SHA: 60c507243987705094a3028e0b46f3bccd5d9504 run: | set -euo pipefail [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] @@ -88,7 +88,7 @@ jobs: id: proof env: KIND_NODE_IMAGE: ${{ steps.workflow-tool-versions.outputs.kind-node-image }} - SOURCE_SHA: 906fb30de00192d29d88513769cdd2bc3ec544f7 + SOURCE_SHA: 60c507243987705094a3028e0b46f3bccd5d9504 run: | set -euo pipefail if [[ -e "$PROOF_DIR" || -L "$PROOF_DIR" ]]; then @@ -253,7 +253,7 @@ jobs: evidence="$PROOF_DIR/admission-only.txt" claim="$PROOF_DIR/cluster-ownership.claim" expected_claim="$(printf 'cluster=%s\nrun_id=%s\nrun_attempt=%s\nsource_sha=%s' \ - "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "906fb30de00192d29d88513769cdd2bc3ec544f7")" + "$KIND_CLUSTER_NAME" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "60c507243987705094a3028e0b46f3bccd5d9504")" if [[ ! -f "$claim" || -L "$claim" ]]; then echo "cleanup=not_claimed_no_cluster_deletion" exit 0 From 23c993212b00be6f1ee84084027a338893abf3e5 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 20:19:54 +1300 Subject: [PATCH 008/199] Point review recovery to release-matched state guidance --- design/developer-workflows/pr-lifecycle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index fc04859888..ea3fa72744 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -15,7 +15,7 @@ FireMUD owns the project authority and safety requirements below. Follow the act - Adjudicate findings as accepted, routed, or rejected with a concrete outcome and evidence. Accepted findings remain source-owned correction obligations until verified fixed. Routed observations identify another owner without claiming that owner’s acceptance or fix. Target owners independently disposition incoming routes and verify resolutions; retargeting preserves the open obligation and prior ownership, including honest unassigned work. Open outgoing routes do not hold the source’s merge readiness. Preserve source linkage and original evidence when correcting a disposition; newly accepted findings still require fixes. - Summary-only and outside-diff findings require verification and disposition as well as inline findings. Historical accepted-fixed evidence does not replace current verification. Resolve a thread only after its exact finding is fixed at the current published head; do not conceal unresolved work through thread resolution or record edits. - Routine bot findings do not need public replies or reflexive `@coderabbit` exchanges. Record the assessment, decision, and any fix and verification proof in FireController; resolve verified-fixed threads without extra chat under the current-published-head rule above. Reply only when genuine clarification or reconsideration is needed, or to provide necessary context for human reviewers, and only within applicable communication authorization. -- Keep private captures, review history, findings, and uncertain publication intents intact. Recover only through the installed release’s supported guarded operations within existing authority. Recording, recovery, imports, or publication alone grant no provider credit, fix proof, CI result, or merge authority. Do not blind-repost an uncertain checkpoint, invent attribution, or infer delivery failure from public absence. Unsupported or ambiguous recovery remains a reported hold for FireController Worker. +- Keep private captures, review history, findings, and uncertain publication intents intact. Before retrying held or failed review work, use the installed release’s `firecontroller-reviews` state-based recovery reference (`references/recovery.md`) to select the operation for the retained state. Preserve FireMUD’s exact-comparison, stop, allocation, and publication boundaries; recovery does not authorize replaying terminal work or overriding unrelated holds. Recover only through the installed release’s supported guarded operations within existing authority. Recording, recovery, imports, or publication alone grant no provider credit, fix proof, CI result, or merge authority. Do not blind-repost an uncertain checkpoint, invent attribution, or infer delivery failure from public absence. Unsupported or ambiguous recovery remains a reported hold for FireController Worker. - Follow the configured admission, provider-exclusion, quota, and cooldown controls; do not request against an active or rate-limited target or enable paid capacity. Use included quota only. Supported operations and recorded allowances do not themselves grant authority or clear unrelated holds. - For CI observation using a shared GitHub credential budget, coordinate one observer across relevant workers and runs. Prefer the supported native batched CI wait and existing inbox notices for followed PR merges, closures, and review completions; other workers consume those results and continue independent work. Add review-activity or known-operation waits when a relevant review hold or retained operation needs observation. Do not fan out simultaneous per-run watchers or duplicate an active observer. Use narrow run-list or run-view reads at least 60 seconds apart only when a supported wait cannot supply the required evidence, and check status at meaningful readiness transitions. Honor evidenced reset/retry-after times; report a hold when no time is available. From 7988a44a324e3dbef981e02754ce06b2d8564e92 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:41:28 +1300 Subject: [PATCH 009/199] feat(recovery): preserve fail-closed release journal foundation --- .../recovery/InitialGameplayRecoverCodec.java | 303 +++++++ .../InitialGameplayRecoverRequest.java | 174 ++++ .../InitialGameplayRecoverCodecTest.java | 168 ++++ .../build.gradle.kts | 15 + .../RecoveryControllerServiceApplication.java | 11 + .../RecoveryControllerOwnerConfiguration.java | 46 + ...itialGameplayReleaseConflictException.java | 9 + .../InitialGameplayReleaseJournal.java | 45 + .../InitialGameplayReleaseTupleCodec.java | 101 +++ .../JooqInitialGameplayReleaseJournal.java | 684 ++++++++++++++ .../model/InitialGameplayReleaseCommands.java | 42 + .../model/InitialGameplayReleaseModel.java | 847 ++++++++++++++++++ .../model/MaintenanceLockCredential.java | 54 ++ ...eniedInitialGameplayReleaseEffectPort.java | 19 + ...nitialGameplayReleaseEvidenceProvider.java | 12 + .../InitialGameplayReleaseController.java | 274 ++++++ .../InitialGameplayReleaseEffectPort.java | 70 ++ ...nitialGameplayReleaseEvidenceProvider.java | 42 + .../OwnerBoundaryUnavailableException.java | 9 + .../src/main/resources/application.yml | 61 ++ .../V1__initial_gameplay_release_journal.sql | 83 ++ ...ReleaseJournalPostgresIntegrationTest.java | 363 ++++++++ .../InitialGameplayReleaseModelTest.java | 490 ++++++++++ .../InitialGameplayReleaseControllerTest.java | 118 +++ settings.gradle.kts | 3 + 25 files changed, 4043 insertions(+) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverRequest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java create mode 100644 services/recovery-controller-service/build.gradle.kts create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/RecoveryControllerServiceApplication.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseConflictException.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseCommands.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEvidenceProvider.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/OwnerBoundaryUnavailableException.java create mode 100644 services/recovery-controller-service/src/main/resources/application.yml create mode 100644 services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql create mode 100644 services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java new file mode 100644 index 0000000000..2441a520ff --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java @@ -0,0 +1,303 @@ +package net.firedevops.firemud.common.recovery; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReason; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReasonCode; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.LaunchAssociation; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.MaintenanceLockPresence; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Mutation; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.PeerStorageBinding; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Scope; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Target; + +/** + * One closed action-family implementation of ADR 0047's exact mutationDigest/v1 byte grammar. All + * scalar wire values are strings; nulls, numbers, arrays and optional lock inputs are forbidden. + * The request identity and fixed target owner are context, deliberately outside the digest. + */ +public final class InitialGameplayRecoverCodec { + public static final int MAX_RAW_BYTES = 16384; + public static final int MAX_RAW_STRING_CHARACTERS = 4096; + public static final int MAX_DEPTH = 4; + public static final int MAX_OBJECT_MEMBERS = 8; + public static final int MAX_CANONICAL_SEGMENT_BYTES = 8192; + public static final int MAX_PREIMAGE_BYTES = 16384; + + private static final JsonFactory JSON = + JsonFactory.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(MAX_DEPTH) + .maxStringLength(MAX_RAW_STRING_CHARACTERS) + .maxNumberLength(1) + .build()) + .build(); + + private InitialGameplayRecoverCodec() {} + + /** + * Reads bounded raw UTF-8 in the declared member order without a generic tree/map decoder. + * Original bytes are validated before normalization; no replacement-character repair is used. + */ + public static InitialGameplayRecoverRequest decode(byte[] raw) { + Objects.requireNonNull(raw, "raw"); + if (raw.length > MAX_RAW_BYTES) throw invalid(); + try { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(raw)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Recover request must be valid UTF-8", exception); + } + try (JsonParser parser = JSON.createParser(raw)) { + require(parser.nextToken(), JsonToken.START_OBJECT); + literal( + parser, "actionFamilySchemaId", InitialGameplayRecoverRequest.ACTION_FAMILY_SCHEMA_ID); + literal( + parser, + "actionFamilySchemaVersion", + InitialGameplayRecoverRequest.ACTION_FAMILY_SCHEMA_VERSION); + var requestId = + InitialGameplayRecoverRequest.parseUuid(string(parser, "controlPlaneRequestId")); + literal(parser, "targetOwner", InitialGameplayRecoverRequest.TARGET_OWNER); + start(parser, "scope"); + Scope scope = + new Scope( + InitialGameplayRecoverRequest.parseUuid(string(parser, "canonicalTenantId")), + string(parser, "targetNamespace"), + InitialGameplayRecoverRequest.parseUuid(string(parser, "playableStateNamespaceId"))); + end(parser); + start(parser, "target"); + start(parser, "launchAssociation"); + LaunchAssociation association = + new LaunchAssociation( + InitialGameplayRecoverRequest.parseUuid(string(parser, "gameInstanceUuid")), + InitialGameplayRecoverRequest.parseUuid( + string(parser, "tenantAssociationOperationId")), + string(parser, "worldSlug"), + InitialGameplayRecoverRequest.parseUuid( + string(parser, "launchControlPlaneRequestId")), + string(parser, "launchDescriptorId"), + string(parser, "descriptorRequestDigest"), + string(parser, "descriptorResultDigest"), + string(parser, "releaseAttestationEvidenceDigest")); + end(parser); + start(parser, "peerStorageBinding"); + PeerStorageBinding binding = + new PeerStorageBinding( + string(parser, "targetNamespace"), string(parser, "clusterIdentity"), + string(parser, "peerWorkloadIdentity"), string(parser, "storageIdentity"), + string(parser, "storageRevision"), string(parser, "bindingDigest")); + end(parser); + Target target = + new Target( + association, + binding, + string(parser, "evidenceRef"), + string(parser, "evidenceDigest")); + end(parser); + start(parser, "mutation"); + var operationId = InitialGameplayRecoverRequest.parseUuid(string(parser, "operationId")); + literal(parser, "verb", "recover"); + literal(parser, "workflow", "initial-gameplay-release"); + literal(parser, "maintenanceLockPresence", "RESULT_ONLY"); + end(parser); + start(parser, "auditReason"); + literal(parser, "code", "INITIAL_GAMEPLAY_RELEASE"); + AuditReason reason = + new AuditReason(AuditReasonCode.INITIAL_GAMEPLAY_RELEASE, string(parser, "detail")); + end(parser); + end(parser); + if (parser.nextToken() != null) throw invalid(); + return new InitialGameplayRecoverRequest( + requestId, + scope, + target, + new Mutation(operationId, MaintenanceLockPresence.RESULT_ONLY), + reason); + } catch (IOException exception) { + throw new IllegalArgumentException("Malformed recover request", exception); + } + } + + /** Exact seven-field byte preimage; expectedVersion is schema-declared absent, never null. */ + public static byte[] mutationPreimage(InitialGameplayRecoverRequest request) { + Objects.requireNonNull(request, "request"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + segment(output, "mutationDigest/v1".getBytes(StandardCharsets.UTF_8)); + field(output, "actionFamilySchemaId", InitialGameplayRecoverRequest.ACTION_FAMILY_SCHEMA_ID); + field( + output, + "actionFamilySchemaVersion", + InitialGameplayRecoverRequest.ACTION_FAMILY_SCHEMA_VERSION); + field(output, "scope", scope(request.scope())); + field(output, "target", target(request.target())); + segment(output, "expectedVersion".getBytes(StandardCharsets.UTF_8)); + segment(output, "absent".getBytes(StandardCharsets.UTF_8)); + output.write('0'); + segment(output, new byte[0]); + field( + output, + "mutation", + ordered( + "operationId", + request.mutation().operationId().toString(), + "verb", + request.mutation().verb(), + "workflow", + request.mutation().workflow(), + "maintenanceLockPresence", + request.mutation().maintenanceLockPresence().name())); + field( + output, + "auditReason", + ordered( + "code", request.auditReason().code().name(), "detail", request.auditReason().detail())); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + return output.toByteArray(); + } + + public static String mutationDigest(InitialGameplayRecoverRequest request) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(mutationPreimage(request))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Map scope(Scope scope) { + return ordered( + "canonicalTenantId", + scope.canonicalTenantId().toString(), + "targetNamespace", + scope.targetNamespace(), + "playableStateNamespaceId", + scope.playableStateNamespaceId().toString()); + } + + private static Map target(Target target) { + LaunchAssociation launch = target.launchAssociation(); + PeerStorageBinding binding = target.peerStorageBinding(); + return ordered( + "launchAssociation", + ordered( + "gameInstanceUuid", launch.gameInstanceUuid().toString(), + "tenantAssociationOperationId", launch.tenantAssociationOperationId().toString(), + "worldSlug", launch.worldSlug(), + "launchControlPlaneRequestId", launch.launchControlPlaneRequestId().toString(), + "launchDescriptorId", launch.launchDescriptorId(), + "descriptorRequestDigest", launch.descriptorRequestDigest(), + "descriptorResultDigest", launch.descriptorResultDigest(), + "releaseAttestationEvidenceDigest", launch.releaseAttestationEvidenceDigest()), + "peerStorageBinding", + ordered( + "targetNamespace", + binding.targetNamespace(), + "clusterIdentity", + binding.clusterIdentity(), + "peerWorkloadIdentity", + binding.peerWorkloadIdentity(), + "storageIdentity", + binding.storageIdentity(), + "storageRevision", + binding.storageRevision(), + "bindingDigest", + binding.bindingDigest()), + "evidenceRef", + target.evidenceRef(), + "evidenceDigest", + target.evidenceDigest()); + } + + private static Map ordered(Object... entries) { + Map result = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + if (result.size() > MAX_OBJECT_MEMBERS) throw invalid(); + return result; + } + + private static void field(ByteArrayOutputStream output, String name, Object value) { + segment(output, name.getBytes(StandardCharsets.UTF_8)); + value(output, value); + } + + private static void value(ByteArrayOutputStream output, Object value) { + ByteArrayOutputStream payload = new ByteArrayOutputStream(); + String type; + if (value instanceof String string) { + type = "string"; + payload.writeBytes(string.getBytes(StandardCharsets.UTF_8)); + } else if (value instanceof Map object) { + type = "object"; + segment(payload, Integer.toString(object.size()).getBytes(StandardCharsets.US_ASCII)); + for (var member : object.entrySet()) + field(payload, (String) member.getKey(), member.getValue()); + } else { + throw invalid(); + } + segment(output, type.getBytes(StandardCharsets.UTF_8)); + output.write('1'); + segment(output, payload.toByteArray()); + } + + private static void segment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_CANONICAL_SEGMENT_BYTES) throw invalid(); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String string(JsonParser parser, String name) throws IOException { + member(parser, name); + require(parser.nextToken(), JsonToken.VALUE_STRING); + return InitialGameplayRecoverRequest.text(parser.getText(), MAX_RAW_STRING_CHARACTERS); + } + + private static void literal(JsonParser parser, String name, String value) throws IOException { + if (!value.equals(string(parser, name))) throw invalid(); + } + + private static void start(JsonParser parser, String name) throws IOException { + member(parser, name); + require(parser.nextToken(), JsonToken.START_OBJECT); + } + + private static void member(JsonParser parser, String name) throws IOException { + require(parser.nextToken(), JsonToken.FIELD_NAME); + if (!name.equals(parser.currentName())) throw invalid(); + } + + private static void end(JsonParser parser) throws IOException { + require(parser.nextToken(), JsonToken.END_OBJECT); + } + + private static void require(JsonToken actual, JsonToken expected) { + if (actual != expected) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid closed initial-gameplay-recover/v1 input"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverRequest.java new file mode 100644 index 0000000000..fa8aa0410a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverRequest.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.common.recovery; + +import java.text.Normalizer; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; + +/** + * Closed initial-recover selectors, never proof of ownership, authorization, a lock or a fence. + * Account redemption and the receiving owner's live association/storage checks remain mandatory. + * This is not ADR 0048's reservation or post-authorization execution tuple. + */ +public record InitialGameplayRecoverRequest( + UUID controlPlaneRequestId, + Scope scope, + Target target, + Mutation mutation, + AuditReason auditReason) { + public static final String ACTION_FAMILY_SCHEMA_ID = "initial-gameplay-recover/v1"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String TARGET_OWNER = "recovery-controller-service"; + + public InitialGameplayRecoverRequest { + controlPlaneRequestId = uuid(controlPlaneRequestId); + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(mutation, "mutation"); + Objects.requireNonNull(auditReason, "auditReason"); + if (!scope.targetNamespace().equals(target.peerStorageBinding().targetNamespace())) { + throw new IllegalArgumentException("Peer/storage namespace differs from scope"); + } + } + + public record Scope( + UUID canonicalTenantId, String targetNamespace, UUID playableStateNamespaceId) { + public Scope { + canonicalTenantId = uuid(canonicalTenantId); + targetNamespace = namespace(targetNamespace); + playableStateNamespaceId = uuid(playableStateNamespaceId); + } + } + + public record Target( + LaunchAssociation launchAssociation, + PeerStorageBinding peerStorageBinding, + String evidenceRef, + String evidenceDigest) { + public Target { + Objects.requireNonNull(launchAssociation, "launchAssociation"); + Objects.requireNonNull(peerStorageBinding, "peerStorageBinding"); + evidenceRef = text(evidenceRef, 512); + evidenceDigest = digest(evidenceDigest); + } + } + + /** Exact selectors for a Game Session owner read, not a caller-issued association attestation. */ + public record LaunchAssociation( + UUID gameInstanceUuid, + UUID tenantAssociationOperationId, + String worldSlug, + UUID launchControlPlaneRequestId, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest) { + public LaunchAssociation { + gameInstanceUuid = uuid(gameInstanceUuid); + tenantAssociationOperationId = uuid(tenantAssociationOperationId); + worldSlug = text(worldSlug, 128); + launchControlPlaneRequestId = uuid(launchControlPlaneRequestId); + launchDescriptorId = text(launchDescriptorId, 256); + descriptorRequestDigest = digest(descriptorRequestDigest); + descriptorResultDigest = digest(descriptorResultDigest); + releaseAttestationEvidenceDigest = digest(releaseAttestationEvidenceDigest); + } + } + + /** Complete requested binding; the owner must independently authenticate/revalidate it. */ + public record PeerStorageBinding( + String targetNamespace, + String clusterIdentity, + String peerWorkloadIdentity, + String storageIdentity, + String storageRevision, + String bindingDigest) { + public PeerStorageBinding { + targetNamespace = namespace(targetNamespace); + clusterIdentity = text(clusterIdentity, 256); + peerWorkloadIdentity = text(peerWorkloadIdentity, 256); + if (!peerWorkloadIdentity.equals( + "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service")) { + throw new IllegalArgumentException("Expected same-namespace Game Session peer selector"); + } + storageIdentity = text(storageIdentity, 256); + storageRevision = text(storageRevision, 128); + bindingDigest = digest(bindingDigest); + } + } + + public enum MaintenanceLockPresence { + RESULT_ONLY + } + + /** No lock credential can be supplied to this action, including through an optional arm. */ + public record Mutation(UUID operationId, MaintenanceLockPresence maintenanceLockPresence) { + public Mutation { + operationId = uuid(operationId); + Objects.requireNonNull(maintenanceLockPresence, "maintenanceLockPresence"); + } + + public String verb() { + return "recover"; + } + + public String workflow() { + return "initial-gameplay-release"; + } + } + + public enum AuditReasonCode { + INITIAL_GAMEPLAY_RELEASE + } + + public record AuditReason(AuditReasonCode code, String detail) { + public AuditReason { + Objects.requireNonNull(code, "code"); + detail = text(detail, 1024); + } + } + + static UUID uuid(UUID value) { + Objects.requireNonNull(value, "UUID"); + if (value.equals(new UUID(0, 0))) throw new IllegalArgumentException("UUID must be non-nil"); + return value; + } + + static UUID parseUuid(String value) { + if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw new IllegalArgumentException("UUID must be canonical lowercase text"); + } + return uuid(UUID.fromString(value)); + } + + static String text(String value, int limit) { + Objects.requireNonNull(value, "text"); + if (GameTenantCreationDigest.utf8ByteLength(value) > limit) { + throw new IllegalArgumentException("Raw text exceeds family limit"); + } + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + if (normalized.isBlank() + || !normalized.equals(normalized.strip()) + || normalized.codePoints().anyMatch(Character::isISOControl) + || GameTenantCreationDigest.utf8ByteLength(normalized) > limit) { + throw new IllegalArgumentException("Text must be bounded nonblank Unicode without controls"); + } + return normalized; + } + + static String namespace(String value) { + value = text(value, 63); + if (!value.matches("[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")) { + throw new IllegalArgumentException("Namespace must be a Kubernetes namespace"); + } + return value; + } + + static String digest(String value) { + Objects.requireNonNull(value, "digest"); + if (!GameTenantCreationDigest.isDigest(value)) { + throw new IllegalArgumentException("Evidence digest must be lowercase sha256-prefixed hex"); + } + return value; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java new file mode 100644 index 0000000000..4be37b64ea --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.recovery; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; +import java.util.List; +import org.junit.jupiter.api.Test; + +class InitialGameplayRecoverCodecTest { + private static final String D = "sha256:" + "a".repeat(64); + private static final String WIRE = + """ + {"actionFamilySchemaId":"initial-gameplay-recover/v1","actionFamilySchemaVersion":"1", + "controlPlaneRequestId":"00000000-0000-4000-8000-000000000001","targetOwner":"recovery-controller-service", + "scope":{"canonicalTenantId":"00000000-0000-4000-8000-000000000002","targetNamespace":"test","playableStateNamespaceId":"00000000-0000-4000-8000-000000000003"}, + "target":{"launchAssociation":{"gameInstanceUuid":"00000000-0000-4000-8000-000000000004","tenantAssociationOperationId":"00000000-0000-4000-8000-000000000005","worldSlug":"world","launchControlPlaneRequestId":"00000000-0000-4000-8000-000000000006","launchDescriptorId":"launch","descriptorRequestDigest":"%s","descriptorResultDigest":"%s","releaseAttestationEvidenceDigest":"%s"}, + "peerStorageBinding":{"targetNamespace":"test","clusterIdentity":"cluster","peerWorkloadIdentity":"spiffe://firemud/ns/test/sa/game-session-service","storageIdentity":"pg","storageRevision":"1","bindingDigest":"%s"},"evidenceRef":"evidence","evidenceDigest":"%s"}, + "mutation":{"operationId":"00000000-0000-4000-8000-000000000007","verb":"recover","workflow":"initial-gameplay-release","maintenanceLockPresence":"RESULT_ONLY"}, + "auditReason":{"code":"INITIAL_GAMEPLAY_RELEASE","detail":"initial"}} + """ + .formatted(D, D, D, D, D); + + // Static cross-language artifact: lowercase hex of the exact ADR 0047 preimage bytes. + private static final String PREIMAGE_HEX = + "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673132373a696e697469616c2d67616d65706c61792d7265636f7665722f763132353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313137393a313a3331373a63616e6f6e6963616c54656e616e744964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d30303030303030303030303231353a7461726765744e616d657370616365363a737472696e6731343a7465737432343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d303030303030303030303033363a746172676574363a6f626a65637431313134353a313a3431373a6c61756e63684173736f63696174696f6e363a6f626a656374313632373a313a3831363a67616d65496e7374616e636555756964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d30303030303030303030303432383a74656e616e744173736f63696174696f6e4f7065726174696f6e4964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d303030303030303030303035393a776f726c64536c7567363a737472696e6731353a776f726c6432373a6c61756e6368436f6e74726f6c506c616e65526571756573744964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d30303030303030303030303631383a6c61756e636844657363726970746f724964363a737472696e6731363a6c61756e636832333a64657363726970746f7252657175657374446967657374363a737472696e673137313a7368613235363a6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616132323a64657363726970746f72526573756c74446967657374363a737472696e673137313a7368613235363a6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616133323a72656c656173654174746573746174696f6e45766964656e6365446967657374363a737472696e673137313a7368613235363a6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616131383a7065657253746f7261676542696e64696e67363a6f626a656374313331353a313a3631353a7461726765744e616d657370616365363a737472696e6731343a7465737431353a636c75737465724964656e74697479363a737472696e6731373a636c757374657232303a70656572576f726b6c6f61644964656e74697479363a737472696e673134383a7370696666653a2f2f666972656d75642f6e732f746573742f73612f67616d652d73657373696f6e2d7365727669636531353a73746f726167654964656e74697479363a737472696e6731323a706731353a73746f726167655265766973696f6e363a737472696e6731313a3131333a62696e64696e67446967657374363a737472696e673137313a7368613235363a6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616131313a65766964656e6365526566363a737472696e6731383a65766964656e636531343a65766964656e6365446967657374363a737472696e673137313a7368613235363a6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616131353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a656374313138343a313a3431313a6f7065726174696f6e4964363a737472696e673133363a30303030303030302d303030302d343030302d383030302d303030303030303030303037343a76657262363a737472696e6731373a7265636f766572383a776f726b666c6f77363a737472696e673132343a696e697469616c2d67616d65706c61792d72656c6561736532333a6d61696e74656e616e63654c6f636b50726573656e6365363a737472696e673131313a524553554c545f4f4e4c5931313a6175646974526561736f6e363a6f626a6563743137313a313a32343a636f6465363a737472696e673132343a494e495449414c5f47414d45504c41595f52454c45415345363a64657461696c363a737472696e6731373a696e697469616c"; + private static final String DIGEST = + "55b684f3d25ea838ce74c31c18f6852d4d70cf0d298f1694c96929e865cfb670"; + // Same immutable prefix, followed by the independently framed 95-byte NFC audit-reason field. + private static final String UNICODE_PREIMAGE_HEX = + PREIMAGE_HEX.substring(0, PREIMAGE_HEX.length() - 194) + + "31313a6175646974526561736f6e363a6f626a6563743136393a313a32343a636f6465363a737472696e673132343a494e495449414c5f47414d45504c41595f52454c45415345363a64657461696c363a737472696e6731353a636166c3a9"; + private static final String UNICODE_DIGEST = + "e9c2302aa9dc1493f29e0c25a10eedd2c6c2a270a7f55018722593a667cd8458"; + + @Test + void matchesStaticCrossLanguagePreimageHexAndDigest() { + var request = decode(WIRE); + assertThat(InitialGameplayRecoverCodec.mutationPreimage(request)) + .isEqualTo(HexFormat.of().parseHex(PREIMAGE_HEX)); + assertThat(InitialGameplayRecoverCodec.mutationDigest(request)).isEqualTo(DIGEST); + assertThat(new String(HexFormat.of().parseHex(PREIMAGE_HEX), StandardCharsets.UTF_8)) + .contains("15:expectedVersion6:absent00:", "maintenanceLockPresence6:string111:RESULT_ONLY") + .doesNotContain("controlPlaneRequestId", "targetOwner", "maintenanceLockToken"); + } + + @Test + void requestIdentityIsRetainedButExcludedFromMutationDigest() { + var changed = decode(WIRE.replace("000000000001", "000000000009")); + assertThat(changed.controlPlaneRequestId()).isNotEqualTo(decode(WIRE).controlPlaneRequestId()); + assertThat(InitialGameplayRecoverCodec.mutationDigest(changed)).isEqualTo(DIGEST); + } + + @Test + void everyVariablePayloadFieldChangesTheDigest() { + for (String suffix : + List.of( + "000000000002", + "000000000003", + "000000000004", + "000000000005", + "000000000006", + "000000000007")) { + assertChanged(WIRE.replace(suffix, "000000000009")); + } + for (String field : + List.of( + "worldSlug", + "launchDescriptorId", + "clusterIdentity", + "storageIdentity", + "storageRevision", + "evidenceRef", + "detail")) { + assertChanged(WIRE.replaceAll("(\\\"" + field + "\\\":\\\")([^\\\"]+)", "$1changed")); + } + for (String field : + List.of( + "descriptorRequestDigest", + "descriptorResultDigest", + "releaseAttestationEvidenceDigest", + "bindingDigest", + "evidenceDigest")) { + assertChanged( + WIRE.replace("\"" + field + "\":\"" + D, "\"" + field + "\":\"sha256:" + "b".repeat(64))); + } + // Scope namespace and the two matching peer/storage selector fields change together. + assertChanged( + WIRE.replace("\"targetNamespace\":\"test\"", "\"targetNamespace\":\"other\"") + .replace("/ns/test/", "/ns/other/")); + } + + @Test + void nfcEquivalentAuditDetailsHaveIdenticalBytes() { + var composed = decode(WIRE.replace("\"initial\"", "\"caf\u00e9\"")); + var decomposed = decode(WIRE.replace("\"initial\"", "\"cafe\u0301\"")); + assertThat(InitialGameplayRecoverCodec.mutationPreimage(composed)) + .isEqualTo(InitialGameplayRecoverCodec.mutationPreimage(decomposed)) + .isEqualTo(HexFormat.of().parseHex(UNICODE_PREIMAGE_HEX)); + assertThat(InitialGameplayRecoverCodec.mutationDigest(composed)).isEqualTo(UNICODE_DIGEST); + assertThat(InitialGameplayRecoverCodec.mutationDigest(decomposed)).isEqualTo(UNICODE_DIGEST); + } + + @Test + void rejectsUnknownDuplicateMissingAndOutOfOrderFields() { + rejects(WIRE.replace("\"scope\":", "\"unknown\":\"x\",\"scope\":")); + rejects( + WIRE.replace("\"worldSlug\":\"world\"", "\"worldSlug\":\"world\",\"worldSlug\":\"world\"")); + rejects(WIRE.replace("\"worldSlug\":\"world\",", "")); + rejects( + WIRE.replace( + "\"storageIdentity\":\"pg\",\"storageRevision\":\"1\"", + "\"storageRevision\":\"1\",\"storageIdentity\":\"pg\"")); + rejects(WIRE.replace("\"detail\"", "\"deta\\u0069l\",\"detail\"")); + } + + @Test + void rejectsEveryLockAndAuthorityEscape() { + for (String value : List.of("REQUIRED", "NOT_APPLICABLE", "OPTIONAL", "", "sentinel")) { + rejects(WIRE.replace("RESULT_ONLY", value)); + } + for (String field : + List.of( + "maintenanceLockToken", + "maintenanceLockIdentity", + "operatorAuthorizationReference", + "authorityTuple", + "ownerAssociationVerified")) { + rejects(WIRE.replace("\"auditReason\":", "\"" + field + "\":\"asserted\",\"auditReason\":")); + } + rejects(WIRE.replace("\"auditReason\":", "\"expectedVersion\":null,\"auditReason\":")); + rejects(WIRE.replace("\"RESULT_ONLY\"", "null")); + rejects(WIRE.replace("\"recover\"", "\"resume\"")); + rejects(WIRE.replace("initial-gameplay-release", "cold-start-restore")); + rejects(WIRE.replace("recovery-controller-service", "game-session-service")); + } + + @Test + void rejectsNoncanonicalIdsWrongTypesMalformedUnicodeAndOverlimits() { + rejects( + WIRE.replace( + "00000000-0000-4000-8000-000000000001", "00000000-0000-0000-0000-000000000000")); + rejects( + WIRE.replace( + "00000000-0000-4000-8000-000000000001", "AAAAAAAA-0000-4000-8000-000000000001")); + rejects(WIRE.replace("\"storageRevision\":\"1\"", "\"storageRevision\":1e3")); + rejects(WIRE.replace("\"storageRevision\":\"1\"", "\"storageRevision\":[]")); + rejects(WIRE.replace("\"initial\"", "\"\\ud800\"")); + rejects(WIRE.replace("\"initial\"", "\"" + "x".repeat(1025) + "\"")); + rejects(WIRE + " ".repeat(InitialGameplayRecoverCodec.MAX_RAW_BYTES)); + rejects(WIRE + "{}"); + assertThatThrownBy(() -> InitialGameplayRecoverCodec.decode(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + } + + private static InitialGameplayRecoverRequest decode(String wire) { + return InitialGameplayRecoverCodec.decode(wire.getBytes(StandardCharsets.UTF_8)); + } + + private static void assertChanged(String wire) { + assertThat(InitialGameplayRecoverCodec.mutationDigest(decode(wire))).isNotEqualTo(DIGEST); + } + + private static void rejects(String wire) { + assertThatThrownBy(() -> decode(wire)).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/recovery-controller-service/build.gradle.kts b/services/recovery-controller-service/build.gradle.kts new file mode 100644 index 0000000000..5e66a297c5 --- /dev/null +++ b/services/recovery-controller-service/build.gradle.kts @@ -0,0 +1,15 @@ +apply(from = "${rootDir}/gradle/proto-convention.gradle") + +plugins { + id("net.firedevops.firemud.secured-sql-aop-service-conventions") + id("net.firedevops.firemud.jooq-conventions") +} + +firemudJooq { + packageName.set("net.firedevops.firemud.recovery.jooq") +} + +dependencies { + implementation(project(":common-platform-core")) + testImplementation(project(":common-test-support")) +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/RecoveryControllerServiceApplication.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/RecoveryControllerServiceApplication.java new file mode 100644 index 0000000000..615fb6442e --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/RecoveryControllerServiceApplication.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.recovery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RecoveryControllerServiceApplication { + public static void main(String[] args) { + SpringApplication.run(RecoveryControllerServiceApplication.class, args); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java new file mode 100644 index 0000000000..34f2ff07a8 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.recovery.config; + +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.journal.JooqInitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEvidenceProvider; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseController; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider; +import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RecoveryControllerOwnerConfiguration { + @Bean + @ConditionalOnMissingBean(InitialGameplayReleaseEvidenceProvider.class) + InitialGameplayReleaseEvidenceProvider deniedInitialGameplayReleaseEvidenceProvider() { + return new DeniedInitialGameplayReleaseEvidenceProvider(); + } + + @Bean + @ConditionalOnMissingBean(InitialGameplayReleaseEffectPort.class) + InitialGameplayReleaseEffectPort deniedInitialGameplayReleaseEffectPort() { + return new DeniedInitialGameplayReleaseEffectPort(); + } + + @Bean + @ConditionalOnMissingBean(InitialGameplayReleaseJournal.class) + InitialGameplayReleaseJournal initialGameplayReleaseJournal( + DSLContext dsl, InitialGameplayReleaseTupleCodec tupleCodec) { + return new JooqInitialGameplayReleaseJournal(dsl, tupleCodec); + } + + @Bean + @ConditionalOnMissingBean(InitialGameplayReleaseController.class) + InitialGameplayReleaseController initialGameplayReleaseController( + InitialGameplayReleaseJournal journal, + InitialGameplayReleaseTupleCodec tupleCodec, + InitialGameplayReleaseEvidenceProvider evidenceProvider, + InitialGameplayReleaseEffectPort effectPort) { + return new InitialGameplayReleaseController(journal, tupleCodec, evidenceProvider, effectPort); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseConflictException.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseConflictException.java new file mode 100644 index 0000000000..d51b3f17d6 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseConflictException.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.recovery.journal; + +public class InitialGameplayReleaseConflictException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public InitialGameplayReleaseConflictException(String message) { + super(message); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java new file mode 100644 index 0000000000..4d2b027d0f --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.recovery.journal; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectKind; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PublicTransitionTuple; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; + +/** Durable owner store for the initial-gameplay-release operation and effects. */ +public interface InitialGameplayReleaseJournal { + Operation create(Scope scope, UUID controllerIssuedLockIdentity); + + Optional find(UUID operationId); + + Operation bindVerifiedEvidence( + Scope scope, + String scopeDigest, + InitialGameplayReleaseEvidence evidence, + String evidenceDigest, + Instant now); + + Optional findTransition(PublicTransitionTuple tuple); + + Operation transition(PublicTransitionTuple tuple, Instant now); + + Optional findNextEffect(UUID operationId); + + OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Instant now); + + OutboxEntry recordRetryableEffect( + UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); + + OutboxEntry recordAmbiguousEffect( + UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); + + Operation recordEffectReadback( + UUID operationId, UUID effectId, UUID attemptId, EffectReadback readback, Instant now); + + Optional findEffect(UUID operationId, EffectKind effectKind); +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java new file mode 100644 index 0000000000..2edde5af5c --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.recovery.journal; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import org.springframework.stereotype.Component; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/** Stable JSON and digest encoding for the operation-owned immutable tuples. */ +@Component +public final class InitialGameplayReleaseTupleCodec { + private final ObjectMapper objectMapper; + + public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { + this.objectMapper = + Objects.requireNonNull(objectMapper, "objectMapper must not be null").rebuild().build(); + } + + public String toJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JacksonException exception) { + throw new IllegalStateException("Unable to encode initial gameplay release tuple", exception); + } + } + + public String digest(Object value) { + final byte[] canonical; + try { + canonical = Rfc8785CanonicalJson.canonicalizeUtf8(toJson(value)); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Initial gameplay release tuple is not canonical JSON", exception); + } + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + public String operationTupleDigest( + Scope scope, + java.util.UUID maintenanceLockIdentity, + InitialGameplayReleaseModel.InitialGameplayReleaseEvidence evidence) { + return digest(new OperationProofTuple(scope, maintenanceLockIdentity, evidence)); + } + + public record OperationProofTuple( + Scope scope, + java.util.UUID maintenanceLockIdentity, + InitialGameplayReleaseModel.InitialGameplayReleaseEvidence evidence) {} + + public InitialGameplayReleaseModel.Scope readScope(String json) { + try { + return objectMapper.readValue(json, InitialGameplayReleaseModel.Scope.class); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Unable to read persisted initial gameplay release scope", exception); + } + } + + public InitialGameplayReleaseModel.PeerStorageBinding readPeerStorageBinding(String json) { + try { + return objectMapper.readValue(json, InitialGameplayReleaseModel.PeerStorageBinding.class); + } catch (JacksonException exception) { + throw new IllegalStateException("Unable to read persisted peer/storage binding", exception); + } + } + + public InitialGameplayReleaseModel.InitialGameplayReleaseEvidence readEvidence(String json) { + try { + return objectMapper.readValue( + json, InitialGameplayReleaseModel.InitialGameplayReleaseEvidence.class); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Unable to read persisted initial gameplay release evidence", exception); + } + } + + public InitialGameplayReleaseModel.TypedEffect readEffect(String kind, String json) { + try { + if (InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED + == InitialGameplayReleaseModel.EffectKind.fromDatabaseValue(kind)) { + return objectMapper.readValue( + json, InitialGameplayReleaseModel.PreparePlayableStateFencedEffect.class); + } + return objectMapper.readValue( + json, InitialGameplayReleaseModel.CommitOwnerAuthorizedHandoffEffect.class); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Unable to read persisted initial gameplay release effect", exception); + } + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java new file mode 100644 index 0000000000..cf94d3adc5 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -0,0 +1,684 @@ +package net.firedevops.firemud.recovery.journal; + +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.CommitOwnerAuthorizedHandoffEffect; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectKind; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackState; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PreparePlayableStateFencedEffect; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PublicTransitionTuple; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TypedEffect; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredDigest; +import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredText; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.jooq.impl.DSL; + +/** + * PostgreSQL compare-and-set journal and transactional outbox for initial gameplay release only. + */ +public final class JooqInitialGameplayReleaseJournal implements InitialGameplayReleaseJournal { + private static final String TRANSITION_TABLE = + "recovery_control.initial_gameplay_release_transition"; + private static final String OUTBOX_TABLE = "recovery_control.initial_gameplay_release_outbox"; + + private final DSLContext dsl; + private final InitialGameplayReleaseTupleCodec tupleCodec; + + public JooqInitialGameplayReleaseJournal( + DSLContext dsl, InitialGameplayReleaseTupleCodec tupleCodec) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.tupleCodec = Objects.requireNonNull(tupleCodec, "tupleCodec must not be null"); + } + + @Override + public Operation create(Scope scope, UUID controllerIssuedLockIdentity) { + Objects.requireNonNull(scope, "scope must not be null"); + Objects.requireNonNull( + controllerIssuedLockIdentity, "controllerIssuedLockIdentity must not be null"); + String scopeDigest = tupleCodec.digest(scope); + JSONB scopePayload = JSONB.valueOf(tupleCodec.toJson(scope)); + JSONB bindingPayload = JSONB.valueOf(tupleCodec.toJson(scope.peerStorageBinding())); + Instant now = Instant.now(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_operation ( + operation_id, operation_kind, target_namespace, playable_state_namespace_id, + peer_storage_binding, scope_payload, evidence_ref, scope_digest, + maintenance_lock_identity, phase, revision, created_at, updated_at + ) VALUES (?, 'initial_gameplay_release', ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, 'collecting', 1, CAST(? AS timestamptz), CAST(? AS timestamptz)) + ON CONFLICT (operation_id) DO NOTHING + """, + scope.operationId(), + scope.targetNamespace(), + scope.playableStateNamespaceId(), + bindingPayload, + scopePayload, + scope.evidenceRef(), + scopeDigest, + controllerIssuedLockIdentity, + toOffsetDateTime(now), + toOffsetDateTime(now)); + Operation operation = selectOperation(tx, scope.operationId(), true); + requireSameScope(operation.scope(), scope, scopeDigest); + return operation; + }); + } + + @Override + public Optional find(UUID operationId) { + Objects.requireNonNull(operationId, "operationId must not be null"); + return Optional.ofNullable(selectOperation(dsl, operationId, false)); + } + + @Override + public Operation bindVerifiedEvidence( + Scope scope, + String scopeDigest, + InitialGameplayReleaseEvidence evidence, + String evidenceDigest, + Instant now) { + Objects.requireNonNull(scope, "scope must not be null"); + requiredDigest(scopeDigest, "scopeDigest"); + Objects.requireNonNull(evidence, "evidence must not be null"); + requiredDigest(evidenceDigest, "evidenceDigest"); + Objects.requireNonNull(now, "now must not be null"); + evidence.validateFor(scope); + if (!scopeDigest.equals(tupleCodec.digest(scope)) + || !evidenceDigest.equals(tupleCodec.digest(evidence))) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: evidence tuple digest changed"); + } + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Operation current = selectOperation(tx, scope.operationId(), true); + requireSameScope(current.scope(), scope, scopeDigest); + if (current.evidence() != null) { + if (evidenceDigest.equals(tupleCodec.digest(current.evidence())) + && evidence.evidenceIdentity().equals(current.evidence().evidenceIdentity())) { + return current; + } + throw conflict("owner evidence changed after it was bound"); + } + if (current.phase() != Phase.COLLECTING) { + throw conflict("operation is not collecting owner evidence"); + } + int changed = + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_operation + SET phase = ?, evidence_snapshot = CAST(? AS jsonb), evidence_identity = ?, evidence_digest = ?, + revision = revision + 1, updated_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND phase = ? AND revision = ? AND evidence_snapshot IS NULL + """, + Phase.READY_TO_REOPEN.databaseValue(), + JSONB.valueOf(tupleCodec.toJson(evidence)), + evidence.evidenceIdentity(), + evidenceDigest, + toOffsetDateTime(now), + scope.operationId(), + Phase.COLLECTING.databaseValue(), + current.revision()); + if (changed != 1) { + throw conflict("owner evidence compare-and-set lost"); + } + return selectOperation(tx, scope.operationId(), false); + }); + } + + @Override + public Operation transition(PublicTransitionTuple tuple, Instant now) { + Objects.requireNonNull(tuple, "tuple must not be null"); + Objects.requireNonNull(now, "now must not be null"); + String tupleDigest = tupleCodec.digest(tuple); + JSONB tuplePayload = JSONB.valueOf(tupleCodec.toJson(tuple)); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Operation current = selectOperation(tx, tuple.operationId(), true); + requireTransitionMatchesOperation(tuple, current); + Record previous = + tx.fetchOne( + "SELECT tuple_digest FROM " + + TRANSITION_TABLE + + " WHERE operation_id = ? AND verb = ?", + tuple.operationId(), + tuple.verb().wireValue()); + if (previous != null) { + if (!tupleDigest.equals(previous.get("tuple_digest", String.class))) { + throw conflict("public transition tuple changed"); + } + return current; + } + if (current.phase() != tuple.expectedPhase()) { + throw conflict("public transition expected phase is stale"); + } + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_transition ( + operation_id, verb, tuple_digest, tuple_payload, expected_phase, result_phase + ) VALUES (?, ?, ?, CAST(? AS jsonb), ?, ?) + """, + tuple.operationId(), + tuple.verb().wireValue(), + tupleDigest, + tuplePayload, + tuple.expectedPhase().databaseValue(), + tuple.verb().resultPhase().databaseValue()); + int changed = + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_operation + SET phase = ?, revision = revision + 1, updated_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND phase = ? AND revision = ? + """, + tuple.verb().resultPhase().databaseValue(), + toOffsetDateTime(now), + tuple.operationId(), + tuple.expectedPhase().databaseValue(), + current.revision()); + if (changed != 1) { + throw conflict("public transition compare-and-set lost"); + } + Operation transitioned = selectOperation(tx, tuple.operationId(), false); + if (tuple.verb() == TransitionVerb.RESUME) { + enqueueEffect(tx, prepareEffect(transitioned), now); + } + return transitioned; + }); + } + + @Override + public Optional findTransition(PublicTransitionTuple tuple) { + Objects.requireNonNull(tuple, "tuple must not be null"); + Operation operation = selectOperation(dsl, tuple.operationId(), false); + requireTransitionMatchesOperation(tuple, operation); + Record previous = + dsl.fetchOne( + "SELECT tuple_digest FROM " + TRANSITION_TABLE + " WHERE operation_id = ? AND verb = ?", + tuple.operationId(), + tuple.verb().wireValue()); + if (previous == null) { + return Optional.empty(); + } + if (!tupleCodec.digest(tuple).equals(previous.get("tuple_digest", String.class))) { + throw conflict("public transition tuple changed"); + } + return Optional.of(operation); + } + + @Override + public Optional findNextEffect(UUID operationId) { + Record record = + dsl.fetchOne( + """ + SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + payload_digest, state, + attempt_count, last_attempt_id, last_outcome_code, acknowledged_at + FROM recovery_control.initial_gameplay_release_outbox + WHERE operation_id = ? AND state <> 'acknowledged' + ORDER BY created_at, outbox_id + LIMIT 1 + """, + operationId); + return Optional.ofNullable(record).map(this::toOutboxEntry); + } + + @Override + public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Instant now) { + Objects.requireNonNull(attemptId, "attemptId must not be null"); + Objects.requireNonNull(now, "now must not be null"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Operation operation = selectOperation(tx, operationId, true); + OutboxEntry current = selectOutbox(tx, operationId, effectId, true); + if (current.state() == EffectOutboxState.DISPATCHED + || current.state() == EffectOutboxState.AMBIGUOUS + || current.state() == EffectOutboxState.ACKNOWLEDGED) { + return current; + } + requirePhaseForEffect(operation.phase(), current.effect().kind()); + int changed = + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_outbox + SET state = 'dispatched', attempt_count = attempt_count + 1, + last_attempt_id = ?, last_outcome_code = NULL, + readback_identity = NULL, readback_payload = NULL, readback_digest = NULL, + updated_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND effect_id = ? AND state IN ('pending', 'retryable') + """, + attemptId, + toOffsetDateTime(now), + operationId, + effectId); + if (changed != 1) { + return selectOutbox(tx, operationId, effectId, false); + } + return selectOutbox(tx, operationId, effectId, false); + }); + } + + @Override + public OutboxEntry recordRetryableEffect( + UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { + return recordNonterminalEffectOutcome( + operationId, effectId, attemptId, outcomeCode, EffectOutboxState.RETRYABLE, now); + } + + @Override + public OutboxEntry recordAmbiguousEffect( + UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { + return recordNonterminalEffectOutcome( + operationId, effectId, attemptId, outcomeCode, EffectOutboxState.AMBIGUOUS, now); + } + + private OutboxEntry recordNonterminalEffectOutcome( + UUID operationId, + UUID effectId, + UUID attemptId, + String outcomeCode, + EffectOutboxState resultState, + Instant now) { + requiredText(outcomeCode, "outcomeCode"); + if (!outcomeCode.matches("[A-Z0-9_]{1,64}")) { + throw new IllegalArgumentException("outcomeCode must be a bounded uppercase code"); + } + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + OutboxEntry current = selectOutbox(tx, operationId, effectId, true); + if (current.lastAttemptId() != null && !current.lastAttemptId().equals(attemptId)) { + throw conflict("effect attempt identity changed"); + } + if (current.state() == resultState) { + return current; + } + if (current.state() != EffectOutboxState.DISPATCHED) { + throw conflict("effect is not in a dispatchable attempt"); + } + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_outbox + SET state = ?, last_outcome_code = ?, updated_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND effect_id = ? AND state = 'dispatched' + AND last_attempt_id = ? + """, + resultState.databaseValue(), + outcomeCode, + toOffsetDateTime(now), + operationId, + effectId, + attemptId); + return selectOutbox(tx, operationId, effectId, false); + }); + } + + @Override + public Operation recordEffectReadback( + UUID operationId, UUID effectId, UUID attemptId, EffectReadback readback, Instant now) { + Objects.requireNonNull(readback, "readback must not be null"); + Objects.requireNonNull(now, "now must not be null"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Operation operation = selectOperation(tx, operationId, true); + OutboxEntry current = selectOutbox(tx, operationId, effectId, true); + requireReadbackMatches(readback, current, operationId, effectId); + String readbackDigest = tupleCodec.digest(readback); + if (current.state() == EffectOutboxState.ACKNOWLEDGED) { + Record stored = + tx.fetchOne( + "SELECT readback_digest FROM " + + OUTBOX_TABLE + + " WHERE operation_id = ? AND effect_id = ?", + operationId, + effectId); + if (current.lastAttemptId() != null + && current.lastAttemptId().equals(attemptId) + && stored != null + && readbackDigest.equals(stored.get("readback_digest", String.class))) { + return operation; + } + throw conflict("effect readback changed after acknowledgement"); + } + if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { + throw conflict("effect readback belongs to another attempt"); + } + if (current.state() != EffectOutboxState.DISPATCHED + && current.state() != EffectOutboxState.AMBIGUOUS) { + throw conflict("effect is not awaiting readback reconciliation"); + } + Record timestamps = + tx.fetchOne( + "SELECT updated_at FROM " + + OUTBOX_TABLE + + " WHERE operation_id = ? AND effect_id = ?", + operationId, + effectId); + if (timestamps == null) { + throw conflict("effect dispatch timestamp is unavailable"); + } + OffsetDateTime dispatchTime = timestamps.get("updated_at", OffsetDateTime.class); + if (dispatchTime == null) { + throw conflict("effect dispatch timestamp is unavailable"); + } + Instant dispatchedAt = dispatchTime.toInstant(); + if (readback.observedAt().isBefore(dispatchedAt)) { + throw conflict("effect readback is stale"); + } + if (readback.state() == EffectReadbackState.UNKNOWN_OR_PARTIAL) { + setReadbackState( + tx, current, readback, readbackDigest, EffectOutboxState.AMBIGUOUS, now); + return operation; + } + if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT) { + setReadbackState( + tx, current, readback, readbackDigest, EffectOutboxState.RETRYABLE, now); + return operation; + } + requireSuccessfulReadbackState(readback, current.effect().kind()); + setReadbackState( + tx, current, readback, readbackDigest, EffectOutboxState.ACKNOWLEDGED, now); + if (current.effect().kind() == EffectKind.PREPARE_PLAYABLE_STATE_FENCED) { + if (operation.phase() != Phase.RESUME_AUTHORIZED) { + throw conflict("preparation effect is outside the authorized phase"); + } + updatePhase(tx, operation, Phase.RELEASING, now, null); + enqueueEffect(tx, handoffEffect(operation), now); + } else { + if (operation.phase() != Phase.RELEASING) { + throw conflict("handoff effect is outside the releasing phase"); + } + updatePhase(tx, operation, Phase.FINALIZED, now, now); + } + return selectOperation(tx, operationId, false); + }); + } + + @Override + public Optional findEffect(UUID operationId, EffectKind effectKind) { + Record record = + dsl.fetchOne( + """ + SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + payload_digest, state, + attempt_count, last_attempt_id, last_outcome_code, acknowledged_at + FROM recovery_control.initial_gameplay_release_outbox + WHERE operation_id = ? AND effect_kind = ? + """, + operationId, + effectKind.databaseValue()); + return Optional.ofNullable(record).map(this::toOutboxEntry); + } + + private void setReadbackState( + DSLContext tx, + OutboxEntry current, + EffectReadback readback, + String readbackDigest, + EffectOutboxState state, + Instant now) { + boolean acknowledged = state == EffectOutboxState.ACKNOWLEDGED; + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_outbox + SET state = ?, last_outcome_code = ?, readback_identity = ?, readback_payload = CAST(? AS jsonb), + readback_digest = ?, acknowledged_at = CAST(? AS timestamptz), updated_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND effect_id = ? AND last_attempt_id = ? + """, + state.databaseValue(), + readback.state().name(), + readback.readbackIdentity(), + JSONB.valueOf(tupleCodec.toJson(readback)), + readbackDigest, + acknowledged ? toOffsetDateTime(now) : null, + toOffsetDateTime(now), + readback.operationId(), + readback.effectId(), + current.lastAttemptId()); + } + + private void updatePhase( + DSLContext tx, Operation operation, Phase result, Instant now, Instant finalizedAt) { + int changed = + tx.execute( + """ + UPDATE recovery_control.initial_gameplay_release_operation + SET phase = ?, revision = revision + 1, updated_at = CAST(? AS timestamptz), finalized_at = CAST(? AS timestamptz) + WHERE operation_id = ? AND phase = ? AND revision = ? + """, + result.databaseValue(), + toOffsetDateTime(now), + toOffsetDateTime(finalizedAt), + operation.scope().operationId(), + operation.phase().databaseValue(), + operation.revision()); + if (changed != 1) { + throw conflict("effect phase compare-and-set lost"); + } + } + + private void enqueueEffect(DSLContext tx, TypedEffect effect, Instant now) { + String payload = tupleCodec.toJson(effect); + String payloadDigest = tupleCodec.digest(effect); + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_outbox ( + outbox_id, operation_id, effect_id, effect_kind, operation_tuple_digest, + payload_digest, payload, state, attempt_count, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, CAST(? AS jsonb), 'pending', 0, CAST(? AS timestamptz), CAST(? AS timestamptz)) + """, + UUID.randomUUID(), + effect.operationId(), + effect.effectId(), + effect.kind().databaseValue(), + effect.operationTupleDigest(), + payloadDigest, + JSONB.valueOf(payload), + toOffsetDateTime(now), + toOffsetDateTime(now)); + } + + private TypedEffect prepareEffect(Operation operation) { + return new PreparePlayableStateFencedEffect( + operation.scope().operationId(), + UUID.randomUUID(), + operation.maintenanceLockIdentity(), + operation.scope(), + operationTupleDigest(operation), + operation.evidence().evidenceIdentity()); + } + + private TypedEffect handoffEffect(Operation operation) { + return new CommitOwnerAuthorizedHandoffEffect( + operation.scope().operationId(), + UUID.randomUUID(), + UUID.randomUUID(), + operation.maintenanceLockIdentity(), + operation.scope(), + operationTupleDigest(operation), + operation.evidence().evidenceIdentity()); + } + + private String operationTupleDigest(Operation operation) { + return tupleCodec.operationTupleDigest( + operation.scope(), operation.maintenanceLockIdentity(), operation.evidence()); + } + + private Operation selectOperation(DSLContext context, UUID operationId, boolean forUpdate) { + Record record = + context.fetchOne( + """ + SELECT operation_id, operation_kind, target_namespace, playable_state_namespace_id, + peer_storage_binding, scope_payload, evidence_ref, scope_digest, + maintenance_lock_identity, phase, revision, evidence_snapshot, + evidence_identity, evidence_digest, created_at, updated_at, finalized_at + FROM recovery_control.initial_gameplay_release_operation + WHERE operation_id = ? + """ + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + if (record == null) { + throw new IllegalArgumentException("INITIAL_GAMEPLAY_RELEASE_NOT_FOUND"); + } + JSONB scopeJson = record.get("scope_payload", JSONB.class); + JSONB evidenceJson = record.get("evidence_snapshot", JSONB.class); + JSONB bindingJson = record.get("peer_storage_binding", JSONB.class); + Scope scope = tupleCodec.readScope(scopeJson.data()); + if (!"initial_gameplay_release".equals(record.get("operation_kind", String.class)) + || !scope.targetNamespace().equals(record.get("target_namespace", String.class)) + || !scope + .playableStateNamespaceId() + .equals(record.get("playable_state_namespace_id", UUID.class)) + || !scope.evidenceRef().equals(record.get("evidence_ref", String.class)) + || !scope.peerStorageBinding().equals(tupleCodec.readPeerStorageBinding(bindingJson.data())) + || !tupleCodec.digest(scope).equals(record.get("scope_digest", String.class))) { + throw new IllegalStateException("Persisted initial gameplay release scope is inconsistent"); + } + InitialGameplayReleaseEvidence evidence = + evidenceJson == null ? null : tupleCodec.readEvidence(evidenceJson.data()); + if (evidence != null + && (!evidence.evidenceIdentity().equals(record.get("evidence_identity", String.class)) + || !tupleCodec.digest(evidence).equals(record.get("evidence_digest", String.class)))) { + throw new IllegalStateException( + "Persisted initial gameplay release evidence is inconsistent"); + } + return new Operation( + scope, + record.get("maintenance_lock_identity", UUID.class), + Phase.fromDatabaseValue(record.get("phase", String.class)), + record.get("revision", Long.class), + evidence, + toInstant(record.get("created_at", OffsetDateTime.class)), + toInstant(record.get("updated_at", OffsetDateTime.class)), + toInstant(record.get("finalized_at", OffsetDateTime.class))); + } + + private OutboxEntry selectOutbox( + DSLContext context, UUID operationId, UUID effectId, boolean forUpdate) { + Record record = + context.fetchOne( + """ + SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + payload_digest, state, + attempt_count, last_attempt_id, last_outcome_code, acknowledged_at + FROM recovery_control.initial_gameplay_release_outbox + WHERE operation_id = ? AND effect_id = ? + """ + + (forUpdate ? " FOR UPDATE" : ""), + operationId, + effectId); + if (record == null) { + throw new IllegalArgumentException("INITIAL_GAMEPLAY_RELEASE_EFFECT_NOT_FOUND"); + } + return toOutboxEntry(record); + } + + private OutboxEntry toOutboxEntry(Record record) { + JSONB payload = record.get("payload", JSONB.class); + String effectKind = record.get("effect_kind", String.class); + Instant acknowledgedAt = toInstant(record.get("acknowledged_at", OffsetDateTime.class)); + TypedEffect effect = tupleCodec.readEffect(effectKind, payload.data()); + if (!tupleCodec.digest(effect).equals(record.get("payload_digest", String.class)) + || !effect + .operationTupleDigest() + .equals(record.get("operation_tuple_digest", String.class))) { + throw new IllegalStateException("Persisted initial gameplay release effect is inconsistent"); + } + return new OutboxEntry( + record.get("outbox_id", UUID.class), + effect, + record.get("payload_digest", String.class), + EffectOutboxState.fromDatabaseValue(record.get("state", String.class)), + record.get("attempt_count", Integer.class), + record.get("last_attempt_id", UUID.class), + record.get("last_outcome_code", String.class), + acknowledgedAt); + } + + private void requireSameScope(Scope actual, Scope requested, String expectedDigest) { + if (!actual.equals(requested) || !expectedDigest.equals(tupleCodec.digest(actual))) { + throw conflict("operation scope tuple changed"); + } + } + + private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Operation operation) { + if (!tuple.operationId().equals(operation.scope().operationId()) + || !tuple.scopeDigest().equals(tupleCodec.digest(operation.scope())) + || !tuple.maintenanceLockIdentity().equals(operation.maintenanceLockIdentity()) + || !tuple.evidenceRef().equals(operation.scope().evidenceRef()) + || operation.evidence() == null + || !tuple.evidenceIdentity().equals(operation.evidence().evidenceIdentity()) + || !tuple.evidenceDigest().equals(tupleCodec.digest(operation.evidence()))) { + throw conflict("public transition tuple does not match the operation-owned tuple"); + } + } + + private void requireReadbackMatches( + EffectReadback readback, OutboxEntry outbox, UUID operationId, UUID effectId) { + if (!readback.operationId().equals(operationId) + || !readback.operationId().equals(outbox.effect().operationId()) + || !readback.effectId().equals(effectId) + || readback.effectKind() != outbox.effect().kind() + || readback.authority() + != InitialGameplayReleaseModel.EffectReadbackAuthority + .GAME_SESSION_DURABLE_CURRENT_STATE + || !readback.operationTupleDigest().equals(outbox.effect().operationTupleDigest()) + || !readback.payloadDigest().equals(outbox.payloadDigest())) { + throw conflict("effect readback does not match the exact dispatched tuple"); + } + } + + private void requireSuccessfulReadbackState(EffectReadback readback, EffectKind effectKind) { + EffectReadbackState expected = + effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED + ? EffectReadbackState.PREPARED_FENCED + : EffectReadbackState.OWNER_HANDOFF_APPLIED; + if (readback.state() != expected) { + throw conflict("effect readback did not prove its exact durable outcome"); + } + } + + private void requirePhaseForEffect(Phase phase, EffectKind effectKind) { + Phase expected = + effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED + ? Phase.RESUME_AUTHORIZED + : Phase.RELEASING; + if (phase != expected) { + throw conflict("effect is not authorized in the current owner phase"); + } + } + + private static Instant toInstant(OffsetDateTime value) { + return value == null ? null : value.toInstant(); + } + + private static OffsetDateTime toOffsetDateTime(Instant value) { + return value == null ? null : value.atOffset(ZoneOffset.UTC); + } + + private static InitialGameplayReleaseConflictException conflict(String reason) { + return new InitialGameplayReleaseConflictException("IDEMPOTENCY_CONFLICT: " + reason); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseCommands.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseCommands.java new file mode 100644 index 0000000000..8c86883a14 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseCommands.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.recovery.model; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; + +/** Typed inputs for the narrow initial gameplay release owner. */ +public final class InitialGameplayReleaseCommands { + private InitialGameplayReleaseCommands() {} + + public record ContinueRecovery( + UUID operationId, + Phase expectedPhase, + MaintenanceLockCredential maintenanceLock, + String evidenceRef) { + public ContinueRecovery { + operationId = InitialGameplayReleaseModel.requiredUuid(operationId, "operationId"); + Objects.requireNonNull(expectedPhase, "expectedPhase must not be null"); + Objects.requireNonNull(maintenanceLock, "maintenanceLock must not be null"); + evidenceRef = InitialGameplayReleaseModel.requiredText(evidenceRef, "evidenceRef"); + if (expectedPhase != Phase.READY_TO_REOPEN) { + throw new IllegalArgumentException("continueRecovery requires ready_to_reopen"); + } + } + } + + public record Resume( + UUID operationId, + Phase expectedPhase, + MaintenanceLockCredential maintenanceLock, + String evidenceRef) { + public Resume { + operationId = InitialGameplayReleaseModel.requiredUuid(operationId, "operationId"); + Objects.requireNonNull(expectedPhase, "expectedPhase must not be null"); + Objects.requireNonNull(maintenanceLock, "maintenanceLock must not be null"); + evidenceRef = InitialGameplayReleaseModel.requiredText(evidenceRef, "evidenceRef"); + if (expectedPhase != Phase.AWAITING_RESUME) { + throw new IllegalArgumentException("resume requires awaiting_resume"); + } + } + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java new file mode 100644 index 0000000000..7b8cceb418 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java @@ -0,0 +1,847 @@ +package net.firedevops.firemud.recovery.model; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Typed, operation-specific records for the initial gameplay release owner. */ +public final class InitialGameplayReleaseModel { + private InitialGameplayReleaseModel() {} + + public enum Phase { + COLLECTING("collecting"), + READY_TO_REOPEN("ready_to_reopen"), + AWAITING_RESUME("awaiting_resume"), + RESUME_AUTHORIZED("resume_authorized"), + RELEASING("releasing"), + FINALIZED("finalized"); + + private final String databaseValue; + + Phase(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } + + public static Phase fromDatabaseValue(String value) { + for (Phase phase : values()) { + if (phase.databaseValue.equals(value)) { + return phase; + } + } + throw new IllegalArgumentException("Unknown initial gameplay release phase"); + } + } + + public enum TransitionVerb { + CONTINUE_RECOVERY("continueRecovery", Phase.READY_TO_REOPEN, Phase.AWAITING_RESUME), + RESUME("resume", Phase.AWAITING_RESUME, Phase.RESUME_AUTHORIZED); + + private final String wireValue; + private final Phase expectedPhase; + private final Phase resultPhase; + + TransitionVerb(String wireValue, Phase expectedPhase, Phase resultPhase) { + this.wireValue = wireValue; + this.expectedPhase = expectedPhase; + this.resultPhase = resultPhase; + } + + public String wireValue() { + return wireValue; + } + + public Phase expectedPhase() { + return expectedPhase; + } + + public Phase resultPhase() { + return resultPhase; + } + } + + public enum ProofDisposition { + VERIFIED, + FAILED, + UNAVAILABLE + } + + public enum WriterDisposition { + STOPPED, + FENCED, + ACTIVE, + UNKNOWN + } + + public enum OwnerService { + WORLD_MANAGEMENT("world-management-service"), + ENTITY_MANAGEMENT("entity-management-service"); + + private final String serviceName; + + OwnerService(String serviceName) { + this.serviceName = serviceName; + } + + public String serviceName() { + return serviceName; + } + } + + public enum EffectKind { + PREPARE_PLAYABLE_STATE_FENCED("prepare_playable_state_fenced"), + COMMIT_OWNER_AUTHORIZED_HANDOFF("commit_owner_authorized_handoff"); + + private final String databaseValue; + + EffectKind(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } + + public static EffectKind fromDatabaseValue(String value) { + for (EffectKind kind : values()) { + if (kind.databaseValue.equals(value)) { + return kind; + } + } + throw new IllegalArgumentException("Unknown initial gameplay release effect kind"); + } + } + + public enum EffectOutboxState { + PENDING("pending"), + DISPATCHED("dispatched"), + RETRYABLE("retryable"), + AMBIGUOUS("ambiguous"), + ACKNOWLEDGED("acknowledged"); + + private final String databaseValue; + + EffectOutboxState(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } + + public static EffectOutboxState fromDatabaseValue(String value) { + for (EffectOutboxState state : values()) { + if (state.databaseValue.equals(value)) { + return state; + } + } + throw new IllegalArgumentException("Unknown initial gameplay release outbox state"); + } + } + + public enum EffectReadbackState { + PREPARED_FENCED, + OWNER_HANDOFF_APPLIED, + PROVEN_NO_EFFECT, + UNKNOWN_OR_PARTIAL + } + + public enum EffectReadbackAuthority { + GAME_SESSION_DURABLE_CURRENT_STATE + } + + public record PeerStorageBinding( + String targetNamespace, + String clusterIdentity, + String peerWorkloadIdentity, + String storageIdentity, + String storageRevision, + String bindingDigest) { + public PeerStorageBinding { + targetNamespace = requiredNamespace(targetNamespace, "targetNamespace"); + clusterIdentity = requiredText(clusterIdentity, "clusterIdentity"); + peerWorkloadIdentity = requiredText(peerWorkloadIdentity, "peerWorkloadIdentity"); + storageIdentity = requiredText(storageIdentity, "storageIdentity"); + storageRevision = requiredText(storageRevision, "storageRevision"); + bindingDigest = requiredDigest(bindingDigest, "bindingDigest"); + } + } + + /** + * Caller-requested scope. The peer/storage binding is still revalidated by the configured owner + * evidence provider; this record alone is never an authorization or a proof of provisioning. + */ + public record Scope( + UUID operationId, + UUID canonicalTenantId, + String targetNamespace, + UUID playableStateNamespaceId, + PeerStorageBinding peerStorageBinding, + String evidenceRef) { + public Scope { + operationId = requiredUuid(operationId, "operationId"); + // This immutable identity binds the operation to a tenant; it is not authorization or + // proof that the requested namespace belongs to that tenant. + canonicalTenantId = requiredUuid(canonicalTenantId, "canonicalTenantId"); + targetNamespace = requiredNamespace(targetNamespace, "targetNamespace"); + playableStateNamespaceId = requiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(peerStorageBinding, "peerStorageBinding must not be null"); + evidenceRef = requiredText(evidenceRef, "evidenceRef"); + if (!targetNamespace.equals(peerStorageBinding.targetNamespace())) { + throw new IllegalArgumentException( + "peer/storage binding targetNamespace must exactly match targetNamespace"); + } + } + } + + public record Operation( + Scope scope, + UUID maintenanceLockIdentity, + Phase phase, + long revision, + InitialGameplayReleaseEvidence evidence, + Instant createdAt, + Instant updatedAt, + Instant finalizedAt) { + public Operation { + Objects.requireNonNull(scope, "scope must not be null"); + maintenanceLockIdentity = requiredUuid(maintenanceLockIdentity, "maintenanceLockIdentity"); + Objects.requireNonNull(phase, "phase must not be null"); + if (revision < 1) { + throw new IllegalArgumentException("revision must be positive"); + } + Objects.requireNonNull(createdAt, "createdAt must not be null"); + Objects.requireNonNull(updatedAt, "updatedAt must not be null"); + if ((phase == Phase.FINALIZED) != (finalizedAt != null)) { + throw new IllegalArgumentException("finalizedAt must exactly match the finalized phase"); + } + if (evidence != null && phase == Phase.COLLECTING) { + throw new IllegalArgumentException("collecting operation cannot retain readiness evidence"); + } + if (phase != Phase.COLLECTING && evidence == null) { + throw new IllegalArgumentException("non-collecting operation requires owner evidence"); + } + if (evidence != null) { + evidence.validateFor(scope); + } + } + + @Override + public String toString() { + return "Operation[scope=" + + scope + + ", maintenanceLockIdentity=redacted, phase=" + + phase + + ", revision=" + + revision + + ", evidence=" + + evidence + + ", createdAt=" + + createdAt + + ", updatedAt=" + + updatedAt + + ", finalizedAt=" + + finalizedAt + + "]"; + } + } + + public record MigrationProof( + UUID migrationOperationId, + ProofDisposition disposition, + String storageIdentity, + String inventoryRevision, + String inventoryDigest) { + public MigrationProof { + migrationOperationId = requiredUuid(migrationOperationId, "migrationOperationId"); + Objects.requireNonNull(disposition, "disposition must not be null"); + storageIdentity = requiredText(storageIdentity, "storageIdentity"); + inventoryRevision = requiredText(inventoryRevision, "inventoryRevision"); + inventoryDigest = requiredDigest(inventoryDigest, "inventoryDigest"); + } + } + + public record LayoutDescriptor( + String descriptorIdentity, String revision, String digest, List partitionIds) { + public LayoutDescriptor { + descriptorIdentity = requiredText(descriptorIdentity, "descriptorIdentity"); + revision = requiredText(revision, "revision"); + digest = requiredDigest(digest, "layout digest"); + partitionIds = sortedUniquePositiveIds(partitionIds, "partitionIds", true); + } + + public List partitionIds() { + return List.copyOf(partitionIds); + } + } + + public record PartitionAcknowledgement( + int partitionId, + String acknowledgementIdentity, + String acknowledgedLayoutDigest, + String readbackDigest, + int capacity) { + public PartitionAcknowledgement { + if (partitionId < 0) { + throw new IllegalArgumentException("partitionId must be non-negative"); + } + acknowledgementIdentity = requiredText(acknowledgementIdentity, "acknowledgementIdentity"); + acknowledgedLayoutDigest = + requiredDigest(acknowledgedLayoutDigest, "acknowledgedLayoutDigest"); + readbackDigest = requiredDigest(readbackDigest, "readbackDigest"); + if (capacity <= 0) { + throw new IllegalArgumentException("partition capacity must be positive"); + } + } + } + + public record IssuerLayoutProof( + UUID layoutOperationId, + LayoutDescriptor descriptor, + String accountIssuerSourceIdentity, + long operationFence, + UUID coverageFence, + String inventoryRevision, + String inventoryDigest, + List acknowledgements, + Map capacityVector) { + public IssuerLayoutProof { + layoutOperationId = requiredUuid(layoutOperationId, "layoutOperationId"); + Objects.requireNonNull(descriptor, "descriptor must not be null"); + accountIssuerSourceIdentity = + requiredText(accountIssuerSourceIdentity, "accountIssuerSourceIdentity"); + if (operationFence <= 0) { + throw new IllegalArgumentException("operationFence must be positive"); + } + coverageFence = requiredUuid(coverageFence, "coverageFence"); + inventoryRevision = requiredText(inventoryRevision, "inventoryRevision"); + inventoryDigest = requiredDigest(inventoryDigest, "inventoryDigest"); + acknowledgements = sortedAcknowledgements(acknowledgements); + capacityVector = positiveCapacityVector(capacityVector); + } + + public List acknowledgements() { + return List.copyOf(acknowledgements); + } + + public Map capacityVector() { + return Map.copyOf(capacityVector); + } + } + + public record WriterInventory( + String revision, + String digest, + String legacyWriterIdentity, + List applicableWriterIdentities) { + public WriterInventory { + revision = requiredText(revision, "writer inventory revision"); + digest = requiredDigest(digest, "writer inventory digest"); + legacyWriterIdentity = requiredText(legacyWriterIdentity, "legacyWriterIdentity"); + applicableWriterIdentities = + sortedUniqueTexts(applicableWriterIdentities, "applicableWriterIdentities"); + if (applicableWriterIdentities.contains(legacyWriterIdentity)) { + throw new IllegalArgumentException("legacy writer must be separate from fenced writers"); + } + } + + public List applicableWriterIdentities() { + return List.copyOf(applicableWriterIdentities); + } + } + + public record WriterFenceAcknowledgement( + String writerIdentity, + WriterDisposition disposition, + String fenceIdentity, + String inventoryDigest) { + public WriterFenceAcknowledgement { + writerIdentity = requiredText(writerIdentity, "writerIdentity"); + Objects.requireNonNull(disposition, "disposition must not be null"); + fenceIdentity = requiredText(fenceIdentity, "fenceIdentity"); + inventoryDigest = requiredDigest(inventoryDigest, "writer fence inventoryDigest"); + } + } + + public record WriterFenceProof( + WriterInventory inventory, + WriterDisposition legacyWriterDisposition, + List writerAcknowledgements) { + public WriterFenceProof { + Objects.requireNonNull(inventory, "inventory must not be null"); + Objects.requireNonNull(legacyWriterDisposition, "legacyWriterDisposition must not be null"); + writerAcknowledgements = sortedWriterAcknowledgements(writerAcknowledgements); + } + + public List writerAcknowledgements() { + return List.copyOf(writerAcknowledgements); + } + } + + public record OwnerInitializationProof( + OwnerService ownerService, + UUID initializationOperationId, + UUID playableStateNamespaceId, + ProofDisposition disposition, + String sourceIdentity, + String resultDigest) { + public OwnerInitializationProof { + Objects.requireNonNull(ownerService, "ownerService must not be null"); + initializationOperationId = + requiredUuid(initializationOperationId, "initializationOperationId"); + playableStateNamespaceId = requiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(disposition, "disposition must not be null"); + sourceIdentity = requiredText(sourceIdentity, "sourceIdentity"); + resultDigest = requiredDigest(resultDigest, "resultDigest"); + } + } + + public record RegionLeaseProof( + String regionIdentity, String leaseIdentity, long executorGeneration) { + public RegionLeaseProof { + regionIdentity = requiredText(regionIdentity, "regionIdentity"); + leaseIdentity = requiredText(leaseIdentity, "leaseIdentity"); + if (executorGeneration <= 0) { + throw new IllegalArgumentException("executorGeneration must be positive"); + } + } + } + + /** Immutable, owner-resolved proof snapshot; command DTOs cannot supply or replace this value. */ + public record InitialGameplayReleaseEvidence( + String evidenceRef, + String evidenceIdentity, + MigrationProof migration, + IssuerLayoutProof issuerLayout, + WriterFenceProof writerFencing, + OwnerInitializationProof worldInitialization, + OwnerInitializationProof entityInitialization, + RegionLeaseProof regionLease) { + public InitialGameplayReleaseEvidence { + evidenceRef = requiredText(evidenceRef, "evidenceRef"); + evidenceIdentity = requiredText(evidenceIdentity, "evidenceIdentity"); + Objects.requireNonNull(migration, "migration must not be null"); + Objects.requireNonNull(issuerLayout, "issuerLayout must not be null"); + Objects.requireNonNull(writerFencing, "writerFencing must not be null"); + Objects.requireNonNull(worldInitialization, "worldInitialization must not be null"); + Objects.requireNonNull(entityInitialization, "entityInitialization must not be null"); + Objects.requireNonNull(regionLease, "regionLease must not be null"); + } + + public void validateFor(Scope scope) { + Objects.requireNonNull(scope, "scope must not be null"); + requireExact(scope.evidenceRef(), evidenceRef, "evidenceRef"); + requireExact( + scope.peerStorageBinding().storageIdentity(), + migration.storageIdentity(), + "storageIdentity"); + if (migration.disposition() != ProofDisposition.VERIFIED) { + throw new IllegalArgumentException("storage migration is not owner-verified"); + } + requireExact( + migration.inventoryRevision(), + issuerLayout.inventoryRevision(), + "issuer inventoryRevision"); + requireExact( + migration.inventoryDigest(), issuerLayout.inventoryDigest(), "issuer inventoryDigest"); + requireExact( + migration.inventoryRevision(), + writerFencing.inventory().revision(), + "writer inventory revision"); + requireExact( + migration.inventoryDigest(), + writerFencing.inventory().digest(), + "writer inventory digest"); + validateIssuerLayout(issuerLayout); + validateWriterFencing(writerFencing); + validateInitialization(worldInitialization, OwnerService.WORLD_MANAGEMENT, scope); + validateInitialization(entityInitialization, OwnerService.ENTITY_MANAGEMENT, scope); + if (regionLease.leaseIdentity().isBlank()) { + throw new IllegalArgumentException("current region lease identity is required"); + } + } + + private static void validateIssuerLayout(IssuerLayoutProof proof) { + if (!proof + .descriptor() + .partitionIds() + .equals( + proof.acknowledgements().stream() + .map(PartitionAcknowledgement::partitionId) + .toList())) { + throw new IllegalArgumentException( + "issuer layout lacks an exact partition acknowledgement set"); + } + if (!proof + .descriptor() + .partitionIds() + .equals(new ArrayList<>(new TreeMap<>(proof.capacityVector()).keySet()))) { + throw new IllegalArgumentException("issuer layout capacity vector is incomplete"); + } + for (PartitionAcknowledgement acknowledgement : proof.acknowledgements()) { + requireExact( + proof.descriptor().digest(), + acknowledgement.acknowledgedLayoutDigest(), + "partition acknowledged layout digest"); + requireExact( + proof.capacityVector().get(acknowledgement.partitionId()), + acknowledgement.capacity(), + "partition capacity"); + } + } + + private static void validateWriterFencing(WriterFenceProof proof) { + if (proof.legacyWriterDisposition() != WriterDisposition.STOPPED) { + throw new IllegalArgumentException("legacy writer is not proven stopped"); + } + List expected = proof.inventory().applicableWriterIdentities(); + List actual = + proof.writerAcknowledgements().stream() + .map(WriterFenceAcknowledgement::writerIdentity) + .toList(); + if (!expected.equals(actual)) { + throw new IllegalArgumentException( + "writer fencing acknowledgements do not cover the inventory"); + } + for (WriterFenceAcknowledgement acknowledgement : proof.writerAcknowledgements()) { + if (acknowledgement.disposition() != WriterDisposition.FENCED) { + throw new IllegalArgumentException("an applicable writer is not proven fenced"); + } + requireExact( + proof.inventory().digest(), + acknowledgement.inventoryDigest(), + "writer inventory digest"); + } + } + + private static void validateInitialization( + OwnerInitializationProof proof, OwnerService expectedOwner, Scope scope) { + if (proof.ownerService() != expectedOwner + || proof.disposition() != ProofDisposition.VERIFIED) { + throw new IllegalArgumentException( + "initialization proof has the wrong owner or is not verified"); + } + if (!scope.playableStateNamespaceId().equals(proof.playableStateNamespaceId())) { + throw new IllegalArgumentException( + "initialization proof uses another playable-state namespace"); + } + } + } + + public record PublicTransitionTuple( + UUID operationId, + String scopeDigest, + TransitionVerb verb, + Phase expectedPhase, + UUID maintenanceLockIdentity, + String evidenceRef, + String evidenceIdentity, + String evidenceDigest) { + public PublicTransitionTuple { + operationId = requiredUuid(operationId, "operationId"); + scopeDigest = requiredDigest(scopeDigest, "scopeDigest"); + Objects.requireNonNull(verb, "verb must not be null"); + Objects.requireNonNull(expectedPhase, "expectedPhase must not be null"); + maintenanceLockIdentity = requiredUuid(maintenanceLockIdentity, "maintenanceLockIdentity"); + evidenceRef = requiredText(evidenceRef, "evidenceRef"); + evidenceIdentity = requiredText(evidenceIdentity, "evidenceIdentity"); + evidenceDigest = requiredDigest(evidenceDigest, "evidenceDigest"); + if (verb.expectedPhase() != expectedPhase) { + throw new IllegalArgumentException("public transition uses an invalid expected phase"); + } + } + + @Override + public String toString() { + return "PublicTransitionTuple[operationId=" + + operationId + + ", scopeDigest=" + + scopeDigest + + ", verb=" + + verb + + ", expectedPhase=" + + expectedPhase + + ", maintenanceLockIdentity=redacted, evidenceRef=" + + evidenceRef + + ", evidenceIdentity=" + + evidenceIdentity + + ", evidenceDigest=" + + evidenceDigest + + "]"; + } + } + + public sealed interface TypedEffect + permits PreparePlayableStateFencedEffect, CommitOwnerAuthorizedHandoffEffect { + UUID operationId(); + + UUID effectId(); + + UUID maintenanceLockIdentity(); + + Scope scope(); + + String operationTupleDigest(); + + String evidenceIdentity(); + + EffectKind kind(); + } + + public record PreparePlayableStateFencedEffect( + UUID operationId, + UUID effectId, + UUID maintenanceLockIdentity, + Scope scope, + String operationTupleDigest, + String evidenceIdentity) + implements TypedEffect { + public PreparePlayableStateFencedEffect { + operationId = requiredUuid(operationId, "operationId"); + effectId = requiredUuid(effectId, "effectId"); + maintenanceLockIdentity = requiredUuid(maintenanceLockIdentity, "maintenanceLockIdentity"); + Objects.requireNonNull(scope, "scope must not be null"); + operationTupleDigest = requiredDigest(operationTupleDigest, "operationTupleDigest"); + evidenceIdentity = requiredText(evidenceIdentity, "evidenceIdentity"); + if (!operationId.equals(scope.operationId())) { + throw new IllegalArgumentException("effect operationId must match its immutable scope"); + } + } + + @Override + public EffectKind kind() { + return EffectKind.PREPARE_PLAYABLE_STATE_FENCED; + } + + @Override + public String toString() { + return "PreparePlayableStateFencedEffect[operationId=" + + operationId + + ", effectId=" + + effectId + + ", maintenanceLockIdentity=redacted, scope=" + + scope + + ", operationTupleDigest=" + + operationTupleDigest + + ", evidenceIdentity=" + + evidenceIdentity + + "]"; + } + } + + public record CommitOwnerAuthorizedHandoffEffect( + UUID operationId, + UUID effectId, + UUID ownerHandoffIdentity, + UUID maintenanceLockIdentity, + Scope scope, + String operationTupleDigest, + String evidenceIdentity) + implements TypedEffect { + public CommitOwnerAuthorizedHandoffEffect { + operationId = requiredUuid(operationId, "operationId"); + effectId = requiredUuid(effectId, "effectId"); + ownerHandoffIdentity = requiredUuid(ownerHandoffIdentity, "ownerHandoffIdentity"); + maintenanceLockIdentity = requiredUuid(maintenanceLockIdentity, "maintenanceLockIdentity"); + Objects.requireNonNull(scope, "scope must not be null"); + operationTupleDigest = requiredDigest(operationTupleDigest, "operationTupleDigest"); + evidenceIdentity = requiredText(evidenceIdentity, "evidenceIdentity"); + if (!operationId.equals(scope.operationId())) { + throw new IllegalArgumentException("effect operationId must match its immutable scope"); + } + } + + @Override + public EffectKind kind() { + return EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF; + } + + @Override + public String toString() { + return "CommitOwnerAuthorizedHandoffEffect[operationId=" + + operationId + + ", effectId=" + + effectId + + ", ownerHandoffIdentity=" + + ownerHandoffIdentity + + ", maintenanceLockIdentity=redacted, scope=" + + scope + + ", operationTupleDigest=" + + operationTupleDigest + + ", evidenceIdentity=" + + evidenceIdentity + + "]"; + } + } + + public record EffectReadback( + UUID operationId, + UUID effectId, + EffectKind effectKind, + String operationTupleDigest, + String payloadDigest, + EffectReadbackState state, + EffectReadbackAuthority authority, + String readbackIdentity, + Instant observedAt) { + public EffectReadback { + operationId = requiredUuid(operationId, "operationId"); + effectId = requiredUuid(effectId, "effectId"); + Objects.requireNonNull(effectKind, "effectKind must not be null"); + operationTupleDigest = requiredDigest(operationTupleDigest, "operationTupleDigest"); + payloadDigest = requiredDigest(payloadDigest, "payloadDigest"); + Objects.requireNonNull(state, "state must not be null"); + Objects.requireNonNull(authority, "authority must not be null"); + readbackIdentity = requiredText(readbackIdentity, "readbackIdentity"); + Objects.requireNonNull(observedAt, "observedAt must not be null"); + } + } + + public record OutboxEntry( + UUID outboxId, + TypedEffect effect, + String payloadDigest, + EffectOutboxState state, + int attemptCount, + UUID lastAttemptId, + String lastOutcomeCode, + Instant acknowledgedAt) { + public OutboxEntry { + outboxId = requiredUuid(outboxId, "outboxId"); + Objects.requireNonNull(effect, "effect must not be null"); + payloadDigest = requiredDigest(payloadDigest, "payloadDigest"); + Objects.requireNonNull(state, "state must not be null"); + if (attemptCount < 0) { + throw new IllegalArgumentException("attemptCount must not be negative"); + } + if (lastAttemptId != null) { + lastAttemptId = requiredUuid(lastAttemptId, "lastAttemptId"); + } + if ((state == EffectOutboxState.ACKNOWLEDGED) != (acknowledgedAt != null)) { + throw new IllegalArgumentException("acknowledgedAt must exactly match acknowledged state"); + } + } + } + + public static String requiredDigest(String value, String name) { + String text = requiredText(value, name); + if (!text.matches("[a-f0-9]{64}")) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 hex digest"); + } + return text; + } + + public static UUID requiredUuid(UUID value, String name) { + Objects.requireNonNull(value, name + " must not be null"); + if (value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L) { + throw new IllegalArgumentException(name + " must not be the nil UUID"); + } + return value; + } + + private static String requiredNamespace(String value, String name) { + if (!GrpcPeerIdentity.isValidNamespace(value)) { + throw new IllegalArgumentException(name + " must be a valid Kubernetes namespace"); + } + return value; + } + + public static String requiredText(String value, String name) { + Objects.requireNonNull(value, name + " must not be null"); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " must not be blank"); + } + return value; + } + + private static List sortedUniquePositiveIds( + List values, String name, boolean allowZero) { + Objects.requireNonNull(values, name + " must not be null"); + List sorted = values.stream().sorted().toList(); + if (sorted.isEmpty()) { + throw new IllegalArgumentException(name + " must not be empty"); + } + if (sorted.stream().anyMatch(value -> value == null || (allowZero ? value < 0 : value <= 0))) { + throw new IllegalArgumentException(name + " contains an invalid id"); + } + if (sorted.stream().distinct().count() != sorted.size()) { + throw new IllegalArgumentException(name + " contains duplicate ids"); + } + return List.copyOf(sorted); + } + + private static List sortedUniqueTexts(List values, String name) { + Objects.requireNonNull(values, name + " must not be null"); + List sorted = values.stream().map(value -> requiredText(value, name)).sorted().toList(); + if (sorted.stream().distinct().count() != sorted.size()) { + throw new IllegalArgumentException(name + " contains duplicate identities"); + } + return List.copyOf(sorted); + } + + private static List sortedAcknowledgements( + List values) { + Objects.requireNonNull(values, "acknowledgements must not be null"); + List sorted = + values.stream() + .sorted(Comparator.comparingInt(PartitionAcknowledgement::partitionId)) + .toList(); + if (sorted.stream().map(PartitionAcknowledgement::partitionId).distinct().count() + != sorted.size()) { + throw new IllegalArgumentException("acknowledgements contain duplicate partitions"); + } + return List.copyOf(sorted); + } + + private static List sortedWriterAcknowledgements( + List values) { + Objects.requireNonNull(values, "writerAcknowledgements must not be null"); + List sorted = + values.stream() + .sorted(Comparator.comparing(WriterFenceAcknowledgement::writerIdentity)) + .toList(); + if (sorted.stream().map(WriterFenceAcknowledgement::writerIdentity).distinct().count() + != sorted.size()) { + throw new IllegalArgumentException("writer acknowledgements contain duplicate writers"); + } + return List.copyOf(sorted); + } + + private static Map positiveCapacityVector(Map values) { + Objects.requireNonNull(values, "capacityVector must not be null"); + TreeMap sorted = new TreeMap<>(); + values.forEach( + (partitionId, capacity) -> { + if (partitionId == null || partitionId < 0 || capacity == null || capacity <= 0) { + throw new IllegalArgumentException("capacityVector contains an invalid entry"); + } + sorted.put(partitionId, capacity); + }); + if (sorted.isEmpty()) { + throw new IllegalArgumentException("capacityVector must not be empty"); + } + return Collections.unmodifiableMap(sorted); + } + + private static void requireExact(String expected, String actual, String name) { + if (!Objects.equals(expected, actual)) { + throw new IllegalArgumentException(name + " does not match the immutable operation scope"); + } + } + + private static void requireExact(Integer expected, int actual, String name) { + if (expected == null || expected != actual) { + throw new IllegalArgumentException(name + " does not match the acknowledged value"); + } + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java new file mode 100644 index 0000000000..b4e546c984 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.recovery.model; + +import java.util.Objects; +import java.util.UUID; + +/** The controller-issued lock credential; string rendering is intentionally redacted. */ +public final class MaintenanceLockCredential { + private final UUID identity; + + private MaintenanceLockCredential(UUID identity) { + this.identity = InitialGameplayReleaseModel.requiredUuid(identity, "identity"); + } + + public static MaintenanceLockCredential issue(UUID identity) { + return new MaintenanceLockCredential(identity); + } + + public static MaintenanceLockCredential fromProtectedTransport(String token) { + Objects.requireNonNull(token, "token must not be null"); + try { + UUID identity = UUID.fromString(token); + if (!identity.toString().equals(token)) { + throw new IllegalArgumentException("maintenance-lock credential is not canonical"); + } + return new MaintenanceLockCredential(identity); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("maintenance-lock credential is invalid", exception); + } + } + + public UUID identity() { + return identity; + } + + public String protectedTransportValue() { + return identity.toString(); + } + + @Override + public boolean equals(Object other) { + return other instanceof MaintenanceLockCredential credential + && identity.equals(credential.identity); + } + + @Override + public int hashCode() { + return identity.hashCode(); + } + + @Override + public String toString() { + return "MaintenanceLockCredential[redacted]"; + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java new file mode 100644 index 0000000000..1f204e70dc --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.recovery.service; + +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TypedEffect; + +/** + * Safe default until the Game Session typed effect and current-readback owner path is registered. + */ +public class DeniedInitialGameplayReleaseEffectPort implements InitialGameplayReleaseEffectPort { + @Override + public EffectApplyResult apply(TypedEffect effect, UUID attemptId) { + return EffectApplyResult.retryableNoEffect("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); + } + + @Override + public EffectReadbackResolution readback(TypedEffect effect, UUID attemptId) { + return EffectReadbackResolution.unavailable(); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEvidenceProvider.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEvidenceProvider.java new file mode 100644 index 0000000000..8d35504a49 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEvidenceProvider.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.recovery.service; + +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; + +/** Safe default until the real authenticated peer and owner evidence adapters are registered. */ +public class DeniedInitialGameplayReleaseEvidenceProvider + implements InitialGameplayReleaseEvidenceProvider { + @Override + public EvidenceResolution read(Scope scope) { + return EvidenceResolution.unavailable(); + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java new file mode 100644 index 0000000000..cd0752ce14 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -0,0 +1,274 @@ +package net.firedevops.firemud.recovery.service; + +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.ContinueRecovery; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.Resume; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PublicTransitionTuple; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; +import net.firedevops.firemud.recovery.model.MaintenanceLockCredential; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort.ApplyStatus; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort.EffectApplyResult; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort.EffectReadbackResolution; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.EvidenceResolution; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; + +/** + * Narrow initial-gameplay-release owner. It has no HTTP ingress or autonomous effect dispatcher. + */ +public final class InitialGameplayReleaseController { + private final InitialGameplayReleaseJournal journal; + private final InitialGameplayReleaseTupleCodec tupleCodec; + private final InitialGameplayReleaseEvidenceProvider evidenceProvider; + private final InitialGameplayReleaseEffectPort effectPort; + private final Clock clock; + + public InitialGameplayReleaseController( + InitialGameplayReleaseJournal journal, + InitialGameplayReleaseTupleCodec tupleCodec, + InitialGameplayReleaseEvidenceProvider evidenceProvider, + InitialGameplayReleaseEffectPort effectPort) { + this(journal, tupleCodec, evidenceProvider, effectPort, Clock.systemUTC()); + } + + InitialGameplayReleaseController( + InitialGameplayReleaseJournal journal, + InitialGameplayReleaseTupleCodec tupleCodec, + InitialGameplayReleaseEvidenceProvider evidenceProvider, + InitialGameplayReleaseEffectPort effectPort, + Clock clock) { + this.journal = Objects.requireNonNull(journal, "journal must not be null"); + this.tupleCodec = Objects.requireNonNull(tupleCodec, "tupleCodec must not be null"); + this.evidenceProvider = + Objects.requireNonNull(evidenceProvider, "evidenceProvider must not be null"); + this.effectPort = Objects.requireNonNull(effectPort, "effectPort must not be null"); + this.clock = Objects.requireNonNull(clock, "clock must not be null"); + } + + /** + * Denies operation creation until Account redemption, genuine owner association/storage checks, + * and exclusive maintenance fence/lock acquisition exist. Typed selectors grant no authority. + */ + public RecoveryCreated recover(InitialGameplayRecoverRequest command) { + Objects.requireNonNull(command, "command must not be null"); + throw unavailable("INITIAL_GAMEPLAY_RECOVER_AUTHORIZATION_AND_EXCLUSIVE_FENCE_UNAVAILABLE"); + } + + /** Resolves all source-owned proof and only then binds the immutable readiness tuple. */ + public Operation refreshReadiness(UUID operationId, MaintenanceLockCredential maintenanceLock) { + Operation operation = requireOperation(operationId); + requireLock(operation, maintenanceLock); + EvidenceResolution resolution = evidenceProvider.read(operation.scope()); + if (resolution.status() != ResolutionStatus.AVAILABLE) { + throw unavailable("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_" + resolution.status().name()); + } + InitialGameplayReleaseEvidence evidence = resolution.evidence(); + evidence.validateFor(operation.scope()); + String digest = tupleCodec.digest(evidence); + return journal.bindVerifiedEvidence( + operation.scope(), tupleCodec.digest(operation.scope()), evidence, digest, clock.instant()); + } + + /** + * The only public continuation transition. It can move ready_to_reopen to awaiting_resume and + * never releases the owner fence. + */ + public Operation continueRecovery(ContinueRecovery command) { + Objects.requireNonNull(command, "command must not be null"); + return transition( + command.operationId(), + command.expectedPhase(), + command.maintenanceLock(), + command.evidenceRef(), + TransitionVerb.CONTINUE_RECOVERY); + } + + /** Separately records explicit authorization from awaiting_resume to resume_authorized. */ + public Operation resume(Resume command) { + Objects.requireNonNull(command, "command must not be null"); + return transition( + command.operationId(), + command.expectedPhase(), + command.maintenanceLock(), + command.evidenceRef(), + TransitionVerb.RESUME); + } + + /** + * Performs one outbox attempt or reconciles its exact prior attempt by owner readback. This + * method is deliberately not scheduled or exposed as a network endpoint in this source-only + * stage. + */ + public Operation reconcileNextEffect(UUID operationId) { + Operation operation = requireOperation(operationId); + Optional next = journal.findNextEffect(operationId); + if (next.isEmpty()) { + return operation; + } + OutboxEntry outbox = next.orElseThrow(); + if (outbox.state() == EffectOutboxState.PENDING + || outbox.state() == EffectOutboxState.RETRYABLE) { + return applyEffect(operation, outbox); + } + return readBackEffect(operation, outbox, outbox.lastAttemptId()); + } + + private Operation applyEffect(Operation operation, OutboxEntry outbox) { + UUID attemptId = UUID.randomUUID(); + OutboxEntry dispatched = + journal.claimEffect( + operation.scope().operationId(), + outbox.effect().effectId(), + attemptId, + clock.instant()); + if (dispatched.state() != EffectOutboxState.DISPATCHED + || !attemptId.equals(dispatched.lastAttemptId())) { + return requireOperation(operation.scope().operationId()); + } + final EffectApplyResult applyResult; + try { + applyResult = effectPort.apply(dispatched.effect(), attemptId); + } catch (RuntimeException exception) { + journal.recordAmbiguousEffect( + operation.scope().operationId(), + dispatched.effect().effectId(), + attemptId, + "EFFECT_CALL_OUTCOME_UNKNOWN", + clock.instant()); + return requireOperation(operation.scope().operationId()); + } + if (applyResult.status() == ApplyStatus.RETRYABLE_NO_EFFECT) { + journal.recordRetryableEffect( + operation.scope().operationId(), + dispatched.effect().effectId(), + attemptId, + applyResult.outcomeCode(), + clock.instant()); + return requireOperation(operation.scope().operationId()); + } + if (applyResult.status() == ApplyStatus.AMBIGUOUS) { + journal.recordAmbiguousEffect( + operation.scope().operationId(), + dispatched.effect().effectId(), + attemptId, + applyResult.outcomeCode(), + clock.instant()); + return requireOperation(operation.scope().operationId()); + } + return readBackEffect(operation, dispatched, attemptId); + } + + private Operation readBackEffect(Operation operation, OutboxEntry outbox, UUID attemptId) { + if (attemptId == null) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: dispatched effect has no attempt identity"); + } + EffectReadbackResolution resolution; + try { + resolution = effectPort.readback(outbox.effect(), attemptId); + } catch (RuntimeException exception) { + return operation; + } + if (resolution.status() != InitialGameplayReleaseEffectPort.ReadbackStatus.AVAILABLE) { + return operation; + } + EffectReadback readback = resolution.readback(); + if (resolution.observedAt().isBefore(readback.observedAt())) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: effect readback observation time changed"); + } + return journal.recordEffectReadback( + operation.scope().operationId(), + outbox.effect().effectId(), + attemptId, + readback, + clock.instant()); + } + + private Operation transition( + UUID operationId, + Phase expectedPhase, + MaintenanceLockCredential maintenanceLock, + String evidenceRef, + TransitionVerb verb) { + Operation operation = requireOperation(operationId); + requireLock(operation, maintenanceLock); + if (!operation.scope().evidenceRef().equals(evidenceRef)) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: evidence reference changed"); + } + if (operation.evidence() == null) { + throw new OwnerBoundaryUnavailableException("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_NOT_READY"); + } + PublicTransitionTuple tuple = + new PublicTransitionTuple( + operationId, + tupleCodec.digest(operation.scope()), + verb, + expectedPhase, + operation.maintenanceLockIdentity(), + evidenceRef, + operation.evidence().evidenceIdentity(), + tupleCodec.digest(operation.evidence())); + Optional prior = journal.findTransition(tuple); + if (prior.isPresent()) { + return prior.orElseThrow(); + } + verifyFreshEvidence(operation); + return journal.transition(tuple, clock.instant()); + } + + private void verifyFreshEvidence(Operation operation) { + EvidenceResolution resolution = evidenceProvider.read(operation.scope()); + if (resolution.status() != ResolutionStatus.AVAILABLE) { + throw unavailable("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_" + resolution.status().name()); + } + InitialGameplayReleaseEvidence currentEvidence = resolution.evidence(); + currentEvidence.validateFor(operation.scope()); + if (!operation.evidence().evidenceIdentity().equals(currentEvidence.evidenceIdentity()) + || !tupleCodec.digest(operation.evidence()).equals(tupleCodec.digest(currentEvidence))) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: owner evidence changed after readiness was recorded"); + } + } + + private Operation requireOperation(UUID operationId) { + return journal + .find(Objects.requireNonNull(operationId, "operationId must not be null")) + .orElseThrow(() -> new IllegalArgumentException("INITIAL_GAMEPLAY_RELEASE_NOT_FOUND")); + } + + private static void requireLock(Operation operation, MaintenanceLockCredential maintenanceLock) { + Objects.requireNonNull(maintenanceLock, "maintenanceLock must not be null"); + if (!operation.maintenanceLockIdentity().equals(maintenanceLock.identity())) { + throw new InitialGameplayReleaseConflictException( + "IDEMPOTENCY_CONFLICT: maintenance-lock identity changed"); + } + } + + private static OwnerBoundaryUnavailableException unavailable(String code) { + return new OwnerBoundaryUnavailableException(code); + } + + public record RecoveryCreated(Operation operation, MaintenanceLockCredential maintenanceLock) { + public RecoveryCreated { + Objects.requireNonNull(operation, "operation must not be null"); + Objects.requireNonNull(maintenanceLock, "maintenanceLock must not be null"); + if (!operation.maintenanceLockIdentity().equals(maintenanceLock.identity())) { + throw new IllegalArgumentException("issued lock does not match the stored operation"); + } + } + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java new file mode 100644 index 0000000000..40571e3b2a --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.recovery.service; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TypedEffect; + +/** + * Game Session owner boundary for exact typed effects and owner-produced durable/current readbacks. + */ +public interface InitialGameplayReleaseEffectPort { + EffectApplyResult apply(TypedEffect effect, UUID attemptId); + + EffectReadbackResolution readback(TypedEffect effect, UUID attemptId); + + record EffectApplyResult(ApplyStatus status, String outcomeCode) { + public EffectApplyResult { + if (status == ApplyStatus.RETRYABLE_NO_EFFECT || status == ApplyStatus.AMBIGUOUS) { + if (outcomeCode == null || outcomeCode.isBlank()) { + throw new IllegalArgumentException( + "non-success apply outcomes require a typed outcome code"); + } + } + } + + public static EffectApplyResult applied() { + return new EffectApplyResult(ApplyStatus.APPLIED, null); + } + + public static EffectApplyResult retryableNoEffect(String outcomeCode) { + return new EffectApplyResult(ApplyStatus.RETRYABLE_NO_EFFECT, outcomeCode); + } + + public static EffectApplyResult ambiguous(String outcomeCode) { + return new EffectApplyResult(ApplyStatus.AMBIGUOUS, outcomeCode); + } + } + + enum ApplyStatus { + APPLIED, + RETRYABLE_NO_EFFECT, + AMBIGUOUS + } + + record EffectReadbackResolution( + ReadbackStatus status, EffectReadback readback, Instant observedAt) { + public EffectReadbackResolution { + if ((status == ReadbackStatus.AVAILABLE) != (readback != null)) { + throw new IllegalArgumentException("readback must be present exactly for AVAILABLE"); + } + if (status == ReadbackStatus.AVAILABLE && observedAt == null) { + throw new IllegalArgumentException("available readback requires observation time"); + } + } + + public static EffectReadbackResolution available(EffectReadback readback) { + return new EffectReadbackResolution( + ReadbackStatus.AVAILABLE, readback, readback.observedAt()); + } + + public static EffectReadbackResolution unavailable() { + return new EffectReadbackResolution(ReadbackStatus.UNAVAILABLE, null, null); + } + } + + enum ReadbackStatus { + AVAILABLE, + UNAVAILABLE + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java new file mode 100644 index 0000000000..2b225e3354 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.recovery.service; + +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; + +/** + * Reads immutable evidence from the actual peer, storage, Account, World, Entity, and lease owners. + */ +public interface InitialGameplayReleaseEvidenceProvider { + EvidenceResolution read(Scope scope); + + record EvidenceResolution(ResolutionStatus status, InitialGameplayReleaseEvidence evidence) { + public EvidenceResolution { + if ((status == ResolutionStatus.AVAILABLE) != (evidence != null)) { + throw new IllegalArgumentException("evidence must be present exactly for AVAILABLE"); + } + } + + public static EvidenceResolution available(InitialGameplayReleaseEvidence evidence) { + return new EvidenceResolution(ResolutionStatus.AVAILABLE, evidence); + } + + public static EvidenceResolution denied() { + return new EvidenceResolution(ResolutionStatus.DENIED, null); + } + + public static EvidenceResolution notFound() { + return new EvidenceResolution(ResolutionStatus.NOT_FOUND, null); + } + + public static EvidenceResolution unavailable() { + return new EvidenceResolution(ResolutionStatus.UNAVAILABLE, null); + } + } + + enum ResolutionStatus { + AVAILABLE, + DENIED, + NOT_FOUND, + UNAVAILABLE + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/OwnerBoundaryUnavailableException.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/OwnerBoundaryUnavailableException.java new file mode 100644 index 0000000000..5a8bdea5dd --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/OwnerBoundaryUnavailableException.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.recovery.service; + +public class OwnerBoundaryUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public OwnerBoundaryUnavailableException(String code) { + super(code); + } +} diff --git a/services/recovery-controller-service/src/main/resources/application.yml b/services/recovery-controller-service/src/main/resources/application.yml new file mode 100644 index 0000000000..7063724fb2 --- /dev/null +++ b/services/recovery-controller-service/src/main/resources/application.yml @@ -0,0 +1,61 @@ +spring: + application: + name: recovery-controller-service + datasource: + # This endpoint must identify the isolated recovery-control PostgreSQL instance and volume. + # Do not point it at the shared business PostgreSQL instance: business restores must not rewind + # the recovery journal. There is deliberately no shared-database fallback. + url: jdbc:postgresql://${FIREMUD_RECOVERY_CONTROL_DB_HOST}:${FIREMUD_RECOVERY_CONTROL_DB_PORT:5432}/firemud_recovery_control + username: ${FIREMUD_RECOVERY_CONTROL_DB_USER} + password: ${FIREMUD_RECOVERY_CONTROL_DB_PASSWORD} + flyway: + enabled: true + schemas: recovery_control + defaultSchema: recovery_control + table: flyway_schema_history_recovery_control + locations: classpath:db/migration + placeholders: + serviceSchema: recovery_control + ssl: + bundle: + pem: + firemud-grpc: + keystore: + certificate: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} + private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} + truststore: + certificate: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + grpc: + server: + port: 6565 + shutdown-grace-period: 30s + ssl: + enabled: true + bundle: firemud-grpc + client-auth: REQUIRE + +management: + endpoints: + access: + default: read-only + web: + exposure: + include: + - health + - prometheus + - info + endpoint: + health: + probes: + enabled: true + group: + liveness: + include: livenessState + readiness: + include: readinessState,db + +firemud: + grpc: + cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} + private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} + ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} diff --git a/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql b/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql new file mode 100644 index 0000000000..f6c2f010f3 --- /dev/null +++ b/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql @@ -0,0 +1,83 @@ +CREATE SCHEMA IF NOT EXISTS recovery_control; + +CREATE TABLE recovery_control.initial_gameplay_release_operation ( + operation_id UUID PRIMARY KEY, + operation_kind VARCHAR(40) NOT NULL DEFAULT 'initial_gameplay_release' + CHECK (operation_kind = 'initial_gameplay_release'), + target_namespace VARCHAR(253) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + peer_storage_binding JSONB NOT NULL, + scope_payload JSONB NOT NULL, + evidence_ref TEXT NOT NULL, + scope_digest CHAR(64) NOT NULL, + maintenance_lock_identity UUID NOT NULL UNIQUE, + phase VARCHAR(32) NOT NULL + CHECK (phase IN ( + 'collecting', + 'ready_to_reopen', + 'awaiting_resume', + 'resume_authorized', + 'releasing', + 'finalized' + )), + evidence_snapshot JSONB, + evidence_identity TEXT, + evidence_digest CHAR(64), + revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + finalized_at TIMESTAMPTZ, + CHECK ( + (evidence_snapshot IS NULL AND evidence_identity IS NULL AND evidence_digest IS NULL) + OR + (evidence_snapshot IS NOT NULL AND evidence_identity IS NOT NULL AND evidence_digest IS NOT NULL) + ), + CHECK ((phase = 'finalized') = (finalized_at IS NOT NULL)) +); + +CREATE TABLE recovery_control.initial_gameplay_release_transition ( + operation_id UUID NOT NULL + REFERENCES recovery_control.initial_gameplay_release_operation(operation_id), + verb VARCHAR(24) NOT NULL CHECK (verb IN ('continueRecovery', 'resume')), + tuple_digest CHAR(64) NOT NULL, + tuple_payload JSONB NOT NULL, + expected_phase VARCHAR(32) NOT NULL, + result_phase VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, verb) +); + +CREATE TABLE recovery_control.initial_gameplay_release_outbox ( + outbox_id UUID PRIMARY KEY, + operation_id UUID NOT NULL + REFERENCES recovery_control.initial_gameplay_release_operation(operation_id), + effect_id UUID NOT NULL, + effect_kind VARCHAR(48) NOT NULL + CHECK (effect_kind IN ('prepare_playable_state_fenced', 'commit_owner_authorized_handoff')), + operation_tuple_digest CHAR(64) NOT NULL, + payload_digest CHAR(64) NOT NULL, + payload JSONB NOT NULL, + state VARCHAR(20) NOT NULL + CHECK (state IN ('pending', 'dispatched', 'retryable', 'ambiguous', 'acknowledged')), + attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), + last_attempt_id UUID, + last_outcome_code VARCHAR(64), + readback_identity TEXT, + readback_payload JSONB, + readback_digest CHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + acknowledged_at TIMESTAMPTZ, + UNIQUE (operation_id, effect_id), + UNIQUE (operation_id, effect_kind), + CHECK ( + (readback_identity IS NULL AND readback_payload IS NULL AND readback_digest IS NULL) + OR + (readback_identity IS NOT NULL AND readback_payload IS NOT NULL AND readback_digest IS NOT NULL) + ), + CHECK ((state = 'acknowledged') = (acknowledged_at IS NOT NULL)) +); + +CREATE INDEX idx_initial_gameplay_release_outbox_pending + ON recovery_control.initial_gameplay_release_outbox (created_at, outbox_id) + WHERE state IN ('pending', 'retryable', 'dispatched', 'ambiguous'); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java new file mode 100644 index 0000000000..7516f977cc --- /dev/null +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -0,0 +1,363 @@ +package integration.net.firedevops.firemud.recovery; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.journal.JooqInitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectKind; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackAuthority; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackState; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.IssuerLayoutProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.LayoutDescriptor; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.MigrationProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OwnerInitializationProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OwnerService; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PartitionAcknowledgement; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PeerStorageBinding; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.ProofDisposition; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PublicTransitionTuple; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.RegionLeaseProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterDisposition; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterFenceAcknowledgement; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterFenceProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterInventory; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class InitialGameplayReleaseJournalPostgresIntegrationTest { + private static final String SCHEMA = "recovery_control"; + private static final String DIGEST = "b".repeat(64); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static Connection connection; + private static DSLContext dsl; + private static InitialGameplayReleaseTupleCodec tupleCodec; + private static InitialGameplayReleaseJournal journal; + + @BeforeAll + static void setUp() throws Exception { + Flyway.configure() + .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + connection = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dsl = DSL.using(connection, SQLDialect.POSTGRES); + tupleCodec = + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + journal = new JooqInitialGameplayReleaseJournal(dsl, tupleCodec); + } + + @AfterAll + static void tearDown() throws Exception { + if (connection != null) { + connection.close(); + } + } + + @BeforeEach + void clearJournal() { + dsl.execute( + "TRUNCATE TABLE recovery_control.initial_gameplay_release_outbox, " + + "recovery_control.initial_gameplay_release_transition, " + + "recovery_control.initial_gameplay_release_operation"); + } + + @Test + void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() { + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + Scope scope = scope(); + UUID lockIdentity = UUID.randomUUID(); + + Operation created = journal.create(scope, lockIdentity); + Operation duplicateCreate = journal.create(scope, UUID.randomUUID()); + assertThat(created.phase()).isEqualTo(Phase.COLLECTING); + assertThat(duplicateCreate.maintenanceLockIdentity()).isEqualTo(lockIdentity); + assertThat(journal.find(created.scope().operationId())).contains(created); + + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base.plusSeconds(1)); + assertThat(ready.phase()).isEqualTo(Phase.READY_TO_REOPEN); + assertThat(ready.evidence()).isEqualTo(proof); + + PublicTransitionTuple continueTuple = transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY); + assertThat(journal.findTransition(continueTuple)).isEmpty(); + Operation awaitingResume = journal.transition(continueTuple, base.plusSeconds(2)); + assertThat(awaitingResume.phase()).isEqualTo(Phase.AWAITING_RESUME); + assertThat(journal.transition(continueTuple, base.plusSeconds(3))).isEqualTo(awaitingResume); + + PublicTransitionTuple resumeTuple = transitionTuple(awaitingResume, TransitionVerb.RESUME); + Operation authorized = journal.transition(resumeTuple, base.plusSeconds(4)); + assertThat(authorized.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); + OutboxEntry prepare = + journal + .findEffect(scope.operationId(), EffectKind.PREPARE_PLAYABLE_STATE_FENCED) + .orElseThrow(); + assertThat(prepare.state()).isEqualTo(EffectOutboxState.PENDING); + + UUID prepareAttempt = UUID.randomUUID(); + prepare = + journal.claimEffect( + scope.operationId(), prepare.effect().effectId(), prepareAttempt, base.plusSeconds(5)); + EffectReadback prepareReadback = + new EffectReadback( + scope.operationId(), + prepare.effect().effectId(), + prepare.effect().kind(), + prepare.effect().operationTupleDigest(), + prepare.payloadDigest(), + EffectReadbackState.PREPARED_FENCED, + EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + "gamesession-preparation-readback-1", + base.plusSeconds(6)); + Operation releasing = + journal.recordEffectReadback( + scope.operationId(), + prepare.effect().effectId(), + prepareAttempt, + prepareReadback, + base.plusSeconds(7)); + assertThat(releasing.phase()).isEqualTo(Phase.RELEASING); + assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .get() + .extracting(OutboxEntry::state) + .isEqualTo(EffectOutboxState.PENDING); + + OutboxEntry handoff = + journal + .findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF) + .orElseThrow(); + UUID handoffAttempt = UUID.randomUUID(); + handoff = + journal.claimEffect( + scope.operationId(), handoff.effect().effectId(), handoffAttempt, base.plusSeconds(8)); + EffectReadback handoffReadback = + new EffectReadback( + scope.operationId(), + handoff.effect().effectId(), + handoff.effect().kind(), + handoff.effect().operationTupleDigest(), + handoff.payloadDigest(), + EffectReadbackState.OWNER_HANDOFF_APPLIED, + EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + "gamesession-owner-handoff-readback-1", + base.plusSeconds(9)); + Operation finalized = + journal.recordEffectReadback( + scope.operationId(), + handoff.effect().effectId(), + handoffAttempt, + handoffReadback, + base.plusSeconds(10)); + + assertThat(finalized.phase()).isEqualTo(Phase.FINALIZED); + assertThat(finalized.finalizedAt()).isEqualTo(base.plusSeconds(10)); + assertThat(journal.findNextEffect(scope.operationId())).isEmpty(); + } + + @Test + void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + Scope scope = scope(); + Operation operation = journal.create(scope, UUID.randomUUID()); + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base.plusSeconds(1)); + + PublicTransitionTuple wrongLock = + new PublicTransitionTuple( + ready.scope().operationId(), + tupleCodec.digest(scope), + TransitionVerb.CONTINUE_RECOVERY, + Phase.READY_TO_REOPEN, + UUID.randomUUID(), + scope.evidenceRef(), + proof.evidenceIdentity(), + tupleCodec.digest(proof)); + assertThatThrownBy(() -> journal.transition(wrongLock, base.plusSeconds(2))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + PublicTransitionTuple wrongEvidence = + new PublicTransitionTuple( + ready.scope().operationId(), + tupleCodec.digest(scope), + TransitionVerb.CONTINUE_RECOVERY, + Phase.READY_TO_REOPEN, + ready.maintenanceLockIdentity(), + "different-evidence-reference", + proof.evidenceIdentity(), + tupleCodec.digest(proof)); + assertThatThrownBy(() -> journal.transition(wrongEvidence, base.plusSeconds(2))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(journal.find(operation.scope().operationId()).orElseThrow().phase()) + .isEqualTo(Phase.READY_TO_REOPEN); + + Operation awaiting = + journal.transition( + transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base.plusSeconds(3)); + Operation authorized = + journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(4)); + OutboxEntry prepare = journal.findNextEffect(scope.operationId()).orElseThrow(); + UUID attemptId = UUID.randomUUID(); + OutboxEntry dispatched = + journal.claimEffect( + scope.operationId(), prepare.effect().effectId(), attemptId, base.plusSeconds(5)); + assertThat(dispatched.state()).isEqualTo(EffectOutboxState.DISPATCHED); + journal.recordAmbiguousEffect( + scope.operationId(), + prepare.effect().effectId(), + attemptId, + "TRANSPORT_OUTCOME_UNKNOWN", + base.plusSeconds(6)); + OutboxEntry retryRead = + journal.claimEffect( + scope.operationId(), + prepare.effect().effectId(), + UUID.randomUUID(), + base.plusSeconds(7)); + + assertThat(retryRead.state()).isEqualTo(EffectOutboxState.AMBIGUOUS); + assertThat(retryRead.lastAttemptId()).isEqualTo(attemptId); + assertThat(retryRead.attemptCount()).isEqualTo(1); + assertThat(authorized.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); + } + + @Test + void createRetryWithChangedCanonicalTenantConflicts() { + Scope original = scope(); + Operation created = journal.create(original, UUID.randomUUID()); + Scope changedTenant = + new Scope( + original.operationId(), + UUID.randomUUID(), + original.targetNamespace(), + original.playableStateNamespaceId(), + original.peerStorageBinding(), + original.evidenceRef()); + + assertThat(tupleCodec.digest(changedTenant)).isNotEqualTo(tupleCodec.digest(original)); + assertThatThrownBy(() -> journal.create(changedTenant, UUID.randomUUID())) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(journal.find(original.operationId())).contains(created); + } + + private static PublicTransitionTuple transitionTuple(Operation operation, TransitionVerb verb) { + return new PublicTransitionTuple( + operation.scope().operationId(), + tupleCodec.digest(operation.scope()), + verb, + verb.expectedPhase(), + operation.maintenanceLockIdentity(), + operation.scope().evidenceRef(), + operation.evidence().evidenceIdentity(), + tupleCodec.digest(operation.evidence())); + } + + private static Scope scope() { + return new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-a", "recovery-peer", "storage-uid-1", "revision-7", DIGEST), + "immutable-initial-layout-evidence"); + } + + private static InitialGameplayReleaseEvidence evidence(Scope scope) { + LayoutDescriptor descriptor = + new LayoutDescriptor("issuer-layout-v1", "layout-r4", DIGEST, List.of(0, 1)); + IssuerLayoutProof issuerLayout = + new IssuerLayoutProof( + UUID.randomUUID(), + descriptor, + "account-issuer-source-identity-1", + 101, + UUID.randomUUID(), + "writer-inventory-r9", + DIGEST, + List.of( + new PartitionAcknowledgement(0, "partition-0-ack", DIGEST, DIGEST, 32), + new PartitionAcknowledgement(1, "partition-1-ack", DIGEST, DIGEST, 64)), + Map.of(0, 32, 1, 64)); + WriterInventory inventory = + new WriterInventory( + "writer-inventory-r9", DIGEST, "legacy-layout-writer", List.of("writer-a", "writer-b")); + WriterFenceProof writers = + new WriterFenceProof( + inventory, + WriterDisposition.STOPPED, + List.of( + new WriterFenceAcknowledgement( + "writer-a", WriterDisposition.FENCED, "fence-a", DIGEST), + new WriterFenceAcknowledgement( + "writer-b", WriterDisposition.FENCED, "fence-b", DIGEST))); + return new InitialGameplayReleaseEvidence( + scope.evidenceRef(), + "evidence-owner-record-31", + new MigrationProof( + UUID.randomUUID(), + ProofDisposition.VERIFIED, + scope.peerStorageBinding().storageIdentity(), + "writer-inventory-r9", + DIGEST), + issuerLayout, + writers, + new OwnerInitializationProof( + OwnerService.WORLD_MANAGEMENT, + UUID.randomUUID(), + scope.playableStateNamespaceId(), + ProofDisposition.VERIFIED, + "world-init-source-1", + DIGEST), + new OwnerInitializationProof( + OwnerService.ENTITY_MANAGEMENT, + UUID.randomUUID(), + scope.playableStateNamespaceId(), + ProofDisposition.VERIFIED, + "entity-init-source-1", + DIGEST), + new RegionLeaseProof("region-a", "lease-identity-51", 10)); + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java new file mode 100644 index 0000000000..07f28d81e9 --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -0,0 +1,490 @@ +package net.firedevops.firemud.recovery.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.IssuerLayoutProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.LayoutDescriptor; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.MigrationProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OwnerInitializationProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OwnerService; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PartitionAcknowledgement; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PeerStorageBinding; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.ProofDisposition; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.RegionLeaseProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterDisposition; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterFenceAcknowledgement; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterFenceProof; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterInventory; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class InitialGameplayReleaseModelTest { + private static final String DIGEST = "a".repeat(64); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Test + void scopeKeepsKubernetesTargetSeparateFromPlayableStateNamespace() { + UUID playableNamespace = UUID.randomUUID(); + Scope scope = scope(playableNamespace); + + assertThat(scope.targetNamespace()).isEqualTo("release-target"); + assertThat(scope.playableStateNamespaceId()).isEqualTo(playableNamespace); + assertThatThrownBy( + () -> + new Scope( + scope.operationId(), + scope.canonicalTenantId(), + "another-target", + playableNamespace, + scope.peerStorageBinding(), + scope.evidenceRef())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("targetNamespace"); + } + + @Test + void scopeAndPeerBindingRequireExactKubernetesNamespaceSyntax() { + Scope validScope = scope(UUID.randomUUID()); + for (String invalidNamespace : List.of("Release-target", "release target", "a".repeat(64))) { + assertThatThrownBy( + () -> + new PeerStorageBinding( + invalidNamespace, + "cluster-peer", + "peer-workload", + "storage-uid", + "storage-r7", + DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Kubernetes namespace"); + assertThatThrownBy( + () -> + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + invalidNamespace, + UUID.randomUUID(), + validScope.peerStorageBinding(), + validScope.evidenceRef())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Kubernetes namespace"); + } + } + + @Test + void operationProofAndLockIdentitiesRejectNilUuid() { + Scope validScope = scope(UUID.randomUUID()); + InitialGameplayReleaseEvidence validEvidence = evidence(validScope); + + assertThatThrownBy( + () -> + new Scope( + NIL_UUID, + validScope.canonicalTenantId(), + validScope.targetNamespace(), + validScope.playableStateNamespaceId(), + validScope.peerStorageBinding(), + validScope.evidenceRef())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new Scope( + UUID.randomUUID(), + NIL_UUID, + validScope.targetNamespace(), + validScope.playableStateNamespaceId(), + validScope.peerStorageBinding(), + validScope.evidenceRef())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new Scope( + UUID.randomUUID(), + validScope.canonicalTenantId(), + validScope.targetNamespace(), + NIL_UUID, + validScope.peerStorageBinding(), + validScope.evidenceRef())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new InitialGameplayReleaseModel.Operation( + validScope, + NIL_UUID, + Phase.COLLECTING, + 1, + null, + java.time.Instant.EPOCH, + java.time.Instant.EPOCH, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new MigrationProof( + NIL_UUID, + ProofDisposition.VERIFIED, + validScope.peerStorageBinding().storageIdentity(), + "inventory-r3", + DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy(() -> MaintenanceLockCredential.issue(NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy(() -> MaintenanceLockCredential.fromProtectedTransport(NIL_UUID.toString())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new IssuerLayoutProof( + NIL_UUID, + validEvidence.issuerLayout().descriptor(), + validEvidence.issuerLayout().accountIssuerSourceIdentity(), + validEvidence.issuerLayout().operationFence(), + UUID.randomUUID(), + validEvidence.issuerLayout().inventoryRevision(), + validEvidence.issuerLayout().inventoryDigest(), + validEvidence.issuerLayout().acknowledgements(), + validEvidence.issuerLayout().capacityVector())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new IssuerLayoutProof( + UUID.randomUUID(), + validEvidence.issuerLayout().descriptor(), + validEvidence.issuerLayout().accountIssuerSourceIdentity(), + validEvidence.issuerLayout().operationFence(), + NIL_UUID, + validEvidence.issuerLayout().inventoryRevision(), + validEvidence.issuerLayout().inventoryDigest(), + validEvidence.issuerLayout().acknowledgements(), + validEvidence.issuerLayout().capacityVector())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new OwnerInitializationProof( + OwnerService.WORLD_MANAGEMENT, + NIL_UUID, + validScope.playableStateNamespaceId(), + ProofDisposition.VERIFIED, + "world-source", + DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + assertThatThrownBy( + () -> + new OwnerInitializationProof( + OwnerService.WORLD_MANAGEMENT, + UUID.randomUUID(), + NIL_UUID, + ProofDisposition.VERIFIED, + "world-source", + DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nil UUID"); + } + + @Test + void exactOwnerEvidenceRequiresCompleteLayoutWriterAndIndependentOwnerProofs() { + Scope scope = scope(UUID.randomUUID()); + InitialGameplayReleaseEvidence evidence = evidence(scope); + + evidence.validateFor(scope); + assertThat(evidence.issuerLayout().operationFence()).isPositive(); + assertThat(evidence.issuerLayout().coverageFence()).isNotNull(); + assertThat(evidence.worldInitialization().ownerService()) + .isEqualTo(OwnerService.WORLD_MANAGEMENT); + assertThat(evidence.entityInitialization().ownerService()) + .isEqualTo(OwnerService.ENTITY_MANAGEMENT); + } + + @Test + void proofCollectionAccessorsCannotExposeMutableInternalState() { + InitialGameplayReleaseEvidence evidence = evidence(scope(UUID.randomUUID())); + + assertThatThrownBy(() -> evidence.issuerLayout().descriptor().partitionIds().add(2)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.issuerLayout().acknowledgements().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.issuerLayout().capacityVector().put(2, 14)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> evidence.writerFencing().inventory().applicableWriterIdentities().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> evidence.writerFencing().writerAcknowledgements().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void evidenceCannotUseWorldInitializationAsEntityInitializationProof() { + Scope scope = scope(UUID.randomUUID()); + InitialGameplayReleaseEvidence valid = evidence(scope); + InitialGameplayReleaseEvidence copiedWorldProof = + new InitialGameplayReleaseEvidence( + valid.evidenceRef(), + valid.evidenceIdentity(), + valid.migration(), + valid.issuerLayout(), + valid.writerFencing(), + valid.worldInitialization(), + valid.worldInitialization(), + valid.regionLease()); + + assertThatThrownBy(() -> copiedWorldProof.validateFor(scope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wrong owner"); + } + + @Test + void readinessRejectsMissingPartitionAcknowledgementAndWriterFence() { + Scope scope = scope(UUID.randomUUID()); + InitialGameplayReleaseEvidence valid = evidence(scope); + IssuerLayoutProof incompleteLayout = + new IssuerLayoutProof( + valid.issuerLayout().layoutOperationId(), + valid.issuerLayout().descriptor(), + valid.issuerLayout().accountIssuerSourceIdentity(), + valid.issuerLayout().operationFence(), + valid.issuerLayout().coverageFence(), + valid.issuerLayout().inventoryRevision(), + valid.issuerLayout().inventoryDigest(), + List.of(valid.issuerLayout().acknowledgements().getFirst()), + Map.of(0, 10, 1, 12)); + InitialGameplayReleaseEvidence missingWriterFence = + new InitialGameplayReleaseEvidence( + valid.evidenceRef(), + valid.evidenceIdentity(), + valid.migration(), + valid.issuerLayout(), + new WriterFenceProof( + valid.writerFencing().inventory(), + WriterDisposition.STOPPED, + List.of(valid.writerFencing().writerAcknowledgements().getFirst())), + valid.worldInitialization(), + valid.entityInitialization(), + valid.regionLease()); + + assertThatThrownBy(() -> withLayout(valid, incompleteLayout).validateFor(scope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("partition acknowledgement"); + assertThatThrownBy(() -> missingWriterFence.validateFor(scope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cover the inventory"); + } + + @Test + void tenantAndUuidCoverageFenceSurviveCodecAndBindTheScopeDigest() { + InitialGameplayReleaseTupleCodec codec = + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + Scope original = scope(UUID.randomUUID()); + Scope otherTenant = + new Scope( + original.operationId(), + UUID.randomUUID(), + original.targetNamespace(), + original.playableStateNamespaceId(), + original.peerStorageBinding(), + original.evidenceRef()); + InitialGameplayReleaseEvidence proof = evidence(original); + + assertThat(codec.readScope(codec.toJson(original))).isEqualTo(original); + assertThat(codec.digest(original)).isNotEqualTo(codec.digest(otherTenant)); + assertThat(codec.readEvidence(codec.toJson(proof)).issuerLayout().coverageFence()) + .isEqualTo(proof.issuerLayout().coverageFence()); + + String legacyScopeJson = + codec + .toJson(original) + .replace("\"canonicalTenantId\":\"" + original.canonicalTenantId() + "\",", ""); + assertThatThrownBy(() -> codec.readScope(legacyScopeJson)).isInstanceOf(RuntimeException.class); + String nilTenantScopeJson = + codec + .toJson(original) + .replace( + "\"canonicalTenantId\":\"" + original.canonicalTenantId() + "\"", + "\"canonicalTenantId\":\"" + NIL_UUID + "\""); + assertThatThrownBy(() -> codec.readScope(nilTenantScopeJson)) + .isInstanceOf(RuntimeException.class); + + String legacyNumericFenceJson = + codec + .toJson(proof) + .replace( + "\"coverageFence\":\"" + proof.issuerLayout().coverageFence() + "\"", + "\"coverageFence\":34"); + assertThatThrownBy(() -> codec.readEvidence(legacyNumericFenceJson)) + .isInstanceOf(RuntimeException.class); + } + + @Test + void readinessAndDigestIgnoreCapacityMapIterationOrder() { + Scope scope = scope(UUID.randomUUID()); + InitialGameplayReleaseEvidence original = evidence(scope); + IssuerLayoutProof layout = original.issuerLayout(); + Map reversed = new java.util.LinkedHashMap<>(); + reversed.put(1, 12); + reversed.put(0, 10); + InitialGameplayReleaseEvidence reordered = + withLayout( + original, + new IssuerLayoutProof( + layout.layoutOperationId(), + layout.descriptor(), + layout.accountIssuerSourceIdentity(), + layout.operationFence(), + layout.coverageFence(), + layout.inventoryRevision(), + layout.inventoryDigest(), + layout.acknowledgements(), + reversed)); + original.validateFor(scope); + reordered.validateFor(scope); + InitialGameplayReleaseTupleCodec codec = + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + assertThat(codec.digest(reordered)).isEqualTo(codec.digest(original)); + assertThatThrownBy(() -> reordered.issuerLayout().capacityVector().put(2, 1)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void continuationAndResumePhasesAreNotInterchangeable() { + assertThatThrownBy( + () -> + new net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands + .ContinueRecovery( + UUID.randomUUID(), + Phase.AWAITING_RESUME, + MaintenanceLockCredential.issue(UUID.randomUUID()), + "evidence-ref")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ready_to_reopen"); + assertThatThrownBy( + () -> + new net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.Resume( + UUID.randomUUID(), + Phase.READY_TO_REOPEN, + MaintenanceLockCredential.issue(UUID.randomUUID()), + "evidence-ref")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("awaiting_resume"); + } + + @Test + void maintenanceLockCredentialRedactsItsWireValueFromDefaultRendering() { + UUID lockIdentity = UUID.randomUUID(); + MaintenanceLockCredential credential = MaintenanceLockCredential.issue(lockIdentity); + Scope scope = scope(UUID.randomUUID()); + InitialGameplayReleaseModel.Operation operation = + new InitialGameplayReleaseModel.Operation( + scope, + lockIdentity, + Phase.COLLECTING, + 1, + null, + java.time.Instant.EPOCH, + java.time.Instant.EPOCH, + null); + InitialGameplayReleaseModel.PreparePlayableStateFencedEffect effect = + new InitialGameplayReleaseModel.PreparePlayableStateFencedEffect( + scope.operationId(), UUID.randomUUID(), lockIdentity, scope, DIGEST, "proof-identity"); + + assertThat(credential.toString()).doesNotContain(lockIdentity.toString()); + assertThat(operation.toString()).doesNotContain(lockIdentity.toString()); + assertThat(effect.toString()).doesNotContain(lockIdentity.toString()); + assertThat(credential.protectedTransportValue()).isEqualTo(lockIdentity.toString()); + } + + private static Scope scope(UUID playableNamespace) { + return new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + playableNamespace, + new PeerStorageBinding( + "release-target", "cluster-peer", "peer-workload", "storage-uid", "storage-r7", DIGEST), + "initial-layout-evidence-17"); + } + + static InitialGameplayReleaseEvidence evidence(Scope scope) { + LayoutDescriptor descriptor = + new LayoutDescriptor("initial-layout-v1", "layout-r1", DIGEST, List.of(0, 1)); + IssuerLayoutProof layout = + new IssuerLayoutProof( + UUID.randomUUID(), + descriptor, + "account-issuer-source-29", + 21, + UUID.randomUUID(), + "inventory-r3", + DIGEST, + List.of( + new PartitionAcknowledgement(0, "ack-0", DIGEST, DIGEST, 10), + new PartitionAcknowledgement(1, "ack-1", DIGEST, DIGEST, 12)), + Map.of(0, 10, 1, 12)); + WriterInventory inventory = + new WriterInventory( + "inventory-r3", DIGEST, "legacy-writer", List.of("writer-a", "writer-b")); + WriterFenceProof writerFencing = + new WriterFenceProof( + inventory, + WriterDisposition.STOPPED, + List.of( + new WriterFenceAcknowledgement( + "writer-a", WriterDisposition.FENCED, "fence-a", DIGEST), + new WriterFenceAcknowledgement( + "writer-b", WriterDisposition.FENCED, "fence-b", DIGEST))); + return new InitialGameplayReleaseEvidence( + scope.evidenceRef(), + "initial-release-proof-17", + new MigrationProof( + UUID.randomUUID(), + ProofDisposition.VERIFIED, + scope.peerStorageBinding().storageIdentity(), + "inventory-r3", + DIGEST), + layout, + writerFencing, + new OwnerInitializationProof( + OwnerService.WORLD_MANAGEMENT, + UUID.randomUUID(), + scope.playableStateNamespaceId(), + ProofDisposition.VERIFIED, + "world-source-4", + DIGEST), + new OwnerInitializationProof( + OwnerService.ENTITY_MANAGEMENT, + UUID.randomUUID(), + scope.playableStateNamespaceId(), + ProofDisposition.VERIFIED, + "entity-source-8", + DIGEST), + new RegionLeaseProof("region-west-1", "lease-59", 11)); + } + + private static InitialGameplayReleaseEvidence withLayout( + InitialGameplayReleaseEvidence source, IssuerLayoutProof layout) { + return new InitialGameplayReleaseEvidence( + source.evidenceRef(), + source.evidenceIdentity(), + source.migration(), + layout, + source.writerFencing(), + source.worldInitialization(), + source.entityInitialization(), + source.regionLease()); + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java new file mode 100644 index 0000000000..6b180ed04f --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.recovery.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReason; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReasonCode; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.LaunchAssociation; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.MaintenanceLockPresence; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Mutation; +import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Target; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PeerStorageBinding; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PreparePlayableStateFencedEffect; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class InitialGameplayReleaseControllerTest { + private static final String DIGEST = "c".repeat(64); + + @Test + void validTypedRecoverDeniesBeforeAnyJournalEvidenceOrEffectInteraction() { + InitialGameplayReleaseJournal journal = mock(InitialGameplayReleaseJournal.class); + InitialGameplayReleaseEvidenceProvider evidenceProvider = + mock(InitialGameplayReleaseEvidenceProvider.class); + InitialGameplayReleaseEffectPort effectPort = mock(InitialGameplayReleaseEffectPort.class); + InitialGameplayReleaseController controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + evidenceProvider, + effectPort); + // Valid selectors are deliberately insufficient to prove authority or acquire a lock. + InitialGameplayRecoverRequest request = + new InitialGameplayRecoverRequest( + UUID.randomUUID(), + new InitialGameplayRecoverRequest.Scope( + UUID.randomUUID(), "release-target", UUID.randomUUID()), + new Target( + new LaunchAssociation( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + UUID.randomUUID(), + "launch-1", + "sha256:" + DIGEST, + "sha256:" + DIGEST, + "sha256:" + DIGEST), + new InitialGameplayRecoverRequest.PeerStorageBinding( + "release-target", + "cluster-1", + "spiffe://firemud/ns/release-target/sa/game-session-service", + "storage-1", + "revision-1", + "sha256:" + DIGEST), + "initial-release-evidence-1", + "sha256:" + DIGEST), + new Mutation(UUID.randomUUID(), MaintenanceLockPresence.RESULT_ONLY), + new AuditReason(AuditReasonCode.INITIAL_GAMEPLAY_RELEASE, "Initial release request")); + + assertThatThrownBy(() -> controller.recover(request)) + .isInstanceOf(OwnerBoundaryUnavailableException.class) + .hasMessage("INITIAL_GAMEPLAY_RECOVER_AUTHORIZATION_AND_EXCLUSIVE_FENCE_UNAVAILABLE"); + verifyNoInteractions(journal, evidenceProvider, effectPort); + } + + @Test + void unconfiguredEvidenceProviderDeniesReadinessInsteadOfFabricatingProof() { + DeniedInitialGameplayReleaseEvidenceProvider provider = + new DeniedInitialGameplayReleaseEvidenceProvider(); + Scope scope = + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-1", "recovery-peer", "storage-1", "revision-1", DIGEST), + "initial-release-evidence-1"); + + assertThat(provider.read(scope).status()).isEqualTo(ResolutionStatus.UNAVAILABLE); + assertThat(provider.read(scope).evidence()).isNull(); + } + + @Test + void unconfiguredGameSessionEffectPortDoesNotDispatch() { + DeniedInitialGameplayReleaseEffectPort port = new DeniedInitialGameplayReleaseEffectPort(); + Scope scope = + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-1", "recovery-peer", "storage-1", "revision-1", DIGEST), + "initial-release-evidence-1"); + PreparePlayableStateFencedEffect effect = + new PreparePlayableStateFencedEffect( + scope.operationId(), + UUID.randomUUID(), + UUID.randomUUID(), + scope, + DIGEST, + "proof-identity-1"); + + assertThat(port.apply(effect, UUID.randomUUID()).status()) + .isEqualTo(InitialGameplayReleaseEffectPort.ApplyStatus.RETRYABLE_NO_EFFECT); + assertThat(port.readback(effect, UUID.randomUUID()).status()) + .isEqualTo(InitialGameplayReleaseEffectPort.ReadbackStatus.UNAVAILABLE); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index c8a0d7284e..7d73b9615c 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -49,6 +49,9 @@ project(":game-session-service").projectDir = File("services/game-session-servic include("logging-admin-service") project(":logging-admin-service").projectDir = File("services/logging-admin-service") +include("recovery-controller-service") +project(":recovery-controller-service").projectDir = File("services/recovery-controller-service") + include("social-groups-service") project(":social-groups-service").projectDir = File("services/social-groups-service") From fbe53ca512b67684cba4fc63f0098ca24e7b9ed3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:44:06 +1300 Subject: [PATCH 010/199] ci(recovery): validate source-only foundation and record activation limits --- .github/scripts/classify-change-scope.cjs | 2 ++ .github/scripts/classify-change-scope.test.cjs | 14 +++++++++++++- .github/workflows/ci.yml | 2 ++ .../system-architecture-backup-recovery.md | 8 ++++++++ .../player-access-and-session.md | 4 ++++ 5 files changed, 29 insertions(+), 1 deletion(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index eb3a9c7bdd..252d85791d 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -23,6 +23,7 @@ const ALL_MODULES = [ "common-test-support", "common-web-support", ...ALL_SERVICES, + "recovery-controller-service", "hosted-environment-identity-controller", "load-testing", ]; @@ -36,6 +37,7 @@ const MODULE_PATHS = new Map([ const BOOTABLE_MODULES = new Set([ ...ALL_SERVICES, + "recovery-controller-service", "hosted-environment-identity-controller", ]); diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 320a8eabff..c22afdf752 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -533,7 +533,7 @@ test("shared modules force every Gradle module, including common-temporal", () = assert.equal(result.runAll, true); assert.deepEqual(result.affectedModules, ALL_MODULES); - assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("hosted-environment-identity-controller")); + assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("recovery-controller-service", "hosted-environment-identity-controller")); }); test("controller and load-testing changes receive their own module checks", () => { @@ -599,3 +599,15 @@ test("GitHub malformed file entries fail closed to the complete path", async () assert.deepEqual(result.affectedModules, ALL_MODULES, JSON.stringify(file)); } }); + + +test("source-only recovery controller is validated without joining runtime services", () => { + const result = classifyChangeScope([ + "services/recovery-controller-service/src/main/java/example/Controller.java", + ]); + assert.equal(result.runAll, false); + assert.deepEqual(result.affectedServices, []); + assert.deepEqual(result.affectedModules, ["recovery-controller-service"]); + assert.deepEqual(result.bootableModules, ["recovery-controller-service"]); + assert.equal(ALL_SERVICES.includes("recovery-controller-service"), false); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71a1bc8dda..0c031c5a0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -85,6 +85,7 @@ jobs: "spring-cloud-gateway", "tcp-proxy-service", "world-management-service", + "recovery-controller-service", "hosted-environment-identity-controller", "load-testing", ]; @@ -100,6 +101,7 @@ jobs: "spring-cloud-gateway", "tcp-proxy-service", "world-management-service", + "recovery-controller-service", "hosted-environment-identity-controller", ]; let outputs; diff --git a/design/architecture/system-architecture-backup-recovery.md b/design/architecture/system-architecture-backup-recovery.md index e9010f7830..6689777a47 100644 --- a/design/architecture/system-architecture-backup-recovery.md +++ b/design/architecture/system-architecture-backup-recovery.md @@ -82,6 +82,14 @@ Target state automates backup execution, artifact validation, freshness calculat For the pre-release `secretComplianceRefresh` handoff, the recovery controller issues `controllerContinuationAt` as a trusted UTC timestamp for the exact pending continuation attempt, persists it with the recovery operation and controller-owned continuation identity, and carries it in the immutable operation-bound handoff tuple. The hardening publisher cannot supply, choose, refresh, or infer this value. Before accepting the handoff or reconciling `ready_to_reopen` to `AWAITING_RESUME`, the controller exact-matches `operationId`, continuation identity, and `controllerContinuationAt` against its persisted state and rejects a future, stale, changed, or otherwise mismatched observation; this timestamp is the pre-release freshness reference only, while `finalizedAt` remains reserved for post-finalization projection validation. +### Source-Only Initial Gameplay Release Foundation + +`recovery-controller-service` retains an isolated `initial_gameplay_release` journal, immutable scope/evidence tuples, guarded continuation/resume transitions, and a transactional effect outbox. Its PostgreSQL endpoint must be a dedicated recovery-control instance and volume outside business restore targets; configuration deliberately has no shared-business-database fallback. This foundation is not deployed or registered as a runtime service. + +The typed `initial-gameplay-recover/v1` request binds the control-plane request, recovery operation, canonical tenant, Kubernetes target namespace, separate playable-state namespace, Game Session instance/launch association, peer/storage binding, and evidence/audit selectors. These selectors are not authority. The public owner entry point remains unconditionally fail-closed before journal, evidence, or effect interactions. No public ingress, scheduler, or effect dispatcher is registered; default evidence and effect ports deny. + +Activation still requires real Account authorization/redemption, authenticated owner association/storage verification, an independently proved exclusive maintenance fence and actual acquired lock, genuine current owner evidence/readbacks, and approved isolated deployment/restore topology. A random journal UUID is not a lock or exclusion proof. Later continuation and resume bind the exact retained scope, lock, phase, and evidence; ambiguous effects cannot authorize redispatch or final handoff. Source-level journal tests do not establish these missing end-to-end prerequisites or player-facing recovery readiness. + ## Artifact Erasure Replay Boundary `artifactErasureHighWater` is transactionally bound to the immutable backup snapshot and is never recalculated from restored PostgreSQL. It is the greatest authoritative erasure-ledger sequence visible in that snapshot; `preSnapshotJournalHighWater` is a separately sourced ordering observation recorded before the snapshot and is not itself a replay boundary. When it is lower than the artifact boundary, the immutable backup manifest must contain `interveningErasureCoverageProof` for every sequence in `(preSnapshotJournalHighWater, artifactErasureHighWater]`, represented exactly once with matching identity/digest in the snapshot-visible ledger and external journal; a gap, duplicate, unknown, or ambiguous entry invalidates the artifact and keeps recovery quarantined. At recovery start, the controller captures immutable `initialCatchupHighWater` once. Recovery must complete the fixed initial replay interval `(artifactErasureHighWater, initialCatchupHighWater]` before entering final cutover. During one bounded final cutover, the erasure authority captures immutable `restoreHighWater` once as the final readiness boundary. The controller requires `restoreHighWater >= initialCatchupHighWater >= artifactErasureHighWater`; a lower value, unknown entry, or unprovable interval keeps recovery quarantined. Before `ready_to_reopen`, recovery must replay the one fixed interval `(artifactErasureHighWater, restoreHighWater]` into the restored environment, with the initial interval complete before cutover and only `(initialCatchupHighWater, restoreHighWater]` remaining for cutover. Neither boundary may move during replay. 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..94496cdd44 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -1,5 +1,9 @@ # Player Access and Session +## Initial Gameplay Recovery Foundation Status + +The source-only recovery-controller journal and typed request foundation are retained under PlatformOperations donor consolidation. Focused proof covers immutable scope conflicts, exact continuation/resume tuples, ambiguous-effect refusal, owner-readback-gated journal transitions, and fail-closed recover entry. This is not a runtime recovery capability: Account redemption, genuine exclusive-fence/lock acquisition, independent owner evidence, authenticated ingress/dispatch, and isolated deployment/restore topology remain unimplemented activation dependencies. See the [canonical recovery boundary](../../architecture/system-architecture-backup-recovery.md#source-only-initial-gameplay-release-foundation). No donor/source-note closure follows from this partial foundation. + ## Target-State Authority This is a non-normative implementation tracker for player access and session. Canonical target-state authentication, admission, session, and reconnection contracts remain authoritative in [design/architecture](../../architecture/README.md) and the linked design sources below; this tracker owns current implementation status, proof evidence, gaps, and handoffs, and does not redefine those contracts. From c64e62b5a6a3ab79b70622826305f1663344ad6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:13:13 +1300 Subject: [PATCH 011/199] test(recovery): retain literal codec fixture line endings --- .../common/recovery/InitialGameplayRecoverCodecTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java index 4be37b64ea..91c2fbe9a8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java @@ -20,7 +20,7 @@ class InitialGameplayRecoverCodecTest { "mutation":{"operationId":"00000000-0000-4000-8000-000000000007","verb":"recover","workflow":"initial-gameplay-release","maintenanceLockPresence":"RESULT_ONLY"}, "auditReason":{"code":"INITIAL_GAMEPLAY_RELEASE","detail":"initial"}} """ - .formatted(D, D, D, D, D); + .replace("%s", D); // Static cross-language artifact: lowercase hex of the exact ADR 0047 preimage bytes. private static final String PREIMAGE_HEX = From 93dc29a57a8d287d6e8579faec17ea37c8fc0d79 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:19:11 +1300 Subject: [PATCH 012/199] Separate automatic preview rendering from privileged metadata refresh --- .github/workflows/hosted-identity-request.yml | 19 ++++- .github/workflows/preview-reconciler.yml | 6 +- .github/workflows/preview-runtime-refresh.yml | 78 +++++++++++++++++++ .github/workflows/preview.yml | 33 +++++--- .../architecture/system-architecture-cicd.md | 4 +- .../preview/validate-preview-artifact.py | 4 +- .../tests/preview-runtime-refresh.test.cjs | 72 +++++++++++++++++ 7 files changed, 194 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/preview-runtime-refresh.yml create mode 100644 dev-tools/tests/preview-runtime-refresh.test.cjs diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index b14c1d9896..2f09edbd9e 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -16,7 +16,7 @@ permissions: jobs: validate-target: name: Validate Trusted Preview Target - if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.name == 'PR Preview Environment' && (github.event.workflow_run.event == 'pull_request_target' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository) }} + if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.name == 'PR Preview Environment' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository) }} timeout-minutes: 10 runs-on: ubuntu-latest permissions: @@ -138,8 +138,13 @@ jobs: require_source_field head "$WORKFLOW_RUN_HEAD_SHA" \ "$(jq -r '.head_sha // empty' <<<"$workflow_run_json")" SOURCE_EVENT="$(jq -r '.event // empty' <<<"$workflow_run_json")" - [[ "$SOURCE_EVENT" == pull_request_target || "$SOURCE_EVENT" == repository_dispatch ]] || + [[ "$SOURCE_EVENT" == pull_request || "$SOURCE_EVENT" == repository_dispatch ]] || emit_no_action "Ignoring source run with unsupported event ${SOURCE_EVENT}." + if [[ "$SOURCE_EVENT" == pull_request ]]; then + jq -e '(.pull_requests | type) == "array" and (.pull_requests | length) == 1 and (.pull_requests[0].number | type) == "number" and .pull_requests[0].head.sha == .head_sha' \ + <<<"$workflow_run_json" >/dev/null || + emit_no_action "Ignoring source run without a unique bound pull request association." + fi if [[ "$SOURCE_EVENT" == repository_dispatch ]]; then require_source_field head-branch "$DEFAULT_BRANCH" \ "$(jq -r '.head_branch // empty' <<<"$workflow_run_json")" @@ -161,8 +166,8 @@ jobs: ARTIFACT_KIND=intent ACTION=destroy fi - if [[ "$SOURCE_EVENT" == pull_request_target && "$ARTIFACT_KIND" != render ]]; then - emit_no_action "Ignoring pull_request_target source without a render artifact." + if [[ "$SOURCE_EVENT" == pull_request && "$ARTIFACT_KIND" != render ]]; then + emit_no_action "Ignoring pull_request source without a render artifact." fi download_source_artifact "$ARTIFACT_NAME" if [[ "$ARTIFACT_KIND" == render ]]; then @@ -177,6 +182,12 @@ jobs: fi PR_NUMBER="$(jq -er '.prNumber | select(type == "number" and floor == .)' "$ARTIFACT_DIRECTORY/preview-metadata.json")" EXPECTED_HEAD_SHA="$(jq -er '.headSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" + if [[ "$SOURCE_EVENT" == pull_request ]]; then + jq -e --argjson pr "$PR_NUMBER" --arg head "$EXPECTED_HEAD_SHA" \ + '.head_sha == $head and (.pull_requests | length) == 1 and .pull_requests[0].number == $pr and .pull_requests[0].head.sha == $head' \ + <<<"$workflow_run_json" >/dev/null || + emit_no_action "Ignoring artifact not bound to the source run pull request and head." + fi ARTIFACT_BASE_SHA="$(jq -er '.baseSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" ARTIFACT_MERGE_SHA="$(jq -er '.mergeSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" else diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 383d615af8..401bd2355d 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -607,12 +607,12 @@ jobs: if [[ -n "$candidate_rows" ]]; then active_preview_run_sets=() for active_status in requested queued in_progress waiting pending; do - for active_run_scope in branch pull_request_target workflow_run; do + for active_run_scope in branch pull_request pull_request_target workflow_run; do if [[ "$active_run_scope" == branch ]]; then active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" active_run_branch_filtered=true - elif [[ "$active_run_scope" == pull_request_target ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=pull_request_target&status=${active_status}&per_page=100" + elif [[ "$active_run_scope" == pull_request || "$active_run_scope" == pull_request_target ]]; then + active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100" active_run_branch_filtered=false else active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=workflow_run&status=${active_status}&per_page=100" diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml new file mode 100644 index 0000000000..68135517d9 --- /dev/null +++ b/.github/workflows/preview-runtime-refresh.yml @@ -0,0 +1,78 @@ +name: Refresh Preview Runtime Base + +# Privileged metadata-only observer. Never check out PR code, download artifacts, +# or interpret a PR-authored run title/output as authority. +on: + workflow_run: + workflows: [PR Preview Environment] + types: [completed] + +permissions: {} + +jobs: + refresh: + if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + actions: read + contents: write + pull-requests: read + concurrency: + group: preview-base-refresh-${{ github.event.workflow_run.head_branch }} + cancel-in-progress: false + steps: + - name: Validate GitHub provenance and dispatch current runtime tuple + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const {data: run} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: context.payload.workflow_run.id, + }); + const repository = `${context.repo.owner}/${context.repo.repo}`; + const sha = /^[0-9a-f]{40}$/; + if (run.path !== '.github/workflows/preview.yml' || + run.event !== 'pull_request' || run.conclusion !== 'success' || + run.repository?.full_name !== repository || + run.head_repository?.full_name !== repository || + run.pull_requests?.length !== 1 || !sha.test(run.head_sha)) { + core.info('No trusted current PR source association; no dispatch.'); + return; + } + const source = run.pull_requests[0]; + const {data: pr} = await github.rest.pulls.get({ + ...context.repo, pull_number: source.number, + }); + if (pr.state !== 'open' || pr.head?.repo?.full_name !== repository || + pr.base?.repo?.full_name !== repository || + pr.head.sha !== run.head_sha || source.head?.sha !== run.head_sha || + !['main', 'develop'].includes(pr.base.ref) || + ['dependabot[bot]', 'renovate[bot]'].includes(pr.user?.login) || + !sha.test(pr.merge_commit_sha)) { + core.info('Source is stale or ineligible; no dispatch.'); + return; + } + const {data: base} = await github.rest.git.getRef({ + ...context.repo, ref: `heads/${pr.base.ref}`, + }); + if (!sha.test(base.object?.sha) || source.base?.sha === base.object.sha) { + core.info('No stale source base to repair; no dispatch.'); + return; + } + const {data: merge} = await github.rest.repos.getCommit({ + ...context.repo, ref: pr.merge_commit_sha, + }); + if (merge.sha !== pr.merge_commit_sha || merge.parents?.length !== 2 || + merge.parents[0].sha !== base.object.sha || + merge.parents[1].sha !== pr.head.sha) { + core.info('Current merge is not the exact current base/head tuple; no dispatch.'); + return; + } + await github.rest.repos.createDispatchEvent({ + ...context.repo, event_type: 'pr-runtime-base-refresh', + client_payload: { + pr_number: String(pr.number), base_ref: pr.base.ref, + base_sha: base.object.sha, head_sha: pr.head.sha, + merge_sha: merge.sha, image_tag: `pr-merge-${merge.sha}`, + }, + }); diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 9f26cbc084..e325902c02 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -3,7 +3,7 @@ name: PR Preview Environment run-name: ${{ github.event_name == 'repository_dispatch' && format('Preview dispatch pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha || 'unknown', github.event.client_payload.head_sha, github.event.client_payload.merge_sha || 'unknown') || format('PR preview {0}', github.event.pull_request.number) }} on: - pull_request_target: + pull_request: paths-ignore: - '**/*.md' - 'mkdocs.yml' @@ -28,9 +28,9 @@ jobs: preview-plan: name: Preview Plan runs-on: ubuntu-latest - if: ${{ github.event_name != 'pull_request_target' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.repo.full_name == github.repository && (github.event.action != 'labeled' && github.event.action != 'unlabeled' || github.event.label.name == 'preview:priority') && (github.event.action != 'edited' || github.event.changes.base != null)) }} + if: ${{ github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.repo.full_name == github.repository && (github.event.action != 'labeled' && github.event.action != 'unlabeled' || github.event.label.name == 'preview:priority') && (github.event.action != 'edited' || github.event.changes.base != null)) }} concurrency: - group: preview-plan-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} + group: preview-plan-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} cancel-in-progress: true outputs: action: ${{ steps.derive.outputs.action }} @@ -92,7 +92,7 @@ jobs: exit 1 fi - if [[ "$EVENT_NAME" == pull_request_target ]]; then + if [[ "$EVENT_NAME" == pull_request ]]; then PR_NUMBER="$EVENT_PR_NUMBER" HEAD_SHA="$EVENT_HEAD_SHA" BASE_SHA="" @@ -206,13 +206,13 @@ jobs: echo "::error title=Stale preview head SHA::Supplied head SHA does not equal the current pull request head." >&2 exit 1 fi - if [[ "$ACTION" == deploy && "$EVENT_NAME" == pull_request_target && "${EVENT_BASE_SHA,,}" != "$CURRENT_BASE_SHA" ]]; then + if [[ "$ACTION" == deploy && "$EVENT_NAME" == pull_request && "${EVENT_BASE_SHA,,}" != "$CURRENT_BASE_SHA" ]]; then BASE_REFRESH_REQUIRED=true fi HEAD_SHA="$CURRENT_HEAD_SHA" BASE_SHA="$CURRENT_BASE_SHA" - if [[ "$EVENT_NAME" == pull_request_target && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || + if [[ "$EVENT_NAME" == pull_request && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || [[ "$EVENT_NAME" == repository_dispatch && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] || [[ "$EVENT_NAME" == repository_dispatch && -n "$PLANNED_BASE_SHA" && -n "$PLANNED_IMAGE_TAG" ]]; then BASE_REFRESH_REQUIRED=true @@ -336,7 +336,7 @@ jobs: DERIVED_PR_NUMBER: ${{ steps.derive.outputs.pr_number }} run: | set -euo pipefail - if [[ "$EVENT_NAME" == pull_request_target ]]; then + if [[ "$EVENT_NAME" == pull_request ]]; then PR_AUTHOR="$PR_USER_LOGIN" BASE_REF="$PR_BASE_REF" LABELS_JSON="$(jq -c 'if type == "array" then [.[] | {name: .name}] else . end' <<<"$PR_LABELS_JSON")" @@ -415,7 +415,7 @@ jobs: preview-runtime-base-refresh: name: Refresh PR Runtime Images For Current Base needs: preview-plan - if: ${{ needs.preview-plan.outputs.eligible == 'true' && needs.preview-plan.outputs.action == 'deploy' && needs.preview-plan.outputs.base_refresh_required == 'true' && needs.preview-plan.outputs.image_tag != needs.preview-plan.outputs.base_sha }} + if: ${{ github.event_name == 'repository_dispatch' && needs.preview-plan.outputs.eligible == 'true' && needs.preview-plan.outputs.action == 'deploy' && needs.preview-plan.outputs.base_refresh_required == 'true' && needs.preview-plan.outputs.image_tag != needs.preview-plan.outputs.base_sha }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -522,10 +522,19 @@ jobs: with: egress-policy: audit + # A manual dispatch is a trusted event: never execute candidate scripts or + # local actions in that context. Candidate Helm templates are data only. + - name: Check out trusted default branch render tools + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Check out exact PR merge ref for untrusted render uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge + path: candidate fetch-depth: 2 persist-credentials: false @@ -551,11 +560,11 @@ jobs: run: | set -euo pipefail umask 077 - if ! MERGE_SHA="$(git rev-parse --verify 'HEAD^{commit}')"; then + if ! MERGE_SHA="$(git -C candidate rev-parse --verify 'HEAD^{commit}')"; then echo "::error title=Invalid preview merge ref::The checked-out pull request merge ref is not a commit." >&2 exit 1 fi - if ! merge_parents="$(git rev-list --parents -n 1 "$MERGE_SHA")"; then + if ! merge_parents="$(git -C candidate rev-list --parents -n 1 "$MERGE_SHA")"; then echo "::error title=Invalid preview merge ref::Unable to read the checked-out merge commit parents." >&2 exit 1 fi @@ -571,9 +580,9 @@ jobs: sanitized="$RUNNER_TEMP/preview-rendered-sanitized.yaml" metadata="$RUNNER_TEMP/preview-metadata.json" python3 ./dev-tools/hosted/preview/render-preview-values.py \ - k8s/helm/firemud/values-hosted-shared.example.yaml \ + candidate/k8s/helm/firemud/values-hosted-shared.example.yaml \ "$values" "$PR_NUMBER" "$NAMESPACE" "$RELEASE_NAME" "$HOSTNAME" "$IMAGE_TAG" 32000 - helm template "$RELEASE_NAME" k8s/helm/firemud \ + helm template "$RELEASE_NAME" candidate/k8s/helm/firemud \ -f "$values" --namespace "$NAMESPACE" > "$rendered" # Only these chart-owned objects are intentionally absent from the diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6bf3ae1299..9ed2621af7 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -244,7 +244,9 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, the preview source workflow definition runs from the repository default branch on `pull_request_target` or typed `repository_dispatch`; only its GitHub-hosted, read-only render job checks out the PR merge candidate. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance, current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. Render tools and local actions always come from the default branch; the separate exact PR merge checkout supplies only Helm chart data, never scripts or actions executed by a trusted dispatch. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. + +This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate policy removal (restoring GitHub default protections) or replacement with only `pull_request` and `repository_dispatch`, then verify natural PR/manual-dispatch paths against the merged code. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index dbca5d270f..72860658bd 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -2028,8 +2028,8 @@ def validate_metadata( fail("PR number must be a positive canonical decimal string") normalized_pr_number = int(pr_number) event = metadata.get("event") - if event not in {"pull_request_target", "repository_dispatch"}: - fail("metadata event must be pull_request_target or repository_dispatch") + if event not in {"pull_request", "repository_dispatch"}: + fail("metadata event must be pull_request or repository_dispatch") if event == "repository_dispatch" and metadata.get("action") != "deploy": fail("repository_dispatch render metadata action must be deploy") expected = { diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs new file mode 100644 index 0000000000..7f5da63e8a --- /dev/null +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -0,0 +1,72 @@ +const assert = require('node:assert/strict'); +const {execFileSync} = require('node:child_process'); +const {test} = require('node:test'); +const path = require('node:path'); +const root = path.resolve(__dirname, '../..'); +const workflow = JSON.parse(execFileSync('python3', ['-c', + 'import yaml,json,sys; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))', + path.join(root, '.github/workflows/preview-runtime-refresh.yml')], {encoding: 'utf8'})); +const script = workflow.jobs.refresh.steps[0].with.script; +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40), D = 'd'.repeat(40); +function fixture() { + return { + run: {path: '.github/workflows/preview.yml', event: 'pull_request', conclusion: 'success', + repository: {full_name: 'example/FireMUD'}, head_repository: {full_name: 'example/FireMUD'}, + head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: D}}]}, + pr: {number: 7, state: 'open', head: {sha: C, repo: {full_name: 'example/FireMUD'}}, + base: {ref: 'develop', repo: {full_name: 'example/FireMUD'}}, + merge_commit_sha: A, user: {login: 'developer'}}, + base: {object: {sha: B}}, merge: {sha: A, parents: [{sha: B}, {sha: C}]}, + }; +} +async function execute(f) { + const sent = []; + const github = {rest: { + actions: {getWorkflowRun: async () => ({data: f.run})}, + pulls: {get: async () => ({data: f.pr})}, + git: {getRef: async () => ({data: f.base})}, + repos: {getCommit: async () => ({data: f.merge}), createDispatchEvent: async p => sent.push(p)}, + }}; + await new AsyncFunction('github', 'context', 'core', script)(github, + {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}}}, {info() {}}); + return sent; +} +test('exact stale-base current tuple produces only the typed refresh', async () => { + assert.deepEqual(await execute(fixture()), [{owner: 'example', repo: 'FireMUD', + event_type: 'pr-runtime-base-refresh', client_payload: {pr_number: '7', base_ref: 'develop', + base_sha: B, head_sha: C, merge_sha: A, image_tag: `pr-merge-${A}`}}]); +}); +for (const [name, mutate] of Object.entries({ + wrongPath: f => f.run.path = '.github/workflows/attacker.yml', + wrongEvent: f => f.run.event = 'repository_dispatch', + failedSource: f => f.run.conclusion = 'failure', + wrongRepository: f => f.run.repository.full_name = 'fork/FireMUD', + forkSource: f => f.run.head_repository.full_name = 'fork/FireMUD', + absentAssociation: f => f.run.pull_requests = [], + ambiguousAssociation: f => f.run.pull_requests.push(f.run.pull_requests[0]), + staleHead: f => f.run.head_sha = D, + wrongAssociatedHead: f => f.run.pull_requests[0].head.sha = D, + closed: f => f.pr.state = 'closed', + forkCurrent: f => f.pr.head.repo.full_name = 'fork/FireMUD', + wrongBaseRepository: f => f.pr.base.repo.full_name = 'fork/FireMUD', + unsupportedBase: f => f.pr.base.ref = 'feature/stack', + bot: f => f.pr.user.login = 'renovate[bot]', + currentBase: f => f.run.pull_requests[0].base.sha = B, + invalidBase: f => f.base.object.sha = 'invalid', + invalidMerge: f => f.pr.merge_commit_sha = 'invalid', + wrongMerge: f => f.merge.sha = D, + missingParent: f => f.merge.parents.pop(), + wrongBaseParent: f => f.merge.parents[0].sha = D, + wrongHeadParent: f => f.merge.parents[1].sha = D, +})) test(`fails closed: ${name}`, async () => { + const f = fixture(); mutate(f); assert.deepEqual(await execute(f), []); +}); +test('observer has no checkout, artifact, candidate execution or extra permissions', () => { + assert.deepEqual(workflow.permissions, {}); + assert.deepEqual(workflow.jobs.refresh.permissions, + {actions: 'read', contents: 'write', 'pull-requests': 'read'}); + assert.equal(workflow.jobs.refresh.steps.length, 1); + assert.match(workflow.jobs.refresh.steps[0].uses, /^actions\/github-script@[0-9a-f]{40}$/); + assert.doesNotMatch(script, /downloadArtifact|downloadWorkflowRunArtifact|exec\(|spawn\(/); +}); From d59d455c2b8834e76c91de34c2a9bd11abec758c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:20:06 +1300 Subject: [PATCH 013/199] Qualify preview source events and provenance separation --- .../tests/ci-lightweight-scope-contract.sh | 2 +- ...d-identity-controller-workflow-contract.sh | 31 ++++++------- .../tests/pr-retarget-workflow-contract.sh | 10 ++--- .../tests/preview-eligibility-contract.sh | 4 +- dev-tools/tests/preview-priority-contract.sh | 11 +++-- .../preview-runner-isolation-contract.sh | 44 ++++++++++++++----- 6 files changed, 64 insertions(+), 38 deletions(-) diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index eb5ecd73f2..a32f22642b 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -2101,7 +2101,7 @@ for path_item in ( ): require_list_item( preview, - ("on", "pull_request_target", "paths-ignore"), + ("on", "pull_request", "paths-ignore"), path_item, "preview workflow", ) diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index fc45886f37..38427bcf1a 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -1035,7 +1035,7 @@ assert validate_job["if"] == ( "github.event.workflow_run.conclusion == 'success' && " "github.event.workflow_run.head_repository.full_name == github.repository && " "github.event.workflow_run.name == 'PR Preview Environment' && " - "(github.event.workflow_run.event == 'pull_request_target' || " + "(github.event.workflow_run.event == 'pull_request' || " "github.event.workflow_run.event == 'repository_dispatch')) || " "(github.event_name == 'pull_request_target' && " "github.event.action == 'closed' && " @@ -2776,6 +2776,7 @@ assert set(preview_workflow["jobs"]) == { } refresh_job = preview_workflow["jobs"]["preview-runtime-base-refresh"] assert refresh_job["needs"] == "preview-plan" +assert "github.event_name == 'repository_dispatch'" in refresh_job["if"] assert "base_refresh_required == 'true'" in refresh_job["if"] assert "image_tag != needs.preview-plan.outputs.base_sha" in refresh_job["if"] assert refresh_job["permissions"] == {"contents": "write", "pull-requests": "read"} @@ -4063,7 +4064,7 @@ run_preview_derive_target() { local error_path="$4" env \ PATH="$preview_derive_stub_dir:$PATH" \ - EVENT_NAME=pull_request_target \ + EVENT_NAME=pull_request \ GITHUB_REF=refs/heads/develop \ DEFAULT_BRANCH=develop \ EVENT_ACTION=synchronize \ @@ -4097,7 +4098,7 @@ if run_preview_derive_target \ "$preview_derive_base_lower" \ "$preview_derive_stale_head_output" \ "$TEMP_DIR/preview-derive-stale-head.error"; then - echo "preview plan accepted a stale pull_request_target head SHA" >&2 + echo "preview plan accepted a stale pull_request head SHA" >&2 exit 1 fi grep -Fxq \ @@ -6566,7 +6567,7 @@ if [[ "$1" == run && "$2" == download ]]; then if [[ "${FAKE_ARTIFACT_FILES:-valid}" == valid || "${FAKE_ARTIFACT_FILES:-valid}" == extra ]]; then manifest_sha="$(sha256sum "${VALID_RENDER_MANIFEST:?}" | awk '{print $1}')" jq -nc \ - --arg event "${FAKE_METADATA_EVENT:-pull_request_target}" \ + --arg event "${FAKE_METADATA_EVENT:-pull_request}" \ --arg action "${FAKE_METADATA_ACTION:-}" \ --argjson pr_number "${FAKE_METADATA_PR_NUMBER:-900}" \ --arg base_sha "${FAKE_METADATA_BASE_SHA:-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb}" \ @@ -6590,7 +6591,7 @@ case "$resource" in if [[ -n "${FAKE_WORKFLOW_RUN_JSON:-}" ]]; then printf '%s' "$FAKE_WORKFLOW_RUN_JSON" else - printf '%s' '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' + printf '%s' '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"cccccccccccccccccccccccccccccccccccccccc"}}]}' fi elif [[ "$jq_expression" == .path ]]; then printf '%s' '.github/workflows/preview.yml' @@ -6688,6 +6689,7 @@ target_gh_log="$TEMP_DIR/target-gh.log" INPUT_PR_NUMBER='' \ INPUT_HEAD_SHA='' \ INPUT_ACTION='' \ + FAKE_WORKFLOW_RUN_JSON='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[]}' \ SOURCE_GH_LOG="$target_gh_log" \ GITHUB_OUTPUT="$TEMP_DIR/output" \ bash "$TEMP_DIR/target.sh" @@ -6720,9 +6722,9 @@ chmod +x "$target_fixture_bin/python3" target_real_python3="$(command -v python3)" canonical_artifact_name='preview-render-pr-900-cccccccccccccccccccccccccccccccccccccccc' -valid_workflow_run_json='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' +valid_workflow_run_json='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"cccccccccccccccccccccccccccccccccccccccc"}}]}' distinct_source_sha=dddddddddddddddddddddddddddddddddddddddd -distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' +distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"dddddddddddddddddddddddddddddddddddddddd"}}]}' valid_artifacts_json='[{"artifacts":[{"name":"'"$canonical_artifact_name"'","expired":false},{"name":"old-preview","expired":true},{"name":"unrelated-artifact","expired":false}]}]' run_deploy_target_fixture() { @@ -6830,12 +6832,11 @@ FAKE_FIXTURE_EXPOSURE_MODE=public \ FAKE_FIXTURE_CERTIFICATE_MODE=standalone FAKE_FIXTURE_EXPOSURE_MODE=public \ run_deploy_target_fixture standalone-public 0 'action=deploy' -# workflow_run.head_sha identifies the source/default-branch workflow run here, -# while the PR head remains bound by the current PR and artifact metadata. +# A PR source run must bind both its run head and sole PR association to the artifact head. FAKE_FIXTURE_WORKFLOW_RUN_JSON="$distinct_source_workflow_run_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ - run_deploy_target_fixture distinct-source-head 0 'action=deploy' -grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-distinct-source-head.output" + run_deploy_target_fixture distinct-source-head 0 'Ignoring artifact not bound to the source run pull request and head.' +grep -Fxq "action=none" "$TEMP_DIR/deploy-target-distinct-source-head.output" FAKE_FIXTURE_ARTIFACTS_JSON='[{"artifacts":[]}]' \ run_deploy_target_fixture missing-canonical 0 \ @@ -6957,19 +6958,19 @@ run_invalid_source_field() { run_invalid_source_field \ conclusion \ - '{"conclusion":"failure","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"failure","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run conclusion::Expected success; actual failure.' run_invalid_source_field \ head \ - '{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run head::Expected cccccccccccccccccccccccccccccccccccccccc; actual dddddddddddddddddddddddddddddddddddddddd.' run_invalid_source_field \ path \ - '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/other.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/other.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run path::Expected .github/workflows/preview.yml; actual .github/workflows/other.yml.' run_invalid_source_field \ repository \ - '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"fork/FireMUD"}}' \ + '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"fork/FireMUD"}}' \ '::error title=Unexpected source run repository::Expected example/FireMUD; actual fork/FireMUD.' target_python_log="$TEMP_DIR/closed-target-python.log" diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index b47d12f249..e1eb0cc0e0 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1630,7 +1630,7 @@ if grep -Eq '^concurrency:' "$preview_path"; then echo "Preview workflow must not cancel an active lifecycle from workflow-level concurrency" >&2 exit 1 fi -assert_job_contains preview.yml preview-plan "group: preview-plan-\${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" +assert_job_contains preview.yml preview-plan "group: preview-plan-\${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" assert_job_contains preview.yml preview-plan 'cancel-in-progress: true' assert_job_excludes preview.yml preview-plan 'Publish preview lifecycle state' assert_job_excludes preview.yml preview-plan 'firemud-preview-summary' @@ -1658,7 +1658,7 @@ require_contains "$preview_path" 'run-name: ${{ github.event_name == ' require_contains "$preview_path" "format('Preview dispatch pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha || 'unknown', github.event.client_payload.head_sha, github.event.client_payload.merge_sha || 'unknown')" require_contains "$preview_path" 'contents: read' require_contains "$preview_path" 'pull-requests: read' -require_contains "$preview_path" 'pull_request_target:' +require_contains "$preview_path" 'pull_request:' require_contains "$preview_path" 'types: [preview-deploy, preview-destroy]' require_contains "$preview_path" ' - opened' require_contains "$preview_path" ' - synchronize' @@ -1682,7 +1682,7 @@ if grep -Eq '^ - closed$' "$preview_path"; then fi require_contains "$preview_path" 'Check out trusted default branch for preview plan' require_contains "$preview_path" 'ref: ${{ github.event.repository.default_branch }}' -require_contains "$preview_path" "github.event_name == 'pull_request_target'" +require_contains "$preview_path" "github.event_name == 'pull_request'" require_contains "$preview_path" "github.event_name == 'repository_dispatch'" require_contains "$preview_path" 'github.event.pull_request.head.repo.full_name == github.repository' require_contains "$preview_path" 'github.event.pull_request.base.repo.full_name == github.repository' @@ -1712,7 +1712,7 @@ from pathlib import Path workflow_path = Path(sys.argv[1]) workflow = workflow_path.read_text(encoding="utf-8") predicate_start = workflow.index( - ' if [[ "$EVENT_NAME" == pull_request_target && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] ||' + ' if [[ "$EVENT_NAME" == pull_request && "$CURRENT_BASE_REF" != main && "$CURRENT_BASE_REF" != develop ]] ||' ) predicate_end = workflow.index( '\n if [[ "$ACTION" != deploy ]]; then', @@ -1792,7 +1792,7 @@ assert_job_excludes preview.yml preview-destroy-intent "github.event_name == 'pu # The trusted default-branch workflow owns all runtime and identity mutations. require_contains "$trusted_preview_path" "github.event.workflow_run.head_repository.full_name == github.repository" -require_contains "$trusted_preview_path" "github.event.workflow_run.event == 'pull_request_target' || github.event.workflow_run.event == 'repository_dispatch'" +require_contains "$trusted_preview_path" "github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch'" require_contains "$trusted_preview_path" "github.event_name == 'pull_request_target' && github.event.action == 'closed'" require_contains "$trusted_preview_path" 'require_source_field head-branch "$DEFAULT_BRANCH"' require_contains "$trusted_preview_path" 'preview-(render|intent)-pr-' diff --git a/dev-tools/tests/preview-eligibility-contract.sh b/dev-tools/tests/preview-eligibility-contract.sh index 116f28ddd4..b120aab5a2 100644 --- a/dev-tools/tests/preview-eligibility-contract.sh +++ b/dev-tools/tests/preview-eligibility-contract.sh @@ -375,7 +375,7 @@ run_workflow_eligibility() { event_metadata_output="$TEMP_DIR/event-metadata.out" ( cd "$ROOT_DIR" - EVENT_NAME=pull_request_target \ + EVENT_NAME=pull_request \ EVENT_ACTION=synchronize \ PR_USER_LOGIN=human \ PR_BASE_REF=develop \ @@ -396,7 +396,7 @@ grep -qx 'priority=true' "$event_eligibility_output" malformed_event_metadata_output="$TEMP_DIR/malformed-event-metadata.out" ( cd "$ROOT_DIR" - EVENT_NAME=pull_request_target \ + EVENT_NAME=pull_request \ EVENT_ACTION=synchronize \ PR_USER_LOGIN=human \ PR_BASE_REF=develop \ diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 956e11f721..d86efd5706 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -412,11 +412,13 @@ fake_labels_json() { fi printf '%s' "$labels_json" } -if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then +if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request\&status=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then active_query_status="${resource##*&status=}" active_query_status="${active_query_status%%&*}" if [[ "$resource" == */actions/runs\?branch=* ]]; then active_query_scope=branch + elif [[ "$resource" == */actions/runs\?event=pull_request\&status=* ]]; then + active_query_scope=pull_request elif [[ "$resource" == */actions/runs\?event=pull_request_target\&status=* ]]; then active_query_scope=pull_request_target else @@ -488,7 +490,7 @@ case "$resource" in ;; */actions/runs/42) if [[ "$has_jq" != true ]]; then - printf '%s' '{"conclusion":"success","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","path":".github/workflows/preview.yml","event":"pull_request_target","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900}]}' + printf '%s' '{"conclusion":"success","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}]}' elif [[ "$*" == *".path"* ]]; then printf '%s' '.github/workflows/preview.yml' else @@ -2424,8 +2426,9 @@ grep -Fq 'case "$repair_status" in' "$RECONCILER_RUN" grep -Fq -- 'gh api --paginate --slurp' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal workflow source expressions. grep -Fq -- 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' "$RECONCILER_RUN" -# shellcheck disable=SC2016 # Assert the additional pull_request_target lookup without a branch filter. -grep -Fq -- 'actions/runs?event=pull_request_target&status=${active_status}&per_page=100' "$RECONCILER_RUN" +# shellcheck disable=SC2016 # Event scopes include automatic renders and direct closed cleanup. +grep -Fq -- 'for active_run_scope in branch pull_request pull_request_target workflow_run' "$RECONCILER_RUN" +grep -Fq -- 'actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert workflow_run consumers are included without a branch filter. grep -Fq -- 'actions/runs?event=workflow_run&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert each supported active status is queried independently. diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 70d2398633..251419c88f 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -108,9 +108,9 @@ if not isinstance(preview_jobs, dict) or not preview_jobs: raise AssertionError("preview.yml must define source jobs") if not isinstance(trusted_jobs, dict) or not trusted_jobs: raise AssertionError("hosted-identity-request.yml must define trusted jobs") -if set(preview_triggers) != {"pull_request_target", "repository_dispatch"}: +if set(preview_triggers) != {"pull_request", "repository_dispatch"}: raise AssertionError( - "preview.yml must use only default-branch-owned pull_request_target and repository_dispatch triggers" + "preview.yml must use only credential-free pull_request and default-branch repository_dispatch triggers" ) if preview_triggers["repository_dispatch"] != {"types": ["preview-deploy", "preview-destroy"]}: raise AssertionError("preview.yml must accept only typed preview deploy/destroy dispatches") @@ -255,12 +255,10 @@ for path, job_names in protected_jobs.items(): f"{path.name}:{job_name} still consumes the legacy shared preview kubeconfig secret" ) -# The source workflow definition must not be selectable from a PR branch. -# Typed repository dispatch and pull_request_target execute the default-branch -# workflow; the source job may still check out an exact PR merge only on an -# unprivileged GitHub-hosted runner. +# Automatic pull_request source is untrusted; only typed repository dispatch +# uses the default-branch workflow. Both render with credential-free tools. preview_source = preview_path.read_text(encoding="utf-8") -if "workflow_dispatch" in preview_source or "on:\n pull_request:" in preview_source: +if "workflow_dispatch" in preview_source or "pull_request_target:" in preview_source: raise AssertionError("preview.yml retains a branch-selectable source trigger") if '"$EVENT_NAME" == repository_dispatch && "$GITHUB_REF" != "refs/heads/$DEFAULT_BRANCH"' not in preview_source: raise AssertionError("preview.yml dispatch lacks a default-branch ref guard") @@ -297,6 +295,8 @@ def check_preview_source_permissions(job_name: str, job: dict[str, Any]) -> None raise AssertionError( "preview-runtime-base-refresh must have exactly contents:write and pull-requests:read" ) + if "github.event_name == 'repository_dispatch'" not in str(job.get("if", "")): + raise AssertionError("preview runtime refresh write permissions require dispatch-only gating") return job_permissions_list = permissions(job_permissions) if any(permission.endswith(": write") for permission in job_permissions_list): @@ -388,14 +388,33 @@ except AssertionError: else: raise AssertionError("preview runtime refresh extra permission mutation escaped source checking") +refresh_with_pr_gate = dict(refresh_job) +refresh_with_pr_gate["if"] = "${{ github.event_name == 'pull_request' }}" +try: + check_preview_source_permissions("preview-runtime-base-refresh", refresh_with_pr_gate) +except AssertionError: + pass +else: + raise AssertionError("preview runtime refresh PR write mutation escaped source checking") + # The plan's local actions and scripts must come from the default branch; the # render's PR checkout is exact, unprivileged, and bound to the planned merge. plan_checkouts = checkouts(preview_jobs["preview-plan"]) if len(plan_checkouts) != 1 or plan_checkouts[0].get("with", {}).get("ref") != "${{ github.event.repository.default_branch }}": raise AssertionError("preview plan must check out the trusted default branch") render_checkouts = checkouts(preview_jobs["preview-render"]) -if len(render_checkouts) != 1 or render_checkouts[0].get("with", {}).get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge": - raise AssertionError("preview render must check out the exact PR merge ref") +if len(render_checkouts) != 2: + raise AssertionError("preview render must isolate trusted tools and candidate chart checkouts") +if render_checkouts[0].get("with", {}).get("ref") != "${{ github.event.repository.default_branch }}" or render_checkouts[0].get("with", {}).get("path") is not None: + raise AssertionError("preview render tools must remain rooted at the trusted default branch") +if render_checkouts[1].get("with", {}).get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or render_checkouts[1].get("with", {}).get("path") != "candidate": + raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") +render_text = text(preview_jobs["preview-render"]) +for required in ("git -C candidate", "candidate/k8s/helm/firemud", "python3 ./dev-tools/hosted/preview/"): + if required not in render_text: + raise AssertionError(f"preview render lost isolated trusted-tools/candidate-data boundary: {required}") +if re.search(r"(?:uses:|bash|python3)\s+(?:\./)?candidate/", render_text): + raise AssertionError("preview render executes candidate tools or local actions") for job_name, job in preview_jobs.items(): for checkout in checkouts(job): if checkout.get("with", {}).get("persist-credentials") is not False: @@ -405,12 +424,12 @@ trusted_target = next( if isinstance(step, dict) and step.get("id") == "target" )["run"] for required in ( - "[[ \"$SOURCE_EVENT\" == pull_request_target || \"$SOURCE_EVENT\" == repository_dispatch ]]", + "[[ \"$SOURCE_EVENT\" == pull_request || \"$SOURCE_EVENT\" == repository_dispatch ]]", "require_source_field path '.github/workflows/preview.yml'", 'require_source_field head "$WORKFLOW_RUN_HEAD_SHA"', 'require_source_field head-branch "$DEFAULT_BRANCH"', "Ignoring source run without exactly one canonical preview artifact.", - '"$SOURCE_EVENT" == pull_request_target && "$ARTIFACT_KIND" != render', + '"$SOURCE_EVENT" == pull_request && "$ARTIFACT_KIND" != render', '[[ "$current_head_sha" == "$EXPECTED_HEAD_SHA" ]]', ): if required not in trusted_target: @@ -567,3 +586,6 @@ with tempfile.TemporaryDirectory() as temporary: print("preview runner isolation contract checks passed") PY + +# Exercise the metadata-only observer through this canonical isolation gate. +node --test "$ROOT_DIR/dev-tools/tests/preview-runtime-refresh.test.cjs" From 4ac665536e761b30b82928ddc8de464403fed374 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:21:29 +1300 Subject: [PATCH 014/199] Preserve priority stacked preview refresh eligibility --- .github/workflows/preview-runtime-refresh.yml | 11 ++++++++--- dev-tools/tests/preview-runtime-refresh.test.cjs | 12 +++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 68135517d9..53825f3418 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -43,11 +43,16 @@ jobs: const {data: pr} = await github.rest.pulls.get({ ...context.repo, pull_number: source.number, }); + const labelsValid = Array.isArray(pr.labels) && + pr.labels.every(label => typeof label?.name === 'string'); + const isPriority = labelsValid && pr.labels.some(label => label.name === 'preview:priority'); + const isIntegrationBase = ['main', 'develop'].includes(pr.base?.ref); if (pr.state !== 'open' || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || pr.head.sha !== run.head_sha || source.head?.sha !== run.head_sha || - !['main', 'develop'].includes(pr.base.ref) || - ['dependabot[bot]', 'renovate[bot]'].includes(pr.user?.login) || + !labelsValid || (!isIntegrationBase && !isPriority) || + !/^[A-Za-z0-9._/-]+$/.test(pr.base.ref) || + ['app/dependabot', 'dependabot[bot]', 'app/renovate', 'renovate[bot]'].includes(pr.user?.login) || !sha.test(pr.merge_commit_sha)) { core.info('Source is stale or ineligible; no dispatch.'); return; @@ -55,7 +60,7 @@ jobs: const {data: base} = await github.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}`, }); - if (!sha.test(base.object?.sha) || source.base?.sha === base.object.sha) { + if (!sha.test(base.object?.sha) || (isIntegrationBase && source.base?.sha === base.object.sha)) { core.info('No stale source base to repair; no dispatch.'); return; } diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 7f5da63e8a..9cdf45e888 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -16,7 +16,7 @@ function fixture() { head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: D}}]}, pr: {number: 7, state: 'open', head: {sha: C, repo: {full_name: 'example/FireMUD'}}, base: {ref: 'develop', repo: {full_name: 'example/FireMUD'}}, - merge_commit_sha: A, user: {login: 'developer'}}, + merge_commit_sha: A, labels: [], user: {login: 'developer'}}, base: {object: {sha: B}}, merge: {sha: A, parents: [{sha: B}, {sha: C}]}, }; } @@ -51,6 +51,9 @@ for (const [name, mutate] of Object.entries({ forkCurrent: f => f.pr.head.repo.full_name = 'fork/FireMUD', wrongBaseRepository: f => f.pr.base.repo.full_name = 'fork/FireMUD', unsupportedBase: f => f.pr.base.ref = 'feature/stack', + missingLabels: f => delete f.pr.labels, + malformedLabels: f => f.pr.labels = [{name: 3}], + appBot: f => f.pr.user.login = 'app/renovate', bot: f => f.pr.user.login = 'renovate[bot]', currentBase: f => f.run.pull_requests[0].base.sha = B, invalidBase: f => f.base.object.sha = 'invalid', @@ -70,3 +73,10 @@ test('observer has no checkout, artifact, candidate execution or extra permissio assert.match(workflow.jobs.refresh.steps[0].uses, /^actions\/github-script@[0-9a-f]{40}$/); assert.doesNotMatch(script, /downloadArtifact|downloadWorkflowRunArtifact|exec\(|spawn\(/); }); + +test('priority stacked base refreshes even when source base is current', async () => { + const f = fixture(); f.pr.base.ref = 'feature/stack'; + f.pr.labels = [{name: 'preview:priority'}]; f.run.pull_requests[0].base.sha = B; + const sent = await execute(f); + assert.equal(sent.length, 1); assert.equal(sent[0].client_payload.base_ref, 'feature/stack'); +}); From 3332c929b724f6b1f1847438e909cc3e8febc3a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:22:36 +1300 Subject: [PATCH 015/199] Reuse trusted image selection before automatic refresh --- .github/workflows/preview-runtime-refresh.yml | 19 ++++++++++++ .../architecture/system-architecture-cicd.md | 2 +- .../tests/preview-runtime-refresh.test.cjs | 30 ++++++++++++++----- 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 53825f3418..0cd5686c8b 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -22,8 +22,16 @@ jobs: group: preview-base-refresh-${{ github.event.workflow_run.head_branch }} cancel-in-progress: false steps: + - name: Check out trusted default branch image policy + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Validate GitHub provenance and dispatch current runtime tuple uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + GH_TOKEN: ${{ github.token }} with: script: | const {data: run} = await github.rest.actions.getWorkflowRun({ @@ -73,6 +81,17 @@ jobs: core.info('Current merge is not the exact current base/head tuple; no dispatch.'); return; } + // Reuse the canonical default-branch path classifier rather than + // trusting source outputs or maintaining a second image policy. + const imageTag = require('node:child_process').execFileSync('bash', [ + './dev-tools/hosted/preview/resolve-preview-image-tag.sh', + merge.sha, String(pr.number), base.object.sha, + ], {encoding: 'utf8', env: process.env}).trim(); + if (imageTag !== `pr-merge-${merge.sha}`) { + if (imageTag !== base.object.sha) throw new Error('Unexpected image identity'); + core.info('Canonical image policy selects base images; no refresh.'); + return; + } await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: 'pr-runtime-base-refresh', client_payload: { diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 9ed2621af7..83b32b22d7 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -244,7 +244,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. Render tools and local actions always come from the default branch; the separate exact PR merge checkout supplies only Helm chart data, never scripts or actions executed by a trusted dispatch. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. Render tools and local actions always come from the default branch; the separate exact PR merge checkout supplies only Helm chart data, never scripts or actions executed by a trusted dispatch. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate policy removal (restoring GitHub default protections) or replacement with only `pull_request` and `repository_dispatch`, then verify natural PR/manual-dispatch paths against the merged code. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 9cdf45e888..f98171178c 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -6,7 +6,7 @@ const root = path.resolve(__dirname, '../..'); const workflow = JSON.parse(execFileSync('python3', ['-c', 'import yaml,json,sys; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))', path.join(root, '.github/workflows/preview-runtime-refresh.yml')], {encoding: 'utf8'})); -const script = workflow.jobs.refresh.steps[0].with.script; +const script = workflow.jobs.refresh.steps[1].with.script; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40), D = 'd'.repeat(40); function fixture() { @@ -28,8 +28,15 @@ async function execute(f) { git: {getRef: async () => ({data: f.base})}, repos: {getCommit: async () => ({data: f.merge}), createDispatchEvent: async p => sent.push(p)}, }}; - await new AsyncFunction('github', 'context', 'core', script)(github, - {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}}}, {info() {}}); + await new AsyncFunction('github', 'context', 'core', 'require', script)(github, + {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}}}, {info() {}}, name => { + assert.equal(name, 'node:child_process'); + return {execFileSync(command, args) { + assert.equal(command, 'bash'); + assert.deepEqual(args, ['./dev-tools/hosted/preview/resolve-preview-image-tag.sh', A, '7', B]); + return f.imageTag ?? `pr-merge-${A}`; + }}; + }); return sent; } test('exact stale-base current tuple produces only the typed refresh', async () => { @@ -65,13 +72,15 @@ for (const [name, mutate] of Object.entries({ })) test(`fails closed: ${name}`, async () => { const f = fixture(); mutate(f); assert.deepEqual(await execute(f), []); }); -test('observer has no checkout, artifact, candidate execution or extra permissions', () => { +test('observer checks out only trusted policy and has no artifact or candidate execution', () => { assert.deepEqual(workflow.permissions, {}); assert.deepEqual(workflow.jobs.refresh.permissions, {actions: 'read', contents: 'write', 'pull-requests': 'read'}); - assert.equal(workflow.jobs.refresh.steps.length, 1); - assert.match(workflow.jobs.refresh.steps[0].uses, /^actions\/github-script@[0-9a-f]{40}$/); - assert.doesNotMatch(script, /downloadArtifact|downloadWorkflowRunArtifact|exec\(|spawn\(/); + assert.equal(workflow.jobs.refresh.steps.length, 2); + assert.deepEqual(workflow.jobs.refresh.steps[0].with, + {ref: '${{ github.event.repository.default_branch }}', 'persist-credentials': false}); + assert.match(workflow.jobs.refresh.steps[1].uses, /^actions\/github-script@[0-9a-f]{40}$/); + assert.doesNotMatch(script, /downloadArtifact|downloadWorkflowRunArtifact|spawn\(/); }); test('priority stacked base refreshes even when source base is current', async () => { @@ -80,3 +89,10 @@ test('priority stacked base refreshes even when source base is current', async ( const sent = await execute(f); assert.equal(sent.length, 1); assert.equal(sent[0].client_payload.base_ref, 'feature/stack'); }); + +test('canonical non-runtime base image selection does not dispatch', async () => { + const f = fixture(); f.imageTag = B; assert.deepEqual(await execute(f), []); +}); +test('unexpected canonical image selection fails closed', async () => { + const f = fixture(); f.imageTag = 'untrusted'; await assert.rejects(execute(f), /Unexpected image/); +}); From 092475195164f10e3501d0044533bec611dbb8d9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:02:05 +1300 Subject: [PATCH 016/199] Align preview metadata test fixtures and literal-query lint --- dev-tools/tests/preview-priority-contract.sh | 1 + dev-tools/validation/test_validate_preview_artifact.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index d86efd5706..3b1d516cec 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -2428,6 +2428,7 @@ grep -Fq -- 'gh api --paginate --slurp' "$RECONCILER_RUN" grep -Fq -- 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Event scopes include automatic renders and direct closed cleanup. grep -Fq -- 'for active_run_scope in branch pull_request pull_request_target workflow_run' "$RECONCILER_RUN" +# shellcheck disable=SC2016 # Assert literal workflow query variables. grep -Fq -- 'actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert workflow_run consumers are included without a branch filter. grep -Fq -- 'actions/runs?event=workflow_run&status=${active_status}&per_page=100' "$RECONCILER_RUN" diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 873cbac3d9..ce24c62801 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -1172,7 +1172,7 @@ class PreviewArtifactMetadataTest(unittest.TestCase): def _metadata_fixture(manifest_path): return { "schemaVersion": 1, - "event": "pull_request_target", + "event": "pull_request", "repository": "example/FireMUD", "sourceWorkflow": ".github/workflows/preview.yml", "sourceRunId": 42, From 8bb4db0377e599eb8cf1e60219390fb2a17a2c59 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:31:52 +1300 Subject: [PATCH 017/199] Coalesce optional static summaries across PR head changes --- .github/workflows/static-analysis-summary.yml | 29 +++++----- .../tests/static-analysis-summary-contract.sh | 58 +++++++++++++++++-- 2 files changed, 68 insertions(+), 19 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index b35044a9c2..355ced41af 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -14,10 +14,11 @@ permissions: pull-requests: write concurrency: - group: static-analysis-summary-${{ github.event.workflow_run.head_branch || github.ref }}-${{ github.event.workflow_run.head_sha }} + group: static-analysis-summary-pr-${{ github.event.workflow_run.pull_requests[0].number || github.run_id }} # Serialize the CodeQL and license completion events so a pending summary - # cannot race a terminal summary into creating two comments. A superseded head - # cannot replace the pending callback for the current head. + # cannot race a terminal summary into creating two comments. Every validated + # callback snapshots the live tuple, so an older-head wake can replace pending + # work without losing current-head reconciliation. Never cancel active writes. cancel-in-progress: false jobs: @@ -37,22 +38,22 @@ jobs: with: script: | const pullRequests = context.payload.workflow_run.pull_requests || []; - if (pullRequests.length === 0) { - core.info("No pull request is attached to this workflow run."); + if (pullRequests.length !== 1) { + core.info("Exactly one pull request must be attached to this workflow run."); return; } const pullRequest = pullRequests[0]; const issueNumber = pullRequest.number; - const headSha = context.payload.workflow_run.head_sha; + if (!Number.isSafeInteger(issueNumber) || issueNumber <= 0) return; + const sourceHeadSha = context.payload.workflow_run.head_sha; + if (!/^[0-9a-f]{40}$/.test(sourceHeadSha || "")) return; const { data: currentPullRequest } = await github.rest.pulls.get({ ...context.repo, pull_number: issueNumber, }); - if (currentPullRequest.head?.sha !== headSha) { - core.info("The source run belongs to a superseded pull-request head."); - return; - } + const headSha = currentPullRequest.head?.sha; + if (!/^[0-9a-f]{40}$/.test(headSha || "")) return; const baseSha = currentPullRequest.base?.sha; if (!baseSha) { throw new Error("The current pull-request base SHA is unavailable."); @@ -63,11 +64,11 @@ jobs: ".github/workflows/license-scan.yml": "License Gate", })[sourceWorkflowPath]; // The completion is a wake signal, never proof for the current base. - // An older-base callback can replace a pending callback in this head's - // concurrency group, so validate its original title and snapshot the live tuple. + // An older-head or older-base callback may replace pending work for this PR. + // Validate its original identity, then derive proof only from the live tuple. const sourceBaseSha = String(context.payload.workflow_run.display_title || "") .match(/ base-([0-9a-f]{40}) head-/)?.[1]; - const expectedSourceTitle = `${sourceWorkflowName} pr-${issueNumber} base-${sourceBaseSha} head-${headSha}`; + const expectedSourceTitle = `${sourceWorkflowName} pr-${issueNumber} base-${sourceBaseSha} head-${sourceHeadSha}`; if ( currentPullRequest.state !== "open" || !sourceWorkflowName || @@ -76,7 +77,7 @@ jobs: context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { - core.info("The source run is not bound to the current open pull request and head."); + core.info("The source run is not attributable to this open pull request."); return; } const detailChecks = [ diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index fb98491bc3..bface3a863 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -27,8 +27,8 @@ grep -Fq 'per_page: 100' "$workflow" grep -Fq 'cancel-in-progress: false' "$workflow" # GitHub expressions are literal workflow text, not shell expansions. # shellcheck disable=SC2016 -grep -Fq 'group: static-analysis-summary-${{ github.event.workflow_run.head_branch || github.ref }}-${{ github.event.workflow_run.head_sha }}' "$workflow" -grep -Fq 'currentPullRequest.head?.sha !== headSha' "$workflow" +grep -Fq 'group: static-analysis-summary-pr-${{ github.event.workflow_run.pull_requests[0].number || github.run_id }}' "$workflow" +grep -Fq 'const headSha = currentPullRequest.head?.sha;' "$workflow" grep -Fq 'context.payload.workflow_run.display_title !== expectedSourceTitle' "$workflow" grep -Fq 'finalPullRequest.base?.sha !== baseSha' "$workflow" grep -Fq 'workflowRun?.display_title === expectedTitle' "$workflow" @@ -87,6 +87,7 @@ let currentBaseSha = baseSha; let currentBaseRef = "develop"; let pullRequestReads = 0; let changeBaseDuringRun = false; +let changeHeadDuringRun = false; let deleteStatus = null; let existingBody = "### Static Analysis Summary\nold"; const calls = { paginate: [], deleted: [], updated: [], created: [] }; @@ -97,6 +98,7 @@ const github = { rest: { pulls: { get: async () => { pullRequestReads += 1; + if (changeHeadDuringRun && pullRequestReads === 2) currentHeadSha = "e".repeat(40); if (changeBaseDuringRun && pullRequestReads === 2) currentBaseSha = "c".repeat(40); return { data: { state: "open", head: { sha: currentHeadSha }, base: { sha: currentBaseSha, ref: currentBaseRef } } }; } }, @@ -317,7 +319,8 @@ async function assertCompletionOrders() { if (!completed.has(key) && absentCounterpart) return []; return rows.filter((row) => [100, 200, 300].includes(row.id)).map((row) => ({ ...row, id: row.id + (currentBaseSha === baseSha ? 0 : 1000), - display_title: row.display_title.replace(`base-${baseSha}`, `base-${currentBaseSha}`), + head_sha: currentHeadSha, + display_title: row.display_title.replace(`base-${baseSha}`, `base-${currentBaseSha}`).replace(`head-${headSha}`, `head-${currentHeadSha}`), status: completed.has(key) ? "completed" : "in_progress", conclusion: completed.has(key) ? "success" : null, })); @@ -370,6 +373,15 @@ async function assertCompletionOrders() { await callback(counterpart); if (updates !== writes) throw new Error("older-base callback must not regress the current-base snapshot"); } + // Both producer orders must recover current-head proof even if the + // final wake is an obsolete head and all current-head wakes coalesced. + currentHeadSha = "f".repeat(40); + await callback(first); + if (!comments[0].body.includes("CodeQL gate: `failure`")) { + throw new Error("stale-head wake must reconcile live-head failure"); + } + await callback(counterpart); + currentHeadSha = headSha; currentBaseSha = "e".repeat(40); currentTuplePublished = false; await callback(first); @@ -386,6 +398,40 @@ async function assertCompletionOrders() { global.setTimeout = originalTimeout; } } +async function assertInterruptedRecovery() { + const originalPaginate = github.paginate; + const reset = () => { + currentHeadSha = headSha; currentBaseSha = baseSha; pullRequestReads = 0; + Object.assign(context.payload.workflow_run, { + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + }); + for (const values of Object.values(calls)) values.length = 0; + }; + reset(); + changeHeadDuringRun = true; + await run(github, context, core); + if (calls.updated.length || calls.created.length || calls.deleted.length) { + throw new Error("head movement during reconciliation must not write stale proof"); + } + changeHeadDuringRun = false; + reset(); + github.paginate = async () => { throw new Error("provider interrupted"); }; + let failed = false; + try { await run(github, context, core); } catch (error) { + if (error.message !== "provider interrupted") throw error; + failed = true; + } finally { github.paginate = originalPaginate; } + if (!failed || calls.updated.length || calls.created.length || calls.deleted.length) { + throw new Error("failed snapshot must propagate without publication"); + } + // A retained/pending callback or explicit rerun can recover; no false success + // or automatic retry is invented when the provider is unavailable. + await run(github, context, core); + if (calls.updated.length !== 1 || !calls.updated[0].body.includes("checks failed")) { + throw new Error("later callback must recover after interrupted reconciliation"); + } +} run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); @@ -401,11 +447,12 @@ run(github, context, core).then(async () => { throw new Error("unrelated source names must not query runs or alter comments"); } context.payload.workflow_run.name = "CodeQL Analysis"; - currentHeadSha = "d".repeat(40); + context.payload.workflow_run.head_sha = "invalid"; return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { - throw new Error("superseded source head should not query runs or alter comments"); + throw new Error("malformed source head should not query runs or alter comments"); } + context.payload.workflow_run.head_sha = headSha; currentHeadSha = headSha; currentBaseSha = baseSha; pullRequestReads = 0; @@ -461,6 +508,7 @@ run(github, context, core).then(async () => { if (error?.status !== 500) throw error; deleteStatus = null; await assertCompletionOrders(); + await assertInterruptedRecovery(); console.log("static analysis summary behavioral contract passed"); }, ); From 86bd09461ac81c5504be1cb568e3f29b7b122cb7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:52:50 +1300 Subject: [PATCH 018/199] test(account): profile abort fixture phases and remove Redis batching delay --- ...untGameSessionAbortCompositionFixture.java | 22 +++++++++++++++++++ ...CurrentSourcesPostgresIntegrationTest.java | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java index be95424631..94f33510e1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java @@ -88,6 +88,7 @@ Session openNeverAdmitted(boolean installedBootstrap) throws Exception { } final class Session implements AutoCloseable { + private long phaseStartedAt = System.nanoTime(); private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture accountFixture; final CanonicalGameplayAdmissionAbortCompositionFixture gs; @@ -122,7 +123,9 @@ private Session( boolean includeWrongPeerIdentity) throws Exception { try { + markPhase("redis_start"); accountFixture = accountFixtures.newFixture(redis.client()); + markPhase("account_fixture"); var issuance = accountFixture.committedCandidate.identity(); var credential = accountFixture.responseRecoveryOwner.recoverInitialLoginResponse( @@ -150,6 +153,7 @@ private Session( candidate.issuerIndexLayoutVersion(), candidate.issuerIndexPartitionCount(), java.math.BigInteger.valueOf(prepareMemberRepair || installedBootstrap ? 3 : 2)); + markPhase("account_credential_candidate"); gs = new CanonicalGameplayAdmissionAbortCompositionFixture( accountFixture.dataSource, @@ -157,6 +161,7 @@ private Session( redis.issuerOwnerClient(), installedBootstrap); if (prepareMemberRepair) gs.prepareMemberRepairRedis(); + markPhase("gs_fixture"); pkiDirectory = Files.createTempDirectory(temporaryDirectory, "actual-abort-mtls-"); var identities = new ArrayList<>( @@ -175,6 +180,7 @@ private Session( pkiDirectory, "Account GS abort test CA", identities.toArray(LoopbackMtlsTestPki.IdentitySpec[]::new)); + markPhase("pki_generation"); if (claimedNeverAdmitted) { gsServer = CanonicalGameplayAdmissionAbortManualFactory @@ -219,12 +225,14 @@ private Session( accountFixture.committedIssuanceOwner, Clock.systemUTC()); restartAccount(); + markPhase("mtls_servers_clients"); lease = client .acquire(requestId, jwt, gs.candidate(), gs.target(), gs.generation()) .originalLeaseEvidence(); if (claimedNeverAdmitted) gs.claimOriginalNewCandidateWithoutDispatch(lease); else gs.publish(lease); + markPhase("initial_acquire_claim"); } catch (Exception | Error setupFailure) { try { close(); @@ -412,11 +420,22 @@ CanonicalGameplayAdmissionAbortOutcome abortWith(String callerToken) { .abortFirstNew(gs.transitionId(), callerToken); } + private void markPhase(String phase) { + long now = System.nanoTime(); + if (Boolean.getBoolean("firemud.gameplay.fixture-phase-diagnostics")) { + System.out.println( + "ACCOUNT_ABORT_PHASE " + phase + " elapsed_ms=" + ((now - phaseStartedAt) / 1_000_000)); + } + phaseStartedAt = now; + } + @Override public void close() throws Exception { + markPhase("case_actions"); try { if (client != null) client.close(); if (reverse != null) reverse.close(); + markPhase("close_clients"); } finally { try { if (accountServer != null) accountServer.shutdownNow(); @@ -424,11 +443,14 @@ public void close() throws Exception { if (accountServer != null) assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); if (gsServer != null) assertThat(gsServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + markPhase("close_servers"); } finally { try { if (gs != null) gs.close(); + markPhase("close_gs"); } finally { redis.close(); + markPhase("close_redis"); } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index a36e2e21ba..3b77d05b54 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2723,7 +2723,9 @@ static final class PhysicalRedisFixture implements AutoCloseable { "--appendonly", "yes", "--appendfsync", - "always"); + "always", + "--repl-diskless-sync-delay", + "0"); private final GenericContainer replica = new GenericContainer<>(TestContainerImages.redis()) .withNetwork(network) From a585ea826dc494b5423ab0f8aa267a33e713fe49 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:04:23 +1300 Subject: [PATCH 019/199] test(account): bound container startup recreation and prove cleanup --- ...CurrentSourcesPostgresIntegrationTest.java | 3 + ...ntainerStartupRecoveryIntegrationTest.java | 75 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 3b77d05b54..9ec294910d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2701,6 +2701,7 @@ private static void writeResponseKeyring(Path root) throws Exception { /** Run-owned local primary/replica used only for the authenticated Account-owner case. */ static final class PhysicalRedisFixture implements AutoCloseable { + static final int STARTUP_ATTEMPTS = 2; private static final int REDIS_PORT = 6379; private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); private static final String PRIMARY_ALIAS = "account-gameplay-admission-primary"; @@ -2711,6 +2712,8 @@ static final class PhysicalRedisFixture implements AutoCloseable { private final Network network = Network.newNetwork(); private final GenericContainer primary = new GenericContainer<>(TestContainerImages.redis()) + // Bound startup recreation before any fixture data or application actions exist. + .withStartupAttempts(STARTUP_ATTEMPTS) .withNetwork(network) .withNetworkAliases(PRIMARY_ALIAS) .withExposedPorts(REDIS_PORT) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java new file mode 100644 index 0000000000..f8e243df4a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java @@ -0,0 +1,75 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import com.github.dockerjava.api.exception.NotFoundException; +import java.util.ArrayList; +import java.util.List; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.ContainerLaunchException; +import org.testcontainers.containers.GenericContainer; + +class AccountRedisContainerStartupRecoveryIntegrationTest { + @Test + void startupRecreatesFailedContainerBeforeFixtureUseAndRemovesBothContainers() throws Exception { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + var container = new FailingStartupContainer(1); + try (container) { + container.start(); + assertThat(container.createdIds).hasSize(2).doesNotHaveDuplicates(); + assertRemoved(container.createdIds.getFirst()); + assertThat(container.execInContainer("redis-cli", "PING").getStdout()).contains("PONG"); + assertThat(container.getContainerId()).isEqualTo(container.createdIds.getLast()); + } + container.createdIds.forEach( + AccountRedisContainerStartupRecoveryIntegrationTest::assertRemoved); + } + + @Test + void persistentStartupFailureStopsAfterTwoAttemptsAndRemovesEveryContainer() { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + var container = new FailingStartupContainer(2); + try (container) { + assertThatThrownBy(container::start) + .isInstanceOf(ContainerLaunchException.class) + .hasStackTraceContaining("injected mapped-port startup refusal"); + assertThat(container.createdIds).hasSize(2).doesNotHaveDuplicates(); + assertThat(container.getContainerId()).isNull(); + } + container.createdIds.forEach( + AccountRedisContainerStartupRecoveryIntegrationTest::assertRemoved); + } + + private static void assertRemoved(String id) { + assertThatThrownBy(() -> DockerClientFactory.instance().client().inspectContainerCmd(id).exec()) + .isInstanceOf(NotFoundException.class); + } + + private static final class FailingStartupContainer + extends GenericContainer { + private final List createdIds = new ArrayList<>(); + private final int failures; + + private FailingStartupContainer(int failures) { + super(TestContainerImages.redis()); + this.failures = failures; + withExposedPorts(6379); + withStartupAttempts( + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture + .STARTUP_ATTEMPTS); + } + + @Override + protected void waitUntilContainerStarted() { + super.waitUntilContainerStarted(); + createdIds.add(getContainerId()); + if (createdIds.size() <= failures) { + throw new ContainerLaunchException("injected mapped-port startup refusal"); + } + } + } +} From d21772ec83d369d8e82be28b5bf4c8ac1bcfa1a8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:10:24 +1300 Subject: [PATCH 020/199] test(account): use identity equality for startup fixture --- ...tRedisContainerStartupRecoveryIntegrationTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java index f8e243df4a..47532f6851 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java @@ -63,6 +63,17 @@ private FailingStartupContainer(int failures) { .STARTUP_ATTEMPTS); } + // A test-owned running container is an identity, not a value of its mutable attempt history. + @Override + public boolean equals(Object other) { + return this == other; + } + + @Override + public int hashCode() { + return System.identityHashCode(this); + } + @Override protected void waitUntilContainerStarted() { super.waitUntilContainerStarted(); From 06d2b5614516e804ef87a98882bc5279f6910115 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:20:58 +1300 Subject: [PATCH 021/199] ci: supersede obsolete same-repository PR runtime builds --- .github/workflows/runtime-images.yml | 4 +- .../pr-runtime-image-publication-contract.sh | 89 +++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index d3d85fa62b..01d906d090 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -54,8 +54,10 @@ run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || githu permissions: contents: read +# Same-repository PR edits supersede obsolete local builds. Dispatch and fork +# inputs retain exact-tuple isolation because cancellation precedes admission. 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' }} + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && format('pr-{0}', github.event.pull_request.number)) || (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: diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 803550a80f..300d1718fe 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -6,6 +6,95 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" WORKFLOW="$ROOT_DIR/.github/workflows/publish-pr-runtime-images.yml" RUNTIME_WORKFLOW="$ROOT_DIR/.github/workflows/runtime-images.yml" +# Evaluate the workflow's actual string/boolean concurrency expression against fixed event fixtures. +# This bounded expression uses only property reads, equality, boolean operators and format. +python3 - "$RUNTIME_WORKFLOW" <<'PY_CONCURRENCY' +import copy +import re +import sys +from pathlib import Path + +source = Path(sys.argv[1]).read_text() +group = re.search(r"^ group: (runtime-images-.*)$", source, re.MULTILINE).group(1) +assert re.search(r"^ cancel-in-progress: true$", source, re.MULTILINE) + +class Context: + def __init__(self, value=None): + self.value = value + def __getattr__(self, key): + value = self.value.get(key) if isinstance(self.value, dict) else None + return Context(value) if isinstance(value, dict) or value is None else value + def __bool__(self): + return bool(self.value) + def __eq__(self, other): + return (self.value or "") == (other or "") + def __str__(self): + return "" if self.value is None else str(self.value) + +base = { + "event_name": "pull_request", "workflow": "Build Runtime Images", + "repository": "owner/repo", "run_id": 100, "sha": "merge1", "ref": "refs/pull/7/merge", + "event": {"action": "synchronize", "pull_request": { + "number": 7, "base": {"sha": "base1"}, + "head": {"sha": "head1", "repo": {"full_name": "owner/repo"}}}}, +} + +def evaluate(event): + def expression(match): + code = match.group(1).replace("&&", " and ").replace("||", " or ") + code = re.sub(r"\bnull\b", "None", code) + # Only the checked-in expression is code; event values remain data. + return str(eval(code, {"__builtins__": {}}, { + "github": Context(event), "format": lambda template, *args: template.format(*args)})) + return re.sub(r"\$\{\{(.*?)\}\}", expression, group) + +def check(event, suffix): + expected = "runtime-images-Build Runtime Images-" + suffix + assert evaluate(event) == expected, (evaluate(event), expected) + +check(base, "pr-7-required") +new = copy.deepcopy(base) +new["event"]["pull_request"]["head"]["sha"] = "head2" +new["event"]["pull_request"]["base"]["sha"] = "base2" +new["sha"] = "merge2" +check(new, "pr-7-required") +new["event"]["pull_request"]["number"] = 8 +check(new, "pr-8-required") +for action in ["opened", "reopened", "ready_for_review", "synchronize"]: + event = copy.deepcopy(base) + event["event"]["action"] = action + check(event, "pr-7-required") +metadata = copy.deepcopy(base) +metadata["event"]["action"] = "edited" +check(metadata, "pr-7-metadata") +metadata["event"]["changes"] = {"base": {"ref": {"from": "old-base"}}} +check(metadata, "pr-7-required") +for repository in ["fork/repo", None]: + fork = copy.deepcopy(base) + fork["event"]["pull_request"]["head"]["repo"] = {"full_name": repository} + check(fork, "pr-7-base-base1-head-head1-merge-merge1-required") + fork["event"]["pull_request"]["head"]["sha"] = "head2" + check(fork, "pr-7-base-base1-head-head2-merge-merge1-required") +dispatch = {**base, "event_name": "repository_dispatch", "event": { + "action": "pr-runtime-base-refresh", "client_payload": { + "pr_number": 7, "base_sha": "base1", "head_sha": "head1", "merge_sha": "merge1"}}} +check(dispatch, "pr-7-base-base1-head-head1-merge-merge1-required") +for missing in ["pr_number", "base_sha", "head_sha", "merge_sha"]: + invalid = copy.deepcopy(dispatch) + del invalid["event"]["client_payload"][missing] + check(invalid, "repository-dispatch-run-100-required") +dispatch["event"]["client_payload"]["head_sha"] = "head2" +check(dispatch, "pr-7-base-base1-head-head2-merge-merge1-required") +callback = {**base, "event_name": "workflow_run", "event": { + "workflow_run": {"event": "pull_request", "id": 90, "run_attempt": 2}}} +check(callback, "ci-pr-run-90-attempt-2-required") +callback["event"]["workflow_run"] = {"event": "push", "head_branch": "develop"} +check(callback, "branch-develop-required") +check({**base, "event_name": "push", "event": {}, "ref": "refs/heads/develop"}, + "refs/heads/develop-required") +print("Runtime concurrency: same-repository PR supersession; fork/dispatch/branch isolation passed") +PY_CONCURRENCY + require_contains() { local expected="$1" grep -Fq -- "$expected" "$WORKFLOW" || { From 599b741405fe66ff0c53cc02f04651cc518f677a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:37:14 +1300 Subject: [PATCH 022/199] ci: bind smoke to reviewed runtime concurrency definition --- .github/workflows/smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e17d781603..063654d948 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; + const canonicalRuntimeWorkflowSha256 = "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e"; // 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. From c0efeb064c523b1d0a0e9fe8dcd197b8608beb93 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:16:30 +1300 Subject: [PATCH 023/199] Clarify pinned YAML setup step without duplicate version authority --- .github/workflows/protected-pod-admission-proof.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 59e460e4e8..f5cc9460e5 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -29,7 +29,7 @@ jobs: ref: 60c507243987705094a3028e0b46f3bccd5d9504 persist-credentials: false - - name: Set up repository-pinned Python and PyYAML + - name: Set up repository-pinned Python YAML tooling uses: ./.github/actions/setup-python with: requirements: yaml From fe97e9f84b932a3c6fa836b5fe8d06018b0965ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:06:05 +1300 Subject: [PATCH 024/199] Isolate read-only preview concurrency during trigger transition --- .github/workflows/preview.yml | 4 ++-- dev-tools/tests/preview-runner-isolation-contract.sh | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index e325902c02..8d7a959bde 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest if: ${{ github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.repo.full_name == github.repository && (github.event.action != 'labeled' && github.event.action != 'unlabeled' || github.event.label.name == 'preview:priority') && (github.event.action != 'edited' || github.event.changes.base != null)) }} concurrency: - group: preview-plan-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} + group: preview-readonly-plan-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }} cancel-in-progress: true outputs: action: ${{ steps.derive.outputs.action }} @@ -514,7 +514,7 @@ jobs: permissions: contents: read concurrency: - group: preview-render-${{ needs.preview-plan.outputs.pr_number }} + group: preview-readonly-render-${{ needs.preview-plan.outputs.pr_number }} cancel-in-progress: true steps: - name: Harden runner diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 251419c88f..b82fc2d471 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -305,6 +305,16 @@ def check_preview_source_permissions(job_name: str, job: dict[str, Any]) -> None ) +# During the approved event-policy transition, the old default-branch +# pull_request_target workflow still exists. It must not cancel the new read-only +# plan/render, while successive runs within the new mode still supersede. +for job_name, prefix in (("preview-plan", "preview-readonly-plan-"), ("preview-render", "preview-readonly-render-")): + concurrency = preview_jobs[job_name].get("concurrency", {}) + assert concurrency.get("cancel-in-progress") is True + group = concurrency.get("group", "") + assert group.startswith(prefix) and "${{" in group + assert "github.event.pull_request.number" in group if job_name == "preview-plan" else "needs.preview-plan.outputs.pr_number" in group + for job_name, job in preview_jobs.items(): if not isinstance(job, dict): raise AssertionError(f"preview job {job_name} is not a mapping") From e6c94db8ed706cd842ec43d82146ae1dd7e2f332 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:27:56 +1300 Subject: [PATCH 025/199] test: align retarget contract with isolated preview concurrency --- dev-tools/tests/pr-retarget-workflow-contract.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e1eb0cc0e0..d620be5987 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1630,7 +1630,7 @@ if grep -Eq '^concurrency:' "$preview_path"; then echo "Preview workflow must not cancel an active lifecycle from workflow-level concurrency" >&2 exit 1 fi -assert_job_contains preview.yml preview-plan "group: preview-plan-\${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" +assert_job_contains preview.yml preview-plan "group: preview-readonly-plan-\${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number || github.ref }}" assert_job_contains preview.yml preview-plan 'cancel-in-progress: true' assert_job_excludes preview.yml preview-plan 'Publish preview lifecycle state' assert_job_excludes preview.yml preview-plan 'firemud-preview-summary' From 151656945bfcc37f19abd3c0543a47e0f9954e2e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:31:55 +1300 Subject: [PATCH 026/199] Preserve raw recovery request limits and validated UTF-8 parsing --- .../recovery/InitialGameplayRecoverCodec.java | 20 ++++++++++++------- .../InitialGameplayRecoverCodecTest.java | 19 +++++++++++++++++- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java index 2441a520ff..fb1ca618fc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java @@ -59,16 +59,19 @@ private InitialGameplayRecoverCodec() {} public static InitialGameplayRecoverRequest decode(byte[] raw) { Objects.requireNonNull(raw, "raw"); if (raw.length > MAX_RAW_BYTES) throw invalid(); + final String decoded; try { - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(raw)); + decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(raw)) + .toString(); } catch (CharacterCodingException exception) { throw new IllegalArgumentException("Recover request must be valid UTF-8", exception); } - try (JsonParser parser = JSON.createParser(raw)) { + try (JsonParser parser = JSON.createParser(decoded)) { require(parser.nextToken(), JsonToken.START_OBJECT); literal( parser, "actionFamilySchemaId", InitialGameplayRecoverRequest.ACTION_FAMILY_SCHEMA_ID); @@ -272,7 +275,10 @@ private static void segment(ByteArrayOutputStream output, byte[] bytes) { private static String string(JsonParser parser, String name) throws IOException { member(parser, name); require(parser.nextToken(), JsonToken.VALUE_STRING); - return InitialGameplayRecoverRequest.text(parser.getText(), MAX_RAW_STRING_CHARACTERS); + String raw = parser.getText(); + InitialGameplayRecoverRequest.text(raw, MAX_RAW_STRING_CHARACTERS); + // Field constructors must see the original value to enforce their raw byte limits. + return raw; } private static void literal(JsonParser parser, String name, String value) throws IOException { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java index 91c2fbe9a8..c6388e77a7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java @@ -112,7 +112,7 @@ void rejectsUnknownDuplicateMissingAndOutOfOrderFields() { WIRE.replace( "\"storageIdentity\":\"pg\",\"storageRevision\":\"1\"", "\"storageRevision\":\"1\",\"storageIdentity\":\"pg\"")); - rejects(WIRE.replace("\"detail\"", "\"deta\\u0069l\",\"detail\"")); + rejects(WIRE.replace("\"detail\"", "\"deta\\u0069l\":\"first\",\"detail\"")); } @Test @@ -154,6 +154,23 @@ void rejectsNoncanonicalIdsWrongTypesMalformedUnicodeAndOverlimits() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void rejectsRawFieldsThatShrinkBelowTheirLimitOnlyAfterNormalization() { + rejects(WIRE.replace("\"world\"", "\"" + "e\u0301".repeat(43) + "\"")); + rejects(WIRE.replace("\"initial\"", "\"" + "e\u0301".repeat(342) + "\"")); + } + + @Test + void rejectsUtf16AndUtf32EvenWhenTheirBytesAreValidUtf8() { + for (String encoding : List.of("UTF-16BE", "UTF-16LE", "UTF-32BE", "UTF-32LE")) { + assertThatThrownBy( + () -> + InitialGameplayRecoverCodec.decode( + WIRE.getBytes(java.nio.charset.Charset.forName(encoding)))) + .isInstanceOf(IllegalArgumentException.class); + } + } + private static InitialGameplayRecoverRequest decode(String wire) { return InitialGameplayRecoverCodec.decode(wire.getBytes(StandardCharsets.UTF_8)); } From c24dc94efc7e7dd58405a9b26084dafa7c8cf4a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:33:19 +1300 Subject: [PATCH 027/199] Reject malformed recovery owner results and redact credential errors --- .../model/MaintenanceLockCredential.java | 2 +- .../InitialGameplayReleaseEffectPort.java | 3 +++ .../InitialGameplayReleaseEvidenceProvider.java | 2 ++ .../model/InitialGameplayReleaseModelTest.java | 9 +++++++++ .../InitialGameplayReleaseControllerTest.java | 16 ++++++++++++++++ 5 files changed, 31 insertions(+), 1 deletion(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java index b4e546c984..9fa66bf5db 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/MaintenanceLockCredential.java @@ -24,7 +24,7 @@ public static MaintenanceLockCredential fromProtectedTransport(String token) { } return new MaintenanceLockCredential(identity); } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("maintenance-lock credential is invalid", exception); + throw new IllegalArgumentException("maintenance-lock credential is invalid"); } } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 40571e3b2a..f902b05e0d 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.recovery.service; import java.time.Instant; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TypedEffect; @@ -15,6 +16,7 @@ public interface InitialGameplayReleaseEffectPort { record EffectApplyResult(ApplyStatus status, String outcomeCode) { public EffectApplyResult { + Objects.requireNonNull(status, "status"); if (status == ApplyStatus.RETRYABLE_NO_EFFECT || status == ApplyStatus.AMBIGUOUS) { if (outcomeCode == null || outcomeCode.isBlank()) { throw new IllegalArgumentException( @@ -45,6 +47,7 @@ enum ApplyStatus { record EffectReadbackResolution( ReadbackStatus status, EffectReadback readback, Instant observedAt) { public EffectReadbackResolution { + Objects.requireNonNull(status, "status"); if ((status == ReadbackStatus.AVAILABLE) != (readback != null)) { throw new IllegalArgumentException("readback must be present exactly for AVAILABLE"); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java index 2b225e3354..181b50e10e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEvidenceProvider.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.recovery.service; +import java.util.Objects; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; @@ -11,6 +12,7 @@ public interface InitialGameplayReleaseEvidenceProvider { record EvidenceResolution(ResolutionStatus status, InitialGameplayReleaseEvidence evidence) { public EvidenceResolution { + Objects.requireNonNull(status, "status"); if ((status == ResolutionStatus.AVAILABLE) != (evidence != null)) { throw new IllegalArgumentException("evidence must be present exactly for AVAILABLE"); } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index 07f28d81e9..bf61fc1d3d 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -408,6 +408,15 @@ void maintenanceLockCredentialRedactsItsWireValueFromDefaultRendering() { assertThat(credential.protectedTransportValue()).isEqualTo(lockIdentity.toString()); } + @Test + void invalidMaintenanceCredentialDoesNotLeakThroughExceptionCause() { + assertThatThrownBy( + () -> MaintenanceLockCredential.fromProtectedTransport("secret-invalid-credential")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maintenance-lock credential is invalid") + .hasNoCause(); + } + private static Scope scope(UUID playableNamespace) { return new Scope( UUID.randomUUID(), diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 6b180ed04f..5bb468c25e 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -25,6 +25,22 @@ class InitialGameplayReleaseControllerTest { private static final String DIGEST = "c".repeat(64); + @Test + void ownerResultsRejectMissingStatus() { + assertThatThrownBy( + () -> new InitialGameplayReleaseEvidenceProvider.EvidenceResolution(null, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new InitialGameplayReleaseEffectPort.EffectApplyResult(null, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> new InitialGameplayReleaseEffectPort.EffectReadbackResolution(null, null, null)) + .isInstanceOf(NullPointerException.class); + assertThat(InitialGameplayReleaseEvidenceProvider.EvidenceResolution.unavailable().status()) + .isEqualTo(ResolutionStatus.UNAVAILABLE); + assertThat(InitialGameplayReleaseEffectPort.EffectApplyResult.applied().status()) + .isEqualTo(InitialGameplayReleaseEffectPort.ApplyStatus.APPLIED); + } + @Test void validTypedRecoverDeniesBeforeAnyJournalEvidenceOrEffectInteraction() { InitialGameplayReleaseJournal journal = mock(InitialGameplayReleaseJournal.class); From 1cf160d5dbb6462ca3b04c36ce39cbc15bfe7549 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:41:35 +1300 Subject: [PATCH 028/199] Preserve recovery attempt identity and coherent journal readbacks --- .../InitialGameplayReleaseTupleCodec.java | 11 +- .../JooqInitialGameplayReleaseJournal.java | 44 +++++--- .../model/InitialGameplayReleaseModel.java | 8 ++ .../InitialGameplayReleaseController.java | 17 +-- .../InitialGameplayReleaseEffectPort.java | 6 +- .../V1__initial_gameplay_release_journal.sql | 1 + ...ReleaseJournalPostgresIntegrationTest.java | 31 +++++- .../InitialGameplayReleaseModelTest.java | 10 ++ .../InitialGameplayReleaseControllerTest.java | 103 ++++++++++++++++++ 9 files changed, 200 insertions(+), 31 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 2edde5af5c..7ac6053fd7 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -10,16 +10,19 @@ import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; import org.springframework.stereotype.Component; import tools.jackson.core.JacksonException; +import tools.jackson.core.json.JsonWriteFeature; import tools.jackson.databind.ObjectMapper; /** Stable JSON and digest encoding for the operation-owned immutable tuples. */ @Component public final class InitialGameplayReleaseTupleCodec { private final ObjectMapper objectMapper; + private final tools.jackson.databind.ObjectWriter digestMapper; public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null").rebuild().build(); + this.digestMapper = this.objectMapper.writer().with(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } public String toJson(Object value) { @@ -33,7 +36,11 @@ public String toJson(Object value) { public String digest(Object value) { final byte[] canonical; try { - canonical = Rfc8785CanonicalJson.canonicalizeUtf8(toJson(value)); + // Digest encoding preserves full-width integer identities instead of JCS binary64 rounding. + canonical = + Rfc8785CanonicalJson.canonicalizeUtf8( + digestMapper.writeValueAsString( + new DigestTuple("initial-gameplay-release-tuple/v2", value))); } catch (IOException exception) { throw new IllegalArgumentException( "Initial gameplay release tuple is not canonical JSON", exception); @@ -45,6 +52,8 @@ public String digest(Object value) { } } + private record DigestTuple(String schema, Object value) {} + public String operationTupleDigest( Scope scope, java.util.UUID maintenanceLockIdentity, diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index cf94d3adc5..5b8172999e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -15,7 +15,6 @@ import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TypedEffect; import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredDigest; -import static net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredText; import java.time.Instant; import java.time.OffsetDateTime; @@ -86,7 +85,7 @@ ON CONFLICT (operation_id) DO NOTHING @Override public Optional find(UUID operationId) { Objects.requireNonNull(operationId, "operationId must not be null"); - return Optional.ofNullable(selectOperation(dsl, operationId, false)); + return Optional.ofNullable(selectOperationOrNull(dsl, operationId, false)); } @Override @@ -210,17 +209,21 @@ public Operation transition(PublicTransitionTuple tuple, Instant now) { @Override public Optional findTransition(PublicTransitionTuple tuple) { Objects.requireNonNull(tuple, "tuple must not be null"); - Operation operation = selectOperation(dsl, tuple.operationId(), false); - requireTransitionMatchesOperation(tuple, operation); Record previous = dsl.fetchOne( - "SELECT tuple_digest FROM " + TRANSITION_TABLE + " WHERE operation_id = ? AND verb = ?", + "SELECT o.*, t.tuple_digest AS transition_digest FROM recovery_control.initial_gameplay_release_operation o " + + "JOIN " + + TRANSITION_TABLE + + " t ON t.operation_id=o.operation_id " + + "WHERE o.operation_id=? AND t.verb=?", tuple.operationId(), tuple.verb().wireValue()); if (previous == null) { return Optional.empty(); } - if (!tupleCodec.digest(tuple).equals(previous.get("tuple_digest", String.class))) { + Operation operation = toOperation(previous); + requireTransitionMatchesOperation(tuple, operation); + if (!tupleCodec.digest(tuple).equals(previous.get("transition_digest", String.class))) { throw conflict("public transition tuple changed"); } return Optional.of(operation); @@ -263,13 +266,14 @@ public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, """ UPDATE recovery_control.initial_gameplay_release_outbox SET state = 'dispatched', attempt_count = attempt_count + 1, - last_attempt_id = ?, last_outcome_code = NULL, + last_attempt_id = ?, last_dispatched_at = CAST(? AS timestamptz), last_outcome_code = NULL, readback_identity = NULL, readback_payload = NULL, readback_digest = NULL, updated_at = CAST(? AS timestamptz) WHERE operation_id = ? AND effect_id = ? AND state IN ('pending', 'retryable') """, attemptId, toOffsetDateTime(now), + toOffsetDateTime(now), operationId, effectId); if (changed != 1) { @@ -300,10 +304,7 @@ private OutboxEntry recordNonterminalEffectOutcome( String outcomeCode, EffectOutboxState resultState, Instant now) { - requiredText(outcomeCode, "outcomeCode"); - if (!outcomeCode.matches("[A-Z0-9_]{1,64}")) { - throw new IllegalArgumentException("outcomeCode must be a bounded uppercase code"); - } + InitialGameplayReleaseModel.requiredOutcomeCode(outcomeCode); return dsl.transactionResult( configuration -> { DSLContext tx = DSL.using(configuration); @@ -311,7 +312,7 @@ private OutboxEntry recordNonterminalEffectOutcome( if (current.lastAttemptId() != null && !current.lastAttemptId().equals(attemptId)) { throw conflict("effect attempt identity changed"); } - if (current.state() == resultState) { + if (current.state() == resultState || current.state() == EffectOutboxState.ACKNOWLEDGED) { return current; } if (current.state() != EffectOutboxState.DISPATCHED) { @@ -371,7 +372,7 @@ public Operation recordEffectReadback( } Record timestamps = tx.fetchOne( - "SELECT updated_at FROM " + "SELECT last_dispatched_at FROM " + OUTBOX_TABLE + " WHERE operation_id = ? AND effect_id = ?", operationId, @@ -379,7 +380,7 @@ public Operation recordEffectReadback( if (timestamps == null) { throw conflict("effect dispatch timestamp is unavailable"); } - OffsetDateTime dispatchTime = timestamps.get("updated_at", OffsetDateTime.class); + OffsetDateTime dispatchTime = timestamps.get("last_dispatched_at", OffsetDateTime.class); if (dispatchTime == null) { throw conflict("effect dispatch timestamp is unavailable"); } @@ -527,6 +528,14 @@ private String operationTupleDigest(Operation operation) { } private Operation selectOperation(DSLContext context, UUID operationId, boolean forUpdate) { + Operation operation = selectOperationOrNull(context, operationId, forUpdate); + if (operation == null) { + throw new IllegalArgumentException("INITIAL_GAMEPLAY_RELEASE_NOT_FOUND"); + } + return operation; + } + + private Operation selectOperationOrNull(DSLContext context, UUID operationId, boolean forUpdate) { Record record = context.fetchOne( """ @@ -539,9 +548,10 @@ private Operation selectOperation(DSLContext context, UUID operationId, boolean """ + (forUpdate ? " FOR UPDATE" : ""), operationId); - if (record == null) { - throw new IllegalArgumentException("INITIAL_GAMEPLAY_RELEASE_NOT_FOUND"); - } + return record == null ? null : toOperation(record); + } + + private Operation toOperation(Record record) { JSONB scopeJson = record.get("scope_payload", JSONB.class); JSONB evidenceJson = record.get("evidence_snapshot", JSONB.class); JSONB bindingJson = record.get("peer_storage_binding", JSONB.class); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java index 7b8cceb418..695853736a 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java @@ -756,6 +756,14 @@ private static String requiredNamespace(String value, String name) { return value; } + public static String requiredOutcomeCode(String value) { + requiredText(value, "outcomeCode"); + if (!value.matches("[A-Z0-9_]{1,64}")) { + throw new IllegalArgumentException("outcomeCode must be a bounded uppercase code"); + } + return value; + } + public static String requiredText(String value, String name) { Objects.requireNonNull(value, name + " must not be null"); if (value.isBlank()) { diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index cd0752ce14..2df4beb588 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.recovery.service; import java.time.Clock; +import java.time.Instant; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -115,7 +116,7 @@ public Operation reconcileNextEffect(UUID operationId) { Operation operation = requireOperation(operationId); Optional next = journal.findNextEffect(operationId); if (next.isEmpty()) { - return operation; + return requireOperation(operationId); } OutboxEntry outbox = next.orElseThrow(); if (outbox.state() == EffectOutboxState.PENDING @@ -139,7 +140,8 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { } final EffectApplyResult applyResult; try { - applyResult = effectPort.apply(dispatched.effect(), attemptId); + applyResult = + Objects.requireNonNull(effectPort.apply(dispatched.effect(), attemptId), "applyResult"); } catch (RuntimeException exception) { journal.recordAmbiguousEffect( operation.scope().operationId(), @@ -185,16 +187,15 @@ private Operation readBackEffect(Operation operation, OutboxEntry outbox, UUID a return operation; } EffectReadback readback = resolution.readback(); - if (resolution.observedAt().isBefore(readback.observedAt())) { + Instant now = clock.instant(); + if (resolution.observedAt().isBefore(readback.observedAt()) + || resolution.observedAt().isAfter(now) + || readback.observedAt().isAfter(now)) { throw new InitialGameplayReleaseConflictException( "IDEMPOTENCY_CONFLICT: effect readback observation time changed"); } return journal.recordEffectReadback( - operation.scope().operationId(), - outbox.effect().effectId(), - attemptId, - readback, - clock.instant()); + operation.scope().operationId(), outbox.effect().effectId(), attemptId, readback, now); } private Operation transition( diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index f902b05e0d..7058891d76 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -18,10 +18,8 @@ record EffectApplyResult(ApplyStatus status, String outcomeCode) { public EffectApplyResult { Objects.requireNonNull(status, "status"); if (status == ApplyStatus.RETRYABLE_NO_EFFECT || status == ApplyStatus.AMBIGUOUS) { - if (outcomeCode == null || outcomeCode.isBlank()) { - throw new IllegalArgumentException( - "non-success apply outcomes require a typed outcome code"); - } + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredOutcomeCode( + outcomeCode); } } diff --git a/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql b/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql index f6c2f010f3..d79b02b39e 100644 --- a/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql +++ b/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql @@ -61,6 +61,7 @@ CREATE TABLE recovery_control.initial_gameplay_release_outbox ( CHECK (state IN ('pending', 'dispatched', 'retryable', 'ambiguous', 'acknowledged')), attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), last_attempt_id UUID, + last_dispatched_at TIMESTAMPTZ, last_outcome_code VARCHAR(64), readback_identity TEXT, readback_payload JSONB, diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 7516f977cc..95ec45bb09 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -113,6 +113,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() assertThat(created.phase()).isEqualTo(Phase.COLLECTING); assertThat(duplicateCreate.maintenanceLockIdentity()).isEqualTo(lockIdentity); assertThat(journal.find(created.scope().operationId())).contains(created); + assertThat(journal.find(UUID.randomUUID())).isEmpty(); InitialGameplayReleaseEvidence proof = evidence(scope); Operation ready = @@ -125,6 +126,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() assertThat(journal.findTransition(continueTuple)).isEmpty(); Operation awaitingResume = journal.transition(continueTuple, base.plusSeconds(2)); assertThat(awaitingResume.phase()).isEqualTo(Phase.AWAITING_RESUME); + assertThat(journal.findTransition(continueTuple)).contains(awaitingResume); assertThat(journal.transition(continueTuple, base.plusSeconds(3))).isEqualTo(awaitingResume); PublicTransitionTuple resumeTuple = transitionTuple(awaitingResume, TransitionVerb.RESUME); @@ -151,6 +153,12 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, "gamesession-preparation-readback-1", base.plusSeconds(6)); + journal.recordAmbiguousEffect( + scope.operationId(), + prepare.effect().effectId(), + prepareAttempt, + "TRANSPORT_OUTCOME_UNKNOWN", + base.plusSeconds(7)); Operation releasing = journal.recordEffectReadback( scope.operationId(), @@ -159,6 +167,26 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() prepareReadback, base.plusSeconds(7)); assertThat(releasing.phase()).isEqualTo(Phase.RELEASING); + assertThat( + journal + .recordAmbiguousEffect( + scope.operationId(), + prepare.effect().effectId(), + prepareAttempt, + "LATE_TRANSPORT_OUTCOME_UNKNOWN", + base.plusSeconds(8)) + .state()) + .isEqualTo(EffectOutboxState.ACKNOWLEDGED); + UUID preparedEffectId = prepare.effect().effectId(); + assertThatThrownBy( + () -> + journal.recordAmbiguousEffect( + scope.operationId(), + preparedEffectId, + UUID.randomUUID(), + "WRONG_ATTEMPT", + base.plusSeconds(8))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) .get() .extracting(OutboxEntry::state) @@ -260,7 +288,8 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(retryRead.state()).isEqualTo(EffectOutboxState.AMBIGUOUS); assertThat(retryRead.lastAttemptId()).isEqualTo(attemptId); assertThat(retryRead.attemptCount()).isEqualTo(1); - assertThat(authorized.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); + assertThat(journal.find(scope.operationId()).orElseThrow().phase()) + .isEqualTo(Phase.RESUME_AUTHORIZED); } @Test diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index bf61fc1d3d..c399a1e864 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -417,6 +417,16 @@ void invalidMaintenanceCredentialDoesNotLeakThroughExceptionCause() { .hasNoCause(); } + @Test + void tupleDigestPreservesFullWidthExecutorGeneration() { + InitialGameplayReleaseTupleCodec codec = + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + RegionLeaseProof first = new RegionLeaseProof("region", "lease", 9007199254740992L); + RegionLeaseProof next = new RegionLeaseProof("region", "lease", 9007199254740993L); + assertThat(codec.digest(first)).isNotEqualTo(codec.digest(next)); + assertThat(codec.toJson(next)).contains("9007199254740993"); + } + private static Scope scope(UUID playableNamespace) { return new Scope( UUID.randomUUID(), diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 5bb468c25e..45e436ca7b 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -2,8 +2,12 @@ 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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; import java.util.UUID; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest; @@ -131,4 +135,103 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { assertThat(port.readback(effect, UUID.randomUUID()).status()) .isEqualTo(InitialGameplayReleaseEffectPort.ReadbackStatus.UNAVAILABLE); } + + @Test + void applyOutcomeCodesUseJournalContract() { + for (String invalid : + java.util.List.of("owner_busy", "owner-unavailable", "X".repeat(65), "")) { + assertThatThrownBy( + () -> InitialGameplayReleaseEffectPort.EffectApplyResult.retryableNoEffect(invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> InitialGameplayReleaseEffectPort.EffectApplyResult.ambiguous(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + InitialGameplayReleaseEffectPort.EffectApplyResult.retryableNoEffect("OWNER_BUSY") + .outcomeCode()) + .isEqualTo("OWNER_BUSY"); + } + + @Test + void emptyOutboxReloadsLatestOperation() { + var journal = mock(InitialGameplayReleaseJournal.class); + var operationId = UUID.randomUUID(); + var before = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + var after = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + when(journal.find(operationId)) + .thenReturn(java.util.Optional.of(before), java.util.Optional.of(after)); + when(journal.findNextEffect(operationId)).thenReturn(java.util.Optional.empty()); + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + mock(InitialGameplayReleaseEvidenceProvider.class), + mock(InitialGameplayReleaseEffectPort.class)); + assertThat(controller.reconcileNextEffect(operationId)).isSameAs(after); + } + + @Test + void futureDatedOwnerReadbackCannotAdvanceJournal() { + var journal = mock(InitialGameplayReleaseJournal.class); + var effectPort = mock(InitialGameplayReleaseEffectPort.class); + var scope = + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-1", "recovery-peer", "storage-1", "revision-1", DIGEST), + "evidence"); + var operation = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + when(operation.scope()).thenReturn(scope); + var effect = + new PreparePlayableStateFencedEffect( + scope.operationId(), UUID.randomUUID(), UUID.randomUUID(), scope, DIGEST, "proof"); + var attempt = UUID.randomUUID(); + var outbox = + new net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry( + UUID.randomUUID(), + effect, + DIGEST, + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState + .DISPATCHED, + 1, + attempt, + null, + null); + var now = java.time.Instant.parse("2026-11-18T12:00:00Z"); + var readback = + new net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback( + scope.operationId(), + effect.effectId(), + effect.kind(), + DIGEST, + DIGEST, + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackState + .PREPARED_FENCED, + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel + .EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + "readback", + now.plusSeconds(1)); + when(journal.find(scope.operationId())).thenReturn(java.util.Optional.of(operation)); + when(journal.findNextEffect(scope.operationId())).thenReturn(java.util.Optional.of(outbox)); + when(effectPort.readback(effect, attempt)) + .thenReturn(InitialGameplayReleaseEffectPort.EffectReadbackResolution.available(readback)); + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + mock(InitialGameplayReleaseEvidenceProvider.class), + effectPort, + java.time.Clock.fixed(now, java.time.ZoneOffset.UTC)); + assertThatThrownBy(() -> controller.reconcileNextEffect(scope.operationId())) + .isInstanceOf( + net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException.class); + verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); + } } From 34e120babf9da6bf35888d370ff59d6f1cbf57e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:50:15 +1300 Subject: [PATCH 029/199] Bind recovery readback to terminal owner attempt proof --- .../InitialGameplayReleaseTupleCodec.java | 5 +- .../JooqInitialGameplayReleaseJournal.java | 10 ++-- .../model/InitialGameplayReleaseModel.java | 14 +++++- .../InitialGameplayReleaseEffectPort.java | 5 ++ ...ReleaseJournalPostgresIntegrationTest.java | 38 +++++++++++++++ .../InitialGameplayReleaseModelTest.java | 46 +++++++++++++++++++ .../InitialGameplayReleaseControllerTest.java | 1 + 7 files changed, 111 insertions(+), 8 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 7ac6053fd7..ec8bb24b15 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -21,7 +21,10 @@ public final class InitialGameplayReleaseTupleCodec { public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { this.objectMapper = - Objects.requireNonNull(objectMapper, "objectMapper must not be null").rebuild().build(); + Objects.requireNonNull(objectMapper, "objectMapper must not be null") + .rebuild() + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .build(); this.digestMapper = this.objectMapper.writer().with(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 5b8172999e..9c2f1be77f 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -315,14 +315,16 @@ private OutboxEntry recordNonterminalEffectOutcome( if (current.state() == resultState || current.state() == EffectOutboxState.ACKNOWLEDGED) { return current; } - if (current.state() != EffectOutboxState.DISPATCHED) { + if (current.state() != EffectOutboxState.DISPATCHED + && !(current.state() == EffectOutboxState.AMBIGUOUS + && resultState == EffectOutboxState.RETRYABLE)) { throw conflict("effect is not in a dispatchable attempt"); } tx.execute( """ UPDATE recovery_control.initial_gameplay_release_outbox SET state = ?, last_outcome_code = ?, updated_at = CAST(? AS timestamptz) - WHERE operation_id = ? AND effect_id = ? AND state = 'dispatched' + WHERE operation_id = ? AND effect_id = ? AND state IN ('dispatched', 'ambiguous') AND last_attempt_id = ? """, resultState.databaseValue(), @@ -650,10 +652,8 @@ private void requireReadbackMatches( if (!readback.operationId().equals(operationId) || !readback.operationId().equals(outbox.effect().operationId()) || !readback.effectId().equals(effectId) + || !readback.attemptId().equals(outbox.lastAttemptId()) || readback.effectKind() != outbox.effect().kind() - || readback.authority() - != InitialGameplayReleaseModel.EffectReadbackAuthority - .GAME_SESSION_DURABLE_CURRENT_STATE || !readback.operationTupleDigest().equals(outbox.effect().operationTupleDigest()) || !readback.payloadDigest().equals(outbox.payloadDigest())) { throw conflict("effect readback does not match the exact dispatched tuple"); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java index 695853736a..912f46c967 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java @@ -157,7 +157,9 @@ public enum EffectReadbackState { } public enum EffectReadbackAuthority { - GAME_SESSION_DURABLE_CURRENT_STATE + GAME_SESSION_DURABLE_CURRENT_STATE, + // Owner has durably closed this exact attempt against any delayed apply. + GAME_SESSION_DURABLE_CLOSED_ATTEMPT } public record PeerStorageBinding( @@ -286,7 +288,8 @@ public List partitionIds() { } public record PartitionAcknowledgement( - int partitionId, + @com.fasterxml.jackson.annotation.JsonProperty(value = "partitionId", required = true) + int partitionId, String acknowledgementIdentity, String acknowledgedLayoutDigest, String readbackDigest, @@ -687,6 +690,7 @@ public String toString() { public record EffectReadback( UUID operationId, UUID effectId, + UUID attemptId, EffectKind effectKind, String operationTupleDigest, String payloadDigest, @@ -695,6 +699,7 @@ public record EffectReadback( String readbackIdentity, Instant observedAt) { public EffectReadback { + attemptId = requiredUuid(attemptId, "attemptId"); operationId = requiredUuid(operationId, "operationId"); effectId = requiredUuid(effectId, "effectId"); Objects.requireNonNull(effectKind, "effectKind must not be null"); @@ -702,6 +707,11 @@ public record EffectReadback( payloadDigest = requiredDigest(payloadDigest, "payloadDigest"); Objects.requireNonNull(state, "state must not be null"); Objects.requireNonNull(authority, "authority must not be null"); + if ((state == EffectReadbackState.PROVEN_NO_EFFECT) + != (authority == EffectReadbackAuthority.GAME_SESSION_DURABLE_CLOSED_ATTEMPT)) { + throw new IllegalArgumentException( + "No-effect proof requires durable closure of the exact owner attempt"); + } readbackIdentity = requiredText(readbackIdentity, "readbackIdentity"); Objects.requireNonNull(observedAt, "observedAt must not be null"); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 7058891d76..79b161e9f9 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -12,6 +12,11 @@ public interface InitialGameplayReleaseEffectPort { EffectApplyResult apply(TypedEffect effect, UUID attemptId); + /** + * Returns evidence bound to this exact attempt. PROVEN_NO_EFFECT requires the owner to have + * durably closed the attempt so a delayed claimant can no longer apply it; absence alone is not + * proof. + */ EffectReadbackResolution readback(TypedEffect effect, UUID attemptId); record EffectApplyResult(ApplyStatus status, String outcomeCode) { diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 95ec45bb09..62d7a0c81d 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -146,6 +146,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() new EffectReadback( scope.operationId(), prepare.effect().effectId(), + prepareAttempt, prepare.effect().kind(), prepare.effect().operationTupleDigest(), prepare.payloadDigest(), @@ -153,6 +154,28 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, "gamesession-preparation-readback-1", base.plusSeconds(6)); + UUID prepareEffectId = prepare.effect().effectId(); + EffectReadback otherAttempt = + new EffectReadback( + scope.operationId(), + prepareEffectId, + UUID.randomUUID(), + prepare.effect().kind(), + prepare.effect().operationTupleDigest(), + prepare.payloadDigest(), + EffectReadbackState.PREPARED_FENCED, + EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + "wrong-attempt", + base.plusSeconds(6)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + prepareEffectId, + prepareAttempt, + otherAttempt, + base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); journal.recordAmbiguousEffect( scope.operationId(), prepare.effect().effectId(), @@ -204,6 +227,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() new EffectReadback( scope.operationId(), handoff.effect().effectId(), + handoffAttempt, handoff.effect().kind(), handoff.effect().operationTupleDigest(), handoff.payloadDigest(), @@ -290,6 +314,20 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(retryRead.attemptCount()).isEqualTo(1); assertThat(journal.find(scope.operationId()).orElseThrow().phase()) .isEqualTo(Phase.RESUME_AUTHORIZED); + OutboxEntry definitiveNoEffect = + journal.recordRetryableEffect( + scope.operationId(), + prepare.effect().effectId(), + attemptId, + "OWNER_DECLINED_WITHOUT_EFFECT", + base.plusSeconds(8)); + assertThat(definitiveNoEffect.state()).isEqualTo(EffectOutboxState.RETRYABLE); + UUID nextAttempt = UUID.randomUUID(); + OutboxEntry next = + journal.claimEffect( + scope.operationId(), prepare.effect().effectId(), nextAttempt, base.plusSeconds(9)); + assertThat(next.lastAttemptId()).isEqualTo(nextAttempt); + assertThat(next.attemptCount()).isEqualTo(2); } @Test diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index c399a1e864..7fda646016 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -427,6 +427,52 @@ void tupleDigestPreservesFullWidthExecutorGeneration() { assertThat(codec.toJson(next)).contains("9007199254740993"); } + @Test + void noEffectReadbackRequiresClosedAttemptRatherThanObservedAbsence() { + assertThatThrownBy( + () -> + new InitialGameplayReleaseModel.EffectReadback( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, + DIGEST, + DIGEST, + InitialGameplayReleaseModel.EffectReadbackState.PROVEN_NO_EFFECT, + InitialGameplayReleaseModel.EffectReadbackAuthority + .GAME_SESSION_DURABLE_CURRENT_STATE, + "absence-only", + java.time.Instant.EPOCH)) + .isInstanceOf(IllegalArgumentException.class); + var closed = + new InitialGameplayReleaseModel.EffectReadback( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, + DIGEST, + DIGEST, + InitialGameplayReleaseModel.EffectReadbackState.PROVEN_NO_EFFECT, + InitialGameplayReleaseModel.EffectReadbackAuthority.GAME_SESSION_DURABLE_CLOSED_ATTEMPT, + "terminal-attempt-proof", + java.time.Instant.EPOCH); + assertThat(closed.state()) + .isEqualTo(InitialGameplayReleaseModel.EffectReadbackState.PROVEN_NO_EFFECT); + } + + @Test + void persistedPartitionAcknowledgementRequiresExplicitNonNullPartitionId() { + InitialGameplayReleaseTupleCodec codec = + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + String json = codec.toJson(evidence(scope(UUID.randomUUID()))); + assertThat(json).contains("\"partitionId\":0"); + assertThatThrownBy(() -> codec.readEvidence(json.replace("\"partitionId\":0,", ""))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> codec.readEvidence(json.replace("\"partitionId\":0", "\"partitionId\":null"))) + .isInstanceOf(RuntimeException.class); + } + private static Scope scope(UUID playableNamespace) { return new Scope( UUID.randomUUID(), diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 45e436ca7b..98114952dc 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -209,6 +209,7 @@ void futureDatedOwnerReadbackCannotAdvanceJournal() { new net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback( scope.operationId(), effect.effectId(), + attempt, effect.kind(), DIGEST, DIGEST, From 9d91875a1e45650c683382a725ca04cbcd64ef20 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:57:59 +1300 Subject: [PATCH 030/199] Share physical Redis startup policy with failure proof --- ...untGameSessionAbortCompositionFixture.java | 4 +- ...CurrentSourcesPostgresIntegrationTest.java | 39 +++++++++++-------- ...ntainerStartupRecoveryIntegrationTest.java | 6 +-- 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java index 94f33510e1..4f2c46b27a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java @@ -89,6 +89,7 @@ Session openNeverAdmitted(boolean installedBootstrap) throws Exception { final class Session implements AutoCloseable { private long phaseStartedAt = System.nanoTime(); + private boolean setupComplete; private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture accountFixture; final CanonicalGameplayAdmissionAbortCompositionFixture gs; @@ -233,6 +234,7 @@ private Session( if (claimedNeverAdmitted) gs.claimOriginalNewCandidateWithoutDispatch(lease); else gs.publish(lease); markPhase("initial_acquire_claim"); + setupComplete = true; } catch (Exception | Error setupFailure) { try { close(); @@ -431,7 +433,7 @@ private void markPhase(String phase) { @Override public void close() throws Exception { - markPhase("case_actions"); + markPhase(setupComplete ? "case_actions" : "setup_failed"); try { if (client != null) client.close(); if (reverse != null) reverse.close(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 9ec294910d..5e155c4126 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2711,24 +2711,29 @@ static final class PhysicalRedisFixture implements AutoCloseable { private final Network network = Network.newNetwork(); private final GenericContainer primary = - new GenericContainer<>(TestContainerImages.redis()) - // Bound startup recreation before any fixture data or application actions exist. - .withStartupAttempts(STARTUP_ATTEMPTS) + configurePrimaryStartup(new GenericContainer<>(TestContainerImages.redis())) .withNetwork(network) - .withNetworkAliases(PRIMARY_ALIAS) - .withExposedPorts(REDIS_PORT) - .withCommand( - "redis-server", - "--bind", - "0.0.0.0", - "--protected-mode", - "no", - "--appendonly", - "yes", - "--appendfsync", - "always", - "--repl-diskless-sync-delay", - "0"); + .withNetworkAliases(PRIMARY_ALIAS); + + static GenericContainer configurePrimaryStartup(GenericContainer container) { + // The physical fixture and failure-injection proof share this entire startup policy. + return container + .withStartupAttempts(STARTUP_ATTEMPTS) + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--repl-diskless-sync-delay", + "0"); + } + private final GenericContainer replica = new GenericContainer<>(TestContainerImages.redis()) .withNetwork(network) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java index 47532f6851..d395ff51d3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRedisContainerStartupRecoveryIntegrationTest.java @@ -57,10 +57,8 @@ private static final class FailingStartupContainer private FailingStartupContainer(int failures) { super(TestContainerImages.redis()); this.failures = failures; - withExposedPorts(6379); - withStartupAttempts( - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture - .STARTUP_ATTEMPTS); + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture + .configurePrimaryStartup(this); } // A test-owned running container is an identity, not a value of its mutable attempt history. From c9f138af0ffaea03a2c43cfc83460ed9d31c37f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:00:57 +1300 Subject: [PATCH 031/199] Isolate recovery service configuration and activation proof --- .../system-architecture-backup-recovery.md | 4 + .../player-access-and-session.md | 2 + .../build.gradle.kts | 9 +- .../RecoveryControllerOwnerConfiguration.java | 7 +- .../InitialGameplayReleaseEffectPort.java | 4 + ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../src/main/resources/application.yml | 5 +- .../V1__initial_gameplay_release_journal.sql | 0 ...ReleaseJournalPostgresIntegrationTest.java | 20 ++- ...overyControllerOwnerConfigurationTest.java | 161 ++++++++++++++++++ .../InitialGameplayReleaseModelTest.java | 16 ++ .../InitialGameplayReleaseControllerTest.java | 18 ++ 12 files changed, 234 insertions(+), 13 deletions(-) create mode 100644 services/recovery-controller-service/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports rename services/recovery-controller-service/src/main/resources/db/{migration => recovery-control-migration}/V1__initial_gameplay_release_journal.sql (100%) create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java diff --git a/design/architecture/system-architecture-backup-recovery.md b/design/architecture/system-architecture-backup-recovery.md index 6689777a47..24916008f4 100644 --- a/design/architecture/system-architecture-backup-recovery.md +++ b/design/architecture/system-architecture-backup-recovery.md @@ -90,6 +90,10 @@ The typed `initial-gameplay-recover/v1` request binds the control-plane request, Activation still requires real Account authorization/redemption, authenticated owner association/storage verification, an independently proved exclusive maintenance fence and actual acquired lock, genuine current owner evidence/readbacks, and approved isolated deployment/restore topology. A random journal UUID is not a lock or exclusion proof. Later continuation and resume bind the exact retained scope, lock, phase, and evidence; ambiguous effects cannot authorize redispatch or final handoff. Source-level journal tests do not establish these missing end-to-end prerequisites or player-facing recovery readiness. +Owner readback is bound to the exact effect attempt. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. + +The exclusive-fence activation work must also prove the region lease belongs to the requested scope, prevent or reject lease replacement between evidence read and journal authorization/effect application, and define an audited restart or abandonment path after lease replacement that never releases the maintenance fence prematurely. Those owner protocols are not implemented by the source-only journal; a retained evidence snapshot is not a current lease lock. + ## Artifact Erasure Replay Boundary `artifactErasureHighWater` is transactionally bound to the immutable backup snapshot and is never recalculated from restored PostgreSQL. It is the greatest authoritative erasure-ledger sequence visible in that snapshot; `preSnapshotJournalHighWater` is a separately sourced ordering observation recorded before the snapshot and is not itself a replay boundary. When it is lower than the artifact boundary, the immutable backup manifest must contain `interveningErasureCoverageProof` for every sequence in `(preSnapshotJournalHighWater, artifactErasureHighWater]`, represented exactly once with matching identity/digest in the snapshot-visible ledger and external journal; a gap, duplicate, unknown, or ambiguous entry invalidates the artifact and keeps recovery quarantined. At recovery start, the controller captures immutable `initialCatchupHighWater` once. Recovery must complete the fixed initial replay interval `(artifactErasureHighWater, initialCatchupHighWater]` before entering final cutover. During one bounded final cutover, the erasure authority captures immutable `restoreHighWater` once as the final readiness boundary. The controller requires `restoreHighWater >= initialCatchupHighWater >= artifactErasureHighWater`; a lower value, unknown entry, or unprovable interval keeps recovery quarantined. Before `ready_to_reopen`, recovery must replay the one fixed interval `(artifactErasureHighWater, restoreHighWater]` into the restored environment, with the initial interval complete before cutover and only `(initialCatchupHighWater, restoreHighWater]` remaining for cutover. Neither boundary may move during replay. 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 94496cdd44..99e2569942 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -4,6 +4,8 @@ The source-only recovery-controller journal and typed request foundation are retained under PlatformOperations donor consolidation. Focused proof covers immutable scope conflicts, exact continuation/resume tuples, ambiguous-effect refusal, owner-readback-gated journal transitions, and fail-closed recover entry. This is not a runtime recovery capability: Account redemption, genuine exclusive-fence/lock acquisition, independent owner evidence, authenticated ingress/dispatch, and isolated deployment/restore topology remain unimplemented activation dependencies. See the [canonical recovery boundary](../../architecture/system-architecture-backup-recovery.md#source-only-initial-gameplay-release-foundation). No donor/source-note closure follows from this partial foundation. +Focused executable coverage is in [model/tuple tests](../../../services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java), [controller refusal tests](../../../services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java), and [physical PostgreSQL journal tests](../../../services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java). These cover source contracts, not an enabled real owner. Before activation, explicitly qualify exact-attempt terminal no-effect closure against delayed apply, region-to-scope lease binding, lease changes between evidence and commit, and a fence-preserving recovery/restart path after readiness lease replacement. These remain open owner-integration obligations, not completed fixes. + ## Target-State Authority This is a non-normative implementation tracker for player access and session. Canonical target-state authentication, admission, session, and reconnection contracts remain authoritative in [design/architecture](../../architecture/README.md) and the linked design sources below; this tracker owns current implementation status, proof evidence, gaps, and handoffs, and does not redefine those contracts. diff --git a/services/recovery-controller-service/build.gradle.kts b/services/recovery-controller-service/build.gradle.kts index 5e66a297c5..7f55ea0c39 100644 --- a/services/recovery-controller-service/build.gradle.kts +++ b/services/recovery-controller-service/build.gradle.kts @@ -1,5 +1,3 @@ -apply(from = "${rootDir}/gradle/proto-convention.gradle") - plugins { id("net.firedevops.firemud.secured-sql-aop-service-conventions") id("net.firedevops.firemud.jooq-conventions") @@ -7,9 +5,16 @@ plugins { firemudJooq { packageName.set("net.firedevops.firemud.recovery.jooq") + migrationGlob.set("src/main/resources/db/recovery-control-migration/*.sql") } dependencies { implementation(project(":common-platform-core")) testImplementation(project(":common-test-support")) } + +// The shared convention still declares the default migration directory as an input. +// Include the recovery-owned directory so schema edits invalidate generated sources. +tasks.named("generateJooq") { + inputs.files(fileTree("src/main/resources/db/recovery-control-migration")) +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java index 34f2ff07a8..0fac62b645 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfiguration.java @@ -9,11 +9,14 @@ import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider; import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; -@Configuration +@AutoConfiguration(afterName = "org.springframework.boot.jooq.autoconfigure.JooqAutoConfiguration") +@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) public class RecoveryControllerOwnerConfiguration { @Bean @ConditionalOnMissingBean(InitialGameplayReleaseEvidenceProvider.class) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 79b161e9f9..6787f63100 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -10,6 +10,10 @@ * Game Session owner boundary for exact typed effects and owner-produced durable/current readbacks. */ public interface InitialGameplayReleaseEffectPort { + /** + * RETRYABLE_NO_EFFECT is a definitive owner rejection for this exact attempt, never a timeout or + * absence observation. The owner must not apply the rejected attempt later. + */ EffectApplyResult apply(TypedEffect effect, UUID attemptId); /** diff --git a/services/recovery-controller-service/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/services/recovery-controller-service/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..2444906dea --- /dev/null +++ b/services/recovery-controller-service/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +net.firedevops.firemud.recovery.config.RecoveryControllerOwnerConfiguration diff --git a/services/recovery-controller-service/src/main/resources/application.yml b/services/recovery-controller-service/src/main/resources/application.yml index 7063724fb2..0aa86d87a9 100644 --- a/services/recovery-controller-service/src/main/resources/application.yml +++ b/services/recovery-controller-service/src/main/resources/application.yml @@ -1,4 +1,7 @@ spring: + autoconfigure: + exclude: + - net.firedevops.firemud.common.config.DatabaseAutoConfiguration application: name: recovery-controller-service datasource: @@ -13,7 +16,7 @@ spring: schemas: recovery_control defaultSchema: recovery_control table: flyway_schema_history_recovery_control - locations: classpath:db/migration + locations: classpath:db/recovery-control-migration placeholders: serviceSchema: recovery_control ssl: diff --git a/services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V1__initial_gameplay_release_journal.sql similarity index 100% rename from services/recovery-controller-service/src/main/resources/db/migration/V1__initial_gameplay_release_journal.sql rename to services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V1__initial_gameplay_release_journal.sql diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 62d7a0c81d..6f17e5309e 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -70,14 +70,18 @@ class InitialGameplayReleaseJournalPostgresIntegrationTest { @BeforeAll static void setUp() throws Exception { - Flyway.configure() - .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) - .schemas(SCHEMA) - .defaultSchema(SCHEMA) - .placeholders(Map.of("serviceSchema", SCHEMA)) - .locations("classpath:db/migration") - .load() - .migrate(); + Flyway flyway = + Flyway.configure() + .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/recovery-control-migration") + .load(); + assertThat(flyway.info().all()) + .extracting(info -> info.getScript()) + .containsExactly("V1__initial_gameplay_release_journal.sql"); + flyway.migrate(); connection = DriverManager.getConnection( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java new file mode 100644 index 0000000000..5e49a77525 --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.recovery.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import com.zaxxer.hikari.HikariDataSource; +import java.io.IOException; +import javax.sql.DataSource; +import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.journal.JooqInitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEvidenceProvider; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseController; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.impl.DataSourceConnectionProvider; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration; +import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; +import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; +import org.springframework.boot.jooq.autoconfigure.JooqAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import tools.jackson.databind.json.JsonMapper; + +class RecoveryControllerOwnerConfigurationTest { + private ApplicationContextRunner defaults() { + return new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(RecoveryControllerOwnerConfiguration.class)) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withBean( + InitialGameplayReleaseTupleCodec.class, + () -> new InitialGameplayReleaseTupleCodec(JsonMapper.builder().build())); + } + + @Test + void defaultsRemainDeniedAndJournalBacked() { + defaults() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(InitialGameplayReleaseEvidenceProvider.class); + assertThat(context.getBean(InitialGameplayReleaseEvidenceProvider.class)) + .isInstanceOf(DeniedInitialGameplayReleaseEvidenceProvider.class); + assertThat(context.getBean(InitialGameplayReleaseEffectPort.class)) + .isInstanceOf(DeniedInitialGameplayReleaseEffectPort.class); + assertThat(context.getBean(InitialGameplayReleaseJournal.class)) + .isInstanceOf(JooqInitialGameplayReleaseJournal.class); + assertThat(context).hasSingleBean(InitialGameplayReleaseController.class); + }); + } + + @Test + void replacementAutoConfigurationPrecedesEveryFallback() { + defaults() + .withConfiguration(AutoConfigurations.of(Replacements.class)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(InitialGameplayReleaseEvidenceProvider.class); + assertThat(context).hasSingleBean(InitialGameplayReleaseEffectPort.class); + assertThat(context).hasSingleBean(InitialGameplayReleaseJournal.class); + assertThat(context).hasSingleBean(InitialGameplayReleaseController.class); + assertThat(context).doesNotHaveBean("deniedInitialGameplayReleaseEvidenceProvider"); + assertThat(context).doesNotHaveBean("deniedInitialGameplayReleaseEffectPort"); + assertThat(context.getBean(InitialGameplayReleaseJournal.class)) + .isSameAs(context.getBean("replacementJournal")); + assertThat(context.getBean(InitialGameplayReleaseController.class)) + .isSameAs(context.getBean("replacementController")); + }); + } + + @Test + void dedicatedDatasourceOwnsFlywayAndJooq() { + new ApplicationContextRunner() + .withInitializer( + context -> { + try { + for (var source : + new YamlPropertySourceLoader() + .load("recovery-service", new ClassPathResource("application.yml"))) { + context.getEnvironment().getPropertySources().addLast(source); + } + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + }) + .withUserConfiguration(DatabaseWiring.class) + .withPropertyValues( + "FIREMUD_RECOVERY_CONTROL_DB_HOST=recovery-control.invalid", + "FIREMUD_RECOVERY_CONTROL_DB_PORT=5544", + "FIREMUD_RECOVERY_CONTROL_DB_USER=recovery", + "FIREMUD_RECOVERY_CONTROL_DB_PASSWORD=test-only", + "spring.jooq.sql-dialect=POSTGRES") + // Wiring proof must not depend on a running PostgreSQL or apply migrations. + .withBean(FlywayMigrationStrategy.class, () -> flyway -> {}) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(DatabaseAutoConfiguration.class); + assertThat(context).hasSingleBean(DataSource.class); + HikariDataSource datasource = context.getBean(HikariDataSource.class); + assertThat(datasource.getJdbcUrl()) + .isEqualTo( + "jdbc:postgresql://recovery-control.invalid:5544/firemud_recovery_control"); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getDataSource()).isSameAs(datasource); + assertThat(flyway.getConfiguration().getLocations()) + .extracting(location -> location.getDescriptor()) + .containsExactly("classpath:db/recovery-control-migration"); + var provider = + (DataSourceConnectionProvider) + context.getBean(DSLContext.class).configuration().connectionProvider(); + var proxy = (TransactionAwareDataSourceProxy) provider.dataSource(); + assertThat(proxy.getTargetDataSource()).isSameAs(datasource); + }); + } + + @Configuration(proxyBeanMethods = false) + @ImportAutoConfiguration({ + DatabaseAutoConfiguration.class, + DataSourceAutoConfiguration.class, + FlywayAutoConfiguration.class, + JooqAutoConfiguration.class + }) + static class DatabaseWiring {} + + @AutoConfiguration + static class Replacements { + @Bean + InitialGameplayReleaseEvidenceProvider replacementEvidence() { + return mock(InitialGameplayReleaseEvidenceProvider.class); + } + + @Bean + InitialGameplayReleaseEffectPort replacementEffect() { + return mock(InitialGameplayReleaseEffectPort.class); + } + + @Bean + InitialGameplayReleaseJournal replacementJournal() { + return mock(InitialGameplayReleaseJournal.class); + } + + @Bean + InitialGameplayReleaseController replacementController() { + return mock(InitialGameplayReleaseController.class); + } + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index 7fda646016..b2bf954244 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -335,6 +335,22 @@ void readinessAndDigestIgnoreCapacityMapIterationOrder() { Scope scope = scope(UUID.randomUUID()); InitialGameplayReleaseEvidence original = evidence(scope); IssuerLayoutProof layout = original.issuerLayout(); + Map forward = new java.util.LinkedHashMap<>(); + forward.put(0, 10); + forward.put(1, 12); + original = + withLayout( + original, + new IssuerLayoutProof( + layout.layoutOperationId(), + layout.descriptor(), + layout.accountIssuerSourceIdentity(), + layout.operationFence(), + layout.coverageFence(), + layout.inventoryRevision(), + layout.inventoryDigest(), + layout.acknowledgements(), + forward)); Map reversed = new java.util.LinkedHashMap<>(); reversed.put(1, 12); reversed.put(0, 10); diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 98114952dc..3380ebbc92 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -107,6 +107,24 @@ void unconfiguredEvidenceProviderDeniesReadinessInsteadOfFabricatingProof() { assertThat(provider.read(scope).status()).isEqualTo(ResolutionStatus.UNAVAILABLE); assertThat(provider.read(scope).evidence()).isNull(); + var journal = mock(InitialGameplayReleaseJournal.class); + var operation = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + var lock = + net.firedevops.firemud.recovery.model.MaintenanceLockCredential.issue(UUID.randomUUID()); + when(operation.scope()).thenReturn(scope); + when(operation.maintenanceLockIdentity()).thenReturn(lock.identity()); + when(journal.find(scope.operationId())).thenReturn(java.util.Optional.of(operation)); + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + provider, + new DeniedInitialGameplayReleaseEffectPort()); + assertThatThrownBy(() -> controller.refreshReadiness(scope.operationId(), lock)) + .isInstanceOf(OwnerBoundaryUnavailableException.class) + .hasMessage("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_UNAVAILABLE"); + verify(journal, never()).bindVerifiedEvidence(any(), any(), any(), any(), any()); } @Test From d88bd0963f57af72e3c4b9dfca113b8a39aa4fd4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:05:11 +1300 Subject: [PATCH 032/199] Preserve useful runtime producers and tighten workflow proof --- .github/workflows/ci.yml | 7 +- .github/workflows/preview-reconciler.yml | 15 +- .github/workflows/preview-runtime-refresh.yml | 72 ++++++++- .../protected-pod-admission-proof.yml | 16 +- .github/workflows/runtime-images.yml | 8 +- .github/workflows/smoke.yml | 9 +- .github/workflows/static-analysis-summary.yml | 28 ++-- .../architecture/system-architecture-cicd.md | 4 +- ...d-identity-controller-workflow-contract.sh | 11 ++ .../pr-required-gate-context-contract.sh | 9 +- .../pr-runtime-image-publication-contract.sh | 40 +++-- .../preview-runner-isolation-contract.sh | 75 ++++++++- .../tests/preview-runtime-refresh.test.cjs | 142 +++++++++++++++++- .../tests/static-analysis-summary-contract.sh | 18 ++- 14 files changed, 391 insertions(+), 63 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c031c5a0b..3f52a44f04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,10 +106,11 @@ jobs: ]; let outputs; if (fs.existsSync(classifierPath)) { - const { classifyGithubChangeScope } = require(classifierPath); + const { classifyGithubChangeScope, ALL_MODULES } = require(classifierPath); const scope = await classifyGithubChangeScope(github, context); const moduleScopeAvailable = - Array.isArray(scope.affectedModules) && Array.isArray(scope.bootableModules); + Array.isArray(scope.affectedModules) && Array.isArray(scope.bootableModules) && + Array.isArray(ALL_MODULES) && completeModules.every(module => ALL_MODULES.includes(module)); outputs = { run_all: scope.runAll || !moduleScopeAvailable, affected_services: scope.affectedServices, @@ -122,7 +123,7 @@ jobs: validation_python_changed: scope.validationPythonChanged, postgres_runtime_proof_changed: scope.postgresRuntimeProofChanged === undefined ? true : scope.postgresRuntimeProofChanged, - lightweight_only: scope.lightweightOnly, + lightweight_only: moduleScopeAvailable && scope.lightweightOnly, }; } else { core.warning("Base revision predates the change classifier; using complete validation scope."); diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 401bd2355d..2a5879ca7d 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -523,6 +523,8 @@ jobs: --arg trusted_workflow_name "Trusted Hosted Identity Request" \ --arg default_branch "${DEFAULT_BRANCH}" \ --arg pr_title "PR preview ${pr_number}" \ + --argjson pr_number "$pr_number" \ + --arg head_sha "$head_sha" \ --arg run_name "Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" ' if type != "array" then error("workflow runs are not an array") @@ -540,12 +542,21 @@ jobs: else .[] | select( - ((.name == $workflow_name) or (.name == $trusted_workflow_name)) + ( + (.name == $workflow_name + and ((.path // "" | split("@")[0]) == ".github/workflows/preview.yml")) + or (.name == $trusted_workflow_name + and ((.path // "" | split("@")[0]) == ".github/workflows/hosted-identity-request.yml")) + ) and ( (.firemud_reconciler_branch_filtered == false) or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) ) - and (.display_title == $run_name or .display_title == $pr_title) + and ( + .display_title == $run_name + or (.display_title == $pr_title and .head_sha == $head_sha + and any(.pull_requests[]?; .number == $pr_number)) + ) and ( .status == "requested" or .status == "queued" diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 0cd5686c8b..80eba368fb 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -19,7 +19,7 @@ jobs: contents: write pull-requests: read concurrency: - group: preview-base-refresh-${{ github.event.workflow_run.head_branch }} + group: preview-base-refresh-${{ github.event.workflow_run.id }}-${{ github.event.workflow_run.run_attempt }} cancel-in-progress: false steps: - name: Check out trusted default branch image policy @@ -39,7 +39,11 @@ jobs: }); const repository = `${context.repo.owner}/${context.repo.repo}`; const sha = /^[0-9a-f]{40}$/; - if (run.path !== '.github/workflows/preview.yml' || + const previewPath = '.github/workflows/preview.yml'; + const pathMatches = run.path === previewPath || + (typeof run.path === 'string' && run.path.startsWith(previewPath + '@') && + run.path.length > previewPath.length + 1); + if (!pathMatches || run.event !== 'pull_request' || run.conclusion !== 'success' || run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || @@ -51,16 +55,22 @@ jobs: const {data: pr} = await github.rest.pulls.get({ ...context.repo, pull_number: source.number, }); - const labelsValid = Array.isArray(pr.labels) && - pr.labels.every(label => typeof label?.name === 'string'); - const isPriority = labelsValid && pr.labels.some(label => label.name === 'preview:priority'); + // Execute only the checked-out default-branch eligibility policy. + try { + require('node:child_process').execFileSync('python3', [ + './dev-tools/hosted/preview/preview-eligibility.py', '--revalidate-deploy', + '--expected-repository', repository, '--expected-head-sha', run.head_sha, + ], {encoding: 'utf8', input: JSON.stringify(pr)}); + } catch (error) { + if (error.status !== 1) throw error; + core.info('Canonical preview eligibility refused the current PR; no dispatch.'); + return; + } const isIntegrationBase = ['main', 'develop'].includes(pr.base?.ref); if (pr.state !== 'open' || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || pr.head.sha !== run.head_sha || source.head?.sha !== run.head_sha || - !labelsValid || (!isIntegrationBase && !isPriority) || !/^[A-Za-z0-9._/-]+$/.test(pr.base.ref) || - ['app/dependabot', 'dependabot[bot]', 'app/renovate', 'renovate[bot]'].includes(pr.user?.login) || !sha.test(pr.merge_commit_sha)) { core.info('Source is stale or ineligible; no dispatch.'); return; @@ -92,6 +102,54 @@ jobs: core.info('Canonical image policy selects base images; no refresh.'); return; } + // Event-driven duplicate suppression, not proof of image publication. + // Bound each active-status inventory; never treat a truncated inventory + // as proof that no producer exists. Completed runs do not suppress repair. + const runtimePath = '.github/workflows/runtime-images.yml'; + const {data: runtimeWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: 'runtime-images.yml', + }); + if (runtimeWorkflow.path !== runtimePath || + !Number.isSafeInteger(runtimeWorkflow.id) || runtimeWorkflow.id <= 0) { + throw new Error('Runtime workflow identity is unproven'); + } + const expectedTitle = 'Build Runtime Images secure-pr-artifact ' + + `pr-${pr.number} base-${base.object.sha} head-${pr.head.sha} merge-${merge.sha} mode-required`; + const activeStatuses = ['queued', 'waiting', 'requested', 'pending', 'in_progress']; + for (const status of activeStatuses) { + for (let page = 1; page <= 3; page++) { + const {data: inventory} = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: runtimeWorkflow.id, status, per_page: 100, page, + }); + if (!Array.isArray(inventory.workflow_runs)) throw new Error('Invalid runtime run inventory'); + for (const candidate of inventory.workflow_runs) { + const trustedPath = candidate.path === runtimePath || + candidate.path === `${runtimePath}@refs/heads/${context.payload.repository.default_branch}` || + (candidate.event === 'pull_request' && + candidate.path === `${runtimePath}@refs/pull/${pr.number}/merge`); + if (candidate.workflow_id !== runtimeWorkflow.id || !trustedPath || + candidate.repository?.full_name !== repository || + candidate.head_repository?.full_name !== repository || + !activeStatuses.includes(candidate.status) || candidate.conclusion != null || + candidate.display_title !== expectedTitle) continue; + // Dispatch runs execute default-branch workflow code. PR runs + // additionally need native GitHub head/base association, not title alone. + const dispatchRun = candidate.event === 'repository_dispatch' && + candidate.head_branch === context.payload.repository.default_branch; + const prRun = candidate.event === 'pull_request' && + candidate.head_sha === pr.head.sha && candidate.pull_requests?.length === 1 && + candidate.pull_requests[0].number === pr.number && + candidate.pull_requests[0].head?.sha === pr.head.sha && + candidate.pull_requests[0].base?.sha === base.object.sha; + if (dispatchRun || prRun) { + core.info('Exact current runtime tuple already has an active producer; no dispatch.'); + return; + } + } + if (inventory.workflow_runs.length < 100) break; + if (page === 3) throw new Error('Active runtime inventory exceeds bounded lookup'); + } + } await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: 'pr-runtime-base-refresh', client_payload: { diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index f5cc9460e5..6b941e9c52 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -4,12 +4,6 @@ on: pull_request: paths: - .github/workflows/protected-pod-admission-proof.yml - - .github/actions/load-workflow-tool-versions/** - - .github/actions/setup-kubectl/** - - .github/actions/setup-python/** - - config/workflow-tool-versions.env - - dev-tools/hosted/trust-bootstrap/** - - k8s/trust-bootstrap/deployment-admission.yaml workflow_dispatch: permissions: @@ -128,7 +122,10 @@ jobs: elif ! actual_claim="$(cat "$claim")" || [[ "$actual_claim" != "$expected_claim" ]]; then printf 'cleanup=refused_invalid_ownership_claim\n' status=1 - elif docker inspect "$node" >/dev/null 2>&1; then + elif ! node_names="$(docker ps -a --format '{{.Names}}')"; then + printf 'cleanup=failed_node_lookup\n' + status=1 + elif grep -Fxq "$node" <<<"$node_names"; then local owner_label owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" if [[ "$owner_label" == "$KIND_CLUSTER_NAME" ]]; then @@ -263,7 +260,10 @@ jobs: printf 'cleanup=refused_invalid_ownership_claim\n' | tee -a "$evidence" exit 1 fi - if docker inspect "$node" >/dev/null 2>&1; then + if ! node_names="$(docker ps -a --format '{{.Names}}')"; then + printf 'cleanup=failed_node_lookup\n' | tee -a "$evidence" + exit 1 + elif grep -Fxq "$node" <<<"$node_names"; then owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" if [[ "$owner_label" != "$KIND_CLUSTER_NAME" ]]; then printf 'cleanup=refused_unverified_node_identity node=%s label=%s\n' "$node" "$owner_label" \ diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 01d906d090..bb173e9971 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -54,11 +54,11 @@ run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || githu permissions: contents: read -# Same-repository PR edits supersede obsolete local builds. Dispatch and fork -# inputs retain exact-tuple isolation because cancellation precedes admission. +# Cancellation precedes admission: isolate all PR inputs by exact tuple and +# let an existing producer finish when duplicate requests arrive. concurrency: - group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && format('pr-{0}', github.event.pull_request.number)) || (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 + 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: false jobs: image-meta: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 063654d948..c65ff6da14 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,11 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e"; + const canonicalRuntimeWorkflowSha256 = "0315e611fadc96bc30c8054ead8b9b8d72996785dd89239bec592e16392877ab"; + const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ + "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", + "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", + ]); // 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. @@ -729,7 +733,8 @@ jobs: function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { return definitionHash === canonicalRuntimeWorkflowSha256 || (sourceEvent === "repository_dispatch" && - definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256); + (definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 || + outgoingTrustedRefreshRuntimeWorkflowSha256.has(definitionHash))); } async function verifyCanonicalSmokeProducer(run, candidate, identity) { diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 355ced41af..e68a7dcfe1 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -252,22 +252,11 @@ jobs: "", "CodeQL breakdown", "", + `Source: base ${baseSha}, head ${headSha}`, + "", ...detailResults.map(([name, result]) => `- ${statusIcon(result)} ${name}: \`${result}\``), ].join("\n"); - const { data: finalPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: issueNumber, - }); - if ( - finalPullRequest.state !== "open" || - finalPullRequest.head?.sha !== headSha || - finalPullRequest.base?.sha !== baseSha - ) { - core.info("The pull-request base or head changed while static analysis was being summarized."); - return; - } - const comments = await github.paginate(github.rest.issues.listComments, { ...context.repo, issue_number: issueNumber, @@ -292,6 +281,19 @@ jobs: return Number(comment.id) < Number(oldest.id) ? comment : oldest; }, null); + const { data: finalPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: issueNumber, + }); + if ( + finalPullRequest.state !== "open" || + finalPullRequest.head?.sha !== headSha || + finalPullRequest.base?.sha !== baseSha + ) { + core.info("The pull-request base or head changed while static analysis was being summarized."); + return; + } + if (existing && existing.body !== body) { await github.rest.issues.updateComment({ ...context.repo, diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 83b32b22d7..f28d727137 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -82,7 +82,7 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -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. +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. Runtime producers use nonpreemptive exact PR/base/head/merge concurrency groups, so an old-head rerun or duplicate tuple cannot cancel a useful producer. The refresh observer checks a bounded inventory of active canonical runtime producers and reuses an exact current tuple rather than knowingly dispatching another; the inventory check and dispatch are not atomic. 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. @@ -244,7 +244,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. Render tools and local actions always come from the default branch; the separate exact PR merge checkout supplies only Helm chart data, never scripts or actions executed by a trusted dispatch. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate policy removal (restoring GitHub default protections) or replacement with only `pull_request` and `repository_dispatch`, then verify natural PR/manual-dispatch paths against the merged code. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 38427bcf1a..606bd0bd7d 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6837,6 +6837,17 @@ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$distinct_source_workflow_run_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ run_deploy_target_fixture distinct-source-head 0 'Ignoring artifact not bound to the source run pull request and head.' grep -Fxq "action=none" "$TEMP_DIR/deploy-target-distinct-source-head.output" +# Independently prove neither the API run head nor association can substitute for the other. +run_head_only_json="$(jq -c --arg sha "$distinct_source_sha" '.head_sha=$sha' <<<"$valid_workflow_run_json")" +association_head_only_json="$(jq -c --arg sha "$distinct_source_sha" '.pull_requests[0].head.sha=$sha' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$run_head_only_json" \ +FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ + run_deploy_target_fixture run-head-only 0 'Ignoring source run without a unique bound pull request association.' +grep -Fxq "action=none" "$TEMP_DIR/deploy-target-run-head-only.output" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$association_head_only_json" \ + run_deploy_target_fixture association-head-only 0 'Ignoring source run without a unique bound pull request association.' +grep -Fxq "action=none" "$TEMP_DIR/deploy-target-association-head-only.output" + FAKE_FIXTURE_ARTIFACTS_JSON='[{"artifacts":[]}]' \ run_deploy_target_fixture missing-canonical 0 \ diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index aed084a800..8ea400266b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3513,6 +3513,10 @@ const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = require("node:crypt .update(previousRefreshBytes).digest("hex"); // Separate test authority lets the same verifier exercise both immutable modes. const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); +const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set(JSON.parse( + script.match(/const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set\((\[[\s\S]*?\])\);/)[1] + .replace(/,\s*\]/, "]"))); + 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); @@ -3564,11 +3568,12 @@ 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", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "outgoingTrustedRefreshRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return ${verifier}(data.run, data.candidate, data.identity);`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, - data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, + outgoingTrustedRefreshRuntimeWorkflowSha256, 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); diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 300d1718fe..e0cbad03cd 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -16,20 +16,31 @@ from pathlib import Path source = Path(sys.argv[1]).read_text() group = re.search(r"^ group: (runtime-images-.*)$", source, re.MULTILINE).group(1) -assert re.search(r"^ cancel-in-progress: true$", source, re.MULTILINE) +assert re.search(r"^ cancel-in-progress: false$", source, re.MULTILINE) class Context: def __init__(self, value=None): self.value = value def __getattr__(self, key): value = self.value.get(key) if isinstance(self.value, dict) else None - return Context(value) if isinstance(value, dict) or value is None else value + return Context(value) def __bool__(self): return bool(self.value) def __eq__(self, other): - return (self.value or "") == (other or "") + other = other.value if isinstance(other, Context) else other + left = self.value + if type(left) is type(other): + return left.lower() == other.lower() if isinstance(left, str) else left == other + def number(value): + if value is None or value == "": return 0 + if isinstance(value, bool): return int(value) + try: return float(value) + except (ValueError, TypeError): return float("nan") + return number(left) == number(other) def __str__(self): - return "" if self.value is None else str(self.value) + return "" if self.value is None else str(self.value).lower() if isinstance(self.value, bool) else str(self.value) + def __format__(self, spec): + return format(str(self), spec) base = { "event_name": "pull_request", "workflow": "Build Runtime Images", @@ -52,23 +63,23 @@ def check(event, suffix): expected = "runtime-images-Build Runtime Images-" + suffix assert evaluate(event) == expected, (evaluate(event), expected) -check(base, "pr-7-required") +check(base, "pr-7-base-base1-head-head1-merge-merge1-required") new = copy.deepcopy(base) new["event"]["pull_request"]["head"]["sha"] = "head2" new["event"]["pull_request"]["base"]["sha"] = "base2" new["sha"] = "merge2" -check(new, "pr-7-required") +check(new, "pr-7-base-base2-head-head2-merge-merge2-required") new["event"]["pull_request"]["number"] = 8 -check(new, "pr-8-required") +check(new, "pr-8-base-base2-head-head2-merge-merge2-required") for action in ["opened", "reopened", "ready_for_review", "synchronize"]: event = copy.deepcopy(base) event["event"]["action"] = action - check(event, "pr-7-required") + check(event, "pr-7-base-base1-head-head1-merge-merge1-required") metadata = copy.deepcopy(base) metadata["event"]["action"] = "edited" -check(metadata, "pr-7-metadata") +check(metadata, "pr-7-base-base1-head-head1-merge-merge1-metadata") metadata["event"]["changes"] = {"base": {"ref": {"from": "old-base"}}} -check(metadata, "pr-7-required") +check(metadata, "pr-7-base-base1-head-head1-merge-merge1-required") for repository in ["fork/repo", None]: fork = copy.deepcopy(base) fork["event"]["pull_request"]["head"]["repo"] = {"full_name": repository} @@ -79,6 +90,13 @@ dispatch = {**base, "event_name": "repository_dispatch", "event": { "action": "pr-runtime-base-refresh", "client_payload": { "pr_number": 7, "base_sha": "base1", "head_sha": "head1", "merge_sha": "merge1"}}} check(dispatch, "pr-7-base-base1-head-head1-merge-merge1-required") +for value in [0, False, "", None]: + invalid = copy.deepcopy(dispatch) + invalid["event"]["client_payload"]["pr_number"] = value + check(invalid, "repository-dispatch-run-100-required") +assert Context(1) != "" +assert Context(0) == "" +assert Context(False) == "" for missing in ["pr_number", "base_sha", "head_sha", "merge_sha"]: invalid = copy.deepcopy(dispatch) del invalid["event"]["client_payload"][missing] @@ -92,7 +110,7 @@ callback["event"]["workflow_run"] = {"event": "push", "head_branch": "develop"} check(callback, "branch-develop-required") check({**base, "event_name": "push", "event": {}, "ref": "refs/heads/develop"}, "refs/heads/develop-required") -print("Runtime concurrency: same-repository PR supersession; fork/dispatch/branch isolation passed") +print("Runtime concurrency: nonpreemptive exact PR/dispatch tuple and branch isolation passed") PY_CONCURRENCY require_contains() { diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index b82fc2d471..fa3b1b1244 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -96,6 +96,38 @@ else: raise AssertionError("scalar write-all permissions escaped source checking") + +# Exercise the reconciler's actual active-run filter, not a duplicate predicate. +reconciler_source = reconciler_path.read_text() +active_filter = re.search( + r'--arg run_name [^\n]+ \'\n(.*?)\' <<<"\$\{active_preview_runs_json\}"', + reconciler_source, re.S, +).group(1) +def active_ids(row: dict[str, Any]) -> str: + return subprocess.check_output([ + "jq", "-r", "--arg", "workflow_name", "PR Preview Environment", + "--arg", "trusted_workflow_name", "Trusted Hosted Identity Request", + "--arg", "default_branch", "develop", "--arg", "pr_title", "PR preview 7", + "--argjson", "pr_number", "7", "--arg", "head_sha", "a" * 40, + "--arg", "run_name", "Preview dispatch pr-7-base-b-head-a-merge-c", + active_filter, + ], input=json.dumps([row]), text=True).strip() +active_run = { + "id": 1, "name": "PR Preview Environment", "path": ".github/workflows/preview.yml", + "head_branch": "feature", "head_sha": "a" * 40, "pull_requests": [{"number": 7}], + "display_title": "PR preview 7", "status": "in_progress", + "firemud_reconciler_branch_filtered": False, +} +assert active_ids(active_run) == "1" +for fields in ( + {"path": ".github/workflows/unrelated.yml"}, + {"head_sha": "b" * 40}, + {"pull_requests": [{"number": 8}]}, +): + assert active_ids({**active_run, **fields}) == "" +assert active_ids({**active_run, "display_title": "Preview dispatch pr-7-base-b-head-a-merge-c", + "pull_requests": [], "head_branch": "develop"}) == "1" + preview = load(preview_path) trusted = load(trusted_path) recovery = load(recovery_path) @@ -295,7 +327,9 @@ def check_preview_source_permissions(job_name: str, job: dict[str, Any]) -> None raise AssertionError( "preview-runtime-base-refresh must have exactly contents:write and pull-requests:read" ) - if "github.event_name == 'repository_dispatch'" not in str(job.get("if", "")): + condition = str(job.get("if", "")).strip() + # Accept only the current conjunction grammar; OR is not a mandatory gate. + if not condition.startswith("$"+"{{ github.event_name == 'repository_dispatch' && ") or "||" in condition: raise AssertionError("preview runtime refresh write permissions require dispatch-only gating") return job_permissions_list = permissions(job_permissions) @@ -407,6 +441,15 @@ except AssertionError: else: raise AssertionError("preview runtime refresh PR write mutation escaped source checking") +refresh_with_or_gate = dict(refresh_job) +refresh_with_or_gate["if"] = "$"+"{{ github.event_name == 'repository_dispatch' || github.event_name == 'pull_request' }}" +try: + check_preview_source_permissions("preview-runtime-base-refresh", refresh_with_or_gate) +except AssertionError: + pass +else: + raise AssertionError("OR dispatch gate escaped source checking") + # The plan's local actions and scripts must come from the default branch; the # render's PR checkout is exact, unprivileged, and bound to the planned merge. plan_checkouts = checkouts(preview_jobs["preview-plan"]) @@ -419,6 +462,36 @@ if render_checkouts[0].get("with", {}).get("ref") != "${{ github.event.repositor raise AssertionError("preview render tools must remain rooted at the trusted default branch") if render_checkouts[1].get("with", {}).get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or render_checkouts[1].get("with", {}).get("path") != "candidate": raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") +def check_trusted_working_directories(workflow: dict[str, Any], job: dict[str, Any]) -> None: + inherited = workflow.get("defaults", {}).get("run", {}).get("working-directory", ".") + inherited = job.get("defaults", {}).get("run", {}).get("working-directory", inherited) + for step in job.get("steps", []): + if "run" not in step: + continue + effective = step.get("working-directory", inherited) + if effective not in (".", "./", "$"+"{{ github.workspace }}"): + raise AssertionError("preview executable step must remain rooted in trusted tools") + +for name in ("preview-plan", "preview-render"): + check_trusted_working_directories(preview, preview_jobs[name]) +for mutation in ( + {"defaults": {"run": {"working-directory": "candidate"}}, "steps": [{"run": "true"}]}, + {"steps": [{"run": "true", "working-directory": "candidate"}]}, +): + try: + check_trusted_working_directories(preview, mutation) + except AssertionError: + pass + else: + raise AssertionError("candidate working-directory mutation escaped source checking") +try: + check_trusted_working_directories( + {"defaults": {"run": {"working-directory": "candidate"}}}, {"steps": [{"run": "true"}]} + ) +except AssertionError: + pass +else: + raise AssertionError("workflow default working-directory escaped source checking") render_text = text(preview_jobs["preview-render"]) for required in ("git -C candidate", "candidate/k8s/helm/firemud", "python3 ./dev-tools/hosted/preview/"): if required not in render_text: diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index f98171178c..7872782e67 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -23,17 +23,37 @@ function fixture() { async function execute(f) { const sent = []; const github = {rest: { - actions: {getWorkflowRun: async () => ({data: f.run})}, + actions: { + getWorkflowRun: async () => ({data: f.run}), + getWorkflow: async () => ({data: {id: 42, path: '.github/workflows/runtime-images.yml'}}), + listWorkflowRuns: async args => { + assert.equal(args.workflow_id, 42); + assert.equal(args.per_page, 100); + f.lookups = (f.lookups ?? 0) + 1; + return {data: {workflow_runs: f.fullInventory ?? + (f.producers ?? []).filter(run => run.status === args.status)}}; + }, + }, pulls: {get: async () => ({data: f.pr})}, - git: {getRef: async () => ({data: f.base})}, + git: {getRef: async ({ref}) => { + assert.equal(ref, 'heads/' + f.pr.base.ref); + return {data: f.base}; + }}, repos: {getCommit: async () => ({data: f.merge}), createDispatchEvent: async p => sent.push(p)}, }}; await new AsyncFunction('github', 'context', 'core', 'require', script)(github, - {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}}}, {info() {}}, name => { + {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}, repository: {default_branch: 'develop'}}}, {info() {}}, name => { assert.equal(name, 'node:child_process'); - return {execFileSync(command, args) { + return {execFileSync(command, args, options) { + if (command === 'python3') { + assert.deepEqual(args, ['./dev-tools/hosted/preview/preview-eligibility.py', + '--revalidate-deploy', '--expected-repository', 'example/FireMUD', + '--expected-head-sha', f.run.head_sha]); + assert.deepEqual(JSON.parse(options.input), f.pr); + return execFileSync(command, args, {...options, cwd: root}); + } assert.equal(command, 'bash'); - assert.deepEqual(args, ['./dev-tools/hosted/preview/resolve-preview-image-tag.sh', A, '7', B]); + assert.deepEqual(args, ['./dev-tools/hosted/preview/resolve-preview-image-tag.sh', A, '7', f.base.object.sha]); return f.imageTag ?? `pr-merge-${A}`; }}; }); @@ -85,7 +105,8 @@ test('observer checks out only trusted policy and has no artifact or candidate e test('priority stacked base refreshes even when source base is current', async () => { const f = fixture(); f.pr.base.ref = 'feature/stack'; - f.pr.labels = [{name: 'preview:priority'}]; f.run.pull_requests[0].base.sha = B; + f.pr.labels = [{name: 'preview:priority'}]; f.run.pull_requests[0].base.sha = D; + f.base.object.sha = D; f.merge.parents[0].sha = D; const sent = await execute(f); assert.equal(sent.length, 1); assert.equal(sent[0].client_payload.base_ref, 'feature/stack'); }); @@ -96,3 +117,112 @@ test('canonical non-runtime base image selection does not dispatch', async () => test('unexpected canonical image selection fails closed', async () => { const f = fixture(); f.imageTag = 'untrusted'; await assert.rejects(execute(f), /Unexpected image/); }); + +test('qualified canonical workflow path remains eligible', async () => { + const f = fixture(); f.run.path += '@refs/pull/7/merge'; + assert.equal((await execute(f)).length, 1); + f.run.path = '.github/workflows/preview.yml@'; + assert.deepEqual(await execute(f), []); +}); +test('observer callbacks cannot replace a different source run or attempt', () => { + const group = workflow.jobs.refresh.concurrency.group; + assert.match(group, /workflow_run.id/); + assert.match(group, /workflow_run.run_attempt/); + assert.equal(workflow.jobs.refresh.concurrency['cancel-in-progress'], false); +}); + +test('older base classifiers cannot omit newly introduced validation modules', async () => { + const ci = JSON.parse(execFileSync('python3', ['-c', + 'import yaml,json,sys; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))', + path.join(root, '.github/workflows/ci.yml')], {encoding: 'utf8'})); + const compute = ci.jobs.changes.steps.find(step => step.id === 'compute').with.script; + const complete = JSON.parse(compute.match(/const completeModules = (\[[\s\S]*?\]);/)[1].replace(/,\s*\]/, "]")); + for (const modules of [undefined, complete.filter(name => name !== 'recovery-controller-service'), complete]) { + const outputs = {}; + await new AsyncFunction('require', 'github', 'context', 'core', compute)( + name => name === 'node:fs' ? {existsSync: () => true} : { + ALL_MODULES: modules, + classifyGithubChangeScope: async () => ({ + runAll: false, affectedModules: ['account-service'], bootableModules: ['account-service'], + affectedServices: ['account-service'], lightweightOnly: true, + }), + }, {}, {}, {setOutput: (name, value) => outputs[name] = value, warning() {}}); + if (modules === complete) { + assert.equal(outputs.run_all, 'false'); + assert.deepEqual(JSON.parse(outputs.affected_modules), ['account-service']); + } else { + assert.equal(outputs.run_all, 'true'); + assert.equal(outputs.lightweight_only, 'false'); + assert.ok(JSON.parse(outputs.affected_modules).includes('recovery-controller-service')); + assert.ok(JSON.parse(outputs.bootable_modules).includes('recovery-controller-service')); + } + } +}); + +function producer(f, event = 'repository_dispatch') { + return {id: 100, workflow_id: 42, path: '.github/workflows/runtime-images.yml', + event, head_branch: 'develop', head_sha: event === 'pull_request' ? C : D, + repository: {full_name: 'example/FireMUD'}, head_repository: {full_name: 'example/FireMUD'}, + status: 'in_progress', conclusion: null, + display_title: `Build Runtime Images secure-pr-artifact pr-7 base-${B} head-${C} merge-${A} mode-required`, + pull_requests: [{number: 7, head: {sha: C}, base: {sha: B}}]}; +} +for (const event of ['repository_dispatch', 'pull_request']) { + for (const status of ['queued', 'waiting', 'requested', 'pending', 'in_progress']) { + test(`active exact ${event} ${status} producer suppresses dispatch`, async () => { + const f = fixture(); const run = producer(f, event); run.status = status; f.producers = [run]; + assert.deepEqual(await execute(f), []); + }); + } +} +for (const [name, mutate] of Object.entries({ + otherPR: r => r.display_title = r.display_title.replace('pr-7 ', 'pr-8 '), + otherBase: r => r.display_title = r.display_title.replace(B, D), + otherHead: r => r.display_title = r.display_title.replace(C, D), + otherMerge: r => r.display_title = r.display_title.replace(A, D), + wrongWorkflow: r => r.workflow_id = 9, + wrongPath: r => r.path = '.github/workflows/attacker.yml', + wrongRepo: r => r.repository.full_name = 'fork/FireMUD', + fork: r => r.head_repository.full_name = 'fork/FireMUD', + wrongEvent: r => r.event = 'workflow_dispatch', + wrongDispatchBranch: r => r.head_branch = 'attacker', + completed: r => {r.status = 'completed'; r.conclusion = 'success';}, + inconsistentConclusion: r => r.conclusion = 'failure', +})) test(`unrelated/untrusted producer cannot suppress recovery: ${name}`, async () => { + const f = fixture(); const r = producer(f); mutate(r); f.producers = [r]; + assert.equal((await execute(f)).length, 1); +}); +for (const [name, mutate] of Object.entries({ + head: r => r.head_sha = D, + associationMissing: r => r.pull_requests = [], + associationPR: r => r.pull_requests[0].number = 8, + associationBase: r => r.pull_requests[0].base.sha = D, + associationHead: r => r.pull_requests[0].head.sha = D, +})) test(`PR title alone cannot suppress: ${name}`, async () => { + const f = fixture(); const r = producer(f, 'pull_request'); mutate(r); f.producers = [r]; + assert.equal((await execute(f)).length, 1); +}); +test('bounded inventory saturation fails without dispatch or polling', async () => { + const f = fixture(); f.fullInventory = Array.from({length: 100}, () => ({})); + await assert.rejects(execute(f), /exceeds bounded lookup/); + assert.equal(f.lookups, 3); +}); +test('qualified trusted default workflow path suppresses exact dispatch', async () => { + const f = fixture(); const r = producer(f); + r.path += '@refs/heads/develop'; f.producers = [r]; + assert.deepEqual(await execute(f), []); +}); +test('canonical eligibility refuses absent author metadata', async () => { + const f = fixture(); delete f.pr.user; assert.deepEqual(await execute(f), []); +}); + +test('qualified exact PR merge workflow path suppresses native producer', async () => { + const f = fixture(); const r = producer(f, 'pull_request'); + r.path += '@refs/pull/7/merge'; f.producers = [r]; + assert.deepEqual(await execute(f), []); +}); +test('qualified other PR workflow path cannot suppress native producer', async () => { + const f = fixture(); const r = producer(f, 'pull_request'); + r.path += '@refs/pull/8/merge'; f.producers = [r]; + assert.equal((await execute(f)).length, 1); +}); diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index bface3a863..f5d402a831 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -88,6 +88,7 @@ let currentBaseRef = "develop"; let pullRequestReads = 0; let changeBaseDuringRun = false; let changeHeadDuringRun = false; +let changeHeadDuringComments = false; let deleteStatus = null; let existingBody = "### Static Analysis Summary\nold"; const calls = { paginate: [], deleted: [], updated: [], created: [] }; @@ -224,6 +225,7 @@ const github = { ]; } if (method === commentsList) { + if (changeHeadDuringComments) currentHeadSha = "9".repeat(40); return [ ...Array.from({ length: 35 }, (_, index) => ({ id: 10000 + index, @@ -376,7 +378,12 @@ async function assertCompletionOrders() { // Both producer orders must recover current-head proof even if the // final wake is an obsolete head and all current-head wakes coalesced. currentHeadSha = "f".repeat(40); + const writesBeforeHeadAdvance = updates; await callback(first); + if (updates !== writesBeforeHeadAdvance + 1 || + !comments[0].body.includes(currentHeadSha)) { + throw new Error("older-head wake must publish new head identity in the existing comment"); + } if (!comments[0].body.includes("CodeQL gate: `failure`")) { throw new Error("stale-head wake must reconcile live-head failure"); } @@ -416,6 +423,13 @@ async function assertInterruptedRecovery() { } changeHeadDuringRun = false; reset(); + changeHeadDuringComments = true; + await run(github, context, core); + changeHeadDuringComments = false; + if (calls.updated.length || calls.created.length || calls.deleted.length) { + throw new Error("head movement while listing comments must not write stale proof"); + } + reset(); github.paginate = async () => { throw new Error("provider interrupted"); }; let failed = false; try { await run(github, context, core); } catch (error) { @@ -471,8 +485,8 @@ run(github, context, core).then(async () => { pullRequestReads = 0; changeBaseDuringRun = true; return run(github, context, core).then(() => { - if (calls.paginate.length !== 7 || calls.updated.length !== 1 || calls.deleted.length !== 1) { - throw new Error("base changes during summarization must not query or alter comments"); + if (calls.paginate.length !== 8 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("base changes during summarization must not alter comments"); } currentHeadSha = headSha; currentBaseSha = baseSha; From ab9594f4fb307410b3ea313630f8abc70a899983 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:06:12 +1300 Subject: [PATCH 033/199] Remove unused journal test snapshot after persisted-state assertion --- .../InitialGameplayReleaseJournalPostgresIntegrationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 6f17e5309e..9b705d55f1 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -292,8 +292,7 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { Operation awaiting = journal.transition( transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base.plusSeconds(3)); - Operation authorized = - journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(4)); + journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(4)); OutboxEntry prepare = journal.findNextEffect(scope.operationId()).orElseThrow(); UUID attemptId = UUID.randomUUID(); OutboxEntry dispatched = From bf05bdd95a912ba8ba6c774bed860c40ca9dbb52 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:12:17 +1300 Subject: [PATCH 034/199] Select summary target from canonical title without association-order races --- .github/workflows/static-analysis-summary.yml | 33 +++++++++++----- .../tests/static-analysis-summary-contract.sh | 38 ++++++++++++++++++- 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index e68a7dcfe1..816eab63da 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -14,7 +14,10 @@ permissions: pull-requests: write concurrency: - group: static-analysis-summary-pr-${{ github.event.workflow_run.pull_requests[0].number || github.run_id }} + group: static-analysis-summary-source-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }} + # Serialize by native source repository and branch, independent of association + # ordering or the producer workflow. Shared-branch PRs conservatively serialize. + # Publication below requires this identity still matches the live PR. # Serialize the CodeQL and license completion events so a pending summary # cannot race a terminal summary into creating two comments. Every validated # callback snapshots the live tuple, so an older-head wake can replace pending @@ -37,16 +40,24 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | - const pullRequests = context.payload.workflow_run.pull_requests || []; - if (pullRequests.length !== 1) { - core.info("Exactly one pull request must be attached to this workflow run."); + const sourceRun = context.payload.workflow_run; + const sourceRepositoryId = sourceRun.head_repository?.id; + const sourceBranch = sourceRun.head_branch; + if (!Number.isSafeInteger(sourceRepositoryId) || sourceRepositoryId <= 0 || + typeof sourceBranch !== "string" || !sourceBranch.trim()) return; + const sourceTitle = String(sourceRun.display_title || "").match( + /^(CodeQL Analysis|License Gate) pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/ + ); + if (!sourceTitle) return; + const issueNumber = Number(sourceTitle[2]); + if (!Number.isSafeInteger(issueNumber)) return; + const pullRequests = sourceRun.pull_requests; + if (!Array.isArray(pullRequests) || + pullRequests.filter((pr) => pr?.number === issueNumber).length !== 1) { + core.info("Exactly one association must match the canonical title's pull request."); return; } - - const pullRequest = pullRequests[0]; - const issueNumber = pullRequest.number; - if (!Number.isSafeInteger(issueNumber) || issueNumber <= 0) return; - const sourceHeadSha = context.payload.workflow_run.head_sha; + const sourceHeadSha = sourceRun.head_sha; if (!/^[0-9a-f]{40}$/.test(sourceHeadSha || "")) return; const { data: currentPullRequest } = await github.rest.pulls.get({ ...context.repo, @@ -71,6 +82,8 @@ jobs: const expectedSourceTitle = `${sourceWorkflowName} pr-${issueNumber} base-${sourceBaseSha} head-${sourceHeadSha}`; if ( currentPullRequest.state !== "open" || + currentPullRequest.head?.repo?.id !== sourceRepositoryId || + currentPullRequest.head?.ref !== sourceBranch || !sourceWorkflowName || !sourceBaseSha || (context.payload.workflow_run.name !== sourceWorkflowName && @@ -287,6 +300,8 @@ jobs: }); if ( finalPullRequest.state !== "open" || + finalPullRequest.head?.repo?.id !== sourceRepositoryId || + finalPullRequest.head?.ref !== sourceBranch || finalPullRequest.head?.sha !== headSha || finalPullRequest.base?.sha !== baseSha ) { diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index f5d402a831..f9d558effd 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -27,7 +27,7 @@ grep -Fq 'per_page: 100' "$workflow" grep -Fq 'cancel-in-progress: false' "$workflow" # GitHub expressions are literal workflow text, not shell expansions. # shellcheck disable=SC2016 -grep -Fq 'group: static-analysis-summary-pr-${{ github.event.workflow_run.pull_requests[0].number || github.run_id }}' "$workflow" +grep -Fq 'group: static-analysis-summary-source-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }}' "$workflow" grep -Fq 'const headSha = currentPullRequest.head?.sha;' "$workflow" grep -Fq 'context.payload.workflow_run.display_title !== expectedSourceTitle' "$workflow" grep -Fq 'finalPullRequest.base?.sha !== baseSha' "$workflow" @@ -101,7 +101,7 @@ const github = { pullRequestReads += 1; if (changeHeadDuringRun && pullRequestReads === 2) currentHeadSha = "e".repeat(40); if (changeBaseDuringRun && pullRequestReads === 2) currentBaseSha = "c".repeat(40); - return { data: { state: "open", head: { sha: currentHeadSha }, base: { sha: currentBaseSha, ref: currentBaseRef } } }; + return { data: { state: "open", head: { sha: currentHeadSha, repo: { id: 123 }, ref: "feature" }, base: { sha: currentBaseSha, ref: currentBaseRef } } }; } }, actions: { listWorkflowRuns: codeqlListWorkflowRuns }, checks: { listForRef: checksListForRef }, @@ -275,6 +275,7 @@ const context = { path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", + head_repository: { id: 123 }, display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, pull_requests: [{ number: 42 }], }, @@ -405,6 +406,38 @@ async function assertCompletionOrders() { global.setTimeout = originalTimeout; } } +async function assertAssociationSelection() { + const source = context.payload.workflow_run; + Object.assign(source, { name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}` }); + const reset = () => { + pullRequestReads = 0; + for (const values of Object.values(calls)) values.length = 0; + }; + for (const associations of [[{number: 99}, {number: 42}], [{number: 42}, {number: 99}]]) { + reset(); source.pull_requests = associations; + await run(github, context, core); + if (calls.updated.length !== 1 || calls.paginate.some(({input}) => input.issue_number && input.issue_number !== 42)) { + throw new Error("unrelated associations must not hide or redirect canonical PR publication"); + } + } + for (const associations of [[{number: 42}, {number: 42}], [{number: 99}], null]) { + reset(); source.pull_requests = associations; + await run(github, context, core); + if (pullRequestReads || calls.paginate.length || calls.updated.length || calls.deleted.length) { + throw new Error("missing or duplicate matching association must fail before provider reads"); + } + } + source.pull_requests = [{number: 42}]; + for (const [repository, branch] of [[null, "feature"], [{id: 0}, "feature"], [{id: 123}, ""], [{id: 456}, "feature"], [{id: 123}, "different"]]) { + reset(); source.head_repository = repository; source.head_branch = branch; + await run(github, context, core); + if (calls.paginate.length || calls.updated.length || calls.deleted.length) { + throw new Error("invalid or mismatched concurrency identity must not publish"); + } + } + source.head_repository = {id: 123}; source.head_branch = "feature"; +} async function assertInterruptedRecovery() { const originalPaginate = github.paginate; const reset = () => { @@ -523,6 +556,7 @@ run(github, context, core).then(async () => { deleteStatus = null; await assertCompletionOrders(); await assertInterruptedRecovery(); + await assertAssociationSelection(); console.log("static analysis summary behavioral contract passed"); }, ); From ab201ea66da94e57a8f9ea4b64c6abb00d44ba55 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:28:59 +1300 Subject: [PATCH 035/199] Bind preview refresh to exact-attempt event tuple metadata --- .github/workflows/hosted-identity-request.yml | 6 +- .github/workflows/preview-reconciler.yml | 5 +- .github/workflows/preview-runtime-refresh.yml | 68 ++++++++++++++++++- .github/workflows/preview.yml | 4 ++ .../architecture/system-architecture-cicd.md | 2 +- ...d-identity-controller-workflow-contract.sh | 19 +++++- dev-tools/tests/preview-priority-contract.sh | 14 ++-- .../preview-runner-isolation-contract.sh | 2 + .../tests/preview-runtime-refresh.test.cjs | 44 ++++++++++-- 9 files changed, 140 insertions(+), 24 deletions(-) diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index 2f09edbd9e..bfe8cf49cd 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -141,9 +141,9 @@ jobs: [[ "$SOURCE_EVENT" == pull_request || "$SOURCE_EVENT" == repository_dispatch ]] || emit_no_action "Ignoring source run with unsupported event ${SOURCE_EVENT}." if [[ "$SOURCE_EVENT" == pull_request ]]; then - jq -e '(.pull_requests | type) == "array" and (.pull_requests | length) == 1 and (.pull_requests[0].number | type) == "number" and .pull_requests[0].head.sha == .head_sha' \ + jq -e '.head_sha as $head | (.pull_requests | type) == "array" and any(.pull_requests[]?; (.number | type) == "number" and .number > 0 and (.number | floor) == .number and .head.sha == $head)' \ <<<"$workflow_run_json" >/dev/null || - emit_no_action "Ignoring source run without a unique bound pull request association." + emit_no_action "Ignoring source run without a bound pull request association." fi if [[ "$SOURCE_EVENT" == repository_dispatch ]]; then require_source_field head-branch "$DEFAULT_BRANCH" \ @@ -184,7 +184,7 @@ jobs: EXPECTED_HEAD_SHA="$(jq -er '.headSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" if [[ "$SOURCE_EVENT" == pull_request ]]; then jq -e --argjson pr "$PR_NUMBER" --arg head "$EXPECTED_HEAD_SHA" \ - '.head_sha == $head and (.pull_requests | length) == 1 and .pull_requests[0].number == $pr and .pull_requests[0].head.sha == $head' \ + '.head_sha == $head and ([.pull_requests[] | select(.number == $pr)] | length) == 1 and ([.pull_requests[] | select(.number == $pr)][0].head.sha == $head)' \ <<<"$workflow_run_json" >/dev/null || emit_no_action "Ignoring artifact not bound to the source run pull request and head." fi diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 2a5879ca7d..45a3678ef8 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -554,8 +554,9 @@ jobs: ) and ( .display_title == $run_name - or (.display_title == $pr_title and .head_sha == $head_sha - and any(.pull_requests[]?; .number == $pr_number)) + or (.display_title == $pr_title + and .head_sha == $head_sha + and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) ) and ( .status == "requested" diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 80eba368fb..bdb4b5009e 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -47,11 +47,73 @@ jobs: run.event !== 'pull_request' || run.conclusion !== 'success' || run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || - run.pull_requests?.length !== 1 || !sha.test(run.head_sha)) { + run.id !== context.payload.workflow_run.id || !sha.test(run.head_sha)) { core.info('No trusted current PR source association; no dispatch.'); return; } - const source = run.pull_requests[0]; + const attempt = context.payload.workflow_run.run_attempt; + if (!Number.isSafeInteger(attempt) || attempt <= 0 || run.run_attempt !== attempt) { + core.info('Source attempt changed or is unavailable; no dispatch.'); + return; + } + const jobs = []; + let total; + for (let page = 1; page <= 3; page++) { + const {data} = await github.request( + 'GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs', + {...context.repo, run_id: run.id, attempt_number: attempt, per_page: 100, page}); + if (!Number.isSafeInteger(data.total_count) || data.total_count < 0 || + data.total_count > 300 || !Array.isArray(data.jobs) || data.jobs.length > 100 || + (total !== undefined && total !== data.total_count)) { + throw new Error('Invalid or truncated source-attempt jobs inventory'); + } + total = data.total_count; + jobs.push(...data.jobs); + if (jobs.length === total) break; + if (jobs.length > total || data.jobs.length < 100 || page === 3) { + throw new Error('Incomplete source-attempt jobs inventory'); + } + } + const plans = jobs.filter(job => job.name === 'Preview Plan'); + if (plans.length !== 1) { + core.info('Missing or ambiguous Preview Plan metadata; await a fresh preview render.'); + return; + } + const plan = plans[0]; + if (plan.run_id !== run.id || plan.run_attempt !== attempt || + plan.head_sha !== run.head_sha || + plan.status !== 'completed' || plan.conclusion !== 'success' || !Array.isArray(plan.steps)) { + core.info('Preview Plan does not belong to the successful source attempt; no dispatch.'); + return; + } + const tupleSteps = plan.steps.filter(step => String(step.name || '').startsWith('Preview event tuple')); + const step = tupleSteps.length === 1 ? tupleSteps[0] : null; + // Native attempt metadata records the event tuple, not authority by itself. + // Bind it to run/head/association and Git merge parents before use. + const recorded = step?.status === 'completed' && step?.conclusion === 'success' + ? String(step.name).match(/^Preview event tuple pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40})$/) + : null; + const sourceNumber = Number(recorded?.[1]); + if (!recorded || !Number.isSafeInteger(sourceNumber) || + recorded[3] !== run.head_sha || !Array.isArray(run.pull_requests)) { + core.info('Missing or invalid immutable preview tuple metadata; await a fresh preview render.'); + return; + } + const associations = run.pull_requests.filter(item => item?.number === sourceNumber); + if (associations.length !== 1) { + core.info('Preview tuple has no unique matching PR association; no dispatch.'); + return; + } + const source = associations[0]; + const {data: recordedMerge} = await github.rest.repos.getCommit({ + ...context.repo, ref: recorded[4], + }); + if (recordedMerge.sha !== recorded[4] || recordedMerge.parents?.length !== 2 || + recordedMerge.parents[0].sha !== recorded[2] || + recordedMerge.parents[1].sha !== recorded[3]) { + core.info('Recorded preview merge does not prove its base/head tuple; no dispatch.'); + return; + } const {data: pr} = await github.rest.pulls.get({ ...context.repo, pull_number: source.number, }); @@ -78,7 +140,7 @@ jobs: const {data: base} = await github.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}`, }); - if (!sha.test(base.object?.sha) || (isIntegrationBase && source.base?.sha === base.object.sha)) { + if (!sha.test(base.object?.sha) || (isIntegrationBase && recorded[2] === base.object.sha)) { core.info('No stale source base to repair; no dispatch.'); return; } diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 8d7a959bde..23d88494e8 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -47,6 +47,10 @@ jobs: eligible: ${{ steps.eligibility.outputs.eligible }} eligibility_reason: ${{ steps.eligibility.outputs.reason }} steps: + - name: Preview event tuple pr-${{ github.event.pull_request.number }} base-${{ github.event.pull_request.base.sha }} head-${{ github.event.pull_request.head.sha }} merge-${{ github.sha }} + if: ${{ github.event_name == 'pull_request' }} + run: ':' + - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index f28d727137..90c616c4ba 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -244,7 +244,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. PR-controlled build and render work has no cluster, registry-write, or hosted-identity requester credentials. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata, binds the unique tuple step to the native run head and uniquely matching PR association, checks the recorded merge parents, and compares its recorded base with the current branch ref instead of treating mutable API association fields as event history. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate policy removal (restoring GitHub default protections) or replacement with only `pull_request` and `repository_dispatch`, then verify natural PR/manual-dispatch paths against the merged code. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 606bd0bd7d..ea291d777c 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6832,7 +6832,7 @@ FAKE_FIXTURE_EXPOSURE_MODE=public \ FAKE_FIXTURE_CERTIFICATE_MODE=standalone FAKE_FIXTURE_EXPOSURE_MODE=public \ run_deploy_target_fixture standalone-public 0 'action=deploy' -# A PR source run must bind both its run head and sole PR association to the artifact head. +# A PR source run must bind both its run head and uniquely selected PR association to the artifact head. FAKE_FIXTURE_WORKFLOW_RUN_JSON="$distinct_source_workflow_run_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ run_deploy_target_fixture distinct-source-head 0 'Ignoring artifact not bound to the source run pull request and head.' @@ -6842,13 +6842,26 @@ run_head_only_json="$(jq -c --arg sha "$distinct_source_sha" '.head_sha=$sha' << association_head_only_json="$(jq -c --arg sha "$distinct_source_sha" '.pull_requests[0].head.sha=$sha' <<<"$valid_workflow_run_json")" FAKE_FIXTURE_WORKFLOW_RUN_JSON="$run_head_only_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ - run_deploy_target_fixture run-head-only 0 'Ignoring source run without a unique bound pull request association.' + run_deploy_target_fixture run-head-only 0 'Ignoring source run without a bound pull request association.' grep -Fxq "action=none" "$TEMP_DIR/deploy-target-run-head-only.output" FAKE_FIXTURE_WORKFLOW_RUN_JSON="$association_head_only_json" \ - run_deploy_target_fixture association-head-only 0 'Ignoring source run without a unique bound pull request association.' + run_deploy_target_fixture association-head-only 0 'Ignoring source run without a bound pull request association.' grep -Fxq "action=none" "$TEMP_DIR/deploy-target-association-head-only.output" +# Unrelated native associations do not erase the uniquely selected artifact target. +for association_order in before after; do + multiple_association_json="$(jq -c --arg order "$association_order" ' + .pull_requests = (if $order == "before" then [{number:901,head:{sha:.head_sha}}] + .pull_requests + else .pull_requests + [{number:901,head:{sha:.head_sha}}] end)' <<<"$valid_workflow_run_json")" + FAKE_FIXTURE_WORKFLOW_RUN_JSON="$multiple_association_json" \ + run_deploy_target_fixture "multiple-associations-${association_order}" 0 'action=deploy' +done +duplicate_target_json="$(jq -c '.pull_requests += .pull_requests' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$duplicate_target_json" \ + run_deploy_target_fixture duplicate-target-association 0 'Ignoring artifact not bound to the source run pull request and head.' +grep -Fxq "action=none" "$TEMP_DIR/deploy-target-duplicate-target-association.output" + FAKE_FIXTURE_ARTIFACTS_JSON='[{"artifacts":[]}]' \ run_deploy_target_fixture missing-canonical 0 \ 'Ignoring source run without exactly one canonical preview artifact.' diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 3b1d516cec..a3ee3aa6f9 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -439,7 +439,7 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == jq -cn \ --argjson runs "${FAKE_ACTIVE_PREVIEW_RUNS_JSON:-[]}" \ --arg requested_status "$active_query_status" \ - '[{workflow_runs:[$runs[] | select(.status == $requested_status) | {id:.databaseId,name:"PR Preview Environment",head_branch:"develop",display_title:.displayTitle,status:.status}]}]' + '[{workflow_runs:[$runs[] | select(.status == $requested_status) | {id:.databaseId,path:".github/workflows/preview.yml",name:"PR Preview Environment",head_branch:"develop",display_title:.displayTitle,status:.status}]}]' fi exit 0 fi @@ -2504,7 +2504,7 @@ reconciler_trusted_consumer_output="$TEMP_DIR/reconciler-trusted-consumer.out" FAKE_PR_901_PROOF_COMPLETE=false \ FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" \ - '[{workflow_runs:[{id:5252,name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title,status:"in_progress"}]}]')" \ + '[{workflow_runs:[{id:5252,path:".github/workflows/hosted-identity-request.yml",name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title,status:"in_progress"}]}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_trusted_consumer_output" @@ -2522,7 +2522,7 @@ reconciler_source_title_consumer_output="$TEMP_DIR/reconciler-source-title-consu FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5253,"name":"Trusted Hosted Identity Request","head_branch":"develop","display_title":"PR preview 901","status":"queued"}]}]' \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5253,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"name":"Trusted Hosted Identity Request","head_branch":"develop","display_title":"PR preview 901","status":"queued"}]}]' \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_source_title_consumer_output" @@ -2540,7 +2540,7 @@ reconciler_pull_request_target_output="$TEMP_DIR/reconciler-pull-request-target. FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5254,"name":"PR Preview Environment","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5254,"path":".github/workflows/preview.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"name":"PR Preview Environment","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_target_output" @@ -2558,7 +2558,7 @@ reconciler_workflow_run_output="$TEMP_DIR/reconciler-workflow-run.out" FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5255,"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5255,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_workflow_run_output" @@ -2576,7 +2576,7 @@ reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-adva FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5256,"event":"branch","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"},{"id":5256,"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"in_progress"}]}]' \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5256,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"branch","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"},{"id":5256,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"in_progress"}]}]' \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" @@ -2712,7 +2712,7 @@ reconciler_paginated_active_output="$TEMP_DIR/reconciler-paginated-active.out" --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" \ '[ {workflow_runs: []}, - {workflow_runs: [{id: 4242, name: "PR Preview Environment", head_branch: "develop", display_title: $title, status: "queued"}]} + {workflow_runs: [{id: 4242, path: ".github/workflows/preview.yml", name: "PR Preview Environment", head_branch: "develop", display_title: $title, status: "queued"}]} ]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index fa3b1b1244..7f3ad49bda 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -119,6 +119,8 @@ active_run = { "firemud_reconciler_branch_filtered": False, } assert active_ids(active_run) == "1" +assert active_ids({**active_run, "pull_requests": [{"number": 8}, {"number": 7}]}) == "1" +assert active_ids({**active_run, "pull_requests": [{"number": 7}, {"number": 7}]}) == "" for fields in ( {"path": ".github/workflows/unrelated.yml"}, {"head_sha": "b" * 40}, diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 7872782e67..02cd35196b 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -8,21 +8,29 @@ const workflow = JSON.parse(execFileSync('python3', ['-c', path.join(root, '.github/workflows/preview-runtime-refresh.yml')], {encoding: 'utf8'})); const script = workflow.jobs.refresh.steps[1].with.script; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const E = 'e'.repeat(40); const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40), D = 'd'.repeat(40); function fixture() { return { - run: {path: '.github/workflows/preview.yml', event: 'pull_request', conclusion: 'success', + run: {id: 99, run_attempt: 2, display_title: `PR preview 7 base-${D} head-${C} merge-${E}`, path: '.github/workflows/preview.yml', event: 'pull_request', conclusion: 'success', repository: {full_name: 'example/FireMUD'}, head_repository: {full_name: 'example/FireMUD'}, head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: D}}]}, pr: {number: 7, state: 'open', head: {sha: C, repo: {full_name: 'example/FireMUD'}}, base: {ref: 'develop', repo: {full_name: 'example/FireMUD'}}, merge_commit_sha: A, labels: [], user: {login: 'developer'}}, + jobs: [{name: 'Preview Plan', run_id: 99, run_attempt: 2, head_sha: C, workflow_name: 'PR Preview Environment', status: 'completed', conclusion: 'success', steps: [{name: `Preview event tuple pr-7 base-${D} head-${C} merge-${E}`, status: 'completed', conclusion: 'success'}]}], + recordedMerge: {sha: E, parents: [{sha: D}, {sha: C}]}, base: {object: {sha: B}}, merge: {sha: A, parents: [{sha: B}, {sha: C}]}, }; } async function execute(f) { const sent = []; - const github = {rest: { + const github = {request: async (route, args) => { + assert.equal(route, 'GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs'); + assert.equal(args.run_id, 99); assert.equal(args.attempt_number, 2); + assert.equal(args.per_page, 100); assert.ok(args.page <= 3); + return {data: f.inventory ?? {total_count: f.jobs.length, jobs: f.jobs}}; + }, rest: { actions: { getWorkflowRun: async () => ({data: f.run}), getWorkflow: async () => ({data: {id: 42, path: '.github/workflows/runtime-images.yml'}}), @@ -39,10 +47,10 @@ async function execute(f) { assert.equal(ref, 'heads/' + f.pr.base.ref); return {data: f.base}; }}, - repos: {getCommit: async () => ({data: f.merge}), createDispatchEvent: async p => sent.push(p)}, + repos: {getCommit: async ({ref}) => ({data: ref === E ? f.recordedMerge : f.merge}), createDispatchEvent: async p => sent.push(p)}, }}; await new AsyncFunction('github', 'context', 'core', 'require', script)(github, - {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99}, repository: {default_branch: 'develop'}}}, {info() {}}, name => { + {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99, run_attempt: 2}, repository: {default_branch: 'develop'}}}, {info() {}}, name => { assert.equal(name, 'node:child_process'); return {execFileSync(command, args, options) { if (command === 'python3') { @@ -82,7 +90,19 @@ for (const [name, mutate] of Object.entries({ malformedLabels: f => f.pr.labels = [{name: 3}], appBot: f => f.pr.user.login = 'app/renovate', bot: f => f.pr.user.login = 'renovate[bot]', - currentBase: f => f.run.pull_requests[0].base.sha = B, + currentBase: f => { f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${B} head-${C} merge-${E}`; f.recordedMerge.parents[0].sha = B; }, + legacyTitle: f => f.jobs[0].steps = [], + missingTitle: f => f.jobs = [], + spoofTitleHead: f => f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${D} head-${B} merge-${E}`, + badRecordedParent: f => f.recordedMerge.parents[0].sha = B, + missingRecordedParent: f => f.recordedMerge.parents.pop(), + wrongRun: f => f.run.id = 100, + wrongAttempt: f => f.run.run_attempt = 3, + wrongJobAttempt: f => f.jobs[0].run_attempt = 3, + duplicatePlan: f => f.jobs.push(f.jobs[0]), + duplicateTuple: f => f.jobs[0].steps.push(f.jobs[0].steps[0]), + failedTuple: f => f.jobs[0].steps[0].conclusion = "failure", + malformedTuple: f => f.jobs[0].steps[0].name = "Preview event tuple invalid", invalidBase: f => f.base.object.sha = 'invalid', invalidMerge: f => f.pr.merge_commit_sha = 'invalid', wrongMerge: f => f.merge.sha = D, @@ -226,3 +246,17 @@ test('qualified other PR workflow path cannot suppress native producer', async ( r.path += '@refs/pull/8/merge'; f.producers = [r]; assert.equal((await execute(f)).length, 1); }); + +test('immutable title repairs base despite current mutable association', async () => { + const f = fixture(); + f.run.pull_requests[0].base.sha = B; + f.run.pull_requests.unshift({number: 99, head: {sha: C}, base: {sha: B}}); + assert.equal((await execute(f)).length, 1); +}); + +test('truncated or oversized attempt inventory is refused', async () => { + for (const inventory of [{total_count: 301, jobs: []}, {total_count: 2, jobs: []}]) { + const f = fixture(); f.inventory = inventory; + await assert.rejects(execute(f), /inventory/); + } +}); From 8362d74bd49f3c6477f3c48c48e8c3a0440fa60f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:34:46 +1300 Subject: [PATCH 036/199] Keep classifier contract aligned with conservative module fallback --- dev-tools/tests/ci-lightweight-scope-contract.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index a32f22642b..37868bee60 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -1469,10 +1469,18 @@ require_equal( "ci workflow", ) ci_compute_step = find_step(ci, "changes", "Compute affected jobs", "ci workflow") +for guard in ( + "completeModules.every(module => ALL_MODULES.includes(module))", + "run_all: scope.runAll || !moduleScopeAvailable", + "affected_modules: moduleScopeAvailable ? scope.affectedModules : completeModules", + "bootable_modules: moduleScopeAvailable ? scope.bootableModules : completeBootableModules", + "lightweight_only: moduleScopeAvailable && scope.lightweightOnly", +): + require_contains(ci_compute_step, ("with", "script"), guard, "ci workflow") require_contains( ci_compute_step, ("with", "script"), - "const { classifyGithubChangeScope } = require(classifierPath)", + "const { classifyGithubChangeScope, ALL_MODULES } = require(classifierPath)", "ci workflow", ) require_contains( From 466969b12923ef71c4e0ef6570efe8182f752107 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:11:13 +1300 Subject: [PATCH 037/199] Align retarget contract with runtime producer preservation --- dev-tools/tests/pr-retarget-workflow-contract.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index d620be5987..b0f3698d96 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -700,7 +700,7 @@ if "github.sha" in concurrency_group.split("github.event_name == 'repository_dis raise SystemExit("repository_dispatch concurrency must not use the default-branch github.sha") # Execute the workflow-level selector before its dispatcher can classify a CI # callback. A title/body CI completion must not evict substantive reconciliation. -assert runtime["concurrency"]["cancel-in-progress"] == "true" +assert runtime["concurrency"]["cancel-in-progress"] == "false", "duplicate requests must not cancel a useful running producer" def callback_group(branch, source_id, source_attempt, source_event="pull_request", head="a" * 40): values = { @@ -728,8 +728,8 @@ for branch in ("main", "develop", "feature/parent"): metadata = callback_group(branch, 7002, 1) subsequent_attempt = callback_group(branch, 7001, 2) active = {} - # With cancel-in-progress enabled, assigning the same group evicts its - # earlier run. Interleave both callback orders to retain substantive work. + # Distinct callbacks must remain independently schedulable, even while + # duplicate requests preserve the running producer. Test both arrival orders. for callbacks in (((substantive, "substantive"), (metadata, "metadata")), ((metadata, "metadata"), (substantive, "substantive"))): active.clear() @@ -1560,7 +1560,7 @@ require_contains "$runtime_images_path" 'types: [opened, synchronize, reopened, require_contains "$runtime_images_path" 'types: [pr-runtime-base-refresh]' require_contains "$runtime_images_path" 'repository_dispatch:' require_contains "$runtime_images_path" "&& 'metadata' || 'required' }}" -require_contains "$runtime_images_path" ' cancel-in-progress: true' +require_contains "$runtime_images_path" ' cancel-in-progress: false' require_contains "$runtime_images_path" 'run-name: Build Runtime Images ' require_contains "$runtime_images_path" "format('secure-pr-artifact pr-{0}" require_contains "$runtime_images_path" 'github.event.pull_request.base.sha' From 9aee501fc52141e2918c804e51f3a892efe3e0f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:02:55 +1300 Subject: [PATCH 038/199] Trim hosted dev and preview JVM memory footprint Add previewStack.jvm to the hosted Helm chart and render JAVA_TOOL_OPTIONS (C1-only JIT, 64 MiB code cache, 512 KiB stacks) and MALLOC_ARENA_MAX=2 on every app service. Measured on the dev image set locally: idle RSS for the 11 JVMs fell from 3596 MiB to 3112 MiB with heap sizing unchanged. Co-Authored-By: Claude Opus 5.5 --- .../infrastructure/deployment-environments.md | 1 + k8s/helm/firemud/templates/apps.yaml | 13 +++++++++++++ k8s/helm/firemud/values.yaml | 6 ++++++ 3 files changed, 20 insertions(+) diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 84e7ac59f2..8afab81148 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -357,6 +357,7 @@ The hosted identity controller's egress boundary is exact-destination and operat - Preview deploys currently reset the namespace before each Helm apply, then reseed the minimum bootstrap state needed for reviewer proof. Within one deployed preview instance, PostgreSQL, MinIO/object storage, and other stateful components persist across normal pod restarts and VM reboot, but preview state does not currently persist across preview redeploys. - Preview state is not backed up and is not durable beyond the single preview node. If the node or its attached storage is lost, preview state is lost. - The initial Hetzner/k3s sizing target is one reliably usable full-stack preview on an 8 GB shared-CPU x86 VM. A second concurrent preview is best-effort only and may fail to deploy if capacity is exhausted. +- Hosted dev and preview app services share one JVM footprint profile owned by `previewStack.jvm` in the [hosted Helm chart values](../../../k8s/helm/firemud/values.yaml): C1-only JIT, a 64 MiB reserved code cache, 512 KiB thread stacks, and two glibc malloc arenas. It trades peak JIT throughput for lower resident memory and does not apply to the player-facing Kustomize overlays. - Open, mergeable, non-dependency-bot same-repository pull requests targeting `main` or `develop` request preview allocation automatically. A stacked pull request whose base is another current branch in the same repository is eligible only while it carries the maintainer-controlled `preview:priority` label; forks and dependency-bot updates remain ineligible. Ordinary allocation in the bounded two-slot pool is first-come at the serialized allocation boundary while capacity remains available; GitHub's raw job-scheduling order is not itself an allocation guarantee. The priority label lets a later priority request claim a free slot or reclaim the oldest ordinary preview, but never another currently priority-labelled preview. Allocation, deployment, hosted proof, reclaim, and cleanup share one durable bounded non-cancelling lifecycle queue so a running proof is not deleted underneath itself and normal waiting lifecycle work uses GitHub's expanded queue instead of its replaceable single pending slot. Both target and victim label state are re-read immediately before reclaim. Removing the label from an ordinary `main`/`develop` pull request returns its environment to ordinary status; removing it from a stacked pull request makes that preview ineligible and permits trusted cleanup. A displaced pull request keeps its ordinary CI and historical preview result, while its current hosted status reports that no environment is allocated. - Each successfully allocated eligible preview receives its own namespace and holds a bounded renewable visible lease. An ordinary active lease is protected except for the explicit priority rule above; a priority-labelled active lease is not silently evicted, while an expired lease may be reclaimed even if the pull request remains open. A request that is eligible but not allocated, including because capacity is exhausted or every slot is priority-protected, reports `preview_unavailable`, not passed. - Any review claiming hosted proof requires successful evidence for its current base SHA, head SHA, two-parent merge SHA, and selected immutable image tag. A parent advance invalidates the prior proof even when the child head is unchanged. diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index fdf42aacae..e575b41e13 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -105,6 +105,9 @@ {{- end }} {{- end }} {{- range $key, $_ := $service.extraEnv }} +{{- if has $key (list "JAVA_TOOL_OPTIONS" "MALLOC_ARENA_MAX") }} +{{- fail (printf "previewStack.services.%s.extraEnv key %s collides with the managed previewStack.jvm environment" $service.name $key) }} +{{- end }} {{- if and $mountTelnetTls (has $key $managedTelnetEnv) }} {{- fail (printf "previewStack.services.%s.extraEnv key %s collides with the managed Telnet TLS environment" $service.name $key) }} {{- end }} @@ -192,6 +195,16 @@ spec: value: {{ printf "flyway_schema_history_%s" (default (replace "-" "_" $service.name) $service.schema) | quote }} - name: SERVICE_SCHEMA value: {{ default (replace "-" "_" $service.name) $service.schema | quote }} + {{- with $.Values.previewStack.jvm }} + {{- if .javaToolOptions }} + - name: JAVA_TOOL_OPTIONS + value: {{ .javaToolOptions | quote }} + {{- end }} + {{- if .mallocArenaMax }} + - name: MALLOC_ARENA_MAX + value: {{ .mallocArenaMax | quote }} + {{- end }} + {{- end }} {{- if $service.mountGrpcTls }} {{- if or $usesGrpcWorkloadIdentity (eq $service.name "logging-admin-service") $mountGameplayClientTls }} - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 880ddb6e8b..65d88e3932 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -1,5 +1,11 @@ previewStack: enabled: false + # JVM footprint for the hosted dev and preview stacks, applied to every app + # service. C1-only JIT, a smaller code cache and thread stacks, and two glibc + # malloc arenas cut idle RSS by about 13% with heap sizing unchanged. + jvm: + javaToolOptions: "-XX:TieredStopAtLevel=1 -XX:ReservedCodeCacheSize=64m -Xss512k" + mallocArenaMax: "2" # Hosted environments use the HostedEnvironmentIdentity controller for # certificate identity. Local installs retain standalone cert-manager mode. certificateIdentity: From 090f1c52c8b2a81136c3d61e9d0721b7e86097fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:10:03 +1300 Subject: [PATCH 039/199] Skip required gates on PR metadata-only edits A title or description edit (edited with no base change) now skips every job in the five required-gate workflows, and each gate skips under a non-required "PR Metadata Edit ()" name. The earlier substantive result stands, a retarget still reruns the full gates, and an edit can no longer turn a failing PR green. This retires the metadata preservation machinery: the preserve-required-gate and publish-required-gate-status actions, the Resolve Required Gates callback, their supplementary pending statuses and the extra gate permissions. The runtime-image CI callback and Static Analysis Summary now ignore metadata runs by gate name, and the required-gate contract keeps its smoke fingerprint and PLAY-transition coverage. Co-Authored-By: Claude Opus 5.5 --- .../actions/preserve-required-gate/action.yml | 37 - .../assess-required-gate.sh | 641 ---- .../resolve-deferred-gate.sh | 641 ---- .../validate-exact-attempt-gate.sh | 138 - .../publish-required-gate-status/action.yml | 41 - .../publish-required-gate-status.sh | 212 -- .github/workflows/ci.yml | 67 +- .github/workflows/codeql.yml | 57 +- .github/workflows/license-scan.yml | 57 +- .github/workflows/resolve-required-gates.yml | 68 - .github/workflows/runtime-images.yml | 6 +- .github/workflows/security.yml | 57 +- .github/workflows/smoke.yml | 63 +- .github/workflows/static-analysis-summary.yml | 28 +- .github/workflows/validation-summary.yml | 2 +- .../architecture/system-architecture-cicd.md | 36 +- design/developer-workflows/pr-lifecycle.md | 2 +- .../platform-operations-and-delivery.md | 10 +- .../tests/ci-validation-summary-contract.sh | 7 +- .../pr-required-gate-context-contract.sh | 3139 +---------------- .../tests/pr-retarget-workflow-contract.sh | 44 +- .../tests/static-analysis-summary-contract.sh | 25 +- 22 files changed, 211 insertions(+), 5167 deletions(-) delete mode 100644 .github/actions/preserve-required-gate/action.yml delete mode 100644 .github/actions/preserve-required-gate/assess-required-gate.sh delete mode 100644 .github/actions/preserve-required-gate/resolve-deferred-gate.sh delete mode 100644 .github/actions/preserve-required-gate/validate-exact-attempt-gate.sh delete mode 100644 .github/actions/publish-required-gate-status/action.yml delete mode 100644 .github/actions/publish-required-gate-status/publish-required-gate-status.sh delete mode 100644 .github/workflows/resolve-required-gates.yml diff --git a/.github/actions/preserve-required-gate/action.yml b/.github/actions/preserve-required-gate/action.yml deleted file mode 100644 index d4de614d06..0000000000 --- a/.github/actions/preserve-required-gate/action.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Preserve Required Gate -description: Preserve a successful required check context for metadata-only pull request edits. -inputs: - gate-name: - description: Required check name to preserve. - required: true - workflow-name: - description: Exact workflow display name that owns the required gate. - required: true - workflow-file: - description: Workflow filename used to resolve the owning workflow identity. - required: true - workflow-path: - description: Exact workflow path returned by the Actions API. - required: true -outputs: - assessment: - description: Successful proof or dependency-deferred assessment; invalid proof fails the action. - value: ${{ steps.preserve.outputs.assessment }} -runs: - using: composite - steps: - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - name: Assess prior required gate - id: preserve - shell: bash - env: - GH_TOKEN: ${{ github.token }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REQUIRED_GATE_NAME: ${{ inputs.gate-name }} - EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }} - EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }} - EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }} - run: bash "$GITHUB_ACTION_PATH/assess-required-gate.sh" diff --git a/.github/actions/preserve-required-gate/assess-required-gate.sh b/.github/actions/preserve-required-gate/assess-required-gate.sh deleted file mode 100644 index f76d200da7..0000000000 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ /dev/null @@ -1,641 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ "${GITHUB_EVENT_NAME:-}" != "pull_request" ]]; then - echo "Required-gate preservation requires pull_request context; refusing to preserve." >&2 - exit 1 -fi -for required_variable in GH_TOKEN BASE_SHA HEAD_SHA PR_NUMBER REQUIRED_GATE_NAME EXPECTED_WORKFLOW_NAME EXPECTED_WORKFLOW_FILE EXPECTED_WORKFLOW_PATH GITHUB_REPOSITORY GITHUB_RUN_ID; do - if [[ -z "${!required_variable:-}" ]]; then - echo "Required-gate preservation is missing ${required_variable}; refusing to preserve." >&2 - exit 1 - fi -done -is_github_sha() { - [[ "$1" =~ ^[0-9A-Fa-f]{40}$ ]] -} -if ! is_github_sha "${BASE_SHA}"; then - echo "Required-gate preservation requires a valid pull request base SHA; refusing to preserve." >&2 - exit 1 -fi -if ! is_github_sha "${HEAD_SHA}"; then - echo "Required-gate preservation requires a valid pull request head SHA; refusing to preserve." >&2 - exit 1 -fi -if [[ ! "${PR_NUMBER}" =~ ^[1-9][0-9]*$ ]]; then - echo "Required-gate preservation requires a valid pull request number; refusing to preserve." >&2 - exit 1 -fi -if [[ ! "${EXPECTED_WORKFLOW_FILE}" =~ ^[A-Za-z0-9._-]+\.(yml|yaml)$ || - ! "${EXPECTED_WORKFLOW_PATH}" =~ ^\.github/workflows/[A-Za-z0-9._-]+\.(yml|yaml)$ || - "${EXPECTED_WORKFLOW_PATH}" != ".github/workflows/${EXPECTED_WORKFLOW_FILE}" ]]; then - echo "Required-gate preservation received invalid workflow or job identity; refusing to preserve." >&2 - exit 1 -fi -expected_display_title="${EXPECTED_WORKFLOW_NAME} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" -report_assessment() { - if [[ -n "${GITHUB_OUTPUT:-}" ]]; then - printf 'assessment=%s\n' "$1" >>"${GITHUB_OUTPUT}" - else - echo "One-assessment preservation requires GITHUB_OUTPUT; refusing to preserve." >&2 - exit 1 - fi -} -defer_dependency() { - echo "Required-gate proof is not yet conclusive; deferring without polling." >&2 - report_assessment dependency-deferred - exit 0 -} -is_retryable_gh_failure() { - local exit_status="$1" - local error_text="${2,,}" - if [[ "$error_text" =~ http[[:space:]]+5[0-9]{2} ]]; then - return 0 - fi - if [[ "$error_text" =~ http[[:space:]]+(403|429) ]] && - [[ "$error_text" =~ (rate[[:space:]-]*limit|abuse) ]]; then - return 0 - fi - if [[ "$exit_status" -ne 0 ]] && - [[ "$error_text" =~ (could[[:space:]]not[[:space:]]resolve|failed[[:space:]]to[[:space:]](connect|make[[:space:]]request)|error[[:space:]]connecting|unable[[:space:]]to[[:space:]]connect|connection[[:space:]](reset|refused|timed|closed)|network[[:space:]]is[[:space:]]unreachable|timed[[:space:]]out|timeout|temporary[[:space:]]failure|tls|eof) ]]; then - return 0 - fi - return 1 -} - -is_github_timestamp() { - [[ "$1" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] -} - -recover_validation_job_from_attempt() { - local attempt attempt_snapshot cache_key expected_branch expected_head_repository - attempt_recovered_job_json='' - [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && - "${REQUIRED_GATE_NAME}" == "Validation Gate" ]] || return 1 - attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' <<<"${job_json}")" || return 1 - cache_key="${workflow_run_id}:${attempt}:${job_id}:${check_run_id}" - if [[ -n "${attempt_snapshot_cache[${cache_key}]:-}" ]]; then - attempt_recovered_job_json="$(jq -cer '.job' <<<"${attempt_snapshot_cache[${cache_key}]}")" || return 1 - return 0 - fi - if (( attempt_recovery_reads >= attempt_recovery_read_limit )); then - echo "Exact-attempt historical sparse-candidate recovery exhausted its ${attempt_recovery_read_limit}-snapshot budget; refusing to assess." >&2 - return 3 - fi - attempt_recovery_reads=$((attempt_recovery_reads + 1)) - expected_branch="$(jq -er '.head_branch | select(type == "string" and length > 0)' <<<"${workflow_run_json}")" || return 1 - expected_head_repository="$(jq -er '.head_repository.full_name | select(type == "string" and length > 0)' <<<"${workflow_run_json}")" || return 1 - attempt_snapshot="$(bash "$(dirname "${BASH_SOURCE[0]}")/validate-exact-attempt-gate.sh" \ - "${workflow_run_id}" "${attempt}" "${job_id}" "${check_run_id}" \ - "${REQUIRED_GATE_NAME}" "${expected_workflow_id}" "${EXPECTED_WORKFLOW_NAME}" \ - "${EXPECTED_WORKFLOW_PATH}" "${expected_display_title}" "${PR_NUMBER}" \ - "${BASE_SHA}" "${HEAD_SHA}" "${expected_branch}" "${GITHUB_REPOSITORY}" \ - "${expected_head_repository}" "${check_status}" "${conclusion}" \ - "${details_url}" "${started_at}" "${completed_at}" false)" || return 1 - attempt_snapshot_cache["${cache_key}"]="${attempt_snapshot}" - attempt_recovered_job_json="$(jq -cer '.job' <<<"${attempt_snapshot}")" || return 1 - return 0 -} - -api_error_file="$(mktemp)" -trap 'rm -f "$api_error_file"' EXIT -expected_workflow_id="" -declare -A workflow_run_cache=() -declare -A job_cache=() -declare -A attempt_snapshot_cache=() -attempt_recovery_reads=0 -attempt_recovery_read_limit=3 -attempt_recovered_job_json='' - -# Recognize only the observed pre-execution Validation cancellation shape. A -# cancelled workflow may still contain genuine failures; its conclusion alone -# never suppresses a failed gate. Return 0 only for independently bound proof. -validation_cancelled_before_checks() { - local attempt run_snapshot jobs_snapshot check_snapshot native_job check_id - attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' <<<"${job_json}")" || return 1 - run_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}/attempts/${attempt}")" || return 1 - jq -e --argjson original "${workflow_run_json}" --argjson attempt "${attempt}" ' - . as $run | .run_attempt == $attempt and .status == "completed" and .conclusion == "cancelled" and - all(["id", "workflow_id", "name", "path", "head_sha", "display_title", "repository", "event"][]; - . as $key | $run[$key] == $original[$key]) - ' <<<"${run_snapshot}" >/dev/null || return 1 - jobs_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}/attempts/${attempt}/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jq -e --argjson run "${workflow_run_id}" --argjson attempt "${attempt}" \ - --arg head "${HEAD_SHA}" --arg repo "${GITHUB_REPOSITORY}" --argjson gate "${job_json}" ' - ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - ("Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})"), - ("Build and Test (account-service / $" + "{{ matrix.partition }})"), - ("Build and Test (world-management-service / $" + "{{ matrix.partition }})"), - ("Build and Test (game-session-service / $" + "{{ matrix.partition }})"), "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", - "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", - "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", - "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", "Account Coverage Aggregate", - "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] as $historical_names - | [$gate.steps[] | select(.name == "Declare dev tool contract split")] as $split_markers - | (if ($split_markers | length) == 1 - then [($historical_names + ["Dev Tool Validation Contracts"])] - else [$historical_names, ($historical_names + ["Dev Tool Validation Contracts"])] end) as $inventories - | .[0] as $snapshot - | type == "array" and length == 1 and ($snapshot.jobs | type) == "array" and - ($split_markers | length) <= 1 and - any($inventories[]; . as $names | - $snapshot.total_count == ($names | length) and - ($snapshot.jobs | length) == ($names | length) and - ([$snapshot.jobs[].id] | unique | length) == ($names | length) and - ([$snapshot.jobs[].name] | sort) == ($names | sort)) and - all(.[0].jobs[]; (.id | type) == "number" and .id > 0 and .id == (.id | floor) and - .run_id == $run and .run_attempt == $attempt and .head_sha == $head and .status == "completed" and - (.check_run_url | type) == "string" and - (.check_run_url | startswith("https://api.github.com/repos/" + $repo + "/check-runs/")) and - (.check_run_url | split("/check-runs/") | last | test("^[1-9][0-9]*$")) and - if .name == "Validation Gate" then - . == $gate and .conclusion == "failure" and (.steps | type) == "array" and - ([.steps[] | select(.name == "Enforce validation success" and .status == "completed" and .conclusion == "failure")] | length) == 1 and - ([.steps[] | select(.name == "Preserve successful required gate on metadata-only edit" and .status == "completed" and .conclusion == "skipped")] | length) == 1 and - all(.steps[]; .status == "completed" and - (if .name == "Enforce validation success" then .conclusion == "failure" - else (.conclusion == "success" or .conclusion == "skipped") end)) - elif (.name == "Account Coverage Aggregate" or .name == "Game Session Coverage Aggregate" or .name == "World Coverage Aggregate") then - (.conclusion == "cancelled" or .conclusion == "skipped") and .steps == [] - else .conclusion == "cancelled" and .steps == [] end) - ' <<<"${jobs_snapshot}" >/dev/null || return 1 - while IFS= read -r native_job; do - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${native_job}")" || return 1 - check_snapshot="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${check_id}")" || return 1 - jq -e --argjson job "${native_job}" --argjson id "${check_id}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $job.head_sha and .name == $job.name and .status == $job.status and - .conclusion == $job.conclusion and .details_url == $job.html_url - ' <<<"${check_snapshot}" >/dev/null || return 1 - done < <(jq -c '.[0].jobs[]' <<<"${jobs_snapshot}") -} - -# A metadata-only run emits this same gate name. Its preservation step -# identifies the recursive run; substantive gates skip that step and -# remain authoritative, including failures. -: >"${api_error_file}" -if [[ -z "${expected_workflow_id}" ]]; then - set +e - workflow_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/workflows/${EXPECTED_WORKFLOW_FILE}" \ - 2>"${api_error_file}")" - workflow_status=$? - set -e - if [[ "${workflow_status}" -ne 0 ]]; then - api_error="$(<"${api_error_file}")" - if ! is_retryable_gh_failure "${workflow_status}" "${api_error}"; then - echo "Permanent GitHub API/configuration failure while resolving the expected ${EXPECTED_WORKFLOW_PATH}; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - echo "GitHub API failure while resolving the expected workflow identity; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - set +e - expected_workflow_id="$(jq -r \ - --arg expected_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_path "${EXPECTED_WORKFLOW_PATH}" \ - 'if (.id | type) == "number" and - .name == $expected_name and - .path == $expected_path - then (.id | tostring) else "__missing__" end' \ - <<<"${workflow_json}" 2>>"${api_error_file}")" - workflow_query_status=$? - set -e - if [[ "${workflow_query_status}" -ne 0 || - ! "${expected_workflow_id}" =~ ^[0-9]+$ ]]; then - echo "GitHub API returned malformed expected workflow identity; refusing to preserve." >&2 - exit 1 - fi -fi -set +e -check_runs_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/check-runs" \ - -f check_name="${REQUIRED_GATE_NAME}" \ - -f filter=all \ - -f per_page=100 \ - --paginate \ - --slurp \ - 2>"${api_error_file}")" -api_status=$? -set -e -if [[ "${api_status}" -ne 0 ]]; then - api_error="$(<"${api_error_file}")" - if ! is_retryable_gh_failure "${api_status}" "${api_error}"; then - echo "Permanent GitHub API/configuration failure while checking the prior ${REQUIRED_GATE_NAME}; refusing to retry." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 - fi - echo "GitHub API failure while checking prior required-gate evidence; refusing to preserve." >&2 - [[ -z "${api_error}" ]] || printf '%s\n' "${api_error}" >&2 - exit 1 -fi - -set +e -jq -e ' - if type != "array" or length == 0 then false - elif any(.[]; type != "object" or (.check_runs | type) != "array") then false - else - .[0].total_count as $total - | all(.[]; (.total_count | type) == "number" and .total_count >= 0 and - .total_count == (.total_count | floor) and .total_count == $total) - and ([.[].check_runs[]] | length) == $total - and all(.[].check_runs[]; type == "object" and (.id | type) == "number" and - .id > 0 and .id == (.id | floor)) - and ([.[].check_runs[].id] | unique | length) == $total - end -' <<<"${check_runs_json}" >/dev/null 2>>"${api_error_file}" -check_runs_shape_status=$? -set -e -if [[ "${check_runs_shape_status}" -ne 0 ]]; then - echo "GitHub API returned malformed or incomplete check-run data for the prior ${REQUIRED_GATE_NAME}; refusing to preserve." >&2 - exit 1 -fi - -set +e -candidate_rows="$(jq -r --arg run_id "${GITHUB_RUN_ID}" ' - [.[].check_runs[]? - | select(((.details_url // "") | contains("/actions/runs/\($run_id)/") | not)) - ] as $candidates - | $candidates[] - | [ - (.app.slug // "__missing__"), - (.name // "__missing__"), - (.details_url // "__missing__"), - (if (.id | type) == "number" then (.id | tostring) else "__missing__" end), - (.status // "__missing__"), - (.conclusion // "__null__"), - (.completed_at // "__null__"), - (.started_at // "__null__") - ] - | @tsv' <<<"${check_runs_json}" 2>>"${api_error_file}")" -query_status=$? -set -e -if [[ "${query_status}" -ne 0 ]]; then - echo "GitHub API returned malformed check-run data for the prior ${REQUIRED_GATE_NAME}; refusing to preserve." >&2 - exit 1 -fi - -authoritative_rows=() -pending_rows=() -job_lookup_retryable=false -retry_reason="" -retry_error_text="" -candidate_ambiguous=false -while IFS=$'\t' read -r app_slug check_name details_url check_run_id check_status conclusion completed_at started_at; do - if [[ -z "${app_slug}${check_name}${details_url}${check_run_id}${check_status}${conclusion}${completed_at}${started_at}" ]]; then - continue - fi - if [[ "${app_slug}" != "github-actions" || - "${check_name}" == "__missing__" || - "${check_name}" != "${REQUIRED_GATE_NAME}" || - "${details_url}" == "__missing__" || - "${check_run_id}" == "__missing__" || - "${check_status}" == "__missing__" || - ! "${check_run_id}" =~ ^[0-9]+$ ]]; then - candidate_ambiguous=true - continue - fi - [[ "${conclusion}" == "__null__" ]] && conclusion="" - [[ "${completed_at}" == "__null__" ]] && completed_at="" - [[ "${started_at}" == "__null__" ]] && started_at="" - if [[ ! "${details_url}" =~ /actions/runs/([0-9]+)/job/([0-9]+)([?#].*)?$ ]]; then - candidate_ambiguous=true - continue - fi - workflow_run_id="${BASH_REMATCH[1]}" - job_id="${BASH_REMATCH[2]}" - - workflow_run_json="${workflow_run_cache[${workflow_run_id}]:-}" - if [[ -z "${workflow_run_json}" ]]; then - : >"${api_error_file}" - set +e - workflow_run_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/runs/${workflow_run_id}" \ - 2>"${api_error_file}")" - workflow_run_status=$? - set -e - if [[ "${workflow_run_status}" -ne 0 ]]; then - workflow_run_error="$(<"${api_error_file}")" - if is_retryable_gh_failure "${workflow_run_status}" "${workflow_run_error}"; then - job_lookup_retryable=true - retry_reason="workflow-run API lookup" - retry_error_text="${workflow_run_error}" - break - fi - echo "Permanent GitHub API/configuration failure while identifying prior ${REQUIRED_GATE_NAME} workflow run; refusing to preserve." >&2 - [[ -z "${workflow_run_error}" ]] || printf '%s\n' "${workflow_run_error}" >&2 - exit 1 - fi - workflow_run_cache["${workflow_run_id}"]="${workflow_run_json}" - fi - set +e - workflow_run_identity_state="$(jq -r \ - --arg expected_id "${workflow_run_id}" \ - --arg expected_workflow_id "${expected_workflow_id}" \ - --arg expected_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_path "${EXPECTED_WORKFLOW_PATH}" \ - --arg expected_head "${HEAD_SHA}" \ - --arg expected_base "${BASE_SHA}" \ - --arg expected_repository "${GITHUB_REPOSITORY}" \ - --arg expected_pr "${PR_NUMBER}" \ - --arg expected_display_title "${expected_display_title}" \ - '. as $run - | ((try (.display_title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$")) catch null) // {}) as $title - | if ($run.id | type) == "number" and - ($run.workflow_id | type) == "number" and - ($run.id == ($expected_id | tonumber)) and - ($run.workflow_id == ($expected_workflow_id | tonumber)) and - ($run.name == $expected_name or $run.name == $expected_display_title) and - ( - $run.path == $expected_path or - ( - ($run.path | startswith($expected_path + "@")) and - (($run.path | ltrimstr($expected_path + "@")) | test("^.+$")) - ) - ) and - $run.head_sha == $expected_head and - $run.repository.full_name == $expected_repository and - $run.event == "pull_request" and - (($run.pull_requests // null) | type) == "array" and - ( - (($run.pull_requests | length) > 0 and - any($run.pull_requests[]; ((.number // null) | tostring) == $expected_pr)) or - (($run.pull_requests | length) == 0 and - ($run.display_title // null) == $expected_display_title) - ) - then - if ($run.display_title // null) == $expected_display_title then - "current" - elif (($run.pull_requests | length) > 0) and - $title.name == $expected_name and $title.pr == $expected_pr and - any($run.pull_requests[]; - ((.number // null) | tostring) == $expected_pr and - (.base.sha // "") == $title.base and - (.head.sha // "") == $title.head and - ((.base.sha // "") != $expected_base or (.head.sha // "") != $expected_head)) - then - "stale" - else - "invalid" - end - else "invalid" end' \ - <<<"${workflow_run_json}" 2>>"${api_error_file}")" - workflow_run_query_status=$? - set -e - if [[ "${workflow_run_query_status}" -ne 0 || - ( "${workflow_run_identity_state}" != "current" && - "${workflow_run_identity_state}" != "stale" ) ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${workflow_run_identity_state}" == "stale" ]]; then - continue - fi - job_json="${job_cache[${job_id}]:-}" - job_is_pending=false - job_was_fetched=false - case "${check_status}" in - queued|in_progress|requested|waiting|pending) job_is_pending=true ;; - esac - if [[ -z "${job_json}" || "${job_is_pending}" == "true" ]]; then - : >"${api_error_file}" - set +e - job_json="$(gh api --method GET \ - "/repos/${GITHUB_REPOSITORY}/actions/jobs/${job_id}" \ - 2>"${api_error_file}")" - job_status=$? - job_was_fetched=true - set -e - if [[ "${job_status}" -ne 0 ]]; then - job_error="$(<"${api_error_file}")" - if is_retryable_gh_failure "${job_status}" "${job_error}"; then - job_lookup_retryable=true - retry_reason="job API lookup" - retry_error_text="${job_error}" - break - fi - echo "Permanent GitHub API/configuration failure while identifying a prior ${REQUIRED_GATE_NAME} run; refusing to preserve." >&2 - [[ -z "${job_error}" ]] || printf '%s\n' "${job_error}" >&2 - exit 1 - fi - fi - - set +e - job_identity_ok="$(jq -r \ - --arg expected_job_id "${job_id}" \ - --arg expected_run_id "${workflow_run_id}" \ - --arg expected_gate_name "${REQUIRED_GATE_NAME}" \ - --arg expected_workflow_name "${EXPECTED_WORKFLOW_NAME}" \ - --arg expected_display_title "${expected_display_title}" \ - --arg expected_head "${HEAD_SHA}" \ - --arg expected_check_run_id "${check_run_id}" \ - 'if (.id | type) == "number" and - (.run_id | type) == "number" and - .id == ($expected_job_id | tonumber) and - .run_id == ($expected_run_id | tonumber) and - .name == $expected_gate_name and - (.workflow_name == $expected_workflow_name or - .workflow_name == $expected_display_title) and - .head_sha == $expected_head and - ((.check_run_url // "") | endswith("/check-runs/\($expected_check_run_id)")) - then "true" else "false" end' \ - <<<"${job_json}" 2>>"${api_error_file}")" - job_identity_query_status=$? - set -e - if [[ "${job_identity_query_status}" -ne 0 || - "${job_identity_ok}" != "true" ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${job_was_fetched}" == "true" ]]; then - job_cache["${job_id}"]="${job_json}" - fi - set +e - preserve_step_conclusion="$(jq -r ' - [.steps[]? - | select(.name == "Preserve successful required gate on metadata-only edit") - | (.conclusion // "") - ] - | if length == 1 then .[0] else "unknown" end - ' <<<"${job_json}" 2>>"${api_error_file}")" - job_query_status=$? - set -e - if [[ "${job_query_status}" -ne 0 ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && - "${REQUIRED_GATE_NAME}" == "Validation Gate" && - "${check_status}" == "completed" && - ( "${preserve_step_conclusion}" == "unknown" || -z "${preserve_step_conclusion}" ) ]]; then - case "${conclusion}" in - cancelled|skipped|stale) ;; - *) - preserve_step_state="$(jq -r ' - if (.steps // null) == null then "absent" - elif (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then "invalid" - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) == 1 then "present" - else "invalid" end - end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - if [[ "${preserve_step_state}" == "invalid" ]]; then - candidate_ambiguous=true - continue - fi - if [[ "${preserve_step_state}" == "absent" ]]; then - if recover_validation_job_from_attempt; then - job_json="${attempt_recovered_job_json}" - job_cache["${job_id}"]="${job_json}" - preserve_step_state="$(jq -r ' - if (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then "invalid" - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) == 1 then "present" - else "invalid" end - end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - if [[ "${preserve_step_state}" == "invalid" ]]; then - candidate_ambiguous=true - continue - fi - preserve_step_conclusion="$(jq -r ' - [.steps[]? - | select(.name == "Preserve successful required gate on metadata-only edit") - | (.conclusion // "") - ] - | if length == 1 then .[0] else "unknown" end - ' <<<"${job_json}" 2>>"${api_error_file}")" || { - candidate_ambiguous=true - continue - } - else - recovery_status=$? - if [[ "${recovery_status}" -eq 3 ]]; then exit 1; fi - fi - fi - ;; - esac - fi - if [[ "${preserve_step_conclusion}" == "unknown" || - -z "${preserve_step_conclusion}" ]]; then - if [[ "${check_status}" == "completed" ]]; then - case "${conclusion}" in - cancelled|skipped|stale) continue ;; - esac - # An unresolved completed snapshot may hide substantive failure. - candidate_ambiguous=true - continue - elif [[ "${job_is_pending}" == "true" ]]; then - : # A nonterminal job may not have reached its preservation step yet. - else - candidate_ambiguous=true - continue - fi - elif [[ "${preserve_step_conclusion}" != "skipped" ]]; then - case "${preserve_step_conclusion}" in - success|failure|neutral|cancelled|timed_out|action_required|stale) - continue - ;; - *) candidate_ambiguous=true; continue ;; - esac - fi - - # Failed cancelled aggregates require complete proof before being treated as - # missing validation. Unavailable or different evidence retains failure. - if [[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/ci.yml" && - "${EXPECTED_WORKFLOW_NAME}" == "CI — Validation" && "${REQUIRED_GATE_NAME}" == "Validation Gate" && - "${check_status}" == completed && "${conclusion}" == failure ]]; then - if validation_cancelled_before_checks; then - echo "Cancelled Validation aggregate has no executed prerequisite checks; original proof remains missing." >&2 - continue - fi - fi - - case "${check_status}" in - completed) - case "${conclusion}" in - success|failure|neutral|cancelled|skipped|timed_out|action_required|stale) ;; - *) candidate_ambiguous=true; continue ;; - esac - if [[ -n "${conclusion}" && -n "${completed_at}" && - -n "${started_at}" ]] && - is_github_timestamp "${completed_at}" && - is_github_timestamp "${started_at}"; then - if [[ "${conclusion}" != "cancelled" && - "${conclusion}" != "skipped" && - "${conclusion}" != "stale" ]]; then - authoritative_rows+=("${completed_at}"$'\t'"${workflow_run_id}"$'\t'"${check_run_id}"$'\t'"${job_id}"$'\tcompleted\t'"${conclusion}") - fi - else - candidate_ambiguous=true - fi - ;; - queued|in_progress|requested|waiting|pending) - if [[ -z "${conclusion}" && -z "${completed_at}" ]] && - { [[ -z "${started_at}" ]] || is_github_timestamp "${started_at}"; }; then - started_at="${started_at:-9999-12-31T23:59:59Z}" - pending_rows+=("${started_at}"$'\t'"${workflow_run_id}"$'\t'"${check_run_id}"$'\t'"${job_id}"$'\tpending\t'"${check_status}"$'\t'"${preserve_step_conclusion}") - else - candidate_ambiguous=true - fi - ;; - *) candidate_ambiguous=true ;; - esac -done <<<"${candidate_rows}" - -if [[ "${job_lookup_retryable}" == "true" ]]; then - echo "Required-gate assessment could not resolve ${retry_reason}; refusing to preserve." >&2 - [[ -z "${retry_error_text}" ]] || printf '%s\n' "${retry_error_text}" >&2 - exit 1 -fi -if [[ "${candidate_ambiguous}" == "true" ]]; then - echo "Ambiguous prior ${REQUIRED_GATE_NAME} run metadata; refusing to preserve." >&2 - exit 1 -fi - -prior_status="" -prior_conclusion="" -if ((${#authoritative_rows[@]} > 0)); then - prior_row="$(printf '%s\n' "${authoritative_rows[@]}" | LC_ALL=C sort -t $'\t' -k1,1 -k2,2n -k3,3n -k4,4n | tail -n 1)" -elif ((${#pending_rows[@]} > 0)); then - prior_row="$(printf '%s\n' "${pending_rows[@]}" | LC_ALL=C sort -t $'\t' -k1,1 -k2,2n -k3,3n -k4,4n | tail -n 1)" -else - prior_row=$'none\tnone\tnone\tnone\tnone\t' -fi -IFS=$'\t' read -r _prior_sort _prior_run _prior_check _prior_job prior_status prior_conclusion _prior_preserve_step <<< "${prior_row}" -if [ "${prior_status}" = "completed" ]; then - if [ "${prior_conclusion}" = "success" ]; then - # Opt-in provenance exposes the already selected source; it changes neither - # ordering nor candidate eligibility, and ordinary action output stays stable. - if [[ "${REQUIRED_GATE_INCLUDE_SOURCE:-false}" == true ]]; then - source_attempt="$(jq -er '.run_attempt | select(type == "number" and . > 0 and . == floor)' \ - <<<"${job_cache[${_prior_job}]}")" || exit 1 - printf 'source_run_id=%s\nsource_job_id=%s\nsource_check_run_id=%s\nsource_run_attempt=%s\n' \ - "${_prior_run}" "${_prior_job}" "${_prior_check}" "${source_attempt}" >>"${GITHUB_OUTPUT}" - fi - report_assessment success - exit 0 - fi - echo "Prior ${REQUIRED_GATE_NAME} for unchanged head ${HEAD_SHA} concluded ${prior_conclusion:-unknown}." >&2 - exit 1 -fi -if [[ "${prior_status}" == none || "${prior_status}" == pending ]]; then - defer_dependency -fi -echo "Unexpected prior ${REQUIRED_GATE_NAME} selection state ${prior_status:-unknown}; refusing to preserve." >&2 -exit 1 diff --git a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh b/.github/actions/preserve-required-gate/resolve-deferred-gate.sh deleted file mode 100644 index 1c5aaeef35..0000000000 --- a/.github/actions/preserve-required-gate/resolve-deferred-gate.sh +++ /dev/null @@ -1,641 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -fail_closed() { - echo "$*" >&2 - exit 1 -} -resolution_phase="${1:-admit}" -case "${resolution_phase}" in - preflight|admit|reconcile) ;; - *) fail_closed "Unsupported resolver phase." ;; -esac -report_eligible() { - if [[ "${resolution_phase}" == preflight ]]; then - [[ -n "${GITHUB_OUTPUT:-}" ]] || fail_closed "Preflight requires GITHUB_OUTPUT." - printf 'eligible=%s\n' "$1" >>"${GITHUB_OUTPUT}" - elif [[ "$1" == false && -n "${GITHUB_OUTPUT:-}" ]]; then - # Successful early no-ops also need an explicit empty confirmation. - printf 'accepted_job_ids=[]\n' >>"${GITHUB_OUTPUT}" - fi -} - -[[ "${GITHUB_EVENT_NAME:-}" == workflow_run ]] || fail_closed "Resolver requires workflow_run context." -for required_variable in GH_TOKEN GITHUB_REPOSITORY GITHUB_EVENT_PATH GITHUB_RUN_ID; do - [[ -n "${!required_variable:-}" ]] || fail_closed "Resolver is missing ${required_variable}." -done -[[ "${resolution_phase}" != admit || -n "${GITHUB_OUTPUT:-}" ]] || - fail_closed "Admission requires GITHUB_OUTPUT for acknowledged job IDs." -source_run_id="$(jq -er '.workflow_run.id | select(type == "number" and . > 0 and . == floor)' "${GITHUB_EVENT_PATH}")" -source_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${source_run_id}")" -workflow_path="$(jq -er '.path | select(type == "string")' <<<"${source_json}")" -workflow_file="${workflow_path%%@*}" -case "${workflow_file}" in - .github/workflows/ci.yml) workflow_name='CI — Validation'; gate_name='Validation Gate' ;; - .github/workflows/security.yml) workflow_name='Security Gate'; gate_name='Security Gate' ;; - .github/workflows/codeql.yml) workflow_name='CodeQL Analysis'; gate_name='CodeQL Gate' ;; - .github/workflows/license-scan.yml) workflow_name='License Gate'; gate_name='License Gate' ;; - .github/workflows/smoke.yml) workflow_name='PR Smoke Gate'; gate_name='Smoke Gate' ;; - *) fail_closed "Source does not own a supported required gate." ;; -esac -workflow_filename="${workflow_file##*/}" -workflow_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_filename}")" -workflow_id="$(jq -er --arg name "${workflow_name}" --arg path "${workflow_file}" ' - select(.name == $name and .path == $path) - | .id | select(type == "number" and . > 0 and . == floor)' <<<"${workflow_json}")" -source_title="$(jq -er '.display_title' <<<"${source_json}")" -title_identity="$(jq -ern --arg title "${source_title}" --arg name "${workflow_name}" ' - $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") - | select(.name == $name) | [.pr, .base, .head] | @tsv')" -IFS=$'\t' read -r pr_number base_sha head_sha <<<"${title_identity}" -head_branch="$(jq -er '.head_branch | select(type == "string" and length > 0)' <<<"${source_json}")" -jq -e --argjson id "${source_run_id}" --argjson workflow_id "${workflow_id}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg name "${workflow_name}" \ - --arg title "${source_title}" --arg path "${workflow_file}" --arg head "${head_sha}" ' - .id == $id and .workflow_id == $workflow_id and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .repository.full_name == $repository and .event == "pull_request" and - .status == "completed" and .head_sha == $head' <<<"${source_json}" >/dev/null || - fail_closed "Source workflow identity is not attributable." -jq -e --argjson id "${source_run_id}" --argjson workflow_id "${workflow_id}" --arg head "${head_sha}" ' - .action == "completed" and .workflow_run.id == $id and - .workflow_run.workflow_id == $workflow_id and .workflow_run.head_sha == $head - and .workflow_run.event == "pull_request"' "${GITHUB_EVENT_PATH}" >/dev/null || - fail_closed "Completion event does not match the source workflow." - -# Resolver reruns retain their ID, and latest job snapshots can hide an older -# ambiguous admission. Neither the current nor historical resolver may rerun -# automatically; explicit recovery must establish a separate safe boundary. -resolver_path='.github/workflows/resolve-required-gates.yml' -resolver_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/resolve-required-gates.yml")" -resolver_id="$(jq -er --arg path "${resolver_path}" ' - select(.name == "Resolve Required Gates" and .path == $path) - | .id | select(type == "number" and . > 0 and . == floor)' <<<"${resolver_json}")" -current_resolver_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}")" -jq -e --argjson id "${GITHUB_RUN_ID}" --argjson workflow_id "${resolver_id}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg path "${resolver_path}" \ - --arg title "Resolve Required Gates workflow-${workflow_id} head-${head_sha} source-${source_run_id}" ' - .id == $id and .workflow_id == $workflow_id and .repository.full_name == $repository and - .event == "workflow_run" and (.name == "Resolve Required Gates" or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .display_title == $title and .run_attempt == 1 and .status == "in_progress" and - (.head_sha | type) == "string" and (.head_sha | test("^[0-9A-Fa-f]{40}$")) and - (try (.created_at | fromdateiso8601 | type == "number") catch false)' <<<"${current_resolver_json}" >/dev/null || - fail_closed "Current resolver identity or first attempt is unproved; explicit recovery is required." -current_resolver_created="$(jq -er '.created_at' <<<"${current_resolver_json}")" - -current_pr() { - gh api --method GET "/repos/${GITHUB_REPOSITORY}/pulls/${pr_number}" -} -pr_is_current() { - jq -e --arg repository "${GITHUB_REPOSITORY}" --arg head "${head_sha}" \ - --arg base "${base_sha}" --arg branch "${head_branch}" --argjson pr "${pr_number}" \ - --arg base_branch "${base_branch:-}" --arg head_repository "${head_repository:-}" ' - .number == $pr and .state == "open" and .base.repo.full_name == $repository and - .base.sha == $base and .head.sha == $head and .head.ref == $branch and - (.base.ref | type) == "string" and (.base.ref | length) > 0 and - (.head.repo.full_name | type) == "string" and (.head.repo.full_name | length) > 0 and - ($base_branch == "" or .base.ref == $base_branch) and - ($head_repository == "" or .head.repo.full_name == $head_repository)' <<<"$1" >/dev/null -} -pr_json="$(current_pr)" -if ! pr_is_current "${pr_json}"; then - echo "Source tuple is obsolete; no gate is rerun." - report_eligible false - exit 0 -fi -head_repository="$(jq -er '.head.repo.full_name' <<<"${pr_json}")" -base_branch="$(jq -er '.base.ref' <<<"${pr_json}")" - -# Supplementary statuses may withhold native proof but never replace it. -# This phase does not enter the legacy targeted-rerun admission protocol. -if [[ "${resolution_phase}" == reconcile ]]; then - latest_barrier() { - local inventory='[]' page rows prefix found - # GitHub returns newest first; stop at the first exact context, regardless - # of its actor. Exhaust history only to establish absence, never ownership. - for page in {1..10}; do - rows="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" -f per_page=100 -f page="${page}")" || return 1 - prefix="$(jq -ce --arg context "${gate_name}" ' - if type != "array" or length > 100 then error("invalid status page") else . end - | (map(if type == "object" then .context == $context else false end) | index(true)) as $index - | {found: ($index != null), rows: (if $index == null then . else .[0:($index + 1)] end)}' <<<"${rows}")" || return 1 - found="$(jq -r .found <<<"${prefix}")" - inventory="$(jq -cs '.[0] + .[1].rows' <(printf '%s\n' "${inventory}") <(printf '%s\n' "${prefix}"))" || return 1 - jq -e --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" ' - all(.[]; type == "object" and (.context | type) == "string" and (.context | length) > 0 and - (.id | type) == "number" and .id > 0 and (.id | floor) == .id and .url == $url) and - ([.[].id] | unique | length) == length' <<<"${inventory}" >/dev/null || return 1 - if [[ "${found}" == true ]]; then jq -c '.[-1]' <<<"${inventory}"; return 0; fi - if [[ "$(jq length <<<"${rows}")" -lt 100 ]]; then printf 'null\n'; return 0; fi - done - return 1 # Budget exhaustion cannot establish absence. - } - barrier="$(latest_barrier)" || fail_closed "Supplementary status inventory is unavailable or ambiguous." - if [[ "${barrier}" == null ]]; then exit 0; fi - if ! jq -e '(.state == "pending" or .state == "failure" or .state == "error") and .creator.id == 41898282 and - .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - (.id | type == "number" and . > 0 and . == floor)' <<<"${barrier}" >/dev/null; then - exit 0 # Foreign or already terminal statuses are not ours to modify. - fi - target_url="$(jq -er '.target_url' <<<"${barrier}")" - url_prefix="https://github.com/${GITHUB_REPOSITORY}/actions/runs/" - [[ "${target_url}" == "${url_prefix}"* ]] || exit 0 - target_suffix="${target_url#"${url_prefix}"}" - [[ "${target_suffix}" =~ ^([1-9][0-9]*)/attempts/([1-9][0-9]*)$ ]] || exit 0 - bridge_run_id="${BASH_REMATCH[1]}" - bridge_attempt="${BASH_REMATCH[2]}" - bridge_native() { - local target jobs check check_id historical_title - target="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${bridge_run_id}/attempts/${bridge_attempt}")" || return 1 - historical_title="$(jq -er --arg name "${workflow_name}" --arg pr "${pr_number}" --arg head "${head_sha}" ' - .display_title as $value | $value - | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") - | select(.name == $name and .pr == $pr and .head == $head) | $value' <<<"${target}")" || return 1 - jq -e --argjson id "${bridge_run_id}" --argjson attempt "${bridge_attempt}" \ - --argjson workflow "${workflow_id}" --arg repo "${GITHUB_REPOSITORY}" \ - --arg head_repo "${head_repository}" --arg head "${head_sha}" --arg branch "${head_branch}" \ - --arg title "${historical_title}" --arg name "${workflow_name}" --arg path "${workflow_file}" --argjson pr "${pr_number}" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and - .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .event == "pull_request" and - ((.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "queued" or .status == "in_progress" or .status == "waiting" or - .status == "pending" or .status == "requested") and .conclusion == null)) and - (.pull_requests | type == "array") and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' <<<"${target}" >/dev/null || return 1 - jobs="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${bridge_run_id}/attempts/${bridge_attempt}/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jobs="$(jq -ce --arg name "${gate_name}" --arg head "${head_sha}" --argjson run "${bridge_run_id}" ' - if type != "array" or length == 0 or any(.[]; type != "object" or (.jobs | type) != "array") - then error("malformed jobs") else . end - | .[0].total_count as $total - | if ($total | type) != "number" or $total < 0 or ($total | floor) != $total or - any(.[]; .total_count != $total) or ([.[].jobs[]] | length) != $total or - ([.[].jobs[].id] | unique | length) != $total then error("incomplete jobs") else . end - | [.[].jobs[] | select(.name == $name)] - | if length != 1 then error("ambiguous gate") else .[0] end - | select(.run_id == $run and .head_sha == $head) - | select((.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "queued" or .status == "in_progress" or .status == "waiting" or - .status == "pending" or .status == "requested") and .conclusion == null)) -' <<<"${jobs}")" || return 1 - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${jobs}")" || return 1 - check="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${check_id}")" || return 1 - jq -e --argjson id "${check_id}" --arg head "${head_sha}" --arg name "${gate_name}" \ - --argjson job "${jobs}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $head and .name == $name and .status == $job.status and - .conclusion == $job.conclusion' <<<"${check}" >/dev/null || return 1 - # Keep the full native snapshot for the immediate pre-POST comparison. - jq -cn --argjson run "${target}" --argjson job "${jobs}" --argjson check "${check}" \ - '{run: $run, job: $job, check: $check}' - } - native="$(bridge_native)" || fail_closed "Supplementary barrier lacks bound native metadata evidence." - # Historical metadata proves ownership, including an acknowledged publication - # followed by cancellation/failure. It never supplies current-base proof. - jq -e '[.job.steps[]? | select(.name == "Publish pending required gate status" and - ((.status == "in_progress" and .conclusion == null) or - (.status == "completed" and (.conclusion == "success" or .conclusion == "failure" or - .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required"))))] - | length == 1' <<<"${native}" >/dev/null || - fail_closed "Supplementary barrier lacks attributable publication ownership." - assessment_output="$(mktemp)" - trap 'rm -f "$assessment_output"' EXIT - terminal_state=failure - selected_native='' - # Exclude the historical metadata barrier, not the completion callback's - # original run. The selector still applies its exact CURRENT base/head tuple. - if GITHUB_EVENT_NAME=pull_request GITHUB_RUN_ID="${bridge_run_id}" \ - BASE_SHA="${base_sha}" HEAD_SHA="${head_sha}" PR_NUMBER="${pr_number}" \ - REQUIRED_GATE_NAME="${gate_name}" EXPECTED_WORKFLOW_NAME="${workflow_name}" \ - EXPECTED_WORKFLOW_FILE="${workflow_filename}" EXPECTED_WORKFLOW_PATH="${workflow_file}" \ - REQUIRED_GATE_INCLUDE_SOURCE=true GITHUB_OUTPUT="${assessment_output}" \ - bash "$(dirname "${BASH_SOURCE[0]}")/assess-required-gate.sh"; then - if [[ "$(<"${assessment_output}")" == assessment=dependency-deferred ]]; then exit 0; fi - selected="$(jq -Rsc ' - split("\n") | map(select(length > 0) | split("=")) - | if length != 5 or any(.[]; length != 2) or (map(.[0]) | unique | length) != 5 - then error("ambiguous source provenance") else map({key: .[0], value: .[1]}) | from_entries end - | select(.assessment == "success") - | select((keys | sort) == (["assessment", "source_run_id", "source_job_id", "source_check_run_id", "source_run_attempt"] | sort)) - | select([.source_run_id, .source_job_id, .source_check_run_id, .source_run_attempt] - | all(.[]; test("^[1-9][0-9]*$")))' "${assessment_output}")" || - fail_closed "Selected source provenance is unavailable." - [[ -n "${selected}" ]] || fail_closed "Selected source provenance is malformed." - selected_run="$(jq -r .source_run_id <<<"${selected}")" - selected_job="$(jq -r .source_job_id <<<"${selected}")" - selected_check="$(jq -r .source_check_run_id <<<"${selected}")" - selected_attempt="$(jq -r .source_run_attempt <<<"${selected}")" - selected_source_title="${workflow_name} pr-${pr_number} base-${base_sha} head-${head_sha}" - selected_source_native() { - local run job check preserve_step_state recovered - run="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${selected_run}/attempts/${selected_attempt}")" || return 1 - jq -e --argjson id "${selected_run}" --argjson attempt "${selected_attempt}" --argjson workflow "${workflow_id}" \ - --arg repo "${GITHUB_REPOSITORY}" --arg head_repo "${head_repository}" --arg head "${head_sha}" \ - --arg branch "${head_branch}" --arg title "${selected_source_title}" --arg name "${workflow_name}" \ - --arg path "${workflow_file}" --argjson pr "${pr_number}" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and - .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .event == "pull_request" and .status == "completed" and (.pull_requests | type == "array") and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' <<<"${run}" >/dev/null || return 1 - job="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/jobs/${selected_job}")" || return 1 - jq -e --argjson id "${selected_job}" --argjson run "${selected_run}" --argjson attempt "${selected_attempt}" \ - --arg name "${gate_name}" --arg head "${head_sha}" \ - --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/check-runs/${selected_check}" ' - .id == $id and .run_id == $run and .run_attempt == $attempt and .head_sha == $head and - .name == $name and .status == "completed" and .conclusion == "success" and .check_run_url == $url' \ - <<<"${job}" >/dev/null || return 1 - preserve_step_state="$(jq -er ' - if .steps == null then "absent" - elif (.steps | type) != "array" or any(.steps[]; type != "object" or (.name | type) != "string") then - error("malformed selected job steps") - else - [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $matches - | if ($matches | length) == 0 then "absent" - elif ($matches | length) > 1 then "duplicate" - elif $matches[0].status == "completed" and $matches[0].conclusion == "skipped" then "skipped" - else "conflict" end - end - ' <<<"${job}")" || return 1 - if [[ "${preserve_step_state}" == absent ]]; then - [[ "${workflow_file}" == ".github/workflows/ci.yml" && - "${workflow_name}" == "CI — Validation" && "${gate_name}" == "Validation Gate" ]] || return 1 - recovered="$(bash "$(dirname "${BASH_SOURCE[0]}")/validate-exact-attempt-gate.sh" \ - "${selected_run}" "${selected_attempt}" "${selected_job}" "${selected_check}" \ - "${gate_name}" "${workflow_id}" "${workflow_name}" "${workflow_file}" \ - "${selected_source_title}" "${pr_number}" "${base_sha}" "${head_sha}" \ - "${head_branch}" "${GITHUB_REPOSITORY}" "${head_repository}" \ - completed success "" "" "" true)" || return 1 - printf '%s\n' "${recovered}" - return 0 - fi - [[ "${preserve_step_state}" == skipped ]] || return 1 - check="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/check-runs/${selected_check}")" || return 1 - jq -e --argjson id "${selected_check}" --arg head "${head_sha}" --arg name "${gate_name}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and .head_sha == $head and - .name == $name and .status == "completed" and .conclusion == "success"' <<<"${check}" >/dev/null || return 1 - jq -cnS --argjson run "${run}" --argjson job "${job}" --argjson check "${check}" \ - '{run: $run, jobs: null, job: $job, check: $check}' - } - selected_native="$(selected_source_native)" || fail_closed "Selected current-base source lacks independent native proof." - terminal_state=success - fi - pr_json="$(current_pr)" - pr_is_current "${pr_json}" || exit 0 - fresh_native="$(bridge_native)" || fail_closed "Native supplementary evidence changed or became unavailable." - [[ "${fresh_native}" == "${native}" ]] || exit 0 - if [[ "${terminal_state}" == success ]]; then - fresh_selected="$(selected_source_native)" || fail_closed "Selected current-base native proof became unavailable." - [[ "${fresh_selected}" == "${selected_native}" ]] || exit 0 - fi - fresh_barrier="$(latest_barrier)" || fail_closed "Latest supplementary status became unavailable." - [[ "${fresh_barrier}" == "${barrier}" ]] || exit 0 - # Commit Status writes have no conditional-update primitive. Do not replay an - # unacknowledged POST; later callbacks re-read the latest native/API evidence. - gh api --method POST "/repos/${GITHUB_REPOSITORY}/statuses/${head_sha}" \ - -f state="${terminal_state}" -f context="${gate_name}" -f target_url="${target_url}" \ - -f description="Metadata gate original proof: ${terminal_state}" >/dev/null || - fail_closed "Supplementary status POST was rejected or ambiguous." - exit 0 -fi - -# A capped exact-head query bounds both target discovery and the native history -# window. Resolver completions cannot predate their source creation. Twenty -# retained sources is the source-discovery limit. Resolver history uses -# separate bounded pagination; partial evidence always requires recovery. -evidence_limit=20 -source_listing_read_limit=3 -source_listing_attempt=0 -source_listing_result='' -while (( source_listing_attempt < source_listing_read_limit )); do - source_listing_attempt=$((source_listing_attempt + 1)) - run_pages="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_filename}/runs" \ - -f event=pull_request -f head_sha="${head_sha}" -f per_page="${evidence_limit}")" - if ! source_listing_result="$(jq -cer --argjson limit "${evidence_limit}" --argjson source "${source_run_id}" \ - --argjson workflow_id "${workflow_id}" --arg repository "${GITHUB_REPOSITORY}" --arg head "${head_sha}" ' - def listed_count: - if type != "object" then null - elif (.workflow_runs | type) == "array" then (.workflow_runs | length) else null end; - def source_present: - if type != "object" then false - elif (.workflow_runs | type) == "array" then - any(.workflow_runs[]; if type == "object" then .id == $source else false end) - else false end; - def outcome($classification): { - classification: $classification, - total_count: (if type == "object" then (.total_count // null) else null end), - returned_rows: listed_count, - source_present: source_present - }; - if type != "object" then outcome("malformed-response") - elif (.workflow_runs | type) != "array" then outcome("malformed-workflow-runs") - elif (.total_count | type) != "number" or .total_count < 0 or .total_count != (.total_count | floor) then - outcome("malformed-total-count") - elif .total_count > $limit then outcome("overflow-total-count") - elif any(.workflow_runs[]; type != "object") then outcome("malformed-row") - elif any(.workflow_runs[]; - (.id | type) != "number" or .id <= 0 or .id != (.id | floor)) then outcome("malformed-row-id") - elif any(.workflow_runs[]; (.repository | type) != "object") then outcome("malformed-row-repository") - elif any(.workflow_runs[]; - .workflow_id != $workflow_id or .repository.full_name != $repository or - .head_sha != $head or .event != "pull_request") then outcome("identity-mismatch") - elif any(.workflow_runs[]; - (.created_at | type) != "string" or - (try (.created_at | fromdateiso8601 | type == "number") catch false | not)) then - outcome("malformed-created-at") - elif ([.workflow_runs[].id] | unique | length) != (.workflow_runs | length) then - outcome("duplicate-row-id") - elif (.workflow_runs | length) > .total_count then outcome("malformed-row-count") - elif (.workflow_runs | length) < .total_count then outcome("incomplete-row-count") - elif (source_present | not) then outcome("incomplete-missing-source") - else outcome("complete") end' <<<"${run_pages}")"; then - fail_closed "Exact-head source listing response is not valid JSON." - fi - source_listing_classification="$(jq -er '.classification' <<<"${source_listing_result}")" - case "${source_listing_classification}" in - complete) - break - ;; - incomplete-row-count|incomplete-missing-source) - source_listing_diagnostics="$(jq -er '[.classification, (.total_count // "unknown"), (.returned_rows // "unknown"), .source_present] | @tsv' \ - <<<"${source_listing_result}")" - if (( source_listing_attempt == source_listing_read_limit )); then - fail_closed "Exact-head source coverage remains incomplete after ${source_listing_attempt} reads: classification=${source_listing_classification}, total_count=$(jq -r '.total_count // "unknown"' <<<"${source_listing_result}"), returned_rows=$(jq -r '.returned_rows // "unknown"' <<<"${source_listing_result}"), source_present=$(jq -r '.source_present' <<<"${source_listing_result}"), limit=${evidence_limit}." - fi - echo "Exact-head source listing is incomplete (read ${source_listing_attempt}/${source_listing_read_limit}): ${source_listing_diagnostics}; limit=${evidence_limit}." >&2 - if (( source_listing_attempt == 1 )); then sleep 1; else sleep 2; fi - ;; - *) - fail_closed "Exact-head source coverage rejected: classification=${source_listing_classification}, total_count=$(jq -r '.total_count // "unknown"' <<<"${source_listing_result}"), returned_rows=$(jq -r '.returned_rows // "unknown"' <<<"${source_listing_result}"), source_present=$(jq -r '.source_present' <<<"${source_listing_result}"), limit=${evidence_limit}." - ;; - esac -done -target_ids="$(jq -er '.workflow_runs[].id' <<<"${run_pages}")" - -# Native resolver job/step evidence carries the conservative recovery boundary -# across invocations. A failed or incomplete admission may have sent a POST; -# subsequent callbacks must not guess from a still-visible target attempt 1. -assert_no_ambiguous_admission() { - local resolver_pages resolver_page history_total history_page history_page_count expected_page_records - local prior_ids prior_id prior_json prior_jobs prior_head equal_time_waiting - local prior_admitted_ids prior_admitted_id - # The REST search ceiling is 1,000 records. Fetch explicit pages so neither - # an oversized response nor pagination can start an unbounded history scan. - resolver_pages='[]' - history_total=0 - history_page_count=1 - for (( history_page=1; history_page<=history_page_count; history_page++ )); do - resolver_page="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/workflows/resolve-required-gates.yml/runs" \ - -f event=workflow_run -f created=">=${history_start}" -f per_page=100 -f page="${history_page}")" - jq -e '(.workflow_runs | type) == "array" and - (.total_count | type) == "number" and .total_count > 0 and - .total_count == (.total_count | floor) and .total_count <= 1000' \ - <<<"${resolver_page}" >/dev/null || - fail_closed "Resolver history is malformed or exceeds the 1,000-record API ceiling." - if (( history_page == 1 )); then - history_total="$(jq -er '.total_count' <<<"${resolver_page}")" - history_page_count=$(( (history_total + 99) / 100 )) - fi - expected_page_records=$(( history_total - (history_page - 1) * 100 )) - if (( expected_page_records > 100 )); then expected_page_records=100; fi - jq -e --argjson total "${history_total}" --argjson count "${expected_page_records}" ' - .total_count == $total and (.workflow_runs | length) == $count' \ - <<<"${resolver_page}" >/dev/null || - fail_closed "Resolver history page coverage or total count is inconsistent." - resolver_pages="$(printf '%s\n%s\n' "${resolver_pages}" "${resolver_page}" | \ - jq -cs '.[0] + .[1].workflow_runs')" - done - prior_ids="$(jq -r --argjson workflow_id "${resolver_id}" --argjson current "${GITHUB_RUN_ID}" \ - --argjson total "${history_total}" --arg created "${history_start}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg path "${resolver_path}" \ - --arg prefix "Resolve Required Gates workflow-${workflow_id} head-${head_sha} source-" ' - if length != $total or ([.[].id] | unique | length) != $total or - (any(.[]; .id == $current) | not) then error("incomplete or duplicate resolver history") else . end - | if any(.[]; - (.id | type) != "number" or .id <= 0 or .id != (.id | floor) or - .workflow_id != $workflow_id or .repository.full_name != $repository or .event != "workflow_run" or - (.display_title | type) != "string" or - (try ((.created_at | fromdateiso8601) >= ($created | fromdateiso8601)) catch false | not)) - then error("unattributable resolver history") else . end - | [.[] - | select(.workflow_id == $workflow_id and .id != $current and - .repository.full_name == $repository and .event == "workflow_run" and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - (.display_title | startswith($prefix)) and - (.display_title | ltrimstr($prefix) | test("^[1-9][0-9]*$"))) - | .id | select(type == "number" and . > 0 and . == floor)] | unique | .[]' <<<"${resolver_pages}")" - while IFS= read -r prior_id; do - [[ -n "${prior_id}" ]] || continue - prior_json="$(jq -cer --argjson id "${prior_id}" '.[] | select(.id == $id)' <<<"${resolver_pages}")" - jq -e '.run_attempt == 1' <<<"${prior_json}" >/dev/null || - fail_closed "Matching resolver history contains a rerun or unknown attempt; explicit recovery is required." - prior_head="$(jq -er '.head_sha | select(type == "string" and test("^[0-9A-Fa-f]{40}$"))' <<<"${prior_json}")" - # Under this exact workflow/head concurrency group, a later first-attempt - # callback still pending or queued cannot have reached admission. Require - # native creation ordering; listener revision movement cannot start it. - # Missing steps in any - # other state remain potentially admitting evidence, never a clean no-op. - if jq -e --arg created "${current_resolver_created}" ' - (.status == "pending" or .status == "queued") and .conclusion == null and - (try ((.created_at | fromdateiso8601) > ($created | fromdateiso8601)) catch false)' \ - <<<"${prior_json}" >/dev/null; then - continue - fi - # Native creation timestamps have second precision. A tied callback needs - # explicit first-attempt job evidence that nothing started, without guessing - # order from run IDs or ignoring arbitrary missing admission steps. - equal_time_waiting=false - if jq -e --arg created "${current_resolver_created}" ' - (.status == "pending" or .status == "queued") and .conclusion == null and - (try ((.created_at | fromdateiso8601) == ($created | fromdateiso8601)) catch false)' \ - <<<"${prior_json}" >/dev/null; then - equal_time_waiting=true - fi - prior_jobs="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${prior_id}/attempts/1/jobs" \ - -f per_page="${evidence_limit}")" - jq -e --argjson limit "${evidence_limit}" ' - (.jobs | type) == "array" and (.total_count | type) == "number" and - .total_count >= 0 and .total_count <= $limit and - .total_count == (.total_count | floor) and (.jobs | length) == .total_count and - ([.jobs[].id] | unique | length) == .total_count' <<<"${prior_jobs}" >/dev/null || - fail_closed "Prior resolver job coverage is malformed or incomplete." - # Concurrency may evict a pending callback before allocating any job. Only - # an attributable cancelled first attempt with complete explicit zero-job - # coverage proves it never reached admission; missing jobs are not proof. - if jq -e '.status == "completed" and .conclusion == "cancelled"' <<<"${prior_json}" >/dev/null && - jq -e '.total_count == 0 and .jobs == []' <<<"${prior_jobs}" >/dev/null; then - continue - fi - prior_admitted_ids="$(jq -ce --argjson prior_id "${prior_id}" --argjson limit "${evidence_limit}" \ - --arg head "${prior_head}" --argjson equal_time_waiting "${equal_time_waiting}" ' - [.jobs[] | select(.name == "Resolve deferred metadata gate")] - | if length != 1 then error("missing resolver job") else .[0] end - | if (.id | type) != "number" or .id <= 0 or .id != (.id | floor) or - .run_id != $prior_id or .head_sha != $head then error("unattributable resolver job") else . end - | if $equal_time_waiting then - if .status == "queued" and .conclusion == null and - has("started_at") and .started_at == null and - has("completed_at") and .completed_at == null and - (.steps | type) == "array" and - all(.steps[]; .status == "queued" and has("conclusion") and .conclusion == null) - then [] else error("waiting resolver job may have started") end - elif .conclusion == "skipped" then [] - else - [.steps[]? | select(.name == "Admit deferred gate reruns")] as $admission - | if ($admission | length) != 1 or $admission[0].status != "completed" then - error("missing or incomplete admission") - elif $admission[0].conclusion == "skipped" then [] - elif $admission[0].conclusion == "success" then - "Confirm admitted deferred gate jobs " as $prefix - | [.steps[]? | select((.name | type) == "string" and (.name | startswith($prefix)))] as $confirmation - | if ($confirmation | length) != 1 or $confirmation[0].status != "completed" or - $confirmation[0].conclusion != "success" then error("unconfirmed admission") else . end - | $confirmation[0].name | ltrimstr($prefix) as $encoded - | $encoded | fromjson - | if type != "array" then error("malformed admitted job IDs") else . end - | if length > $limit or (unique | length) != length or tojson != $encoded or - (all(.[]; type == "number" and . > 0 and . == floor) | not) then - error("malformed admitted job IDs") else . end - else error("ambiguous admission") end - end' <<<"${prior_jobs}")" || - fail_closed "Prior matching resolver admission is ambiguous or failed; explicit recovery is required." - while IFS= read -r prior_admitted_id; do - previously_admitted_jobs["${prior_admitted_id}"]=true - done < <(jq -r '.[]' <<<"${prior_admitted_ids}") - done <<<"${prior_ids}" -} -declare -A previously_admitted_jobs=() -# Return a gate job identity only from a completed first attempt with the distinct -# deferred failure, created no later than this resolver. This keeps every -# admitting resolver inside the retained target's history window even when an -# older source expires. Per-attempt lookup avoids mistaking old jobs for a current -# attempt; any human rerun also consumes the automatic allowance. -deferred_job_identity() { - local target_run_id="$1" target_json jobs_json - target_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${target_run_id}")" || return 1 - if ! jq -e --argjson id "${target_run_id}" --argjson workflow_id "${workflow_id}" \ - --arg repository "${GITHUB_REPOSITORY}" --arg head_repository "${head_repository}" \ - --arg head "${head_sha}" --arg branch "${head_branch}" --arg title "${source_title}" \ - --arg name "${workflow_name}" --arg path "${workflow_file}" --argjson pr "${pr_number}" \ - --arg resolver_created "${current_resolver_created}" ' - .id == $id and .workflow_id == $workflow_id and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .repository.full_name == $repository and .head_repository.full_name == $head_repository and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - .event == "pull_request" and .status == "completed" and .conclusion == "failure" and - .run_attempt == 1 and (.created_at | type) == "string" and - (try ((.created_at | fromdateiso8601) <= ($resolver_created | fromdateiso8601)) catch false) and - (.pull_requests | type) == "array" and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr))' \ - <<<"${target_json}" >/dev/null; then - return 0 - fi - jobs_json="$(gh api --method GET "/repos/${GITHUB_REPOSITORY}/actions/runs/${target_run_id}/attempts/1/jobs" \ - -f per_page=100 --paginate --slurp)" || return 1 - jq -er --arg name "${gate_name}" --arg head "${head_sha}" --argjson run_id "${target_run_id}" \ - --arg created "$(jq -er .created_at <<<"${target_json}")" ' - if type != "array" or length == 0 then error("malformed or incomplete target jobs") - elif any(.[]; type != "object" or (.jobs | type) != "array") then error("malformed or incomplete target jobs") - else - .[0].total_count as $total - | if all(.[]; (.total_count | type) == "number" and .total_count >= 0 and - .total_count == (.total_count | floor) and .total_count == $total) - and ([.[].jobs[]] | length) == $total - and all(.[].jobs[]; type == "object" and (.id | type) == "number" and - .id > 0 and .id == (.id | floor)) - and ([.[].jobs[].id] | unique | length) == $total - then . else error("malformed or incomplete target jobs") end - end - | [.[].jobs[] | select(.name == $name)] - | if length != 1 then empty else .[0] end - | select(.run_id == $run_id and .head_sha == $head and .status == "completed" and .conclusion == "failure") - | select([.steps[]? | select(.name == "Preserve successful required gate on metadata-only edit" and - .status == "completed" and .conclusion == "success")] | length == 1) - | select([.steps[]? | select(.name == "Report dependency-deferred required gate" and - .status == "completed" and .conclusion == "failure")] | length == 1) - | select(.id | type == "number" and . > 0 and . == floor) - | [.id, $created] | @tsv' <<<"${jobs_json}" || { - local jq_status=$? - # jq exits 4 for an empty selection: an ordinary failure is not deferred. - [[ "${jq_status}" == 4 ]] || return "${jq_status}" - } -} - -# Freeze eligible native run/job identities before choosing the history floor. -# Later eligibility changes cannot introduce a target outside this covered set. -declare -A candidate_identities=() -candidate_ids=() -candidate_created=() -while IFS= read -r target_run_id; do - [[ -n "${target_run_id}" ]] || continue - identity="$(deferred_job_identity "${target_run_id}")" - [[ -n "${identity}" ]] || continue - candidate_ids+=("${target_run_id}") - candidate_identities["${target_run_id}"]="${identity}" - candidate_created+=("${identity#*$'\t'}") -done <<<"${target_ids}" -if (( ${#candidate_ids[@]} == 0 )); then - report_eligible false - exit 0 -fi -history_start="$(jq -nr --args '$ARGS.positional | min_by(fromdateiso8601)' "${candidate_created[@]}")" -if [[ "${resolution_phase}" == admit ]]; then - assert_no_ambiguous_admission -fi - -assessment_output="$(mktemp)" -trap 'rm -f "$assessment_output"' EXIT -eligible=false -admitted_job_ids=() -for target_run_id in "${candidate_ids[@]}"; do - identity="${candidate_identities["${target_run_id}"]}" - job_id="${identity%%$'\t'*}" - [[ "${previously_admitted_jobs["${job_id}"]:-}" != true ]] || continue - : >"${assessment_output}" - # The child assesses an already-validated target pull_request context. It - # shares the action's exact source selection and cannot write remote state. - if ! GITHUB_EVENT_NAME=pull_request GITHUB_RUN_ID="${target_run_id}" \ - BASE_SHA="${base_sha}" HEAD_SHA="${head_sha}" PR_NUMBER="${pr_number}" \ - REQUIRED_GATE_NAME="${gate_name}" EXPECTED_WORKFLOW_NAME="${workflow_name}" \ - EXPECTED_WORKFLOW_FILE="${workflow_filename}" EXPECTED_WORKFLOW_PATH="${workflow_file}" \ - GITHUB_OUTPUT="${assessment_output}" \ - bash "$(dirname "${BASH_SOURCE[0]}")/assess-required-gate.sh"; then - fail_closed "Original proof is inconclusive or failed; no gate is rerun." - fi - [[ "$(<"${assessment_output}")" == 'assessment=success' ]] || continue - pr_json="$(current_pr)" - pr_is_current "${pr_json}" || continue - # Immediate re-read under workflow-level serialization. This suppresses - # duplicates practically; the API does not document conditional POSTs. - fresh_identity="$(deferred_job_identity "${target_run_id}")" - [[ "${fresh_identity}" == "${identity}" ]] || continue - eligible=true - [[ "${resolution_phase}" != preflight ]] || continue - if ! gh api --method POST "/repos/${GITHUB_REPOSITORY}/actions/jobs/${job_id}/rerun" >/dev/null; then - fail_closed "Targeted rerun outcome is ambiguous or rejected; do not replay the POST. Explicit recovery is required." - fi - admitted_job_ids+=("${job_id}") - previously_admitted_jobs["${job_id}"]=true - echo "Admitted one targeted rerun of deferred gate job ${job_id} in run ${target_run_id}." -done -if [[ "${resolution_phase}" == preflight ]]; then - report_eligible "${eligible}" -else - # Publish only after all POSTs were acknowledged. Partial/ambiguous execution - # has no successful confirmation step and blocks subsequent automation. - admitted_ids_json="$(jq -cn --args '$ARGS.positional | map(tonumber)' "${admitted_job_ids[@]}")" - jq -e --argjson limit "${evidence_limit}" ' - type == "array" and length <= $limit and (unique | length) == length and - all(.[]; type == "number" and . > 0 and . == floor)' <<<"${admitted_ids_json}" >/dev/null || - fail_closed "Acknowledged job IDs are not a bounded attributable set." - printf 'accepted_job_ids=%s\n' "${admitted_ids_json}" >>"${GITHUB_OUTPUT}" -fi diff --git a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh b/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh deleted file mode 100644 index b68cd0889c..0000000000 --- a/.github/actions/preserve-required-gate/validate-exact-attempt-gate.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ "$#" -ne 21 ]]; then - echo "Malformed or unbound exact-attempt evidence: expected 21 identity arguments." >&2 - exit 2 -fi -run_id="$1" -attempt="$2" -job_id="$3" -check_id="$4" -gate_name="$5" -workflow_id="$6" -workflow_name="$7" -workflow_path="$8" -display_title="$9" -pr_number="${10}" -base_sha="${11}" -head_sha="${12}" -head_branch="${13}" -repository="${14}" -head_repository="${15}" -expected_status="${16}" -expected_conclusion="${17}" -expected_details_url="${18}" -expected_started_at="${19}" -expected_completed_at="${20}" -require_skipped="${21}" - -fail_evidence() { - echo "Malformed or unbound exact-attempt evidence: $1" >&2 - exit 2 -} -fail_api() { - echo "GitHub API error while reading exact-attempt $1." >&2 - exit 1 -} -for identity in "$run_id" "$attempt" "$job_id" "$check_id" "$workflow_id" "$pr_number"; do - [[ "$identity" =~ ^[1-9][0-9]*$ ]] || fail_evidence "non-positive native identity" -done -for sha in "$base_sha" "$head_sha"; do - [[ "$sha" =~ ^[0-9A-Fa-f]{40}$ ]] || fail_evidence "invalid PR tuple SHA" -done -[[ "$expected_status" == completed && "$require_skipped" =~ ^(true|false)$ ]] || - fail_evidence "unsupported selected gate state" -[[ -n "$gate_name" && -n "$workflow_name" && -n "$workflow_path" && -n "$display_title" && - -n "$head_branch" && -n "$repository" && -n "$head_repository" ]] || fail_evidence "incomplete expected source tuple" - -if ! attempt_run="$(gh api --method GET "/repos/${repository}/actions/runs/${run_id}/attempts/${attempt}" 2>/dev/null)"; then - fail_api "workflow run" -fi -jq -e --argjson id "$run_id" --argjson attempt "$attempt" --argjson workflow "$workflow_id" \ - --arg repo "$repository" --arg head_repo "$head_repository" --arg name "$workflow_name" \ - --arg path "$workflow_path" --arg title "$display_title" --arg branch "$head_branch" \ - --arg head "$head_sha" --arg base "$base_sha" --argjson pr "$pr_number" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - .display_title == $title and .repository.full_name == $repo and - .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .event == "pull_request" and - .status == "completed" and (.pull_requests | type) == "array" and - ((.pull_requests | length) == 0 or - (any(.pull_requests[]; .number == $pr) and - all(.pull_requests[] | select(.number == $pr); - ((.base.sha // $base) == $base and (.head.sha // $head) == $head))) ) -' <<<"$attempt_run" >/dev/null || fail_evidence "workflow attempt identity or PR tuple differs" - -if ! attempt_jobs="$(gh api --method GET "/repos/${repository}/actions/runs/${run_id}/attempts/${attempt}/jobs" \ - -f per_page=100 2>/dev/null)"; then - fail_api "complete workflow job snapshot" -fi -attempt_job="$(jq -cer --argjson run "$run_id" --argjson attempt "$attempt" --argjson job "$job_id" \ - --argjson check "$check_id" --arg repo "$repository" --arg head "$head_sha" \ - --arg name "$workflow_name" --arg title "$display_title" --arg branch "$head_branch" --arg gate "$gate_name" \ - --arg status "$expected_status" --arg conclusion "$expected_conclusion" \ - --arg details "$expected_details_url" --arg started "$expected_started_at" \ - --arg completed "$expected_completed_at" --argjson require_skipped "$([[ "$require_skipped" == true ]] && echo true || echo false)" ' - if type != "object" or (.jobs | type) != "array" then error("malformed attempt jobs") else . end - | .total_count as $total | .jobs as $jobs - | if ($total | type) != "number" or $total < 1 or $total > 100 or $total != ($total | floor) or - ($jobs | length) != $total or - any($jobs[]; type != "object" or (.id | type) != "number" or .id < 1 or .id != (.id | floor)) or - ([$jobs[].id] | unique | length) != $total or - any($jobs[]; .run_id != $run or .run_attempt != $attempt or .head_sha != $head or .head_branch != $branch or - (.workflow_name != $name and .workflow_name != $title) or - ((.check_run_url // "") | startswith("https://api.github.com/repos/" + $repo + "/check-runs/") | not) or - (((.check_run_url // "") | ltrimstr("https://api.github.com/repos/" + $repo + "/check-runs/")) | - test("^[1-9][0-9]*$") | not)) then - error("incomplete or unbound attempt jobs") - else - [$jobs[] | select(.name == $gate)] as $gate_jobs - | [$jobs[] | select(.id == $job)] as $matches - | if ($gate_jobs | length) != 1 or ($matches | length) != 1 or $gate_jobs[0].id != $job then - error("attempt gate identity is not unique") - else $matches[0] end - | . as $selected - | ($selected.html_url // "") as $html - | ("https://github.com/" + $repo + "/actions/runs/" + ($run | tostring) + "/job/") as $prefix - | if .name != $gate or .run_id != $run or .run_attempt != $attempt or .head_sha != $head or - (.workflow_name != $name and .workflow_name != $title) or - .check_run_url != ("https://api.github.com/repos/" + $repo + "/check-runs/" + ($check | tostring)) or - (($html | startswith($prefix)) | not) or - (($html | ltrimstr($prefix) | (try capture("^(?[1-9][0-9]*)([?#].*)?$").id catch "")) != ($job | tostring)) or - .status != $status or (.conclusion // "") != $conclusion or - ($details != "" and $html != $details) or - ($started != "" and (.started_at // "") != $started) or - ($completed != "" and (.completed_at // "") != $completed) or - (.steps | type) != "array" then - error("attempt gate identity differs") - else . end - | [.steps[] | select(.name == "Preserve successful required gate on metadata-only edit")] as $preserve - | if ($preserve | length) > 1 or - ($require_skipped and (($preserve | length) != 1 or $preserve[0].status != "completed" or $preserve[0].conclusion != "skipped")) then - error("attempt preservation-step evidence differs") - else . end - end - ' <<<"$attempt_jobs")" || fail_evidence "complete structured workflow jobs or selected gate differ" - -if ! check="$(gh api --method GET "/repos/${repository}/check-runs/${check_id}" 2>/dev/null)"; then - fail_api "selected native CheckRun" -fi -jq -e --argjson id "$check_id" --argjson job "$attempt_job" --arg head "$head_sha" \ - --arg name "$gate_name" --arg status "$expected_status" --arg conclusion "$expected_conclusion" \ - --arg details "$expected_details_url" --arg started "$expected_started_at" --arg completed "$expected_completed_at" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and - .head_sha == $head and .name == $name and .status == $status and - (.conclusion // "") == $conclusion and .details_url == $job.html_url and - (.started_at // "") == ($job.started_at // "") and - (.completed_at // "") == ($job.completed_at // "") and - ($details == "" or .details_url == $details) and - ($started == "" or (.started_at // "") == $started) and - ($completed == "" or (.completed_at // "") == $completed) -' <<<"$check" >/dev/null || fail_evidence "selected native CheckRun differs from its exact-attempt gate job" - -jq -cnS --argjson run "$attempt_run" --argjson jobs "$attempt_jobs" \ - --argjson job "$attempt_job" --argjson check "$check" \ - '{run: $run, jobs: ($jobs.jobs | sort_by(.id)), job: $job, check: $check}' diff --git a/.github/actions/publish-required-gate-status/action.yml b/.github/actions/publish-required-gate-status/action.yml deleted file mode 100644 index b0593dd494..0000000000 --- a/.github/actions/publish-required-gate-status/action.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Publish Required Gate Status -description: Publish an attributable supplementary metadata gate status after canonical assessment. -inputs: - assessment: - description: Canonical preservation assessment. - required: true - gate-name: - description: Exact required gate context. - required: true - workflow-name: - description: Exact owning workflow name. - required: true - workflow-file: - description: Owning workflow filename. - required: true - workflow-path: - description: Exact owning workflow path. - required: true -outputs: - publication: - description: pending-acknowledged, success-acknowledged, or unchanged. - value: ${{ steps.publish.outputs.publication }} -runs: - using: composite - steps: - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - name: Publish supplementary required gate status - id: publish - shell: bash - env: - GH_TOKEN: ${{ github.token }} - ASSESSMENT: ${{ inputs.assessment }} - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REQUIRED_GATE_NAME: ${{ inputs.gate-name }} - EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }} - EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }} - EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }} - run: bash "$GITHUB_ACTION_PATH/publish-required-gate-status.sh" diff --git a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh b/.github/actions/publish-required-gate-status/publish-required-gate-status.sh deleted file mode 100644 index ae09f293a3..0000000000 --- a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -fail_closed() { echo "$*" >&2; exit 1; } -report() { printf 'publication=%s\n' "$1" >>"${GITHUB_OUTPUT}"; } -unchanged() { report unchanged; exit 0; } -for variable in GH_TOKEN GITHUB_REPOSITORY GITHUB_EVENT_NAME GITHUB_EVENT_PATH GITHUB_RUN_ID GITHUB_RUN_ATTEMPT GITHUB_OUTPUT BASE_SHA HEAD_SHA PR_NUMBER ASSESSMENT REQUIRED_GATE_NAME EXPECTED_WORKFLOW_NAME EXPECTED_WORKFLOW_FILE EXPECTED_WORKFLOW_PATH; do - [[ -n "${!variable:-}" ]] || fail_closed "Status publisher is missing ${variable}." -done -[[ "${GITHUB_EVENT_NAME}" == pull_request && "${BASE_SHA}" =~ ^[0-9a-fA-F]{40}$ && - "${HEAD_SHA}" =~ ^[0-9a-fA-F]{40}$ && "${PR_NUMBER}" =~ ^[1-9][0-9]*$ && - "${GITHUB_RUN_ID}" =~ ^[1-9][0-9]*$ && "${GITHUB_RUN_ATTEMPT}" =~ ^[1-9][0-9]*$ && - "${GITHUB_REPOSITORY}" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || - fail_closed "Status publisher requires an exact pull-request identity." -case "${ASSESSMENT}" in success|dependency-deferred) ;; *) fail_closed "Invalid canonical assessment." ;; esac -case "${EXPECTED_WORKFLOW_FILE}" in - ci.yml) workflow_name='CI — Validation'; gate_name='Validation Gate' ;; - security.yml) workflow_name='Security Gate'; gate_name='Security Gate' ;; - codeql.yml) workflow_name='CodeQL Analysis'; gate_name='CodeQL Gate' ;; - license-scan.yml) workflow_name='License Gate'; gate_name='License Gate' ;; - smoke.yml) workflow_name='PR Smoke Gate'; gate_name='Smoke Gate' ;; - *) fail_closed "Unsupported required gate workflow." ;; -esac -[[ "${EXPECTED_WORKFLOW_PATH}" == ".github/workflows/${EXPECTED_WORKFLOW_FILE}" && - "${EXPECTED_WORKFLOW_NAME}" == "${workflow_name}" && "${REQUIRED_GATE_NAME}" == "${gate_name}" ]] || - fail_closed "Required gate and owning workflow disagree." -api_root="/repos/${GITHUB_REPOSITORY}" -api_url="https://api.github.com/repos/${GITHUB_REPOSITORY}" -run_url="https://github.com/${GITHUB_REPOSITORY}/actions/runs/" -current_target="${run_url}${GITHUB_RUN_ID}/attempts/${GITHUB_RUN_ATTEMPT}" -current_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" -jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson pr "${PR_NUMBER}" --arg base "${BASE_SHA}" --arg head "${HEAD_SHA}" ' - .action == "edited" and .repository.full_name == $repo and .number == $pr and - .changes.base.ref == null and .pull_request.number == $pr and - .pull_request.base.repo.full_name == $repo and .pull_request.base.sha == $base and - .pull_request.head.sha == $head' "${GITHUB_EVENT_PATH}" >/dev/null || - fail_closed "Status publication requires the bound metadata-only event." -head_branch="$(jq -er '.pull_request.head.ref | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -head_repository="$(jq -er '.pull_request.head.repo.full_name | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -base_branch="$(jq -er '.pull_request.base.ref | select(type == "string" and length > 0)' "${GITHUB_EVENT_PATH}")" -workflow="$(gh api --method GET "${api_root}/actions/workflows/${EXPECTED_WORKFLOW_FILE}")" -workflow_id="$(jq -er --arg name "${workflow_name}" --arg path "${EXPECTED_WORKFLOW_PATH}" ' - select(.name == $name and .path == $path) | .id | select(type == "number" and . > 0 and . == floor)' <<<"${workflow}")" -current_pr() { gh api --method GET "${api_root}/pulls/${PR_NUMBER}"; } -pr_matches() { - jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson pr "${PR_NUMBER}" --arg head "${HEAD_SHA}" \ - --arg base "${BASE_SHA}" --arg branch "${head_branch}" --arg head_repo "${head_repository}" --arg base_ref "${base_branch}" ' - .number == $pr and .state == "open" and .base.repo.full_name == $repo and - .base.sha == $base and .base.ref == $base_ref and .head.sha == $head and - .head.ref == $branch and .head.repo.full_name == $head_repo' <<<"$1" >/dev/null -} -# Rich status records retain creator evidence missing from the combined projection. -latest_status() { - local inventory='[]' page rows prefix found - # GitHub returns newest first; stop at the first exact context, regardless - # of its actor. Exhaust history only to establish absence, never ownership. - for page in {1..10}; do - rows="$(gh api --method GET "${api_root}/statuses/${HEAD_SHA}" -f per_page=100 -f page="${page}")" || return 1 - prefix="$(jq -ce --arg context "${gate_name}" ' - if type != "array" or length > 100 then error("invalid status page") else . end - | (map(if type == "object" then .context == $context else false end) | index(true)) as $index - | {found: ($index != null), rows: (if $index == null then . else .[0:($index + 1)] end)}' <<<"${rows}")" || return 1 - found="$(jq -r .found <<<"${prefix}")" - inventory="$(jq -cs '.[0] + .[1].rows' <(printf '%s\n' "${inventory}") <(printf '%s\n' "${prefix}"))" || return 1 - jq -e --arg url "https://api.github.com/repos/${GITHUB_REPOSITORY}/statuses/${HEAD_SHA}" ' - all(.[]; type == "object" and (.context | type) == "string" and (.context | length) > 0 and - (.id | type) == "number" and .id > 0 and (.id | floor) == .id and .url == $url) and - ([.[].id] | unique | length) == length' <<<"${inventory}" >/dev/null || return 1 - if [[ "${found}" == true ]]; then jq -c '.[-1]' <<<"${inventory}"; return 0; fi - if [[ "$(jq length <<<"${rows}")" -lt 100 ]]; then printf 'null\n'; return 0; fi - done - return 1 # Budget exhaustion cannot establish absence. -} -# This proves ownership, not original source success. Old base SHA and failed or -# cancelled publisher steps identify provenance only and cannot grant proof. -native_identity() { - local run_id="$1" attempt="$2" current="$3" require_current_base="${4:-false}" run title title_base jobs check check_id - if [[ "${current}" == true ]]; then - run="$(gh api --method GET "${api_root}/actions/runs/${run_id}")" || return 1 - else - run="$(gh api --method GET "${api_root}/actions/runs/${run_id}/attempts/${attempt}")" || return 1 - fi - title="$(jq -er '.display_title | select(type == "string")' <<<"${run}")" || return 1 - title_base="$(jq -ern --arg title "${title}" --arg name "${workflow_name}" --arg pr "${PR_NUMBER}" --arg head "${HEAD_SHA}" ' - $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") - | select(.name == $name and .pr == $pr and .head == $head) | .base')" || return 1 - [[ "${current}" != true && "${require_current_base}" != true || "${title_base}" == "${BASE_SHA}" ]] || return 1 - jq -e --argjson id "${run_id}" --argjson attempt "${attempt}" --argjson workflow "${workflow_id}" \ - --arg repo "${GITHUB_REPOSITORY}" --arg head_repo "${head_repository}" --arg branch "${head_branch}" \ - --arg head "${HEAD_SHA}" --arg title "${title}" --arg name "${workflow_name}" --arg path "${EXPECTED_WORKFLOW_PATH}" \ - --argjson pr "${PR_NUMBER}" --argjson current "${current}" --argjson current_number "${current_run_number}" \ - --argjson current_run "${GITHUB_RUN_ID}" --argjson current_attempt "${GITHUB_RUN_ATTEMPT}" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .event == "pull_request" and - (.run_number | type == "number" and . > 0 and . == floor) and - (if $current then .run_number == $current_number else - .run_number < $current_number or - (.run_number == $current_number and .id == $current_run and .run_attempt <= $current_attempt) end) and - .repository.full_name == $repo and .head_repository.full_name == $head_repo and - .head_sha == $head and .head_branch == $branch and .display_title == $title and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - (.pull_requests | type == "array") and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr)) and - (if $current then .status == "in_progress" and .conclusion == null else - (.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "in_progress" or .status == "queued" or .status == "pending" or .status == "waiting" or .status == "requested") and .conclusion == null) end)' <<<"${run}" >/dev/null || return 1 - jobs="$(gh api --method GET "${api_root}/actions/runs/${run_id}/attempts/${attempt}/jobs" -f per_page=100)" || return 1 - jobs="$(jq -ce --arg name "${gate_name}" --arg head "${HEAD_SHA}" --argjson run "${run_id}" --argjson current "${current}" ' - if type != "object" or (.jobs | type) != "array" or (.total_count | type) != "number" or - .total_count < 0 or .total_count > 100 or (.total_count | floor) != .total_count or - (.jobs | length) != .total_count or any(.jobs[]; type != "object" or (.id | type) != "number" or .id <= 0 or (.id | floor) != .id) or - ([.jobs[].id] | unique | length) != .total_count then error("incomplete jobs") else . end - | [.jobs[] | select(.name == $name)] | if length == 1 then .[0] else error("ambiguous native gate") end - | select(.run_id == $run and .head_sha == $head) - | select((.status == "completed" and (.conclusion | type == "string" and length > 0)) or - ((.status == "in_progress" or .status == "queued" or .status == "pending" or .status == "waiting" or .status == "requested") and .conclusion == null)) - | select([.steps[]? | select(.name == "Publish pending required gate status" and - ((.status == "in_progress" and .conclusion == null) or - (.status == "completed" and (.conclusion == "success" or .conclusion == "failure" or - .conclusion == "cancelled" or .conclusion == "timed_out" or .conclusion == "action_required"))))] | length == 1) - | select(if $current then .status == "in_progress" and .conclusion == null and - ([.steps[]? | select(.name == "Preserve successful required gate on metadata-only edit" and - .status == "completed" and .conclusion == "success")] | length == 1) else true end)' <<<"${jobs}")" || return 1 - check_id="$(jq -er '.check_run_url | capture("/check-runs/(?[1-9][0-9]*)$").id' <<<"${jobs}")" || return 1 - check="$(gh api --method GET "${api_root}/check-runs/${check_id}")" || return 1 - jq -e --argjson id "${check_id}" --arg name "${gate_name}" --arg head "${HEAD_SHA}" --argjson job "${jobs}" ' - .id == $id and .app.id == 15368 and .app.slug == "github-actions" and .name == $name and - .head_sha == $head and .status == $job.status and .conclusion == $job.conclusion' <<<"${check}" >/dev/null -} -owned_status() { - local status="$1" require_current_base="${2:-false}" suffix run_id attempt - jq -e --arg url "${api_url}/statuses/${HEAD_SHA}" ' - .creator.id == 41898282 and .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - .url == $url and (.state == "pending" or .state == "success" or .state == "failure" or .state == "error")' <<<"${status}" >/dev/null || return 1 - suffix="$(jq -er '.target_url' <<<"${status}")" || return 1 - [[ "${suffix}" == "${run_url}"* ]] || return 1 - suffix="${suffix#"${run_url}"}" - [[ "${suffix}" =~ ^([1-9][0-9]*)/attempts/([1-9][0-9]*)$ ]] || return 1 - run_id="${BASH_REMATCH[1]}"; attempt="${BASH_REMATCH[2]}" - native_identity "${run_id}" "${attempt}" false "${require_current_base}" -} -acknowledge_existing_pending() { - local status="$1" fresh - [[ "$(jq -r '.state' <<<"${status}")" == pending ]] || return 1 - owned_status "${status}" true || return 1 - native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || - fail_closed "Current metadata native gate is not attributable." - pr="$(current_pr)" - pr_matches "${pr}" || unchanged - fresh="$(latest_status)" || fail_closed "Latest context became unavailable." - [[ "${fresh}" == "${status}" ]] || unchanged - report pending-acknowledged - exit 0 -} -pr="$(current_pr)" -pr_matches "${pr}" || unchanged -# Validate the running metadata workflow even on a no-write success path. -run="$(gh api --method GET "${api_root}/actions/runs/${GITHUB_RUN_ID}")" -jq -e --arg title "${current_title}" --argjson id "${GITHUB_RUN_ID}" --argjson attempt "${GITHUB_RUN_ATTEMPT}" \ - --argjson workflow "${workflow_id}" --arg repo "${GITHUB_REPOSITORY}" --arg head "${HEAD_SHA}" \ - --arg head_repo "${head_repository}" --arg branch "${head_branch}" --arg name "${workflow_name}" \ - --arg path "${EXPECTED_WORKFLOW_PATH}" --argjson pr "${PR_NUMBER}" ' - .id == $id and .run_attempt == $attempt and .workflow_id == $workflow and .repository.full_name == $repo and - (.run_number | type == "number" and . > 0 and . == floor) and - .event == "pull_request" and .display_title == $title and .head_sha == $head and - .head_repository.full_name == $head_repo and .head_branch == $branch and - (.name == $name or .name == $title) and - (.path == $path or (.path | startswith($path + "@") and length > ($path | length) + 1)) and - (.pull_requests | type == "array") and - ((.pull_requests | length) == 0 or any(.pull_requests[]; .number == $pr)) and - .status == "in_progress" and .conclusion == null' <<<"${run}" >/dev/null || fail_closed "Current metadata run is not attributable." -current_run_number="$(jq -er '.run_number' <<<"${run}")" -latest="$(latest_status)" || fail_closed "Latest context is incomplete or ambiguous." -owned=false -if [[ "${latest}" != null ]]; then - if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${latest}"; then :; fi - if owned_status "${latest}"; then owned=true; fi -fi -if [[ "${ASSESSMENT}" == success ]]; then - if [[ "${owned}" != true || "$(jq -r '.state' <<<"${latest}")" == success ]]; then unchanged; fi - assessment_output="$(mktemp)" - trap 'rm -f "$assessment_output"' EXIT - if ! GITHUB_OUTPUT="${assessment_output}" bash "$(dirname "${BASH_SOURCE[0]}")/../preserve-required-gate/assess-required-gate.sh"; then - fail_closed "Refreshed canonical assessment failed; no status is published." - fi - ASSESSMENT="$(sed -n 's/^assessment=//p' "${assessment_output}")" - case "${ASSESSMENT}" in success|dependency-deferred) ;; *) fail_closed "Malformed refreshed assessment." ;; esac -fi -if [[ "${latest}" != null && "${owned}" != true ]]; then unchanged; fi -state=pending -[[ "${ASSESSMENT}" != success ]] || state=success -native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || fail_closed "Current metadata native gate is not attributable." -pr="$(current_pr)" -pr_matches "${pr}" || unchanged -fresh="$(latest_status)" || fail_closed "Latest context became unavailable." -if [[ "${fresh}" != "${latest}" ]]; then - if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${fresh}"; then :; fi - unchanged -fi -# One POST, no retry. Its native REST shape has creator and URL, not sha/app_id. -ack="$(gh api --method POST "${api_root}/statuses/${HEAD_SHA}" -f state="${state}" -f context="${gate_name}" \ - -f target_url="${current_target}" -f description="Metadata gate original proof: ${state}")" || - fail_closed "Status POST was denied or ambiguous; do not replay." -jq -se --arg url "${api_url}/statuses/${HEAD_SHA}" --arg context "${gate_name}" --arg state "${state}" --arg target "${current_target}" ' - if length != 1 then error("ambiguous acknowledgment") else .[0] end - | type == "object" and (.id | type == "number" and . > 0 and . == floor) and .url == $url and - .context == $context and .state == $state and .target_url == $target and - .creator.id == 41898282 and .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - (try (.created_at | fromdateiso8601 | type == "number") catch false) and - (try (.updated_at | fromdateiso8601 | type == "number") catch false)' <<<"${ack}" >/dev/null || - fail_closed "Status POST acknowledgment is malformed or misattributed." -report "${state}-acknowledged" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71a1bc8dda..235ff38efd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1378,15 +1378,10 @@ jobs: # Final gating and PR reporting validation-gate: - name: Validation Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. - actions: read # Inspect the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} env: ACCOUNT_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'account-service') }} ACCOUNT_COVERAGE_AGGREGATE: ${{ needs.account-coverage-aggregate.result }} @@ -1395,7 +1390,8 @@ jobs: GAME_SESSION_COVERAGE_AGGREGATE: ${{ needs.game-session-coverage-aggregate.result }} WORLD_COVERAGE_AGGREGATE: ${{ needs.world-coverage-aggregate.result }} needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tool-validation-contracts, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, build-and-test-account, build-and-test-game-session, build-and-test-world, account-coverage-aggregate, game-session-coverage-aggregate, world-coverage-aggregate] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 @@ -1405,62 +1401,7 @@ jobs: - name: Declare dev tool contract split run: ':' - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Explain validation lane - env: - FIREMUD_METADATA_ONLY: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - run: | - if [[ "$FIREMUD_METADATA_ONLY" == "true" ]]; then - printf '## Metadata-only PR edit\n\nHeavy validation jobs are skipped. Required CI is preserved only from qualified source validation for this comparison.\n' >> "$GITHUB_STEP_SUMMARY" - else - printf '## Source validation\n\nThis run executes the applicable source checks for the PR comparison.\n' >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Validation Gate - workflow-name: CI — Validation - workflow-file: ci.yml - workflow-path: .github/workflows/ci.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Validation Gate - workflow-name: CI — Validation - workflow-file: ci.yml - workflow-path: .github/workflows/ci.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - name: Enforce validation success - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: DOCS_CHANGED: ${{ needs.changes.outputs.docs_changed }} FRONTEND_CHANGED: ${{ needs.changes.outputs.frontend_changed }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 34fe4ec60f..6a7bf93c13 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -207,69 +207,20 @@ jobs: uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 codeql-gate: - name: CodeQL Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. - actions: read # Inspect the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} needs: [changes, analyze] - if: ${{ always() && github.event_name == 'pull_request' }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: CodeQL Gate - workflow-name: CodeQL Analysis - workflow-file: codeql.yml - workflow-path: .github/workflows/codeql.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: CodeQL Gate - workflow-name: CodeQL Analysis - workflow-file: codeql.yml - workflow-path: .github/workflows/codeql.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event.action == 'edited' && github.event.changes.base.ref == null }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - name: Enforce successful CodeQL analysis - if: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} env: CHANGES_RESULT: ${{ needs.changes.result }} SHOULD_RUN: ${{ needs.changes.outputs.should_run }} diff --git a/.github/workflows/license-scan.yml b/.github/workflows/license-scan.yml index 069aadc6ac..e7d2445ef8 100644 --- a/.github/workflows/license-scan.yml +++ b/.github/workflows/license-scan.yml @@ -404,69 +404,20 @@ jobs: fi license-gate: - name: License Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (License Gate)' || 'License Gate' }} needs: [changes, ort-gradle, ort-npm] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} runs-on: ubuntu-latest timeout-minutes: 95 - permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. - actions: read # Inspect the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: License Gate - workflow-name: License Gate - workflow-file: license-scan.yml - workflow-path: .github/workflows/license-scan.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: License Gate - workflow-name: License Gate - workflow-file: license-scan.yml - workflow-path: .github/workflows/license-scan.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - name: Verify ORT results - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: EVENT_NAME: ${{ github.event_name }} CHANGES_RESULT: ${{ needs.changes.result }} diff --git a/.github/workflows/resolve-required-gates.yml b/.github/workflows/resolve-required-gates.yml deleted file mode 100644 index 5b8cc5afad..0000000000 --- a/.github/workflows/resolve-required-gates.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Resolve Required Gates - -on: - workflow_run: - workflows: ['CI — Validation', Security Gate, CodeQL Analysis, License Gate, PR Smoke Gate] - types: [completed] - -run-name: Resolve Required Gates workflow-${{ github.event.workflow_run.workflow_id }} head-${{ github.event.workflow_run.head_sha }} source-${{ github.event.workflow_run.id }} - -permissions: - contents: read - -concurrency: - group: required-gate-resolution-${{ github.event.workflow_run.workflow_id }}-${{ github.event.workflow_run.head_sha }} - cancel-in-progress: false - -jobs: - resolve: - name: Resolve deferred metadata gate - # Admit only attributable pull-request sources through the shared resolver. - if: ${{ github.event.workflow_run.event == 'pull_request' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - checks: read - pull-requests: read - statuses: write # Settle only an attributable supplementary status barrier. - actions: write # Only rerun an attributable completed deferred gate job. - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - - name: Check out trusted resolver - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Set up canonical GitHub CLI - uses: ./.github/actions/setup-gh - - - name: Preflight deferred gate resolution - id: preflight - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh preflight - - - name: Admit deferred gate reruns - id: admission - if: ${{ steps.preflight.outputs.eligible == 'true' }} - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh admit - - - name: Confirm admitted deferred gate jobs ${{ steps.admission.outputs.accepted_job_ids }} - if: ${{ steps.admission.outcome == 'success' }} - # Native first-attempt step identity preserves acknowledged IDs even - # while the target run still exposes a stale attempt-one snapshot. - run: ':' - - - name: Reconcile supplementary required gate status - if: ${{ always() }} - env: - GH_TOKEN: ${{ github.token }} - run: bash .github/actions/preserve-required-gate/resolve-deferred-gate.sh reconcile diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index d3d85fa62b..84e92ae7b2 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -840,10 +840,9 @@ jobs: "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} ); + // Metadata-only edits skip their gate under a non-required name. 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 || @@ -851,8 +850,7 @@ jobs: ![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.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; diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index b4d74bf5b8..ffd5224113 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -135,69 +135,20 @@ jobs: warning_window_days: 14 security-gate: - name: Security Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Security Gate)' || 'Security Gate' }} runs-on: ubuntu-latest timeout-minutes: 95 - permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. - actions: read # Inspect the matching required-gate job's preservation step. - statuses: write # Publish acknowledged supplementary metadata gate barriers. - pull-requests: read # Re-read the current PR tuple before status publication. + permissions: {} needs: [changes, trivy-scan, secret-compliance] - if: ${{ always() }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit - - name: Check out required-gate action - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Security Gate - workflow-name: Security Gate - workflow-file: security.yml - workflow-path: .github/workflows/security.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Security Gate - workflow-name: Security Gate - workflow-file: security.yml - workflow-path: .github/workflows/security.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - name: Enforce security success - if: ${{ github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }} env: CHANGES_RESULT: ${{ needs.changes.result }} LIGHTWEIGHT_ONLY: ${{ needs.changes.outputs.lightweight_only }} diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e17d781603..1a8a1808a4 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -457,16 +457,15 @@ jobs: smoke-gate: outputs: known_play_exception: ${{ steps.track-runtime-smoke.outputs.known_play_exception }} - name: Smoke Gate + name: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }} runs-on: ubuntu-latest permissions: - checks: read # Preserve a prior successful required context on metadata-only edits. - contents: read # Check out the shared required-gate composite action. + contents: read # Read the immutable runtime workflow definition and current base ref. actions: read # Inspect matching runtime-image workflow and job results. - statuses: write # Publish acknowledged supplementary metadata gate barriers. pull-requests: read # Re-read the current PR head and base before accepting smoke. needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' }} + # Metadata-only edits skip under a non-required name; the earlier result stands. + if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} timeout-minutes: 95 steps: - name: Harden runner @@ -477,62 +476,16 @@ jobs: - name: Classify smoke gate execution id: smoke_gate_context env: - SMOKE_GATE_REQUIRED: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} CHANGES_RESULT: ${{ needs.changes.result }} run: | - echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT" - if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then + if [ "$CHANGES_RESULT" = "success" ]; then echo "execute=true" >> "$GITHUB_OUTPUT" else echo "execute=false" >> "$GITHUB_OUTPUT" fi - - name: Check out required-gate action - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Preserve successful required gate on metadata-only edit - id: preserved_gate - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: ./.github/actions/preserve-required-gate - with: - gate-name: Smoke Gate - workflow-name: PR Smoke Gate - workflow-file: smoke.yml - workflow-path: .github/workflows/smoke.yml - - - name: Publish pending required gate status - id: publish-pending-status - if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} - uses: ./.github/actions/publish-required-gate-status - with: - assessment: ${{ steps.preserved_gate.outputs.assessment }} - gate-name: Smoke Gate - workflow-name: PR Smoke Gate - workflow-file: smoke.yml - workflow-path: .github/workflows/smoke.yml - - - name: Report dependency-deferred required gate - if: ${{ !cancelled() && steps.smoke_gate_context.outputs.required != 'true' }} - env: - PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} - ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} - PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} - run: | - case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in - success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) - ;; - *) - echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 - exit 1 - ;; - esac - - name: Fail when smoke dependencies did not succeed - if: ${{ steps.smoke_gate_context.outputs.required == 'true' && steps.smoke_gate_context.outputs.execute != 'true' }} + if: ${{ steps.smoke_gate_context.outputs.execute != 'true' }} env: CHANGES_RESULT: ${{ needs.changes.result }} run: | @@ -608,9 +561,9 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; + const canonicalRuntimeWorkflowSha256 = "8f86c8f566e5821f5c35e883d1e02474357c7a42459c520e82d3de4a8a4e8e68"; // Trusted refreshes can still execute the previous successful default-branch definition. - const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; // 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. diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index b35044a9c2..3efcb75a9e 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -126,8 +126,19 @@ jobs: ); }; - const workflowRunFor = async (workflowId) => { + const checkRunWorkflowId = (checkRun) => { + const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); + return match?.[1] || null; + }; + + // Metadata-only edits skip their gate under a non-required name; the + // earlier substantive run for the same title remains the result. + const workflowRunFor = async (workflowId, gateName, checkRuns) => { const workflowName = workflowId === "codeql.yml" ? "CodeQL Analysis" : "License Gate"; + const metadataRunIds = new Set((Array.isArray(checkRuns) ? checkRuns : []) + .filter((checkRun) => checkRun?.name === `PR Metadata Edit (${gateName})`) + .map(checkRunWorkflowId) + .filter(Boolean)); const expectedTitle = `${workflowName} pr-${issueNumber} base-${baseSha} head-${headSha}`; const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, { ...context.repo, @@ -137,15 +148,11 @@ jobs: per_page: 100, }); return selectLatestWorkflowRun( - workflowRuns.filter((workflowRun) => workflowRun?.display_title === expectedTitle) + workflowRuns.filter((workflowRun) => + workflowRun?.display_title === expectedTitle && !metadataRunIds.has(String(workflowRun.id))) ); }; - const checkRunWorkflowId = (checkRun) => { - const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); - return match?.[1] || null; - }; - const compareCheckRuns = (left, right) => { const leftTimestamp = Math.max( parseTimestamp(left?.completed_at), @@ -218,13 +225,14 @@ jobs: return [label, normalizeStatus(selectedCheckRun, checkName, workflowRun)]; }); + const checkRuns = await loadChecks(); const workflowRuns = { - codeql: await workflowRunFor("codeql.yml"), - license: await workflowRunFor("license-scan.yml"), + codeql: await workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns), + license: await workflowRunFor("license-scan.yml", "License Gate", checkRuns), }; // Each serialized producer completion publishes one bounded snapshot. // A running counterpart stays pending until its completion callback refreshes this comment. - const checks = resolveStatuses(await loadChecks(), workflowRuns); + const checks = resolveStatuses(checkRuns, workflowRuns); const gateResults = checks.slice(0, gateChecks.length); const detailResults = checks.slice(gateChecks.length); diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index 468df29c82..45562f14a2 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -128,7 +128,7 @@ jobs: }; const detector = one("Detect CI-Relevant Changes"); if (detector === "skipped") { - core.info("Skipping metadata-only preservation source"); + core.info("Skipping metadata-only edit source"); return; } const fixedChecks = [ diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6bf3ae1299..bc350ac3fd 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -22,7 +22,7 @@ This document describes the continuous integration strategy for FireMUD using ** - **Create release PRs automatically** using the `release-please` workflow. - **Propose dependency updates automatically** with Renovate against the `develop` branch across the supported dependency managers. - **Generate database ERD diagrams** as build artifacts after each run. The [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) script writes them to `design/erd/`, and the workflow uploads this directory as artifacts. -- **Cancel superseded substantive runs for the same branch** using a concurrency group so CI resources are conserved and deployment jobs do not race for the same environment. Metadata-only title/body edits remain isolated from substantive validation. Required check identities remain stable; metadata edits cannot manufacture proof from a skipped, failed, pending, stale, or ambiguous substantive gate. +- **Cancel superseded substantive runs for the same branch** using a concurrency group so CI resources are conserved and deployment jobs do not race for the same environment. Metadata-only title/body edits skip every job and never replace a required check; see [Required Gates on Metadata Edits](#required-gates-on-metadata-edits). ## Implementation Status @@ -32,35 +32,15 @@ The manual [Game Session factory inventory qualification workflow](../../.github --- -## Required Gate Preservation +## Required Gates on Metadata Edits -The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-five prerequisite jobs, including the four distinct other-module, Account, Game Session, and World Build and Test matrix placeholders and the Account, Game Session, and World Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that any coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception; incomplete current inventories cannot fall back to that older shape. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. +The Validation, Security, CodeQL, License, and Smoke gates keep their exact branch-protection names for every substantive pull-request event: open, new commits, reopen, and a base-branch change. Their workflows still listen to `edited`, because GitHub reports a retarget as an `edited` event and cannot filter it by field before starting a run. -A supplementary Commit Status with the same required gate name may withhold an otherwise successful native Actions CheckRun. Both must succeed when both exist; the native app-pinned CheckRun remains mandatory, and a status creator, actor name, or URL cannot establish App authority. The controller independently evaluates that native proof and all exact-head same-name status barriers, including foreign barriers. A status success alone never supplies required native proof. +A metadata-only edit is an `edited` event whose `changes.base` is absent, such as a title or description change. On that event every job in the five workflows is skipped, and each gate job is skipped under a non-required name, `PR Metadata Edit ()`. The edit therefore produces no check run under a required name, so the latest required check run for the head stays the earlier substantive result. A failing or pending gate stays failing or pending, and an edit cannot turn a pull request green. A skipped job under a required name would count as passing, which is why the gate must never skip under its required name. -All five metadata gate producers call the shared publisher after canonical preservation assessment, loading both helpers from the trusted PR base SHA. Their gate jobs hold `statuses: write` and `pull-requests: read` alongside the existing read permissions; no other producer job gains status-write authority. The producer must publish a same-name pending Commit Status on the exact PR head with the exact target URL `https://github.com///actions/runs//attempts/` from GitHub Actions bot user ID `41898282`, login `github-actions[bot]`, type `Bot`, in a dedicated native step named `Publish pending required gate status` (producer step ID `publish-pending-status`). The resolver independently validates the historical metadata ownership and the current original proof. Historical metadata must bind the exact declared PR/head/workflow/run/attempt and a canonical title with its historical base, complete native jobs, dedicated publisher phase, and native Actions app `15368`; empty REST PR associations remain eligible only through canonical title attribution. Historical metadata may still be running, failed or cancelled: it supplies ownership only, never current-base success. For the current open PR/base/head tuple, the unchanged canonical assessor selects original proof while excluding the historical metadata run, not the substantive completion callback's own source. With `REQUIRED_GATE_INCLUDE_SOURCE=true`, opt-in `source_run_id`, `source_job_id`, `source_check_run_id`, and `source_run_attempt` outputs expose that already-selected successful source without changing ordinary output or selection. The resolver independently reads that exact native run/attempt, substantive gate job and app-pinned successful CheckRun before it can publish success. Failed, unavailable or ambiguous current proof cannot become success; pending current proof leaves the barrier blocking. The selector's existing treatment of cancelled/skipped/stale substantive candidates remains unchanged. +Metadata runs use their own concurrency namespace, so an edit cannot cancel or replace an in-progress substantive run. Completion callbacks that read gate results, such as the [runtime-image refresh](#pull-request-runtime-and-preview-chain), the detached Validation Summary and the Static Analysis Summary, ignore metadata runs: they require the required-name gate job, or exclude runs whose gate carries the metadata name. -The existing substantive and metadata completion callbacks reconcile both completion orders, including a pending status published after original proof has already completed. The existing trusted resolve job holds `statuses: write` for supplementary reconciliation; producer gate jobs hold it only for the shared metadata publisher. The assessor retains its unchanged selection contract. A fresh attributable current-tuple completion may reconcile a recognized owned pending, failure or error barrier using independently selected current substantive proof. This explicitly supersedes the pending-only terminal-write restriction for source recovery: a same-head retarget/base advancement or legitimate source retry must recover without a new metadata edit. Already successful and foreign barriers remain untouched. Historical base-A success cannot authorize current base-B success, and obsolete base-A callbacks remain no-ops. The resolver re-reads current PR identity, both historical ownership and selected current native proof, and the unchanged latest status immediately before posting. Its replacement fence is the selected latest status identity; it does not require an original run number to exceed a later metadata run, since original completion after metadata publication is ordinary. Replaced, stale or unbound statuses are never overwritten. GitHub provides no conditional Commit Status write: the final read and POST are not atomic, and this boundary is practical race suppression rather than an atomic replacement guarantee. A rejected or ambiguous POST is never retried within that callback; subsequent callbacks assess fresh evidence. No polling, global expiry, new credentials, or independent proof ledger is introduced. - -The [publisher action](../../.github/actions/publish-required-gate-status/action.yml) runs in the dedicated metadata-only step after both successful and dependency-deferred assessments, so a successful assessment can also recover an existing owned barrier. It accepts `assessment`, `gate-name`, `workflow-name`, `workflow-file`, and `workflow-path`, and outputs `pending-acknowledged`, `success-acknowledged`, or `unchanged`. A dependency-deferred assessment publishes the current run's pending barrier only when the latest same-context status is absent or independently recognized as owned. If an owned pending barrier already binds the exact current PR, base, head, workflow, run, and attempt, including one that becomes latest during the publisher's replacement fence, the publisher reports `pending-acknowledged` without duplicating the status only after validating the current metadata native gate and re-reading both the unchanged current PR tuple and unchanged latest status identity; a stale-base, moved, foreign, malformed, missing, failed, or successful status cannot use that durable acknowledgment path. A success assessment leaves absent, foreign, and already successful barriers unchanged. An owned pending/failure/error barrier requires a refreshed canonical assessment for the current base before publishing success; refreshed pending follows the pending policy, and failed or ambiguous assessment prevents publication. A dependency-deferred assessment permits the native metadata gate to succeed only with `pending-acknowledged`; `unchanged`, missing, unknown, or contradictory publication outputs fail distinctly as dependency deferral. A successful assessment permits `unchanged`, `success-acknowledged`, or `pending-acknowledged`: the last means refreshed proof became pending and the acknowledged status continues withholding readiness. A successful assessment with an absent or already successful barrier needs no write; a foreign barrier remains untouched and independently blocking when non-successful. Missing or unknown assessment/publication outputs fail closed. The metadata-result guard uses `!cancelled()` with the unchanged metadata predicate so it still executes after publisher failure, and requires the publisher outcome itself to be `success` before accepting any assessment/publication pair. Publisher failure, denial, malformed acknowledgment, cancellation, or missing/skipped execution never grants native gate success. The publisher retains normal success-dependent execution without `continue-on-error`; no caller ignores its errors or changes substantive enforcement. - -Ownership recognition allows an older base in the canonical title as provenance, and accepts a bound dedicated publisher step in progress or completed successfully, unsuccessfully, or cancelled. It binds the exact run/attempt, workflow, repository, head, PR title, gate job and native Actions app without requiring old preservation success. This permits replacing an owned barrier left by overlapping or cancelled metadata runs. Positive native workflow `run_number` and `run_attempt` counters order replacement within the same exact workflow: an older run number is replaceable; equal run numbers require the same run ID and no newer attempt. Historical attempt-specific run/job evidence binds older attempts. Missing or conflicting counters and newer barriers are not overwritten; timestamps and global run IDs do not establish ordering. Skipped, missing, conflicting or unbound publisher evidence is not ownership and grants no overwrite permission. Old-base provenance never becomes current-base proof. The current publishing run must be attributable to its exact metadata-only event and current PR tuple. Both publisher and resolver read rich status records from `/repos///statuses/`; the combined `/commits//status` projection omits `creator` and cannot establish ownership. The [GitHub status-list contract](https://docs.github.com/en/rest/commits/statuses#list-commit-statuses-for-a-reference) returns newest first. Readers stop at the first exact-context record regardless of actor, using that API order even when creation timestamps share a second; they never search older records for an owned predecessor or infer chronology from numeric IDs. Explicit 100-record pages have a ten-page safety budget. Only a short page without a matching context establishes absence; budget exhaustion, unavailable/malformed required pages, duplicate IDs in the traversed prefix, or mismatched head-bound status URLs fail closed. Older records after the selected context are not admission evidence. Null, missing, or foreign creators remain untouched rather than inferred from a URL. Native job reads retain their complete one-page cap of 100 records. Immediately before a single non-retried POST, the publisher re-reads the current PR and unchanged latest context. A successful command must return exactly one valid acknowledgment with a positive status ID, exact `https://api.github.com/repos///statuses/` URL, requested state/context/target URL, bot creator and native timestamps. REST statuses have no per-status SHA or App ID. Missing, malformed, denied or ambiguous acknowledgment never yields a pending native-success allowance. Pending POST acknowledgment has native evidence; repaired recovery and read-only fork-token qualification remain outstanding in [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md#required-ci-gate-preservation). A fork token denied status-write authority leaves the publisher and native gate failed. For a non-cancelled metadata run whose canonical preservation assessment succeeded, the executed failed deferral guard retains eligibility for existing trusted legacy recovery after independent original success. Cancellation remains fail-closed. Callers never escalate fork credentials or substitute a status for original proof. - -Resolver/controller support and the separate producer activation are both present in the current workflows. All five metadata gate producers publish pending statuses after canonical preservation assessment. Per-run native pending-status behavior still depends on an acknowledged publication and independently selected current original proof; workflow activation alone does not establish that proof. The resolver retains its targeted legacy rerun path when the distinct dependency-deferral guard executes and fails after successful canonical assessment, including unchanged deferred publication and denied or ambiguous publisher execution. Its existing attribution, chronology, confirmation, and one-attempt constraints remain mandatory. - -The shared action assesses original proof once without polling. Exact success passes; invalid, ambiguous, or failed proof fails. A pending or unpublished original produces a dependency-deferred assessment and releases the runner after acknowledged pending publication. An unacknowledged successful publisher result or failed publisher execution fails the distinct dependency-deferral guard and native job; cancellation does not execute that guard. The trusted default-branch [resolver](../../.github/workflows/resolve-required-gates.yml) reacts to both substantive and metadata completions, so either completion ordering can resolve a deferred gate. It never executes PR source or writes check conclusions. Only its job holds `actions: write`, to rerun an exact completed deferred gate after the shared selector confirms original success. - -Resolution is serialized by owning workflow identity and head SHA. Only a completed first-attempt metadata run whose gate exposes the distinct deferred failure and whose valid native creation timestamp is no later than the current resolver's creation timestamp is eligible. The same chronology check applies immediately before POST. A queued callback cannot admit a later-created target; that target's own later callback can resolve it. This keeps each admitting resolver within the history window bounded by its retained target even after an older source expires. The resolver re-reads current PR identity and target run/job immediately before one non-retried targeted-job POST. An observed second attempt, including a human rerun, consumes the automatic allowance. After acknowledged POSTs, a successful admission publishes only its actual job IDs in a validated set capped at 20; one subsequent native confirmation step preserves that set in its evaluated name. A complete successful confirmation suppresses later POSTs for those exact jobs even while the target API still reports attempt 1, without blocking a distinct eligible job. A successful zero-POST admission confirms an empty set. Partial or ambiguous admission publishes no set, and a missing, failed, cancelled, incomplete, duplicate, or malformed confirmation requires explicit recovery. No marker is emitted for a job before its POST is acknowledged. These checks suppress duplicates practically; they do not assert an atomic API guarantee. An ambiguous or rejected POST fails closed and requires explicit recovery rather than automatic replay. Success remains the rerun gate's own proof decision. - -The trusted resolver separates preflight from a named admission step. Its native run title binds the original workflow ID and head SHA. Current resolver identity must be attributable and on attempt 1; any matching historical resolver attempt greater than 1 also blocks automation because its latest job snapshot could hide an earlier ambiguous admission. Rerunning the resolver alone cannot establish safe recovery. One complete owning-workflow query filtered by `pull_request` and exact head SHA supplies bounded source evidence. Before reading admission history, the resolver validates and freezes eligible native target run/job identities and their creation timestamps. An empty candidate set returns an empty admission without reading history. The history floor is the earliest frozen eligible target creation timestamp, inclusive of ties. Every admissible resolver was created no earlier than its target, so this window retains possible admissions for every frozen candidate even after an older substantive source expires. A target that becomes eligible later cannot enter this invocation's frozen set; the immediate fresh run/job read must match the frozen job ID and creation timestamp. The complete resolver query uses `created >=` that floor and excludes the validated current resolver only when assessing prior admissions. Source discovery remains one complete page capped at 20 records. Resolver history uses explicit 100-record pages, at most ten pages and 1,000 total records, matching the documented [Actions REST search ceiling](https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow). Every page must report the same positive integer total and its expected record count; the combined history must contain unique IDs and the current resolver. Excess, unavailable, malformed, inconsistent, or incomplete coverage fails closed before admission. The query retains all statuses and uses no assumed source-SHA association for the default-branch listener. Unrelated resolver events still count toward the 1,000-record ceiling, so this bounded budget does not establish fleet-wide scalability; an oversized window or source set requires explicit recovery. A matching first-attempt callback still pending or queued with no conclusion and a strictly later native creation timestamp cannot yet have admitted a POST under the shared workflow/head concurrency group; it does not block the current callback even when the trusted listener revision has advanced. The [native concurrency contract](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency) describes waiting workflows as pending; only later first-attempt callbacks under the exact held group receive this exception. Earlier pending callbacks and uncertain histories remain conservative. Equal timestamps require a complete first-attempt job snapshot with exact run/job identity, queued state, explicit null start/end timestamps, and wholly queued/non-concluded steps; empty steps are acceptable only with that unequivocal never-started job state. Missing, malformed, incomplete, or started evidence remains closed. Native queued-job snapshot availability remains unproved; unavailable evidence holds automation. Each matching resolver job lookup retains complete one-page coverage capped at 20 jobs. An attributable completed/cancelled first-attempt callback with explicit, complete zero-job evidence proves a pending callback was evicted before admission; nonempty, missing, malformed, incomplete, or unknown evidence cannot use that exception. Existing native skipped-admission proof remains a separate clean no-op. A skipped admission is a clean no-op; a failed, cancelled, timed-out, missing, or incomplete admission may have sent a POST and blocks later automation even if the target still reports attempt 1. Unavailable or truncated evidence also blocks admission. This uses retained Actions evidence, not a new receipt. The fresh native rehearsal must establish deployed target-window admission, actual target job/attempt transitions, evaluated confirmation-name persistence, and settled no-op callbacks within the existing budget. Native equal-time queued, zero-job eviction, fork/empty-association, delayed-attempt, and retention-loss cases remain unproved; uncertain evidence holds automation rather than requiring unsafe construction of those cases. The bounded history allowance remains an API ceiling, not proof of fleet-wide scalability or a snapshot-consistency guarantee. - -Native admission evidence is bounded by GitHub retention. Known missing, ambiguous, or deleted admission evidence holds automatic replay; a resolver rerun alone does not prove recovery. Establish the actual target attempt/job outcome and a separate safe boundary before resuming automation for that tuple. - -All five callers use canonical one-pass assessment and the trusted listener admits ordinary pull-request tuples through the identity and evidence checks above. There is no proof-branch condition, PR allowlist, assessment-mode input, or long polling path. Deploy the caller/action/helper/resolver/fixture change coherently on the default branch; PR source alone cannot widen the trusted listener. Do not depend on callbacks from token-initiated reruns for further recovery. - -The fresh disposable [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081) rehearsal exercised the deployed frozen target-window boundary. The substantive Validation completion [callback](https://github.com/benhook1013/FireMUD/actions/runs/37699680343) admitted and confirmed deferred job `113054648672`; its targeted rerun produced successful attempt-2 gate `113060155504`. The other four metadata gates passed on attempt 1. A final settled-source metadata edit produced five successful attempt-1 gates and five successful callbacks with explicitly skipped admission and confirmation. This proves the bounded recovery and settled preservation paths, not five separate deferred admissions or the unproved exotic native cases above. The disposable timing fixture is not part of ordinary CI. Retired proof PR #3056 remains closed without merge, with its branch and evidence preserved; never reopen or reuse its pre-chronology admissions. PR #3081 also remains disposable and must not be merged. Implementation and proof status belongs to [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md). - -The shipped [preservation contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) asserts canonical assessment, ordinary listener scope, and the retained fail-closed identity, evidence, chronology, history, admission, and confirmation boundaries. +The [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) checks the gate names, job conditions and concurrency namespaces for all five workflows. Account Service and Game Session validation each use four independent matrix partitions. Account retains two test forks per partition. On Linux, Game Session caps `integrationTest` at two JVM forks, bounded by Gradle’s worker count; JUnit methods within each suite remain serial, and other platforms retain their existing single-fork behavior. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the module’s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. World Management uses the same provenance and aggregation contract with two whole-class partitions balanced collectively across its unit, integration, and cross-service tasks. The existing Validation Gate requires every selected module matrix group and the corresponding coverage aggregate when any of the three slow services is affected. Ordinary local checks for all three services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. @@ -77,12 +57,12 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | | [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | -| [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits keep the required `Smoke Gate` context but do not dispatch or cancel runtime construction; preservation follows [Required Gate Preservation](#required-gate-preservation), including an acknowledged supplementary pending barrier until matching substantive proof succeeds. | +| [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits skip it under a non-required name and do not dispatch or cancel runtime construction; see [Required Gates on Metadata Edits](#required-gates-on-metadata-edits). | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -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. +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 its executed substantive Validation Gate enforcement 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. diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index db27579ff9..fd55e76c29 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -56,7 +56,7 @@ FireMUD owns the project authority and safety requirements below. Follow the act - Open or update a PR autonomously when an implementation branch reaches a coherent review checkpoint, subject to the topology and approval rules in [Change And Merge Policy](#change-and-merge-policy). Stacked PRs are acceptable when their base dependencies are explicit and they let independent work continue while CI or review runs. If the next authorized work is unambiguous and can be cleanly based on a merge-ready PR, continue autonomously in a stacked PR subject to those rules; a draft PR may expose in-progress work and should be marked ready at a coherent review checkpoint. After the parent merges, retarget the child to `develop` subject to those rules before rebasing or pushing. An explicit pause, unresolved human decision, or dependency requiring merged state stops continuation; do not create tiny placeholder PRs without review-worthy content. - When active work moves to another worktree, report its absolute path and branch so the human's IDE context and delegated-worker paths remain aligned. - CI — Validation runs for pull requests targeting any base branch, including stacked feature branches, with the same change classification, jobs, required Validation Gate, and summary as other PRs. Security, License, and CodeQL gates also cover every PR base, and relevant web-client changes receive ZAP validation. Push scopes remain unchanged: Validation, Security, License, and ZAP use `main` and `develop`, while CodeQL uses `main`. A stacked candidate must contain the applicable workflow changes before relying on their coverage. Smoke and the credential-free runtime-image producer also cover feature bases with their existing runtime path classification; irrelevant changes receive an explicit no-op. Validation success alone does not establish smoke proof. Exact tuple selection, parent-advance refresh, and the separate preview/publication restrictions are owned by the [CI/CD runtime and preview chain](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain). -- When retargeting a stacked PR after its parent merges, change the base before rebasing or pushing the child. Required workflows run replacement validation for base-ref edits and isolate title/body edits from substantive runs. Required gate names and exact original-proof attribution are owned by [CI/CD: Required Gate Preservation](../architecture/system-architecture-cicd.md#required-gate-preservation). Deferred metadata gates publish a pending required status, and trusted completion callbacks clear that barrier only after checking current original proof. A dependency-deferred failure is missing proof, not merge readiness. Ambiguous automatic-rerun outcomes require explicit recovery. +- When retargeting a stacked PR after its parent merges, change the base before rebasing or pushing the child. Required workflows run replacement validation for base-ref edits. Title/body edits skip the required gates under non-required names, so the earlier result stands; see [CI/CD: Required Gates on Metadata Edits](../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits). - For recurring branch, worktree, and PR inventory, use `dev-tools/validation/report-worktree-pr-topology.sh` rather than ad hoc status commands. Renovate PRs are omitted from the selected inventory by default; the report records them in `omitted_renovate`, and `--include-renovate` opts them back in. Pass `--pr ` for a bounded direct base/dependent stack and `--json` for machine-readable evidence; selected reports correlate only exact branch/SHA identities and fail closed on ambiguous matches, while reporting local worktree dirtiness and unpublished or stale local heads. - After a merge, remove its defunct local worktree and merged local/remote branch only after confirming no open PR or active stacked branch depends on it. Preserve unmerged branches and worktrees. - Pass PR-body Markdown through a file or stdin with real newlines rather than literal `\\n` strings. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 3ca382658e..843e6da456 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -136,17 +136,13 @@ Smoke and hosted preview seeders reassert canonical state by stable business ide World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeedProperties` and consumes explicit `{tenantId, gameInstanceId}` targets. It no longer imports `GameplayCatalogProperties` in main-code smoke seeding, declares canonical demo and sandbox targets explicitly, and honors the shared `FIREMUD_BOOTSTRAP_*` overrides. The fresh-bootstrap script invokes helper scripts explicitly so file-mode drift cannot break the repo-owned proof path. The seed boundary does not attempt to become a general fixture framework or seed authored content beyond the smoke/demo contract. -### Required CI Gate Preservation +### Required CI Gates on Metadata Edits -The [activation candidate #3235](https://github.com/benhook1013/FireMUD/pull/3235) exposed a support ownership defect: native pending publication was acknowledged, but combined-status GET records omitted `creator`, preventing legitimate barrier recovery. Security original run `38678278927` succeeded and callback `38678584212` executed reconciliation while owned status `56392930570` remained pending. The source repair uses rich status-history records and adds actual API-shape, bounded pagination, same-second latest-context selection, and foreign-actor fixtures. This records a prepared correction, not live recovery proof; repair merge and a fresh attributable callback using the repaired trusted source remain required before activation can qualify. - -Pending-status producer activation is prepared in source for all five required gates, using the shared trusted-base publisher and explicit assessment/publication outcome guards. The support boundary includes trusted resolver reconciliation, independent native CheckRun/status conjunction in the controller, current-base source recovery, and opt-in selected-source provenance without changing canonical assessor selection. Support is merged and the controller promoted; further activation remains dependent on the merged ownership repair and fresh native pending-to-success qualification on the activation candidate. Source contract coverage exercises caller wiring, publisher outcomes and the accepted result matrix, plus legacy recovery after denied/ambiguous publication and rejection of cancelled/unassessed metadata alongside existing publisher/resolver fixtures; native pending POST acknowledgment is observed, but it does not establish completed activation, repaired pending-to-success recovery, read-only fork-token behavior, cancellation, retarget/base-advancement recovery, or terminal-failure retry recovery. These remain native proof checkpoints until attributable evidence is retained. [CI/CD: Required Gate Preservation](../../architecture/system-architecture-cicd.md#required-gate-preservation) owns the producer identity and resolution contract. - -`PO-3.1` implements canonical one-pass metadata-gate assessment and generic native deferred resolution, including the frozen eligible-target history boundary merged in [PR #3079](https://github.com/benhook1013/FireMUD/pull/3079). The coherent activation source removes isolated proof opt-ins and ordinary polling; default-branch deployment of this change remains pending. [CI/CD: Required Gate Preservation](../../architecture/system-architecture-cicd.md#required-gate-preservation) owns the contract and bounded native evidence. This does not establish broader CI/CD or delivery completion. +A title or description edit skips every job in the five required-gate workflows, and each gate is skipped under a non-required `PR Metadata Edit ()` name, so the earlier substantive result stands and an edit cannot turn a failing PR green. Base retargets still run the full gates. This replaced the earlier metadata preservation machinery (shared preservation and status-publisher actions, the Resolve Required Gates callback and their supplementary pending statuses), which is removed. Disposable proof PRs #3056 and #3081 belonged to that retired design; neither may be merged. Native proof on a disposable PR is pending: a body edit must leave the five required checks unchanged, and a retarget must rerun them. [CI/CD: Required Gates on Metadata Edits](../../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits) owns the contract. The PR runtime producer and Smoke Gate now provide an affirmative native producer guarantee for unavailable GitHub step metadata, with an immutable whole-workflow fingerprint and exact run/job/attempt attribution. The existing required-gate contract exercises successful PR/typed-refresh attribution, native smoke/cleanup outcome failures, altered or unavailable definitions, and older producer fail-closed behavior. Native GitHub execution of this new path remains unproved; the successful runtime run for PR #3200 exposed empty step metadata and its earlier producer cannot qualify retroactively. The [CI/CD workflow owner](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) defines the proof contract and fingerprint upkeep. -Focused source proof is owned by `bash dev-tools/tests/pr-required-gate-context-contract.sh`, `bash dev-tools/tests/pr-retarget-workflow-contract.sh`, and `bash dev-tools/tests/ci-lightweight-scope-contract.sh`. Fixtures cover attribution, original-proof selection, one-pass deferral, chronology, frozen target windows, complete bounded evidence, confirmation, and ambiguous or queued/cancelled admission. Fresh [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081) native rehearsal proved one deferred Validation admission with evaluated confirmation and a successful targeted second attempt, four successful first-attempt metadata gates, then five successful settled-source gates and explicit no-op callbacks. Retired #3056 positives are historical targeted-POST/confirmation evidence only. Neither disposable PR may be merged or its old admissions reused. Equal-time queued snapshots, zero-job eviction, fork/empty-association behavior, delayed target snapshots, and retention loss remain native-proof gaps with fail-closed source coverage and explicit recovery requirements; see the [CI/CD owner](../../architecture/system-architecture-cicd.md#required-gate-preservation). Generic activation still requires source validation, review, and default-branch deployment; these local fixtures do not establish hosted activation. +Focused source proof is owned by `bash dev-tools/tests/pr-required-gate-context-contract.sh` (gate names, job conditions, concurrency, smoke producer fingerprint and PLAY-transition checks), `bash dev-tools/tests/pr-retarget-workflow-contract.sh`, and `bash dev-tools/tests/static-analysis-summary-contract.sh` (metadata runs excluded from the summary). ### Hosted Preview, Dev-Demo, and Deployment Delivery diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index de78292a0f..dce9757e88 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -6,6 +6,7 @@ SUMMARY_PAYLOAD="$(python3 - "$ROOT_DIR" <<'PY' from pathlib import Path import base64 import json +import re import sys import yaml @@ -54,7 +55,11 @@ split_markers = [step for step in ci['jobs']['validation-gate']['steps'] if step.get('name') == 'Declare dev tool contract split'] if split_markers != [{'name': 'Declare dev tool contract split', 'run': ':'}]: raise SystemExit('Split contract inventory must retain its unconditional native source marker') -names = [job['name'] for job in ci['jobs'].values()] +def substantive_name(name): + # Metadata-only edits rename a job; substantive runs use the fallback name. + match = re.fullmatch(r"\$\{\{ .* && 'PR Metadata Edit \((.+)\)' \|\| '\1' \}\}", name) + return match[1] if match else name +names = [substantive_name(job['name']) for job in ci['jobs'].values()] for name in names: if '${{' not in name and json.dumps(name, ensure_ascii=False) not in script: raise SystemExit(f'Detached summary is missing the CI job name {name}') diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index aed084a800..b4d7f211f0 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -2,468 +2,125 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -ACTION="$ROOT_DIR/.github/actions/preserve-required-gate/action.yml" -ASSESS_SCRIPT="$ROOT_DIR/.github/actions/preserve-required-gate/assess-required-gate.sh" -[[ -f "$ACTION" ]] || { - echo "required-gate preservation composite action is missing: $ACTION" >&2 - exit 1 -} -[[ -f "$ASSESS_SCRIPT" ]] || { - echo "required-gate preservation assessment script is missing: $ASSESS_SCRIPT" >&2 - exit 1 -} -# shellcheck disable=SC2016 # Assert literal composite action runtime path. -grep -Fxq ' run: bash "$GITHUB_ACTION_PATH/assess-required-gate.sh"' "$ACTION" || { - echo "required-gate action must invoke its checked-in assessment script" >&2 - exit 1 -} -grep -Fq 'using: composite' "$ACTION" || { - echo "required-gate preservation must be a composite action" >&2 - exit 1 -} -grep -Fq ' gate-name:' "$ACTION" || { - echo "required-gate preservation action must expose a gate-name input" >&2 - exit 1 -} -if grep -Fq 'allow-pending' "$ACTION" || grep -Fq 'ALLOW_PENDING' "$ASSESS_SCRIPT"; then - echo "required-gate preservation must not expose a pending-predecessor success override" >&2 - exit 1 -fi - -assert_required_input_declaration() { - local action_path="$1" - local input_name="$2" - local input_block - - input_block="$(awk -v expected_input="$input_name" ' - /^inputs:$/ { - in_inputs = 1 - next - } - in_inputs && /^[^[:space:]][A-Za-z0-9_-]*:/ { - exit - } - in_inputs && $0 == " " expected_input ":" { - capture = 1 - print - next - } - capture && /^ ? ?[A-Za-z0-9_-]+:/ { - exit - } - capture { - print - } - ' "$action_path")" - if [[ -z "$input_block" ]] || - ! grep -Fxq " ${input_name}:" <<<"$input_block" || - ! grep -Fxq ' required: true' <<<"$input_block"; then - echo "required-gate preservation action must declare ${input_name} as a required input" >&2 - exit 1 - fi -} - -for input_name in workflow-name workflow-file workflow-path; do - assert_required_input_declaration "$ACTION" "$input_name" -done -# Keep a required declaration outside the inputs mapping from satisfying the -# final input's block-local requirement. -malformed_action="$(mktemp)" -sed \ - -e '/^ workflow-path:/,/^runs:/ s/^ required: true$/ required: false/' \ - -e '/^runs:/a\ - required: true' \ - "$ACTION" >"$malformed_action" -malformed_input_status=0 -if (assert_required_input_declaration "$malformed_action" workflow-path) >/dev/null 2>&1; then - malformed_input_status=0 -else - malformed_input_status=$? -fi -rm -f "$malformed_action" -if [[ "$malformed_input_status" -eq 0 ]]; then - echo "required-gate preservation action accepted a required declaration outside its inputs block" >&2 - exit 1 -fi -# shellcheck disable=SC2016 # Assert literal action input interpolation syntax. -if ! grep -Fq 'GH_TOKEN: ${{ github.token }}' "$ACTION" || - ! grep -Fq 'BASE_SHA: ${{ github.event.pull_request.base.sha }}' "$ACTION" || - ! grep -Fq 'HEAD_SHA: ${{ github.event.pull_request.head.sha }}' "$ACTION" || - ! grep -Fq 'REQUIRED_GATE_NAME: ${{ inputs.gate-name }}' "$ACTION" || - ! grep -Fq 'PR_NUMBER: ${{ github.event.pull_request.number }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_NAME: ${{ inputs.workflow-name }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_FILE: ${{ inputs.workflow-file }}' "$ACTION" || - ! grep -Fq 'EXPECTED_WORKFLOW_PATH: ${{ inputs.workflow-path }}' "$ACTION" || - grep -Fq 'EXPECTED_JOB_ID' "$ACTION"; then - echo "required-gate action must retain caller, head, gate, and workflow identity inputs without local job identity" >&2 - exit 1 -fi - -python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PY_LANE' -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import yaml - -workflow = yaml.safe_load(Path(sys.argv[1]).read_text()) -step = next(step for step in workflow["jobs"]["validation-gate"]["steps"] if step["name"] == "Explain validation lane") -assert step["env"]["FIREMUD_METADATA_ONLY"] == "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }}" -with tempfile.TemporaryDirectory(prefix="firemud-ci-lane-") as directory: - for value, heading in [("true", "## Metadata-only PR edit"), ("false", "## Source validation")]: - summary = Path(directory) / f"summary-{value}.md" - environment = dict(os.environ, FIREMUD_METADATA_ONLY=value, GITHUB_STEP_SUMMARY=str(summary)) - subprocess.run(["bash", "-e", "-c", step["run"]], check=True, env=environment) - text = summary.read_text() - assert text.startswith(heading + "\n"), text - assert "qualified source validation" in text if value == "true" else "applicable source checks" in text -PY_LANE - -while IFS='|' read -r workflow gate_job_id gate workflow_name workflow_file workflow_path; do - [[ -n "$workflow" ]] || continue - path="$ROOT_DIR/.github/workflows/$workflow" - [[ -f "$path" ]] || { - echo "required-gate caller workflow is missing: $path" >&2 - exit 1 - } - expected_run_name="run-name: ${workflow_name} \${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}" - grep -Fxq "$expected_run_name" "$path" || { - echo "$workflow must publish its canonical pull-request run title" >&2 - exit 1 - } - gate_block="$(awk -v expected_job_id="$gate_job_id" ' - /^ [A-Za-z0-9_-]+:$/ { - if (capture) { - exit - } - capture = ($0 == " " expected_job_id ":") - } - capture { - print - } - ' "$path")" - [[ -n "$gate_block" ]] || { - echo "$workflow must contain required gate job ID $gate_job_id" >&2 - exit 1 - } - if grep -Fq 'allow-pending:' <<<"$gate_block"; then - echo "$workflow must retain fail-closed required-gate polling" >&2 - exit 1 - fi - if ! grep -Fxq " name: $gate" <<<"$gate_block"; then - echo "$workflow must always emit the required $gate context" >&2 - exit 1 - fi - if ! grep -Fq "Preserve successful required gate on metadata-only edit" <<<"$gate_block"; then - echo "$workflow must preserve the required $gate context on metadata-only edits" >&2 - exit 1 - fi - grep -Fq 'uses: ./.github/actions/preserve-required-gate' <<<"$gate_block" || { - echo "$workflow must call the shared required-gate action" >&2 - exit 1 - } - grep -Fxq " gate-name: $gate" <<<"$gate_block" || { - echo "$workflow must pass its required gate name to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-name: $workflow_name" <<<"$gate_block" || { - echo "$workflow must pass its exact workflow name to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-file: $workflow_file" <<<"$gate_block" || { - echo "$workflow must pass its workflow filename to the shared action" >&2 - exit 1 - } - grep -Fxq " workflow-path: $workflow_path" <<<"$gate_block" || { - echo "$workflow must pass its exact workflow path to the shared action" >&2 - exit 1 - } - preserve_block="$(awk ' - /^ - name: Preserve successful required gate on metadata-only edit$/ { - if (found) exit - found=1 - capture=1 - } - capture { - if (/^ - / && $0 != " - name: Preserve successful required gate on metadata-only edit") exit - print - } - ' <<<"$gate_block")" - if [[ "$workflow" == "smoke.yml" ]]; then - # shellcheck disable=SC2016 # Assert literal smoke classification output syntax. - expected_preserve_condition=" if: \${{ steps.smoke_gate_context.outputs.required != 'true' }}" - else - # shellcheck disable=SC2016 # Assert literal metadata-only pull request syntax. - expected_preserve_condition=" if: \${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }}" - if [[ "$workflow" == "codeql.yml" ]]; then - # CodeQL is pull-request-only at this gate, so its condition omits the redundant event-name check. - expected_preserve_condition=" if: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null }}" - fi - fi - grep -Fq "$expected_preserve_condition" <<<"$preserve_block" || { - echo "$workflow $gate preservation must retain its metadata-only condition" >&2 - exit 1 - } - if grep -Fq 'allow-pending:' <<<"$preserve_block"; then - echo "$workflow must retain fail-closed required-gate polling" >&2 - exit 1 - fi - checkout_block="$(awk ' - /^ - name: Check out required-gate action$/ { - if (found) exit - found=1 - capture=1 - } - capture { - if (/^ - / && $0 != " - name: Check out required-gate action") exit - print - } - ' <<<"$gate_block")" - # shellcheck disable=SC2016 # Assert literal trusted pull request base expression. - grep -Fq ' ref: ${{ github.event.pull_request.base.sha }}' <<<"$checkout_block" || { - echo "$workflow $gate must load the shared action from the trusted pull request base SHA" >&2 - exit 1 - } - # shellcheck disable=SC2016 # Assert literal polling syntax is absent from gate callers. - if grep -Fq 'gh api' <<<"$gate_block" || - grep -Eq 'for[[:space:]]+(attempt|poll_attempt|retry_attempt)[[:space:]]+in|while[[:space:]]+.*(attempt|poll|retry)' <<<"$gate_block"; then - echo "$workflow must delegate required-gate polling to the shared action" >&2 - exit 1 - fi - - first_step="$(awk '/^ steps:$/ {in_steps=1; next} in_steps && /^ - / {print; exit}' <<<"$gate_block")" - [[ "$first_step" == ' - name: Harden runner' ]] || { - echo "$workflow $gate must harden the runner as its unconditional first step" >&2 - exit 1 - } - harden_block="$(awk '/^ - name: Harden runner$/{in_harden=1} in_harden{if (/^ - / && $0 != " - name: Harden runner") exit; print}' <<<"$gate_block")" - harden_action_pattern='^ uses: step-security/harden-runner@[0-9a-f]{40}([[:blank:]]+#.*)?[[:blank:]]*$' - fixture_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - for annotation in '' ' # v2.19.3' ' # verified upstream ref'; do - fixture_uses=" uses: step-security/harden-runner@${fixture_sha}${annotation}" - grep -Eq "$harden_action_pattern" <<<"$fixture_uses" || { - echo "required-gate hardening pin rejected a valid immutable SHA annotation form" >&2 - exit 1 - } - done - for invalid_uses in \ - " uses: actions/harden-runner@${fixture_sha}" \ - ' uses: step-security/harden-runner@v2' \ - " uses: step-security/harden-runner@${fixture_sha%?}"; do - if grep -Eq "$harden_action_pattern" <<<"$invalid_uses"; then - echo "required-gate hardening pin accepted an invalid action reference: $invalid_uses" >&2 - exit 1 - fi - done - if grep -Fq ' if:' <<<"$harden_block" || - ! grep -Eq "$harden_action_pattern" <<<"$harden_block" || - ! grep -Fq ' egress-policy: audit' <<<"$harden_block"; then - echo "$workflow $gate hardening must remain unconditional and retain its pinned audit configuration" >&2 - exit 1 - fi - grep -Fq ' checks: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain checks: read" >&2 - exit 1 - } - grep -Fq ' actions: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain actions: read for job-step classification" >&2 - exit 1 - } - grep -Fq ' contents: read' <<<"$gate_block" || { - echo "$workflow $gate caller must retain contents: read" >&2 - exit 1 - } - python3 - "$path" "$gate_job_id" "$workflow" "$gate" "$workflow_name" <<'PY' +# Required gates on metadata-only PR edits: a title/body edit (edited with no +# base change) skips each required gate under a non-required name, so the +# earlier substantive result stands and an edit can never turn a failing PR +# green. Base retargets keep the required name and rerun the full gate. +python3 - "$ROOT_DIR" <<'PY' from pathlib import Path import sys import yaml +root = Path(sys.argv[1]) +META = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null" +SUBSTANTIVE = "(github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null)" +PR_SUBSTANTIVE = "(github.event.action != 'edited' || github.event.changes.base.ref != null)" +gates = { + # workflow: (workflow name, gate job, gate name, change job name, result step, PR-only, run-scoped metadata group) + "ci.yml": ("CI — Validation", "validation-gate", "Validation Gate", "Detect CI-Relevant Changes", "Enforce validation success", False, True), + "security.yml": ("Security Gate", "security-gate", "Security Gate", "Detect Security-Relevant Changes", "Enforce security success", False, True), + "license-scan.yml": ("License Gate", "license-gate", "License Gate", "Detect License-Relevant Changes", "Verify ORT results", False, False), + "smoke.yml": ("PR Smoke Gate", "smoke-gate", "Smoke Gate", "Detect Smoke-Relevant Changes", "Classify smoke gate execution", True, True), + "codeql.yml": ("CodeQL Analysis", "codeql-gate", "CodeQL Gate", "Detect CodeQL-Relevant Changes", "Enforce successful CodeQL analysis", True, False), +} +retired = ( + "preserve-required-gate", + "publish-required-gate-status", + "resolve-required-gates", + "statuses: write", +) -expected_job_if = { - "validation-gate": "${{ always() }}", - "security-gate": "${{ always() }}", - "license-gate": "${{ always() }}", - "smoke-gate": "${{ always() && github.event_name == 'pull_request' }}", - "codeql-gate": "${{ always() && github.event_name == 'pull_request' }}", -} -result_step_names = { - "validation-gate": "Enforce validation success", - "security-gate": "Enforce security success", - "license-gate": "Verify ORT results", - "smoke-gate": "Classify smoke gate execution", - "codeql-gate": "Enforce successful CodeQL analysis", -} -change_job_names = { - "ci.yml": "Detect CI-Relevant Changes", - "security.yml": "Detect Security-Relevant Changes", - "license-scan.yml": "Detect License-Relevant Changes", - "smoke.yml": "Detect Smoke-Relevant Changes", - "codeql.yml": "Detect CodeQL-Relevant Changes", -} - -path = Path(sys.argv[1]) -job_id = sys.argv[2] -workflow = sys.argv[3] -gate = sys.argv[4] -expected_workflow_name = sys.argv[5] -try: - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) - job = data["jobs"][job_id] -except (KeyError, TypeError, yaml.YAMLError) as exc: - raise SystemExit(f"{workflow} must contain a structured {gate} job: {exc}") from exc - -if not isinstance(job, dict): - raise SystemExit(f"{workflow} {gate} job must be a mapping") -if data.get("name") != expected_workflow_name: - raise SystemExit( - f"{workflow} must declare the caller-supplied workflow name {expected_workflow_name!r}; " - f"found {data.get('name')!r}" - ) -if data.get("jobs", {}).get("changes", {}).get("name") != change_job_names[workflow]: - raise SystemExit( - f"{workflow} changes job name must match the selector's expected " - f"{change_job_names[workflow]!r} pattern" - ) -if job_id not in expected_job_if or job_id not in result_step_names: - raise SystemExit( - f"{workflow} {gate}: unknown gate job ID {job_id!r}; " - "add it to expected_job_if and result_step_names" - ) - -preserve_steps = [step for step in job["steps"] if step.get("name") == "Preserve successful required gate on metadata-only edit"] -deferred_steps = [step for step in job["steps"] if step.get("name") == "Report dependency-deferred required gate"] -if len(preserve_steps) != 1 or preserve_steps[0].get("id") != "preserved_gate": - raise SystemExit(f"{workflow} must bind the preservation output") -if "assessment-mode" in preserve_steps[0].get("with", {}): - raise SystemExit(f"{workflow} must use canonical assessment without a mode opt-in") -if len(deferred_steps) != 1 or deferred_steps[0].get("if") != preserve_steps[0]["if"].replace("${{ ", "${{ !cancelled() && ", 1): - raise SystemExit(f"{workflow} must guard every metadata assessment and publication outcome") -if "exit 1" not in deferred_steps[0].get("run", ""): - raise SystemExit(f"{workflow} must fail distinctly for unacknowledged dependency deferral") -if job.get("if") != expected_job_if[job_id]: - raise SystemExit( - f"{workflow} {gate} must retain its exact job if condition: " - f"{expected_job_if[job_id]!r}" +def evaluate(expression, action, base_ref, event="pull_request"): + """Evaluate the narrow boolean gate expressions used here.""" + body = expression.strip() + if body.startswith("${{") and body.endswith("}}"): + body = body[3:-2].strip() + values = { + "github.event.changes.base.ref": repr(base_ref), + "github.event.action": repr(action), + "github.event_name": repr(event), + "always()": "True", + } + for key, value in values.items(): + body = body.replace(key, value) + body = body.replace("&&", " and ").replace("||", " or ").replace("!=", " != ").replace("null", "None") + return eval(body, {"__builtins__": {}}) + + +for directory in (".github/actions/preserve-required-gate", ".github/actions/publish-required-gate-status"): + if (root / directory).exists(): + raise SystemExit(f"retired metadata preservation machinery must stay deleted: {directory}") +if (root / ".github/workflows/resolve-required-gates.yml").exists(): + raise SystemExit("retired required-gate resolver workflow must stay deleted") + +for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_only, run_scoped) in gates.items(): + path = root / ".github/workflows" / workflow + text = path.read_text(encoding="utf-8") + for token in retired: + if token in text: + raise SystemExit(f"{workflow} still references retired metadata preservation: {token}") + data = yaml.load(text, Loader=yaml.BaseLoader) + if data.get("name") != workflow_name: + raise SystemExit(f"{workflow} must keep workflow name {workflow_name!r}") + if set(data["on"]["pull_request"]["types"]) != {"opened", "synchronize", "reopened", "edited"}: + raise SystemExit(f"{workflow} must still trigger on edited so base retargets rerun the gate") + expected_title = ( + f"{workflow_name} ${{{{ github.event_name == 'pull_request' && format('pr-{{0}} base-{{1}} head-{{2}}', " + "github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}" ) + if data.get("run-name") != expected_title: + raise SystemExit(f"{workflow} must publish its canonical pull-request run title") + if data["jobs"]["changes"].get("name") != change_job: + raise SystemExit(f"{workflow} change detection job must stay {change_job!r}") -needs = job.get("needs") -if isinstance(needs, str): - dependencies = [needs] -elif isinstance(needs, list): - dependencies = needs -else: - raise SystemExit(f"{workflow} {gate} must define needs as a scalar or list") -if "changes" not in dependencies: - raise SystemExit(f"{workflow} {gate} must depend on the changes job") - -steps = job.get("steps") -if not isinstance(steps, list): - raise SystemExit(f"{workflow} {gate} must define steps as a list") -result_steps = [ - step - for step in steps - if isinstance(step, dict) and step.get("name") == result_step_names[job_id] -] -if len(result_steps) != 1: - raise SystemExit( - f"{workflow} {gate} must contain exactly one {result_step_names[job_id]!r} step" - ) -result_env = result_steps[0].get("env") -if not isinstance(result_env, dict) or result_env.get("CHANGES_RESULT") != "${{ needs.changes.result }}": - raise SystemExit( - f"{workflow} {gate} must read needs.changes.result through the exact " - f"{result_step_names[job_id]!r} CHANGES_RESULT field" + gate = data["jobs"][gate_job] + if gate.get("name") != f"${{{{ {META} && 'PR Metadata Edit ({gate_name})' || '{gate_name}' }}}}": + raise SystemExit(f"{workflow} {gate_name} must take a non-required name on metadata-only edits") + expected_if = ( + f"${{{{ always() && github.event_name == 'pull_request' && {PR_SUBSTANTIVE} }}}}" + if pr_only else f"${{{{ always() && {SUBSTANTIVE} }}}}" ) -PY - - group_line=$(grep -m1 '^ group:' "$path" || true) - if [[ "$workflow" == "ci.yml" || "$workflow" == "security.yml" || "$workflow" == "smoke.yml" ]]; then - if [[ "$group_line" != *"format('metadata-{0}', github.run_id) || 'required' }}"* ]]; then - echo "$workflow concurrency group must give every metadata-only run a unique namespace" >&2 - exit 1 - fi - elif [[ "$group_line" != *"&& 'metadata' || 'required' }}"* ]]; then - echo "$workflow concurrency group must separate metadata and required PR runs" >&2 - exit 1 - fi - if [[ "$group_line" != *"github.event.pull_request.number"* ]]; then - echo "$workflow concurrency group must remain scoped to the PR number" >&2 - exit 1 - fi - if ! grep -Fq ' cancel-in-progress: true' "$path"; then - echo "$workflow must cancel only within its metadata/required concurrency namespace" >&2 - exit 1 - fi - if grep -Fq "cancel-in-progress: \${{ github.event_name != 'pull_request' || github.event.action != 'edited'" "$path"; then - echo "$workflow still uses shared-group conditional cancellation that can race required contexts" >&2 - exit 1 - fi -done <<'EOF' -ci.yml|validation-gate|Validation Gate|CI — Validation|ci.yml|.github/workflows/ci.yml -security.yml|security-gate|Security Gate|Security Gate|security.yml|.github/workflows/security.yml -license-scan.yml|license-gate|License Gate|License Gate|license-scan.yml|.github/workflows/license-scan.yml -smoke.yml|smoke-gate|Smoke Gate|PR Smoke Gate|smoke.yml|.github/workflows/smoke.yml -codeql.yml|codeql-gate|CodeQL Gate|CodeQL Analysis|codeql.yml|.github/workflows/codeql.yml -EOF - -# Model two rapid metadata edits against the unchanged head. Each lightweight -# run gets an independent namespace, while the required gate contexts remain -# the sole authoritative checks and optional summaries cannot leave cancelled -# or failed residue in the aggregate rollup. -python3 - "$ROOT_DIR" <<'PY' -from pathlib import Path -import sys - -import yaml - -root = Path(sys.argv[1]) -workflows = { - "ci.yml": ("validation-gate", "Validation Gate", True), - "security.yml": ("security-gate", "Security Gate", True), - "license-scan.yml": ("license-gate", "License Gate", False), - "smoke.yml": ("smoke-gate", "Smoke Gate", True), - "codeql.yml": ("codeql-gate", "CodeQL Gate", False), -} + if gate.get("if") != expected_if: + raise SystemExit(f"{workflow} {gate_name} must skip only metadata-only edits: {expected_if}") + # Metadata edits skip; opens, pushes, reopens and base retargets run. + if evaluate(gate["if"], "edited", None): + raise SystemExit(f"{workflow} {gate_name} must skip a title/body edit") + for action, base_ref in (("edited", "develop"), ("opened", None), ("synchronize", None), ("reopened", None)): + if not evaluate(gate["if"], action, base_ref): + raise SystemExit(f"{workflow} {gate_name} must run for {action} (base change={base_ref})") + if not pr_only and not evaluate(gate["if"], None, None, event="push"): + raise SystemExit(f"{workflow} {gate_name} must still run on push") + needs = gate.get("needs") + if "changes" not in (needs if isinstance(needs, list) else [needs]): + raise SystemExit(f"{workflow} {gate_name} must depend on change detection") + result_steps = [step for step in gate.get("steps", []) if step.get("name") == result_step] + if len(result_steps) != 1 or result_steps[0].get("env", {}).get("CHANGES_RESULT") != "${{ needs.changes.result }}": + raise SystemExit(f"{workflow} {gate_name} must enforce through one {result_step!r} step reading CHANGES_RESULT") + if any("if" in step and "edited" in step["if"] for step in gate.get("steps", [])): + raise SystemExit(f"{workflow} {gate_name} steps must not branch on edits; the job condition owns that") + + # Every other job also stays idle for metadata-only edits, and none of + # them may hold a required gate name. + for job_id, job in data["jobs"].items(): + if job_id == gate_job: + continue + condition = job.get("if", "") + if "github.event.action != 'edited' || github.event.changes.base.ref != null" not in condition: + raise SystemExit(f"{workflow} job {job_id} can run for a metadata-only edit") + if job.get("name") in {name for _, _, name, *_ in gates.values()}: + raise SystemExit(f"{workflow} job {job_id} must not reuse a required gate name") -metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" -for workflow, (gate_job, gate_name, run_scoped_metadata) in workflows.items(): - path = root / ".github" / "workflows" / workflow - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + # Metadata runs never cancel or replace the substantive run. concurrency = data["concurrency"] group = concurrency["group"] - required_group_parts = ( - "github.event.pull_request.number", - "github.event.action == 'edited'", - "github.event.changes.base.ref == null", - "|| 'required'", - ) - if any(part not in group for part in required_group_parts): - raise SystemExit(f"{workflow} concurrency expression lost PR-scoped metadata isolation") - metadata_suffix = "format('metadata-{0}', github.run_id)" if run_scoped_metadata else "&& 'metadata' || 'required'" - if metadata_suffix not in group: - raise SystemExit(f"{workflow} concurrency expression changed its metadata group") + suffix = "format('metadata-{0}', github.run_id) || 'required'" if run_scoped else "&& 'metadata' || 'required'" + if "github.event.pull_request.number" not in group or META.split(" && ", 1)[1] not in group or suffix not in group: + raise SystemExit(f"{workflow} concurrency group must keep metadata runs out of the PR's required namespace") if concurrency.get("cancel-in-progress") != "true": - raise SystemExit(f"{workflow} must cancel obsolete required-gate runs") - - gate = data["jobs"][gate_job] - if gate.get("name") != gate_name: - raise SystemExit(f"{workflow} required gate context changed") - -for workflow in ("ci.yml", "security.yml", "smoke.yml"): - path = root / ".github" / "workflows" / workflow - data = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) - for job_name, job in data["jobs"].items(): - if job_name == workflows[workflow][0]: - continue - condition = job.get("if", "") if isinstance(job, dict) else "" - if metadata_guard not in condition: - raise SystemExit( - f"{workflow} job {job_name} can run for a metadata-only edited event" - ) + raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") PY # shellcheck disable=SC2016 # Match the checked-in arithmetic assignment literally. @@ -896,2594 +553,6 @@ async function scenario(kind, event = "pull_request") { })().catch(error => {console.error(error); process.exitCode = 1;}); NODE -cat >"$tmp_dir/gh" <<'EOF' -#!/usr/bin/env bash -set -euo pipefail -count_file="${GH_RETRY_COUNT_FILE:?}" -if [[ "${GH_SCENARIO:-}" == attempt-fallback-* ]]; then - python3 - "${GH_SCENARIO}" "$@" <<'ATTEMPT_FALLBACK_FIXTURE' -import json -import os -import sys - -scenario = sys.argv[1] -args = sys.argv[2:] -endpoint = next(argument for argument in args if argument.startswith("/repos/")) -if os.environ.get("GH_CALL_COUNT_DIR"): - from pathlib import Path - Path(os.environ["GH_CALL_COUNT_DIR"]).mkdir(parents=True, exist_ok=True) - if "/actions/runs/" in endpoint and "/attempts/" in endpoint: - with (Path(os.environ["GH_CALL_COUNT_DIR"]) / "attempt-endpoints").open("a") as stream: - stream.write(endpoint + "\n") - if scenario == "attempt-fallback-recovery-limit" and "/actions/jobs/" in endpoint: - with (Path(os.environ["GH_CALL_COUNT_DIR"]) / "candidate-direct-jobs").open("a") as stream: - stream.write(endpoint + "\n") -repo = "example/firemud" -head = "a" * 40 -base = "b" * 40 -title = f"CI — Validation pr-123 base-{base} head-{head}" -attempt = 2 if "attempt-two" in scenario else 1 -if scenario == "attempt-fallback-newer-failure": - ids = [100, 101] -elif scenario == "attempt-fallback-recovery-limit": - ids = [100, 101, 102, 103] -else: - ids = [100] -rows = [] -for index, identity in enumerate(ids): - conclusion = "failure" if identity == 101 else "success" - start = f"2026-07-30T0{index + 1}:00:00Z" - finish = f"2026-07-30T0{index + 1}:30:00Z" - rows.append({"app": {"slug": "github-actions"}, "name": "Validation Gate", "id": identity, - "details_url": f"https://github.com/{repo}/actions/runs/{identity}/job/{identity}", - "status": "completed", "conclusion": conclusion, "completed_at": finish, - "started_at": start, "created_at": start}) -if endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith(f"/commits/{head}/check-runs"): - result = [{"total_count": len(rows), "check_runs": rows}] -elif "/actions/runs/" in endpoint and endpoint.endswith(f"/attempts/{attempt}/jobs"): - call_number = 1 - if os.environ.get("GH_CALL_COUNT_DIR"): - from pathlib import Path - Path(os.environ["GH_CALL_COUNT_DIR"]).mkdir(parents=True, exist_ok=True) - call_file = Path(os.environ["GH_CALL_COUNT_DIR"]) / f"attempt-jobs-{endpoint.split('/actions/runs/')[1].split('/')[0]}-{attempt}" - call_number = int(call_file.read_text()) + 1 if call_file.exists() else 1 - call_file.write_text(str(call_number)) - assert "per_page=100" in args and "--paginate" not in args and "--slurp" not in args, args - assert scenario != "attempt-fallback-known-skipped", "known preservation evidence must stay on the ordinary path" - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - candidate = next(row for row in rows if row["id"] == identity) - index = ids.index(identity) - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", - "conclusion": "skipped" if scenario != "attempt-fallback-metadata" else "success"}] - job = {"id": identity, "run_id": identity, - "run_attempt": 1 if scenario == "attempt-fallback-attempt-two-mismatch" else attempt, "head_sha": head, "head_branch": "proof-branch", - "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": candidate["conclusion"], "created_at": candidate["created_at"], - "started_at": candidate["started_at"], "completed_at": candidate["completed_at"], - "html_url": candidate["details_url"], "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{identity}", - "steps": steps} - if scenario == "attempt-fallback-empty": - job["steps"] = [] - if scenario == "attempt-fallback-no-steps": - job.pop("steps") - if scenario == "attempt-fallback-wrong-check-url": - job["check_run_url"] = f"https://api.github.com/repos/{repo}/check-runs/999" - if scenario == "attempt-fallback-duplicate": - result = {"total_count": 2, "jobs": [job, dict(job)]} - elif scenario == "attempt-fallback-malformed": - result = {"total_count": "1", "jobs": [job]} - elif scenario == "attempt-fallback-oversized": - others = [{"id": 1000 + index, "run_id": identity, "run_attempt": 1, "head_sha": head, "head_branch": "proof-branch", - "workflow_name": "CI — Validation", "name": f"Build and Test (module-{index:03d})", - "status": "completed", "conclusion": "success", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{1000 + index}"} - for index in range(100)] - result = {"total_count": 101, "jobs": [job, *others]} - elif scenario == "attempt-fallback-incomplete": - result = {"total_count": 2, "jobs": [job]} - else: - if scenario == "attempt-fallback-wrong-attempt": - job["run_attempt"] = 2 - if scenario == "attempt-fallback-wrong-head": - job["head_sha"] = "d" * 40 - if scenario == "attempt-fallback-wrong-workflow": - job["workflow_name"] = "Security Checks" - result = {"total_count": 1, "jobs": [job]} -elif "/actions/runs/" in endpoint and "/attempts/" in endpoint: - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - if scenario == "attempt-fallback-attempt-two-api-error": - raise SystemExit(31) - result = {"id": identity, "workflow_id": 42, - "run_attempt": 1 if scenario == "attempt-fallback-attempt-two-mismatch" else attempt, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "head_branch": "proof-branch", "display_title": title, - "repository": {"full_name": repo}, "head_repository": {"full_name": repo}, "event": "pull_request", - "status": "completed", - "pull_requests": [{"number": 123, "base": {"sha": base}, "head": {"sha": head}}]} - if scenario == "attempt-fallback-stale-tuple": - result["display_title"] = result["display_title"].replace(base, "c" * 40) -elif "/actions/runs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - result = {"id": identity, "workflow_id": 42, "run_attempt": attempt, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "head_branch": "proof-branch", "display_title": title, - "repository": {"full_name": repo}, "head_repository": {"full_name": repo}, "event": "pull_request", - "pull_requests": [{"number": 123, "base": {"sha": base}, "head": {"sha": head}}]} -elif "/actions/jobs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - candidate = next(row for row in rows if row["id"] == identity) - result = {"id": identity, "run_id": identity, "run_attempt": attempt, "head_sha": head, - "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": candidate["conclusion"], "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{identity}", - "steps": []} - if scenario == "attempt-fallback-known-skipped": - result["steps"] = [ - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}, - ] - if scenario == "attempt-fallback-duplicate-direct": - result["steps"] = [ - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}, - {"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "failure"}, - ] - if scenario == "attempt-fallback-malformed-direct": - result["steps"] = "unavailable" -elif "/check-runs/" in endpoint: - identity = int(endpoint.rsplit("/", 1)[1]) - candidate = next(row for row in rows if row["id"] == identity) - result = {"id": identity, "app": {"id": 15368, "slug": "github-actions"}, "head_sha": head, - "name": "Validation Gate", "status": "completed", "conclusion": candidate["conclusion"], - "details_url": candidate["details_url"], "started_at": candidate["started_at"], - "completed_at": candidate["completed_at"]} - if scenario == "attempt-fallback-wrong-app": - result["app"]["id"] = 1 - if scenario == "attempt-fallback-wrong-check-details": - result["details_url"] += "?changed=true" -else: - raise AssertionError(endpoint) -print(json.dumps(result)) -ATTEMPT_FALLBACK_FIXTURE - exit 0 -fi -if [[ "${GH_SCENARIO:-}" == cancellation-* ]]; then - python3 - "$GH_SCENARIO" "$@" <<'CANCELLATION_FIXTURE' -import copy -import json -import os -import sys -scenario = sys.argv[1] -endpoint = next(argument for argument in sys.argv[2:] if argument.startswith("/repos/")) -head, base = os.environ["HEAD_SHA"], os.environ["BASE_SHA"] -repo = os.environ["GITHUB_REPOSITORY"] -title = f"CI — Validation pr-{os.environ['PR_NUMBER']} base-{base} head-{head}" -names = ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", - "Build and Test (account-service / $" + "{{ matrix.partition }})", - "Build and Test (world-management-service / $" + "{{ matrix.partition }})", - "Build and Test (game-session-service / $" + "{{ matrix.partition }})", "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", - "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", - "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", - "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", - "Account Coverage Aggregate", "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] -# Retain the exact old 26-job inventory; the new split adds exactly one name. -if scenario.startswith("cancellation-dev-tool-"): - names.insert(-1, "Dev Tool Validation Contracts") -def step(name, conclusion): - return {"name": name, "status": "completed", "conclusion": conclusion} -# Exact split-matrix cancellation shape: prerequisites never reached a step; -# slow-service aggregation prerequisites were skipped without running, -# while the always() gate failed only its enforcement step after cancellation. -jobs = [{"id": 500 + index, "run_id": 100, "run_attempt": 1, "head_sha": head, - "name": name, "workflow_name": "CI — Validation", "status": "completed", - "conclusion": "cancelled", "steps": [], - "html_url": f"https://github.com/{repo}/actions/runs/100/job/{500 + index}", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{600 + index}"} - for index, name in enumerate(names)] -aggregate = next(job for job in jobs if job["name"] == "Account Coverage Aggregate") -aggregate["conclusion"] = "skipped" -game_session_aggregate = next(job for job in jobs if job["name"] == "Game Session Coverage Aggregate") -game_session_aggregate["conclusion"] = "skipped" -gate = jobs[-1] -gate["conclusion"] = "failure" -gate["steps"] = [step("Set up job", "success"), step("Pre Harden runner", "success"), - step("Harden runner", "success"), step("Check out required-gate action", "skipped"), - step("Preserve successful required gate on metadata-only edit", "skipped"), - step("Publish pending required gate status", "skipped"), - step("Report dependency-deferred required gate", "skipped"), - step("Enforce validation success", "failure"), step("Post Harden runner", "success"), - step("Complete job", "success")] -if scenario.startswith("cancellation-dev-tool-"): - gate["steps"].append(step("Declare dev tool contract split", "skipped")) -if scenario == "cancellation-dev-tool-duplicate-marker": - gate["steps"].append(step("Declare dev tool contract split", "skipped")) -if scenario == "cancellation-old-shape": - jobs = [job for job in jobs if job["name"] not in ( - "Build and Test (account-service / $" + "{{ matrix.partition }})", - "Build and Test (game-session-service / $" + "{{ matrix.partition }})")] -if scenario == "cancellation-partial-new-shape": - jobs = [job for job in jobs if job["name"] != - "Build and Test (game-session-service / $" + "{{ matrix.partition }})"] -if scenario == "cancellation-pre-world-shape": - jobs = [job for job in jobs if job["name"] not in ( - "Build and Test (world-management-service / $" + "{{ matrix.partition }})", - "World Coverage Aggregate")] -if scenario == "cancellation-world-missing-partition": - jobs = [job for job in jobs if job["name"] != - "Build and Test (world-management-service / $" + "{{ matrix.partition }})"] -if scenario == "cancellation-world-aggregate-executed": - world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") - world["steps"] = [step("Verify complete World partition and report union", "success")] -if scenario == "cancellation-world-aggregate-failed": - world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") - world["conclusion"] = "failure" -if scenario == "cancellation-real-failure": - jobs[1]["conclusion"] = "failure" - jobs[1]["steps"] = [step("Run lint", "failure")] -if scenario == "cancellation-hidden-step-failure": - jobs[1]["steps"] = [step("Assert", "failure")] -if scenario == "cancellation-executed-check": - jobs[1]["steps"] = [step("Assert", "success")] -if scenario == "cancellation-gate-other-failure": - gate["steps"][2]["conclusion"] = "failure" -if scenario == "cancellation-unknown-assertion": - jobs[1]["steps"] = [step("Assert", "unknown")] -if scenario == "cancellation-timed-out": - jobs[1]["conclusion"] = "timed_out" -if scenario == "cancellation-action-required": - jobs[1]["conclusion"] = "action_required" -if scenario == "cancellation-metadata": - gate["steps"][4]["conclusion"] = "failure" -if scenario == "cancellation-aggregate-executed": - aggregate["steps"] = [step("Verify complete Account partition and report union", "success")] -if scenario == "cancellation-aggregate-failed": - aggregate["conclusion"] = "failure" - aggregate["steps"] = [step("Verify complete Account partition and report union", "failure")] -if scenario == "cancellation-game-session-aggregate-executed": - game_session_aggregate["steps"] = [step("Verify complete Game Session partition and report union", "success")] -if scenario == "cancellation-game-session-aggregate-failed": - game_session_aggregate["conclusion"] = "failure" - game_session_aggregate["steps"] = [step("Verify complete Game Session partition and report union", "failure")] -if scenario == "cancellation-dev-tool-real-failure": - sibling = next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts") - sibling["conclusion"] = "failure" - sibling["steps"] = [step("Validate dev tool validation contracts", "failure")] -if scenario == "cancellation-dev-tool-executed": - next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts")["steps"] = [step("Set up Python", "success")] -if scenario == "cancellation-dev-tool-skipped": - next(job for job in jobs if job["name"] == "Dev Tool Validation Contracts")["conclusion"] = "skipped" -run = {"id": 100, "workflow_id": 42, "run_attempt": 1, "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "head_sha": head, "display_title": title, - "repository": {"full_name": repo}, "event": "pull_request", "pull_requests": [], - "status": "completed", "conclusion": "cancelled"} -def check(job): - return {"id": int(job["check_run_url"].rsplit("/", 1)[1]), "app": {"slug": "github-actions", "id": 15368}, - "name": job["name"], "head_sha": head, "details_url": job["html_url"], - "status": job["status"], "conclusion": job["conclusion"], - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T02:00:00Z"} -if endpoint.endswith("/actions/workflows/ci.yml"): - output = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/commits/" + head + "/check-runs"): - with open(os.environ["GH_RETRY_COUNT_FILE"], "w") as stream: - stream.write("1") - checks = [check(gate)] - if scenario in ("cancellation-pending", "cancellation-recovery", "cancellation-older-success"): - replacement = check(gate) - replacement.update(id=420, details_url=f"https://github.com/{repo}/actions/runs/101/job/221", - status="queued", conclusion=None, started_at=None, completed_at=None) - if os.environ.get("GH_CANCELLATION_RECOVERED") == "true" or scenario == "cancellation-older-success": - replacement.update(status="completed", conclusion="success", started_at="2026-07-30T03:00:00Z", - completed_at="2026-07-30T04:00:00Z" if scenario != "cancellation-older-success" else "2026-07-30T00:30:00Z") - checks.append(replacement) - output = [{"total_count": len(checks), "check_runs": checks}] -elif endpoint.endswith("/actions/jobs/220"): - output = gate -elif endpoint.endswith("/actions/jobs/221"): - output = copy.deepcopy(gate) - output.update(id=221, run_id=101, check_run_url=f"https://api.github.com/repos/{repo}/check-runs/420") - output["steps"][4]["conclusion"] = "skipped" -elif "/actions/jobs/" in endpoint: - job_id = int(endpoint.rsplit("/", 1)[1]) - output = copy.deepcopy(next(job for job in jobs if job["id"] == job_id)) -elif "/attempts/1/jobs" in endpoint: - snapshot = copy.deepcopy(jobs) - if scenario == "cancellation-partial": - snapshot.pop(0) - if scenario == "cancellation-wrong-attempt": - snapshot[0]["run_attempt"] = 2 - if scenario == "cancellation-wrong-head": - snapshot[0]["head_sha"] = "c" * 40 - if scenario == "cancellation-duplicate": - snapshot[0] = snapshot[1] - if scenario == "cancellation-missing-steps": - del snapshot[0]["steps"] - if scenario == "cancellation-dev-tool-wrong-name": - snapshot[-2]["name"] = "Unknown Contract Checks" - if scenario == "cancellation-dev-tool-duplicate-name": - snapshot[-2]["name"] = "Dev Tool Contract Checks" - if scenario == "cancellation-dev-tool-missing-sibling": - snapshot = [job for job in snapshot if job["name"] != "Dev Tool Validation Contracts"] - if scenario == "cancellation-dev-tool-missing-original": - snapshot = [job for job in snapshot if job["name"] != "Dev Tool Contract Checks"] - if scenario == "cancellation-dev-tool-missing-other": - snapshot = [job for job in snapshot if job["name"] != "ShellCheck"] - if scenario == "cancellation-dev-tool-extra-name": - extra = copy.deepcopy(snapshot[-2]) - extra.update(id=900, name="Unknown Contract Checks") - snapshot.append(extra) - output = [{"total_count": len(snapshot), "jobs": snapshot}] -elif "/check-runs/" in endpoint: - output = check(next(job for job in jobs if job["check_run_url"].endswith("/" + endpoint.rsplit("/", 1)[1]))) - if scenario == "cancellation-wrong-app": - output["app"]["id"] = 1 - if scenario == "cancellation-check-conflict": - output["conclusion"] = "success" -elif "/actions/runs/" in endpoint: - output = copy.deepcopy(run) - if endpoint.endswith("/101"): - output.update(id=101, conclusion=None, status="queued") - if scenario == "cancellation-run-conflict" and "/attempts/" in endpoint: - output["display_title"] = "unbound" - if scenario in ("cancellation-later-attempt", "cancellation-later-attempt-failed-source"): - # Latest run is attempt 2; candidate gate belongs to retained attempt 1. - if "/attempts/" not in endpoint: - output.update(run_attempt=2, conclusion="success") - elif scenario == "cancellation-later-attempt-failed-source": - output["conclusion"] = "failure" -else: - raise AssertionError(endpoint) -print(json.dumps(output)) -CANCELLATION_FIXTURE - exit 0 -fi -if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - mkdir -p "$GH_CALL_COUNT_DIR" -fi -if [[ "$*" == *"/actions/workflows/${EXPECTED_WORKFLOW_FILE}/runs"* ]]; then - if [[ "$*" == *"head_sha="* || "$*" != *"event=pull_request"* || - "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated active workflow lookup used a branch-tip filter or omitted event/pagination" >&2 - exit 90 - fi - active_status="" - for argument in "$@"; do - case "$argument" in - status=*) active_status="${argument#status=}" ;; - esac - done - case "$active_status" in - in_progress|queued|requested|waiting|pending) ;; - *) - echo "simulated active workflow lookup omitted a single supported status filter" >&2 - exit 90 - ;; - esac - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - active_call_file="$GH_CALL_COUNT_DIR/active-$active_status" - active_call_count=0 - [[ -f "$active_call_file" ]] && active_call_count="$(<"$active_call_file")" - printf '%s' "$((active_call_count + 1))" >"$active_call_file" - fi - case "${GH_SCENARIO:-}" in - active-workflow-delayed-gate|active-workflow-late-arrival|active-workflow-wrong-base|active-workflow-metadata-only|active-workflow-mismatched-tuple) - if [[ "${GH_SCENARIO}" == "active-workflow-late-arrival" && - "$(<"$count_file")" -ne 92 ]]; then - printf '[{"workflow_runs":[]} ]\n' - exit 0 - fi - if [[ "$active_status" != "in_progress" ]]; then - printf '[{"workflow_runs":[]} ]\n' - exit 0 - fi - display_title="CI — Validation pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - [[ "${GH_SCENARIO}" == "active-workflow-wrong-base" ]] && display_title="CI — Validation pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - run_head_sha="${HEAD_SHA}" - pull_requests='[]' - if [[ "${GH_SCENARIO}" == "active-workflow-delayed-gate" || - "${GH_SCENARIO}" == "active-workflow-late-arrival" ]]; then - # GitHub may report the synthetic merge SHA for pull_request runs; - # the populated PR tuple remains the authoritative identity. - run_head_sha=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO}" == "active-workflow-mismatched-tuple" ]]; then - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"dddddddddddddddddddddddddddddddddddddddd\"}}]" - fi - printf '[{"workflow_runs":[{"id":100,"workflow_id":42,"name":"%s","path":".github/workflows/ci.yml","head_sha":"%s","display_title":"%s","repository":{"full_name":"example/firemud"},"event":"pull_request","status":"in_progress","pull_requests":%s}]}]\n' "$display_title" "$run_head_sha" "$display_title" "$pull_requests" - ;; - active-workflow-malformed-list) - printf '[{"workflow_runs":"invalid"}]\n' - ;; - *) - printf '[{"workflow_runs":[]}]\n' - ;; - esac - exit 0 -fi -if [[ "$*" == *"/actions/workflows/"* ]]; then - if [[ "$*" != *"/actions/workflows/${EXPECTED_WORKFLOW_FILE}"* ]]; then - echo "simulated workflow lookup did not target the expected workflow filename" >&2 - exit 90 - fi - if [[ "${GH_SCENARIO:-}" == "no-local-workflow-file" ]]; then - : >"$count_file" - fi - if [[ "${GH_SCENARIO:-}" == "workflow-identity-mismatch" ]]; then - cat <<'JSON' -{"id":99,"name":"Security Checks","path":".github/workflows/security.yml"} -JSON - else - cat <<'JSON' -{"id":42,"name":"CI — Validation","path":".github/workflows/ci.yml"} -JSON - fi - exit 0 -fi -if [[ "$*" == *"/actions/runs/100/jobs"* ]]; then - if [[ "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated workflow jobs lookup omitted pagination" >&2 - exit 90 - fi - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - active_jobs_file="$GH_CALL_COUNT_DIR/run-jobs-100" - active_jobs_count=0 - [[ -f "$active_jobs_file" ]] && active_jobs_count="$(<"$active_jobs_file")" - printf '%s' "$((active_jobs_count + 1))" >"$active_jobs_file" - fi - change_conclusion=success - [[ "${GH_SCENARIO:-}" == "active-workflow-metadata-only" ]] && change_conclusion=skipped - printf '[{"jobs":[{"id":20,"name":"Detect CI-Relevant Changes","status":"completed","conclusion":"%s"}]}]\n' "$change_conclusion" - exit 0 -fi -if [[ "$*" == *"/actions/jobs/"* ]]; then - job_endpoint="${!#}" - job_id="${job_endpoint##*/}" - run_id="$job_id" - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - job_call_file="$GH_CALL_COUNT_DIR/jobs-$job_id" - job_call_count=0 - [[ -f "$job_call_file" ]] && job_call_count="$(<"$job_call_file")" - printf '%s' "$((job_call_count + 1))" >"$job_call_file" - fi - if [[ "${GH_SCENARIO:-}" == "job-failure-retry" && "$job_id" == "100" && - ! -e "${count_file}.job-failure-once" ]]; then - : >"${count_file}.job-failure-once" - echo "gh: HTTP 503 Service Unavailable" >&2 - exit 1 - fi - job_workflow_name='CI — Validation' - if [[ "${GH_SCENARIO:-}" == "dynamic-run-name" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - job_workflow_name="${job_workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "wrong-job-workflow-name" ]]; then - job_workflow_name='Security Checks' - fi - metadata=false - if [[ "${GH_SCENARIO:-}" == "multiple-metadata" ]] || - [[ "${GH_SCENARIO:-}" == "latest-pending-preferred" && "${job_id}" == "101" ]] || - [[ "${GH_SCENARIO:-}" == "cache-metadata-across-polls" && "${job_id}" == "100" ]]; then - metadata=true - fi - if [[ "${metadata}" == "true" ]]; then - case "${GH_SCENARIO}:${job_id}" in - multiple-metadata:100) preserve_conclusion=success ;; - multiple-metadata:101) preserve_conclusion=failure ;; - multiple-metadata:102) preserve_conclusion=timed_out ;; - multiple-metadata:103) preserve_conclusion=cancelled ;; - *) preserve_conclusion=success ;; - esac - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"%s","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"%s"}]}\n' "$job_id" "$run_id" "$job_workflow_name" "$job_id" "$preserve_conclusion" - elif [[ "${GH_SCENARIO:-}" == "unverified-pending-gate" && "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-preservation-step-not-concluded" && - "${job_id}" == "100" && "$(<"$count_file")" -le 3 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-gate-discovery-throttle" && - "${job_id}" == "100" && "$(<"$count_file")" -le 5 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "pending-missing-step-with-failed-substantive" && - "${job_id}" == "101" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"in_progress","completed_at":null,"conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "completed-preservation-step-lag" && - "${job_id}" == "100" && "$(<"$count_file")" -eq 1 ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" == "completed-preservation-step-persistent-lag" && - "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - elif [[ "${GH_SCENARIO:-}" =~ ^completed-(cancelled|skipped|stale)-missing-step$ && - "${job_id}" == "100" ]]; then - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"CI — Validation","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":null}]}\n' "$job_id" "$run_id" "$job_id" - else - printf '{"id":%s,"run_id":%s,"run_attempt":1,"name":"Validation Gate","workflow_name":"%s","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","check_run_url":"https://api.github.com/repos/example/firemud/check-runs/%s","steps":[{"name":"Preserve successful required gate on metadata-only edit","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"skipped"}]}\n' "$job_id" "$run_id" "$job_workflow_name" "$job_id" - fi - exit 0 -fi -if [[ "$*" == *"/actions/runs/"* ]]; then - run_endpoint="${!#}" - run_id="${run_endpoint##*/}" - if [[ -n "${GH_CALL_COUNT_DIR:-}" ]]; then - run_call_file="$GH_CALL_COUNT_DIR/runs-$run_id" - run_call_count=0 - [[ -f "$run_call_file" ]] && run_call_count="$(<"$run_call_file")" - printf '%s' "$((run_call_count + 1))" >"$run_call_file" - fi - workflow_name='CI — Validation' - workflow_path='.github/workflows/ci.yml' - workflow_id=42 - run_repository='example/firemud' - head_repository='example/firemud' - pull_requests='[{"number":123}]' - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-${HEAD_SHA}" - if [[ "${GH_SCENARIO:-}" == "dynamic-run-name" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - workflow_name="$display_title" - display_title="$workflow_name" - elif [[ "${GH_SCENARIO:-}" == "wrong-run-name" ]]; then - workflow_name='Security Checks' - fi - if [[ "${GH_SCENARIO:-}" == "valid-new-tuple" ]]; then - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO:-}" == "stale-then-current-tuple" ]]; then - if [[ "${run_id}" == "200" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"cccccccccccccccccccccccccccccccccccccccc\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - else - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - fi - fi - if [[ "${GH_SCENARIO:-}" == "fork-empty-association" || - "${GH_SCENARIO:-}" == "dynamic-run-name-fork-empty" ]]; then - pull_requests='[]' - head_repository='other-owner/firemud' - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-pr" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-456 base-${BASE_SHA} head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-base" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - elif [[ "${GH_SCENARIO:-}" == "populated-wrong-base" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-cccccccccccccccccccccccccccccccccccccccc head-${HEAD_SHA}" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"cccccccccccccccccccccccccccccccccccccccc\"},\"head\":{\"sha\":\"${HEAD_SHA}\"}}]" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-head" ]]; then - pull_requests='[]' - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-dddddddddddddddddddddddddddddddddddddddd" - elif [[ "${GH_SCENARIO:-}" == "populated-wrong-head" ]]; then - display_title="${workflow_name} pr-${PR_NUMBER} base-${BASE_SHA} head-dddddddddddddddddddddddddddddddddddddddd" - pull_requests="[{\"number\":${PR_NUMBER},\"base\":{\"sha\":\"${BASE_SHA}\"},\"head\":{\"sha\":\"dddddddddddddddddddddddddddddddddddddddd\"}}]" - elif [[ "${GH_SCENARIO:-}" == "empty-wrong-title" ]]; then - pull_requests='[]' - display_title='not the canonical run title' - elif [[ "${GH_SCENARIO:-}" == "empty-malformed-association" ]]; then - pull_requests='null' - elif [[ "${GH_SCENARIO:-}" == "other-pr-association" ]]; then - pull_requests='[{"number":456}]' - elif [[ "${GH_SCENARIO:-}" == "cross-workflow-same-name" || - "${GH_SCENARIO:-}" == "duplicate-invalid-run-identity" ]]; then - workflow_path='.github/workflows/other.yml' - workflow_id=99 - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix" ]]; then - workflow_path='.github/workflows/ci.yml@main' - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix-plus" ]]; then - workflow_path='.github/workflows/ci.yml@feature+metadata' - elif [[ "${GH_SCENARIO:-}" == "run-path-ref-suffix-at" ]]; then - workflow_path='.github/workflows/ci.yml@feature@metadata' - elif [[ "${GH_SCENARIO:-}" == "malformed-run-path-ref-suffix" ]]; then - workflow_path='.github/workflows/ci.yml@' - elif [[ "${GH_SCENARIO:-}" == "fork-head-same-sha" ]]; then - head_repository='other-owner/firemud' - elif [[ "${GH_SCENARIO:-}" == "wrong-run-repository" ]]; then - run_repository='other-owner/firemud' - head_repository='other-owner/firemud' - fi - printf '{"id":%s,"workflow_id":%s,"name":"%s","path":"%s","head_sha":"%s","display_title":"%s","repository":{"full_name":"%s"},"head_repository":{"full_name":"%s"},"event":"pull_request","pull_requests":%s}\n' "$run_id" "$workflow_id" "$workflow_name" "$workflow_path" "$HEAD_SHA" "$display_title" "$run_repository" "$head_repository" "$pull_requests" - exit 0 -fi -if [[ "$*" != *"/repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}/check-runs"* ]]; then - echo "simulated gh api call did not target the pull request head check-runs endpoint" >&2 - exit 90 -fi -if [[ "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then - echo "simulated gh api call omitted pagination/slurp" >&2 - exit 90 -fi -if [[ "$*" != *"check_name=${REQUIRED_GATE_NAME}"* || "$*" != *"filter=all"* ]]; then - echo "simulated gh api call did not scope the query to the required gate name" >&2 - exit 90 -fi -if [[ "$*" == *"--jq"* ]]; then - echo "simulated gh api call must leave filtering to external jq" >&2 - exit 90 -fi -count=0 -if [[ -f "$count_file" ]]; then - count="$(<"$count_file")" -fi -count=$((count + 1)) -printf '%s' "$count" >"$count_file" -if [[ "${GH_SCENARIO:-}" == check-coverage-* ]]; then - python3 - "$GH_SCENARIO" <<'PYTHON' -import json -import sys -scenario = sys.argv[1] -def check(identity): - return {"app": {"slug": "github-actions"}, "name": "Validation Gate", "id": identity, - "details_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "status": "completed", "conclusion": "success", "completed_at": "2026-07-30T02:00:00Z", - "started_at": "2026-07-30T01:00:00Z"} -pages = [{"total_count": 1, "check_runs": [check(100)]}] -if scenario == "check-coverage-truncated": - # Omit the newer failed original from the existing newer-failure case. - pages[0]["total_count"] = 2 -elif scenario == "check-coverage-missing-total": - pages[0].pop("total_count") -elif scenario == "check-coverage-malformed-total": - pages[0]["total_count"] = "1" -elif scenario == "check-coverage-overcount": - pages[0]["total_count"] = 0 -elif scenario == "check-coverage-invalid-id": - pages[0]["check_runs"][0]["id"] = "100" -elif scenario == "check-coverage-empty-pages": - pages = [] -elif scenario == "check-coverage-duplicate": - pages = [{"total_count": 2, "check_runs": [check(100)]}, {"total_count": 2, "check_runs": [check(100)]}] -elif scenario in {"check-coverage-multi", "check-coverage-inconsistent-total"}: - pages = [{"total_count": 2, "check_runs": [check(100)]}, - {"total_count": 3 if scenario.endswith("inconsistent-total") else 2, "check_runs": [check(101)]}] -else: - raise AssertionError(scenario) -print(json.dumps(pages)) -PYTHON - exit 0 -fi -case "${GH_SCENARIO:-failure-retry}" in - latest-pending-preferred) - if [[ "$count" -eq 1 ]]; then - cat <<'JSON' -[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - else - cat <<'JSON' -[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - fi - ;; - missing-created-at) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - pending-predecessor) - if [[ "$count" -eq 1 ]]; then - cat <<'JSON' -[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - else - cat <<'JSON' -[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}] -JSON - fi - ;; - queued-null-started-at) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"queued","conclusion":null,"started_at":null,"created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - retry-success) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","completed_at":"2026-07-30T03:00:00Z","conclusion":"success","started_at":"2026-07-30T02:00:00Z"}]}]\n' - ;; - no-local-workflow-file) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - no-prior|active-workflow-wrong-base|active-workflow-metadata-only|active-workflow-mismatched-tuple|active-workflow-malformed-list) - printf '[{"total_count":0,"check_runs":[]}]\n' - ;; - delayed-predecessor) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - elif [[ "$count" -eq 2 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - delayed-predecessor-after-19-minutes) - if [[ "$count" -le 77 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:20:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - active-workflow-delayed-gate) - if [[ "$count" -le 97 ]]; then - printf '[{"total_count":0,"check_runs":[]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:30:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - active-workflow-late-arrival) - if [[ "$count" -le 92 ]]; then - printf '[{"total_count":0,"check_runs":[]} ]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:30:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - failed-predecessor) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"failure","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - newer-failure-over-success) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:50:00Z","created_at":"2026-07-30T00:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:50:00Z","created_at":"2026-07-30T01:50:00Z"}]}]\n' - ;; - same-timestamp-newer-failure) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - stale-then-current-tuple) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":201,"details_url":"https://github.com/example/firemud/actions/runs/201/job/201","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - cross-workflow-same-name|fork-empty-association|dynamic-run-name|dynamic-run-name-fork-empty|wrong-run-name|wrong-job-workflow-name|empty-wrong-pr|empty-wrong-base|populated-wrong-base|empty-wrong-head|populated-wrong-head|empty-wrong-title|empty-malformed-association|other-pr-association|valid-new-tuple) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - duplicate-invalid-run-identity) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":201,"details_url":"https://github.com/example/firemud/actions/runs/200/job/201","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - run-path-ref-suffix|run-path-ref-suffix-plus|run-path-ref-suffix-at|malformed-run-path-ref-suffix) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - details-url-query|details-url-fragment|malformed-details-url-suffix) - details_suffix='?check_suite_focus=true' - [[ "${GH_SCENARIO:-}" == "details-url-fragment" ]] && details_suffix='#step:1:2' - [[ "${GH_SCENARIO:-}" == "malformed-details-url-suffix" ]] && details_suffix='@evil' - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200%s","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$details_suffix" - ;; - fork-head-same-sha) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - wrong-run-repository) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - unknown-app) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"other-checks"},"name":"Validation Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - unknown-check-name) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Other Gate","id":200,"details_url":"https://github.com/example/firemud/actions/runs/200/job/200","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - invalid-job-id) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/not-a-number","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - missing-job-id) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-preservation-step-lag) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-preservation-step-persistent-lag) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - completed-cancelled-missing-step|completed-skipped-missing-step|completed-stale-missing-step) - case "${GH_SCENARIO}" in - completed-cancelled-missing-step) non_authoritative_conclusion=cancelled ;; - completed-skipped-missing-step) non_authoritative_conclusion=skipped ;; - completed-stale-missing-step) non_authoritative_conclusion=stale ;; - esac - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"%s","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' "$non_authoritative_conclusion" - ;; - unsupported-status) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"mysterious","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - missing-timestamp) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":99,"details_url":"https://github.com/example/firemud/actions/runs/99/job/99","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:00:00Z","created_at":"2026-07-30T00:00:00Z"}]}]\n' - ;; - multiple-metadata) - printf '[{"total_count":4,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T01:00:00Z","started_at":"2026-07-30T00:50:00Z","created_at":"2026-07-30T00:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"failure","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:50:00Z","created_at":"2026-07-30T01:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":102,"details_url":"https://github.com/example/firemud/actions/runs/102/job/102","status":"completed","conclusion":"timed_out","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T02:50:00Z","created_at":"2026-07-30T02:50:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":103,"details_url":"https://github.com/example/firemud/actions/runs/103/job/103","status":"completed","conclusion":"cancelled","completed_at":"2026-07-30T04:00:00Z","started_at":"2026-07-30T03:50:00Z","created_at":"2026-07-30T03:50:00Z"}]}]\n' - ;; - self-run-excluded) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":1,"details_url":"https://github.com/example/firemud/actions/runs/999/job/1","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"failure","started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"}]}]\n' - ;; - alternate-pending) - case "$count" in - 1) status=requested ;; - 2) status=waiting ;; - 3) status=pending ;; - *) status=completed ;; - esac - if [[ "$status" == "completed" ]]; then - conclusion='"success"' - else - conclusion=null - fi - completed_at=null - if [[ "$status" == "completed" ]]; then - completed_at='"2026-07-30T02:00:00Z"' - fi - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"%s","conclusion":%s,"completed_at":%s,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$status" "$conclusion" "$completed_at" - ;; - pending-preservation-step-not-concluded) - case "$count" in - 1) status=queued ;; - 2) status=in_progress ;; - 3) status=waiting ;; - *) status=completed ;; - esac - if [[ "$status" == "completed" ]]; then - conclusion='"success"' - completed_at='"2026-07-30T02:00:00Z"' - else - conclusion=null - completed_at=null - fi - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"%s","conclusion":%s,"completed_at":%s,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' "$status" "$conclusion" "$completed_at" - ;; - pending-gate-discovery-throttle) - if [[ "$count" -le 5 ]]; then - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - fi - ;; - cache-metadata-across-polls) - if [[ "$count" -eq 1 ]]; then - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - else - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"success","completed_at":"2026-07-30T02:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"completed","conclusion":"success","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"}]}]\n' - fi - ;; - pending-missing-step-with-failed-substantive) - printf '[{"total_count":2,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":101,"details_url":"https://github.com/example/firemud/actions/runs/101/job/101","status":"in_progress","conclusion":null,"completed_at":null,"started_at":"2026-07-30T02:00:00Z","created_at":"2026-07-30T02:00:00Z"},{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","conclusion":"failure","completed_at":"2026-07-30T03:00:00Z","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - timeout-pending|unverified-pending-gate) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"waiting","conclusion":null,"started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - failure-retry) - case "${GH_FAILURE_MODE:-transient}" in - transient|network) - if [[ "$count" -eq 1 ]]; then - if [[ "${GH_FAILURE_MODE}" == "network" ]]; then - echo "gh: error connecting to api.github.com" >&2 - else - echo "gh: HTTP 503 Service Unavailable" >&2 - fi - exit 1 - fi - ;; - rate-limit) - if [[ "$count" -eq 1 ]]; then - echo "gh: HTTP 403 API rate limit exceeded" >&2 - exit 1 - fi - ;; - permanent) - echo "gh: HTTP 422 Unprocessable Entity" >&2 - exit 1 - ;; - permission) - echo "gh: HTTP 403 Resource not accessible by integration; SSO authorization required" >&2 - exit 1 - ;; - *) - echo "unknown simulated gh failure mode" >&2 - exit 91 - ;; - esac - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - job-failure-retry) - printf '[{"total_count":1,"check_runs":[{"app":{"slug":"github-actions"},"name":"Validation Gate","id":100,"details_url":"https://github.com/example/firemud/actions/runs/100/job/100","status":"completed","completed_at":"2026-07-30T02:00:00Z","conclusion":"success","started_at":"2026-07-30T01:00:00Z","created_at":"2026-07-30T01:00:00Z"}]}]\n' - ;; - *) - echo "unknown simulated gh scenario" >&2 - exit 91 - ;; -esac -EOF -cat >"$tmp_dir/sleep" <<'EOF' -#!/usr/bin/env bash -echo "one-pass assessment must never sleep" >&2 -exit 97 -EOF -chmod +x "$tmp_dir/gh" "$tmp_dir/sleep" - -action_script="$(<"$ASSESS_SCRIPT")" -# shellcheck disable=SC2016 # Reject literal GitHub expressions in shell. -if grep -Fq '${{' <<<"$action_script"; then - echo "assessment must receive workflow context through env" >&2; exit 1 -fi -if grep -Eq 'PRESERVATION_MODE|poll_deadline|sleep_until_poll_deadline|find_active_substantive_workflow' <<<"$action_script"; then - echo "assessment must not retain a polling mode or discovery loop" >&2; exit 1 -fi -run_action() { - local count_file="$1" - local failure_mode="$2" - local scenario="${3:-failure-retry}" - local call_count_dir="${4:-}" - # Fixture outputs must never inherit the enclosing Actions step output file. - local assessment_output="${5:-$count_file-output}" - GITHUB_OUTPUT="$assessment_output" \ - GH_RETRY_COUNT_FILE="$count_file" \ - GH_FAILURE_MODE="$failure_mode" \ - GH_SCENARIO="$scenario" \ - GH_CALL_COUNT_DIR="$call_count_dir" \ - PATH="$tmp_dir:$PATH" \ - GITHUB_EVENT_NAME=pull_request \ - GITHUB_REPOSITORY=example/firemud \ - GITHUB_RUN_ID=999 \ - GH_TOKEN=test-token \ - BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb \ - HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - PR_NUMBER=123 \ - REQUIRED_GATE_NAME='Validation Gate' \ - EXPECTED_WORKFLOW_NAME='CI — Validation' \ - EXPECTED_WORKFLOW_FILE=ci.yml \ - EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml \ - bash "$ASSESS_SCRIPT" -} - -# Incomplete or inconsistent successful API responses cannot manufacture proof. -coverage_mode=assess -for coverage_case in truncated missing-total malformed-total overcount invalid-id empty-pages duplicate inconsistent-total; do - coverage_scenario="check-coverage-$coverage_case" - coverage_count="$tmp_dir/$coverage_mode-$coverage_scenario-count" - coverage_output="$tmp_dir/$coverage_mode-$coverage_scenario-output" - coverage_log="$tmp_dir/$coverage_mode-$coverage_scenario-log" - if run_action "$coverage_count" none "$coverage_scenario" "" "$coverage_output" >"$coverage_log" 2>&1; then - echo "required-gate $coverage_mode accepted invalid check coverage: $coverage_case" >&2 - exit 1 - fi - [[ "$(<"$coverage_count")" == 1 && ! -s "$coverage_output" ]] || { - echo "invalid check coverage was retried or emitted an assessment: $coverage_case" >&2 - exit 1 - } - grep -Fq 'malformed or incomplete check-run data' "$coverage_log" || { - echo "invalid check coverage did not fail at the coverage boundary: $coverage_case" >&2 - exit 1 - } -done -coverage_output="$tmp_dir/$coverage_mode-complete-multi-output" -run_action "$tmp_dir/$coverage_mode-complete-multi-count" none check-coverage-multi "" "$coverage_output" -[[ "$(<"$coverage_output")" == assessment=success ]] || { - echo "complete multi-page check coverage lost successful proof" >&2 - exit 1 -} - -attempt_fallback_output="$tmp_dir/attempt-fallback-success-output" -if ! run_action "$tmp_dir/attempt-fallback-success-count" none attempt-fallback-success "" "$attempt_fallback_output" >"$tmp_dir/attempt-fallback-success-log" 2>&1; then - cat "$tmp_dir/attempt-fallback-success-log" >&2 - echo "complete exact-attempt job snapshot did not recover the ordinary skipped preservation step" >&2 - exit 1 -fi -[[ "$(<"$attempt_fallback_output")" == assessment=success ]] || { - echo "complete exact-attempt job snapshot did not recover the ordinary skipped preservation step" >&2 - exit 1 -} -attempt_two_output="$tmp_dir/attempt-fallback-attempt-two-output" -attempt_two_calls="$tmp_dir/attempt-fallback-attempt-two-calls" -REQUIRED_GATE_INCLUDE_SOURCE=true run_action "$tmp_dir/attempt-fallback-attempt-two-count" none \ - attempt-fallback-attempt-two "$attempt_two_calls" "$attempt_two_output" -[[ "$(<"$attempt_two_output")" == $'source_run_id=100\nsource_job_id=100\nsource_check_run_id=100\nsource_run_attempt=2\nassessment=success' ]] || { - echo "successful exact-attempt recovery did not preserve attempt-2 source provenance" >&2 - exit 1 -} -python3 - "$attempt_two_calls/attempt-endpoints" <<'PY_ATTEMPT_TWO' -from pathlib import Path -import sys -endpoints = Path(sys.argv[1]).read_text().splitlines() -assert any(path.endswith("/actions/runs/100/attempts/2") for path in endpoints), endpoints -assert not any("/attempts/1" in path for path in endpoints), endpoints -PY_ATTEMPT_TWO -for scenario in attempt-fallback-attempt-two-mismatch attempt-fallback-attempt-two-api-error; do - output_file="$tmp_dir/$scenario-output" - call_dir="$tmp_dir/$scenario-calls" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "$call_dir" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "unbound exact-attempt source was accepted: $scenario" >&2; exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid exact-attempt source emitted proof: $scenario" >&2; exit 1; } - if [[ "$scenario" == *api-error ]]; then - grep -Fq 'GitHub API error while reading exact-attempt workflow run.' "$tmp_dir/$scenario-log" || { - echo "exact-attempt API failure lost its distinct diagnostic" >&2; exit 1; - } - else - grep -Fq 'Malformed or unbound exact-attempt evidence:' "$tmp_dir/$scenario-log" || { - echo "mismatched attempt identity lost its evidence diagnostic" >&2; exit 1; - } - fi - ! grep -Fq 'test-token' "$tmp_dir/$scenario-log" || { - echo "exact-attempt diagnostic exposed credentials" >&2; exit 1; - } - python3 - "$call_dir/attempt-endpoints" <<'PY_ATTEMPT_FAILURE' -from pathlib import Path -import sys -endpoints = Path(sys.argv[1]).read_text().splitlines() -assert len(endpoints) == 1 and endpoints[0].endswith("/actions/runs/100/attempts/2"), endpoints -PY_ATTEMPT_FAILURE -done -attempt_recovery_limit_calls="$tmp_dir/attempt-fallback-recovery-limit-calls" -if run_action "$tmp_dir/attempt-fallback-recovery-limit-count" none attempt-fallback-recovery-limit \ - "$attempt_recovery_limit_calls" "$tmp_dir/attempt-fallback-recovery-limit-output" \ - >"$tmp_dir/attempt-fallback-recovery-limit-log" 2>&1; then - echo "historical sparse-candidate recovery exceeded its fixed budget" >&2; exit 1 -fi -[[ ! -s "$tmp_dir/attempt-fallback-recovery-limit-output" ]] || { - echo "recovery-budget exhaustion emitted proof" >&2; exit 1; -} -grep -Fq 'exhausted its 3-snapshot budget' "$tmp_dir/attempt-fallback-recovery-limit-log" || { - echo "historical sparse-candidate exhaustion lost its explicit fail-closed diagnostic" >&2; exit 1; -} -python3 - "$attempt_recovery_limit_calls" <<'PY_RECOVERY_LIMIT' -from pathlib import Path -import sys -calls = list(Path(sys.argv[1]).glob("attempt-jobs-*")) -assert len(calls) == 3, calls -assert all(path.read_text() == "1" for path in calls), calls -candidate_jobs = Path(sys.argv[1], "candidate-direct-jobs").read_text().splitlines() -assert [path.rsplit("/", 1)[1] for path in candidate_jobs] == ["100", "101", "102", "103"], candidate_jobs -PY_RECOVERY_LIMIT -attempt_fallback_known_output="$tmp_dir/attempt-fallback-known-skipped-output" -run_action "$tmp_dir/attempt-fallback-known-skipped-count" none attempt-fallback-known-skipped "" "$attempt_fallback_known_output" -[[ "$(<"$attempt_fallback_known_output")" == assessment=success ]] || { - echo "known skipped preservation with sparse unrelated step metadata lost the ordinary assessment path" >&2 - exit 1 -} -attempt_fallback_metadata_output="$tmp_dir/attempt-fallback-metadata-output" -run_action "$tmp_dir/attempt-fallback-metadata-count" none attempt-fallback-metadata "" "$attempt_fallback_metadata_output" -[[ "$(<"$attempt_fallback_metadata_output")" == assessment=dependency-deferred ]] || { - echo "complete exact-attempt metadata preservation was treated as substantive proof" >&2 - exit 1 -} -attempt_fallback_failure_output="$tmp_dir/attempt-fallback-newer-failure-output" -if run_action "$tmp_dir/attempt-fallback-newer-failure-count" none attempt-fallback-newer-failure "" "$attempt_fallback_failure_output" >"$tmp_dir/attempt-fallback-newer-failure-log" 2>&1; then - echo "complete exact-attempt fallback allowed newer substantive failure over older success" >&2 - exit 1 -fi -[[ ! -s "$attempt_fallback_failure_output" ]] || { - echo "newer exact-attempt failure emitted successful proof" >&2 - exit 1 -} -for scenario in attempt-fallback-empty attempt-fallback-no-steps attempt-fallback-duplicate attempt-fallback-malformed attempt-fallback-oversized attempt-fallback-incomplete attempt-fallback-stale-tuple attempt-fallback-wrong-attempt attempt-fallback-wrong-head attempt-fallback-wrong-workflow attempt-fallback-wrong-app attempt-fallback-wrong-check-url attempt-fallback-wrong-check-details attempt-fallback-duplicate-direct attempt-fallback-malformed-direct; do - output_file="$tmp_dir/$scenario-output" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "exact-attempt fallback accepted missing or unbound gate evidence: $scenario" >&2 - exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid exact-attempt fallback emitted proof: $scenario" >&2; exit 1; } -done - -# API uncertainty is an error, never dependency deferral or a retry. -for failure_mode in transient network rate-limit permanent permission; do - count_file="$tmp_dir/failure-$failure_mode" - output_file="$tmp_dir/failure-output-$failure_mode" - if run_action "$count_file" "$failure_mode" failure-retry >"$output_file" 2>&1; then - echo "assessment accepted an API failure: $failure_mode" >&2; exit 1 - fi - [[ "$(<"$count_file")" == 1 && ! -s "$count_file-output" ]] || { - echo "API failure was retried or deferred: $failure_mode" >&2; exit 1; - } -done - -for scenario in no-local-workflow-file latest-pending-preferred missing-created-at self-run-excluded fork-head-same-sha fork-empty-association dynamic-run-name dynamic-run-name-fork-empty run-path-ref-suffix run-path-ref-suffix-plus run-path-ref-suffix-at details-url-query details-url-fragment valid-new-tuple stale-then-current-tuple completed-cancelled-missing-step completed-skipped-missing-step completed-stale-missing-step; do - count_file="$tmp_dir/success-$scenario" - run_action "$count_file" none "$scenario" - [[ "$(<"$count_file")" == 1 && "$(<"$count_file-output")" == assessment=success ]] || { - echo "one assessment lost valid original proof: $scenario" >&2; exit 1; - } -done - -for scenario in no-prior pending-predecessor queued-null-started-at multiple-metadata delayed-predecessor delayed-predecessor-after-19-minutes active-workflow-delayed-gate active-workflow-late-arrival active-workflow-wrong-base active-workflow-metadata-only active-workflow-mismatched-tuple alternate-pending pending-preservation-step-not-concluded pending-gate-discovery-throttle timeout-pending unverified-pending-gate populated-wrong-base populated-wrong-head cache-metadata-across-polls; do - count_file="$tmp_dir/deferred-$scenario" - run_action "$count_file" none "$scenario" - [[ "$(<"$count_file")" == 1 && "$(<"$count_file-output")" == assessment=dependency-deferred ]] || { - echo "one assessment did not defer unresolved original proof: $scenario" >&2; exit 1; - } -done - -for scenario in job-failure-retry completed-preservation-step-lag completed-preservation-step-persistent-lag pending-missing-step-with-failed-substantive failed-predecessor newer-failure-over-success same-timestamp-newer-failure duplicate-invalid-run-identity cross-workflow-same-name malformed-run-path-ref-suffix malformed-details-url-suffix wrong-run-repository wrong-run-name wrong-job-workflow-name unknown-app unknown-check-name invalid-job-id missing-job-id unsupported-status missing-timestamp empty-wrong-pr empty-wrong-base empty-wrong-head empty-wrong-title empty-malformed-association other-pr-association; do - count_file="$tmp_dir/rejected-$scenario" - if run_action "$count_file" none "$scenario" >"$tmp_dir/rejected-log-$scenario" 2>&1; then - echo "assessment accepted invalid or unavailable evidence: $scenario" >&2; exit 1 - fi - [[ "$(<"$count_file")" == 1 && ! -s "$count_file-output" ]] || { - echo "invalid evidence was retried or deferred: $scenario" >&2; exit 1; - } -done -# Cancellation cannot become success: only the exact pre-execution shape is -# removed from authoritative failures, leaving existing missing/pending proof. -for scenario in cancellation-only cancellation-dev-tool-only cancellation-pending cancellation-metadata cancellation-later-attempt; do - output_file="$tmp_dir/$scenario-output" - run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" - [[ "$(<"$output_file")" == assessment=dependency-deferred ]] || { - echo "cancellation lost missing-proof behavior: $scenario" >&2; exit 1; - } -done -for scenario in cancellation-dev-tool-missing-sibling cancellation-dev-tool-duplicate-marker cancellation-dev-tool-wrong-name cancellation-dev-tool-duplicate-name cancellation-dev-tool-missing-original cancellation-dev-tool-missing-other cancellation-dev-tool-extra-name cancellation-dev-tool-real-failure cancellation-dev-tool-executed cancellation-dev-tool-skipped cancellation-pre-world-shape cancellation-world-missing-partition cancellation-world-aggregate-executed cancellation-world-aggregate-failed cancellation-old-shape cancellation-partial-new-shape cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do - output_file="$tmp_dir/$scenario-output" - if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then - echo "cancellation suppressed failed or incomplete proof: $scenario" >&2; exit 1 - fi - [[ ! -s "$output_file" ]] || { echo "invalid cancellation emitted proof: $scenario" >&2; exit 1; } -done -run_action "$tmp_dir/cancellation-older-count" none cancellation-older-success -[[ "$(<"$tmp_dir/cancellation-older-count-output")" == assessment=success ]] || { - echo "cancellation changed older valid original policy" >&2; exit 1; -} -run_action "$tmp_dir/cancellation-recovery-count" none cancellation-recovery -[[ "$(<"$tmp_dir/cancellation-recovery-count-output")" == assessment=dependency-deferred ]] || exit 1 -GH_CANCELLATION_RECOVERED=true run_action "$tmp_dir/cancellation-recovered-count" none cancellation-recovery -[[ "$(<"$tmp_dir/cancellation-recovered-count-output")" == assessment=success ]] || { - echo "replacement completion did not recover canonical assessment" >&2; exit 1; -} - -if run_action "$tmp_dir/initial-identity-count" none workflow-identity-mismatch >"$tmp_dir/initial-identity-log" 2>&1; then - echo "assessment accepted an initial workflow identity mismatch" >&2; exit 1 -fi -[[ ! -e "$tmp_dir/initial-identity-count" ]] || { - echo "assessment queried checks before verifying workflow identity" >&2; exit 1; -} -for guard in event head output; do - count_file="$tmp_dir/guard-count-$guard" - if ( - export GITHUB_EVENT_NAME=pull_request GITHUB_REPOSITORY=example/firemud GITHUB_RUN_ID=999 GH_TOKEN=test-token - export BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa PR_NUMBER=123 - export REQUIRED_GATE_NAME='Validation Gate' EXPECTED_WORKFLOW_NAME='CI — Validation' EXPECTED_WORKFLOW_FILE=ci.yml EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml - export GITHUB_OUTPUT="$tmp_dir/guard-output-$guard" GH_RETRY_COUNT_FILE="$count_file" GH_SCENARIO=no-local-workflow-file GH_FAILURE_MODE=none - case "$guard" in event) export GITHUB_EVENT_NAME=push ;; head) export HEAD_SHA=' ' ;; output) unset GITHUB_OUTPUT ;; esac - PATH="$tmp_dir:$PATH" bash "$ASSESS_SCRIPT" - ) >"$tmp_dir/guard-log-$guard" 2>&1; then - echo "assessment accepted invalid $guard context" >&2; exit 1 - fi - [[ ! -s "$tmp_dir/guard-output-$guard" ]] || { echo "invalid context emitted an assessment" >&2; exit 1; } - if [[ "$guard" != output && -e "$count_file" ]]; then - echo "assessment queried checks before rejecting $guard context" >&2; exit 1 - fi -done - -RESOLVER="$ROOT_DIR/.github/actions/preserve-required-gate/resolve-deferred-gate.sh" -python3 - "$ROOT_DIR" <<'PY' -from pathlib import Path -import sys -import yaml - -root = Path(sys.argv[1]) -workflow = yaml.load((root / ".github/workflows/resolve-required-gates.yml").read_text(), Loader=yaml.BaseLoader) -action = yaml.load((root / ".github/actions/preserve-required-gate/action.yml").read_text(), Loader=yaml.BaseLoader) -assert "assessment-mode" not in action["inputs"] -assert "PRESERVATION_MODE" not in action["runs"]["steps"][-1]["env"] -assert action["outputs"]["assessment"]["value"] == "${{ steps.preserve.outputs.assessment }}" -assert workflow["on"]["workflow_run"]["types"] == ["completed"] -assert set(workflow["on"]["workflow_run"]["workflows"]) == { - "CI — Validation", "Security Gate", "CodeQL Analysis", "License Gate", "PR Smoke Gate", -} -assert workflow["concurrency"] == { - "group": "required-gate-resolution-${{ github.event.workflow_run.workflow_id }}-${{ github.event.workflow_run.head_sha }}", - "cancel-in-progress": "false", -} -job = workflow["jobs"]["resolve"] -import copy -import json - -assert job["if"] == "${{ github.event.workflow_run.event == 'pull_request' }}" -assert "REQUIRED_GATE_PROOF_ALLOWLIST" not in (job.get("env") or {}) -assert job["permissions"] == {"contents": "read", "checks": "read", "pull-requests": "read", "actions": "write", "statuses": "write"} -checkouts = [step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@")] -assert len(checkouts) == 1 and checkouts[0]["with"] == {"ref": "${{ github.sha }}", "persist-credentials": "false"} -preflight = next(step for step in job["steps"] if step["name"] == "Preflight deferred gate resolution") -admission = next(step for step in job["steps"] if step["name"] == "Admit deferred gate reruns") -assert preflight["id"] == "preflight" and preflight["run"].endswith(" preflight") -assert admission["id"] == "admission" -assert admission["if"] == "${{ steps.preflight.outputs.eligible == 'true' }}" and admission["run"].endswith(" admit") -confirmation = job["steps"][job["steps"].index(admission) + 1] -assert confirmation["name"] == "Confirm admitted deferred gate jobs ${{ steps.admission.outputs.accepted_job_ids }}" -assert confirmation["if"] == "${{ steps.admission.outcome == 'success' }}" and confirmation["run"] == ":" -reconcile = job["steps"][-1] -assert reconcile["name"] == "Reconcile supplementary required gate status" -assert reconcile["if"] == "${{ always() }}" and reconcile["run"].endswith(" reconcile") -assert job["steps"].index(reconcile) > job["steps"].index(confirmation) -PY - -mkdir "$tmp_dir/resolver-bin" -cat >"$tmp_dir/resolver-bin/gh" <<'EOF' -#!/usr/bin/env bash -set -euo pipefail -if [[ "${GITHUB_EVENT_NAME:-}" == pull_request ]]; then - exec "${MOCK_ORIGINAL_GH:?}" "$@" -fi -python3 - "$@" <<'PY' -import json -import os -from pathlib import Path -import sys - -args = sys.argv[1:] -state_path = Path(os.environ["RESOLVER_STATE"]) -state = json.loads(state_path.read_text()) -method = args[args.index("--method") + 1] -endpoint = next(arg for arg in args if arg.startswith("/repos/")) -scenario = state["scenario"] -head, base = "a" * 40, "b" * 40 -title = f"CI — Validation pr-123 base-{base} head-{head}" -repository = "other-owner/firemud" if scenario in {"fork-empty", "bridge-fork"} else "example/firemud" -# The existing fork predecessor fixture is run 200. Keep its resolver target -# distinct so the shared selector correctly excludes only the target itself. -target_id = 300 if scenario == "fork-empty" else 200 -metadata_attempt = 2 if scenario in {"bridge-cross-attempt-two", "bridge-cross-metadata-attempt-mismatch"} else 1 -admission_scenario = scenario.startswith("admission-") or scenario == "partial-admission" or scenario.startswith("window-") -if scenario == "admission-distinct" and state.get("posts", 0): - target_id = 201 -current_id = int(os.environ["GITHUB_RUN_ID"]) -source_id = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())["workflow_run"]["id"] -queue_scenario = scenario.startswith(("queued-", "pending-")) -equal_time_scenario = queue_scenario and "-equal" in scenario -rejected_later = scenario in {"pending-callback-started", "pending-callback-malformed", "pending-callback-attempt", "pending-callback-concluded"} -result = None -exit_status = 0 -state.setdefault("calls", []).append(f"{method} {endpoint}") - -def rich_history_case(scenario, barrier, page): - # Native GET /statuses/ is a newest-first array with creator; the - # combined projection above has the same IDs but deliberately no creator. - case = scenario.removeprefix("bridge-").removeprefix("history-") - older = {**barrier, "id": 499, "created_at": "2026-10-14T00:00:00Z", - "creator": {"id": 99, "login": "foreign", "type": "User"}} - unrelated = [{**barrier, "id": 1000 + (page - 1) * 100 + index, "context": f"other-{page}-{index}", - "created_at": "2026-10-15T01:00:00Z"} for index in range(100)] - if case == "latest-owned": return [barrier, older] - if case == "latest-foreign": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"]}] - if case == "null-actor": return [{**barrier, "creator": None}] - if case == "missing-actor": return [{key: value for key, value in barrier.items() if key != "creator"}] - if case == "unknown-state": return [{**barrier, "state": "unknown"}] - if case == "page-two-owned": return unrelated if page == 1 else [barrier, older] - if case == "page-two-absent": return unrelated if page == 1 else [] - if case == "budget": return unrelated - if case == "unavailable-page": - if page == 1: return unrelated - raise RuntimeError("status page unavailable") - if case == "duplicate-page": return unrelated if page == 1 else [{**unrelated[0], "id": 1000}] - if case == "wrong-head-url": return [{**barrier, "url": barrier["url"].replace("a" * 40, "b" * 40)}] - if case == "same-second": return [barrier, {**older, "created_at": barrier["created_at"]}] - if case == "foreign-same-second": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"], "created_at": barrier["created_at"]}] - if case == "first-page-stop": - if page != 1: raise RuntimeError("older pages must not be read") - return [barrier] + unrelated[:99] - if case == "ignore-old-malformed": return [barrier, "bad"] - if case == "overfull": return unrelated + [barrier] - if case == "scalar": return "bad" - if case == "malformed-row": return ["bad"] - raise AssertionError(case) - - -def run(run_id, attempt=None): - return {"id": run_id, "workflow_id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml", - "created_at": "2026-07-30T01:00:00Z" if run_id == 100 else "2026-07-30T02:00:00Z", - "display_title": title.replace(base, "c" * 40) if scenario.startswith("bridge-cross-") and run_id == 200 else title, "head_sha": head, "head_branch": "proof-branch", - "repository": {"full_name": "example/firemud"}, "head_repository": {"full_name": repository}, - "event": "pull_request", "status": "completed", "conclusion": "cancelled" if scenario == "publisher-cancelled" and run_id == target_id else "failure" if run_id in {target_id, 200, 201} else "success", - "run_attempt": state.get("attempt", 1) if attempt is None else attempt, - "pull_requests": [] if scenario == "fork-empty" else [{"number": 123}]} - -def resolver_run(run_id): - source = source_id if run_id == current_id else 100 - status = "in_progress" if run_id == current_id else "completed" - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T02:59:00Z" - if queue_scenario: - source = 100 if run_id == 9000 else 200 - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T03:01:00Z" - if equal_time_scenario: - created = "2026-07-30T03:00:00Z" - if run_id == 9001 and current_id == 9000: - status = "pending" if scenario.startswith("pending-") else "queued" - if scenario == "chronology-before-target": - created = "2026-07-30T01:30:00Z" if run_id == 9000 else "2026-07-30T03:00:00Z" - attempt = state.get("resolver_attempt", 1) if run_id == current_id else 1 - if scenario in {"prior-rerun-skipped", "pending-callback-attempt"} and run_id == 9001: - attempt = 2 - if scenario in {"prior-queued-old", "prior-pending-old"} and run_id == 9001: - status = "pending" if scenario == "prior-pending-old" else "queued" - if scenario == "pending-callback-started" and run_id == 9001: - status = "in_progress" - if scenario == "pending-callback-malformed" and run_id == 9001: - created = None - if scenario.startswith("window-") and run_id == 9001: - created = "2026-07-30T02:00:00Z" - if admission_scenario and not scenario.startswith("window-"): - created = "2026-07-30T03:00:00Z" if run_id == 9000 else "2026-07-30T03:01:00Z" - if scenario == "cancelled-pending-rerun" and run_id == 9001: - attempt = 2 - if scenario == "cancelled-pending-unknown" and run_id == 9001: - status = "unknown" - return {"id": run_id, "workflow_id": 777, "name": "Resolve Required Gates", - "path": ".github/workflows/resolve-required-gates.yml", "event": "workflow_run", - "repository": {"full_name": "example/firemud"}, - "head_sha": "d" * 40 if scenario in {"queued-new-revision", "pending-new-revision"} and run_id == 9001 else "c" * 40, - "run_attempt": attempt, "status": status, "created_at": created, - "conclusion": None if scenario == "cancelled-pending-unknown" and run_id == 9001 else "cancelled" if scenario.startswith("cancelled-pending-") and run_id == 9001 and scenario != "cancelled-pending-unknown" else "failure" if scenario == "pending-callback-concluded" and run_id == 9001 else None if status in {"queued", "pending", "in_progress"} else "success", - "display_title": f"Resolve Required Gates workflow-42 head-{head} source-{source}"} - -if scenario.startswith("bridge-") and method == "POST": - assert endpoint == f"/repos/example/firemud/statuses/{head}", endpoint - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - state.setdefault("status_posts", []).append(fields) - state["barrier_state"] = fields["state"] - if scenario == "bridge-write-denied": - exit_status = 1 -elif scenario.startswith("bridge-") and (endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/statuses/{head}")): - state["status_reads"] = state.get("status_reads", 0) + 1 - barrier = {"id": 500, "url": f"https://api.github.com/repos/example/firemud/statuses/{head}", - "created_at": "2026-10-15T00:00:00Z", "context": "Validation Gate", "state": state.get("barrier_state", "pending"), - "target_url": f"https://github.com/example/firemud/actions/runs/200/attempts/{metadata_attempt}", - "creator": {"id": 41898282, "login": "github-actions[bot]", "type": "Bot"}} - if scenario in {"bridge-foreign", "bridge-cross-foreign"}: - barrier["creator"]["id"] = 99 - elif scenario == "bridge-wrong-url": - barrier["target_url"] = "https://github.com/foreign/repo/actions/runs/200/attempts/1" - elif scenario in {"bridge-replaced", "bridge-cross-replaced"} and state["status_reads"] > 1: - barrier["id"] = 501 - elif scenario == "bridge-terminal": - barrier["state"] = "success" - rich = [] if scenario == "bridge-absent" else [barrier] - combined = {"sha": head, "total_count": len(rich), "statuses": [{key: value for key, value in row.items() if key != "creator"} for row in rich]} - assert all("creator" not in row for row in combined["statuses"]) - if endpoint.endswith("/status"): - result = [combined] # Actual combined projection deliberately omits creator. - else: - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - assert fields["per_page"] == "100" and "--paginate" not in args - page = int(fields["page"]) - state.setdefault("status_pages", []).append(page) - result = rich - if scenario.startswith("bridge-history-"): - try: - result = rich_history_case(scenario, barrier, page) - except RuntimeError: - result = None - exit_status = 1 - if scenario == "bridge-incomplete-status": - result = combined # Wrong endpoint shape must never qualify. -elif (scenario.startswith("bridge-") and "/attempts/" in endpoint and not endpoint.endswith("/jobs") and - endpoint.split("/actions/runs/")[1].split("/")[0] in {"99", "100", "101"}): - identity = int(endpoint.split("/")[-3]) - attempt = int(endpoint.rsplit("/", 1)[1]) - result = run(identity, attempt) - result["conclusion"] = "success" - if scenario == "bridge-cross-source-wrong-title": - result["display_title"] = title.replace(base, "c" * 40) -elif (scenario.startswith("bridge-") and "/actions/runs/" in endpoint and - "/attempts/" in endpoint and endpoint.endswith("/jobs") and - endpoint.split("/actions/runs/")[1].split("/")[0] in {"99", "100", "101"}): - identity = int(endpoint.split("/actions/runs/")[1].split("/")[0]) - attempt = int(endpoint.split("/attempts/")[1].split("/", 1)[0]) - row_attempt = 1 if scenario == "bridge-cross-source-attempt-mismatch" else attempt - job = {"id": identity, "run_id": identity, "run_attempt": row_attempt, "head_sha": head, - "head_branch": "proof-branch", "workflow_name": "CI — Validation", "name": "Validation Gate", - "status": "completed", "conclusion": "success", - "html_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{identity}", - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T01:30:00Z", - "steps": [{"name": "Preserve successful required gate on metadata-only edit", - "status": "completed", "conclusion": "skipped"}]} - if scenario == "bridge-cross-source-metadata": - job["steps"][0]["conclusion"] = "success" - if scenario == "bridge-cross-source-attempt-changed": - reads = state.get("selected_attempt_jobs_reads", 0) + 1 - state["selected_attempt_jobs_reads"] = reads - if reads > 1: - job["steps"][0]["conclusion"] = "success" - result = {"total_count": 1, "jobs": [job]} -elif scenario.startswith("bridge-") and any(endpoint.endswith(f"/actions/jobs/{identity}") for identity in (99, 100, 101)): - identity = int(endpoint.rsplit("/", 1)[1]) - result = {"id": identity, "run_id": identity, "run_attempt": 2 if scenario in {"bridge-cross-attempt-two", "bridge-cross-source-attempt-mismatch"} else 1, "head_sha": head, "name": "Validation Gate", - "status": "completed", "conclusion": "success", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{identity}", - "steps": [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "skipped"}]} - if scenario == "bridge-cross-source-metadata": - result["steps"][0]["conclusion"] = "success" - if scenario in {"bridge-cross-attempt-two", "bridge-cross-source-attempt-mismatch", "bridge-cross-source-attempt-changed"}: - result["steps"] = [] - if scenario == "bridge-cross-source-null-steps": - result["steps"] = None -elif scenario.startswith("bridge-") and any(endpoint.endswith(f"/check-runs/{identity}") for identity in (99, 100, 101)): - identity = int(endpoint.rsplit("/", 1)[1]) - state["selected_check_reads"] = state.get("selected_check_reads", 0) + 1 - result = {"id": identity, "head_sha": head, "name": "Validation Gate", "status": "completed", "conclusion": "success", - "details_url": f"https://github.com/example/firemud/actions/runs/{identity}/job/{identity}", - "started_at": "2026-07-30T01:00:00Z", "completed_at": "2026-07-30T01:30:00Z", - "app": {"id": 99 if scenario == "bridge-cross-source-wrong-app" else 15368, "slug": "github-actions"}} - if scenario == "bridge-cross-source-changed" and state["selected_check_reads"] > 1: - result["conclusion"] = "failure" -elif scenario == "bridge-retry" and endpoint.endswith("/actions/runs/101"): - result = run(101) -elif scenario.startswith("bridge-") and endpoint.endswith(f"/actions/runs/200/attempts/{metadata_attempt}/jobs"): - job = {"id": 2000 + metadata_attempt - 1, "run_id": 200, "run_attempt": 1 if scenario == "bridge-cross-metadata-attempt-mismatch" else metadata_attempt, - "head_sha": head, "workflow_name": "CI — Validation", "name": "Validation Gate", "status": "completed", - "conclusion": "cancelled" if scenario == "bridge-cancelled" else "success", - "check_run_url": f"https://api.github.com/repos/example/firemud/check-runs/{3000 + metadata_attempt - 1}", - "steps": [{"name": name, "status": "completed", "conclusion": "success"} for name in - ("Preserve successful required gate on metadata-only edit", "Publish pending required gate status")]} - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - job.update(status="in_progress", conclusion=None) - # The acknowledged POST is visible before publication completes; the - # preservation step has not yet appeared in this native snapshot. - job["steps"] = [{"name": "Publish pending required gate status", "status": "in_progress", "conclusion": None}] - if scenario == "bridge-failed-producer": - job["steps"][1]["conclusion"] = "failure" - if scenario == "bridge-failed-preservation": - job["steps"][0]["conclusion"] = "failure" - if scenario == "bridge-no-producer": - job["steps"].pop() - result = [{"total_count": 2 if scenario == "bridge-incomplete-jobs" else 1, "jobs": [job]}] -elif scenario.startswith("bridge-") and endpoint.endswith(f"/check-runs/{3000 + metadata_attempt - 1}"): - result = {"id": 3000 + metadata_attempt - 1, "head_sha": head, "name": "Validation Gate", "status": "completed", - "conclusion": "cancelled" if scenario == "bridge-cancelled" else "success", - "app": {"id": 99 if scenario in {"bridge-wrong-app", "bridge-running-wrong-app"} else 15368, "slug": "github-actions"}} - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - result.update(status="in_progress", conclusion=None) -elif scenario.startswith("bridge-") and (endpoint.endswith("/actions/runs/200") or endpoint.endswith(f"/actions/runs/200/attempts/{metadata_attempt}")): - requested_attempt = metadata_attempt if "/attempts/" in endpoint else 1 - result = run(200, requested_attempt) - if scenario == "bridge-cross-metadata-attempt-mismatch" and "/attempts/" in endpoint: - result["run_attempt"] = 1 - result["conclusion"] = "cancelled" if scenario == "bridge-cancelled" else "success" - if scenario in {"bridge-running", "bridge-running-wrong-app", "bridge-cross-running"} and not state.get("metadata_completed"): - result.update(status="in_progress", conclusion=None) - if scenario == "bridge-wrong-attempt" or (scenario == "bridge-cross-earlier-attempt" and endpoint.endswith("/actions/runs/200")): - result["run_attempt"] = 2 - if scenario == "bridge-empty-association": - result["pull_requests"] = [] - if scenario == "bridge-wrong-title": - result["display_title"] = title.replace("pr-123", "pr-456") -elif method == "POST": - job_id = int(endpoint.split("/")[-2]) - assert job_id in {2000, 2001} and endpoint.endswith(f"/actions/jobs/{job_id}/rerun"), endpoint - state["posts"] = state.get("posts", 0) + 1 - state.setdefault("post_jobs", []).append(job_id) - if scenario in {"ambiguous-post", "same-id-rerun"} or (scenario == "partial-admission" and job_id == 2001): - state["ambiguous_admission"] = True - exit_status = 1 - print("simulated connection lost after admission", file=sys.stderr) - elif not admission_scenario: - state["attempt"] = 2 -elif endpoint.endswith("/actions/workflows/resolve-required-gates.yml"): - result = {"id": 777, "name": "Resolve Required Gates", "path": ".github/workflows/resolve-required-gates.yml"} -elif endpoint.endswith("/actions/runs/9000") or endpoint.endswith("/actions/runs/9001"): - result = resolver_run(int(endpoint.rsplit("/", 1)[1])) -elif endpoint.endswith("/actions/workflows/resolve-required-gates.yml/runs"): - assert "--paginate" not in args and "--slurp" not in args - assert "created=>=2026-07-30T02:00:00Z" in args and "per_page=100" in args - state["history_floor"] = "2026-07-30T02:00:00Z" - assert "head_sha=" + head not in args and not any(arg.startswith("status=") for arg in args) - page = int(next(arg.split("=", 1)[1] for arg in args if arg.startswith("page="))) - assert 1 <= page <= 10 - state.setdefault("history_pages", []).append(page) - runs = [resolver_run(9000)] - if scenario.startswith("history-") or scenario in {"window-final-admitted", "window-final-ambiguous"}: - count = 1000 if scenario == "history-ceiling" else 201 - for index in range(count - 2): - unrelated = resolver_run(10000 + index) - unrelated["display_title"] = f"Resolve Required Gates workflow-43 head-{'e' * 40} source-{10000 + index}" - runs.append(unrelated) - # A matching admission on the final page must not be skipped. - runs.append(resolver_run(9001)) - if scenario == "history-duplicate": - runs[100] = runs[1] - elif scenario == "history-missing-current": - runs[0] = runs[2].copy() - runs[0]["id"] = 20000 - elif scenario == "history-before-floor": - runs[100]["created_at"] = "2026-07-29T01:00:00Z" - elif scenario.startswith(("prior-", "cancelled-pending-", "window-")) or queue_scenario or ( - state.get("ambiguous_admission") and scenario != "same-id-rerun" - ): - runs.append(resolver_run(9001)) - if current_id == 9001 and not any(item["id"] == current_id for item in runs): - runs.append(resolver_run(current_id)) - if scenario == "window-old-source": - old = [dict(resolver_run(20000 + index), created_at="2026-07-30T01:30:00Z") for index in range(1001)] - runs.extend(old) - if scenario != "history-before-floor": - runs = [item for item in runs if item["created_at"] is None or item["created_at"] >= "2026-07-30T02:00:00Z"] - total = 1001 if scenario in {"prior-oversized", "history-overcap"} else len(runs) + (1 if scenario == "prior-incomplete" else 0) - result = {"total_count": total, "workflow_runs": runs[(page - 1) * 100:page * 100]} - if page == 2: - if scenario == "history-incomplete": - result["workflow_runs"].pop() - elif scenario == "history-missing-total": - result.pop("total_count") - elif scenario == "history-malformed-total": - result["total_count"] = str(total) - elif scenario == "history-inconsistent-total": - result["total_count"] += 1 - elif scenario == "history-malformed-page": - result["workflow_runs"] = None - elif scenario == "history-unavailable-page": - exit_status = 1 -elif endpoint.endswith("/actions/runs/9001/attempts/1/jobs") or endpoint.endswith("/actions/runs/9000/attempts/1/jobs"): - prior_id = int(endpoint.split("/")[-4]) - if queue_scenario: - assert (current_id == 9001 and prior_id == 9000) or ( - (equal_time_scenario or rejected_later) and current_id == 9000 and prior_id == 9001 - ), "strictly later waiting callback was queried as potentially admitted" - assert "--paginate" not in args and "--slurp" not in args and "per_page=20" in args - if scenario == "prior-unavailable": - exit_status = 1 - else: - conclusion = "skipped" if scenario in {"prior-noop", "prior-cancelled-between-steps", "prior-rerun-skipped"} or (scenario.startswith("history-") and scenario != "history-ambiguous-tail") else "failure" - if queue_scenario and not rejected_later: - conclusion = "success" - if scenario.startswith("window-"): - conclusion = "failure" if scenario in {"window-boundary-ambiguous", "window-final-ambiguous"} else "success" - if scenario == "prior-cancelled-admission": - conclusion = "cancelled" - steps = [{"name": "Preflight deferred gate resolution", "status": "completed", "conclusion": "success"}, - {"name": "Admit deferred gate reruns", "status": "completed", "conclusion": conclusion}] - if scenario in {"prior-missing-step", "prior-queued-old", "prior-pending-old"}: - steps.pop() - result = {"total_count": 1, "jobs": [{"id": prior_id * 10, "run_id": prior_id, "name": "Resolve deferred metadata gate", - "head_sha": resolver_run(prior_id)["head_sha"], - "status": "completed", "conclusion": "cancelled" if scenario.startswith("prior-cancelled") else "failure", - "steps": steps}]} - record = state.get("native_admissions", {}).get(str(prior_id)) - if record: - steps[-1].update(status="completed", conclusion=record["admission_conclusion"]) - steps.extend(record["confirmations"]) - elif conclusion == "success": - steps.append({"name": "Confirm admitted deferred gate jobs " + ("[2000]" if scenario in {"window-boundary-admitted", "window-final-admitted", "window-source-expiry", "window-ties"} else "[]"), "status": "completed", "conclusion": "success"}) - if scenario.startswith("cancelled-pending-"): - result = {"total_count": 0, "jobs": []} - if scenario == "cancelled-pending-nonempty": - result = {"total_count": 1, "jobs": [{"id": 90010, "run_id": prior_id, - "head_sha": resolver_run(prior_id)["head_sha"], "name": "Resolve deferred metadata gate", - "status": "completed", "conclusion": "cancelled", "steps": []}]} - elif scenario == "cancelled-pending-incomplete": - result["total_count"] = 1 - elif scenario == "cancelled-pending-malformed": - result["jobs"] = None - elif scenario == "cancelled-pending-missing": - result.pop("total_count") - elif scenario == "cancelled-pending-started": - result = {"total_count": 1, "jobs": [{"id": 90010, "run_id": prior_id, - "head_sha": resolver_run(prior_id)["head_sha"], "name": "Resolve deferred metadata gate", - "status": "in_progress", "conclusion": None, "steps": []}]} - if equal_time_scenario and current_id == 9000: - job = result["jobs"][0] - job.update(status="queued", conclusion=None, started_at=None, completed_at=None, steps=[]) - if scenario in {"queued-equal-started", "pending-equal-started"}: - job.update(status="in_progress", started_at="2026-07-30T03:00:00Z") - elif scenario in {"queued-equal-missing", "pending-equal-missing"}: - job.pop("started_at") - elif scenario in {"queued-equal-malformed", "pending-equal-malformed"}: - job["steps"] = None - elif scenario in {"queued-equal-incomplete", "pending-equal-incomplete"}: - result["total_count"] = 2 - elif scenario in {"queued-equal-wrong-job", "pending-equal-wrong-job"}: - job["run_id"] = 9002 - elif scenario == "pending-equal-started-step": - job["steps"] = [{"name": "Set up job", "status": "in_progress", "conclusion": None}] -elif endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/actions/workflows/ci.yml/runs"): - assert "--paginate" not in args and "--slurp" not in args - assert "head_sha=" + head in args and "event=pull_request" in args and "per_page=20" in args - state["source_listing_reads"] = state.get("source_listing_reads", 0) + 1 - runs = [run(100), run(200 if admission_scenario else target_id)] - if scenario in {"partial-admission", "window-ties", "window-new-target"} or (scenario == "admission-distinct" and state.get("posts", 0)): - runs.append(run(201)) - if scenario == "window-source-expiry": - runs = [run(200)] - total_count = 21 if scenario == "source-oversized" else len(runs) - if scenario == "source-transient-row-count" and state["source_listing_reads"] == 1: - total_count += 1 - elif scenario == "source-third-read-complete" and state["source_listing_reads"] <= 2: - total_count += 1 - elif scenario == "source-incomplete-then-malformed": - if state["source_listing_reads"] == 1: - total_count += 1 - else: - runs = ["bad"] - total_count = 1 - elif scenario == "source-transient-missing-source" and state["source_listing_reads"] == 1: - runs = [run(200)] - total_count = len(runs) - elif scenario == "source-empty-then-complete" and state["source_listing_reads"] == 1: - runs = [] - total_count = 0 - elif scenario == "source-persistent-incomplete": - total_count += 1 - elif scenario == "source-empty-persistent": - runs = [] - total_count = 0 - elif scenario == "source-malformed-schema": - runs[0].pop("created_at") - elif scenario == "source-identity-mismatch": - runs[0]["head_sha"] = "f" * 40 - elif scenario == "source-malformed-row": - runs = ["bad"] - total_count = 1 - elif scenario == "source-malformed-repository": - runs[0]["repository"] = "bad" - result = {"total_count": total_count, "workflow_runs": runs} - if scenario == "source-scalar-response": - result = "bad" - elif scenario == "source-array-response": - result = [] -elif endpoint.endswith("/pulls/123"): - state["pr_reads"] = state.get("pr_reads", 0) + 1 - result = {"number": 123, "state": "open", "base": {"sha": base, "ref": "develop", "repo": {"full_name": "example/firemud"}}, - "head": {"sha": "c" * 40 if scenario == "stale-pr" or (scenario == "bridge-pr-changed" and state["pr_reads"] > 1) else head, "ref": "proof-branch", "repo": {"full_name": repository}}} - if scenario == "bridge-cross-obsolete": - result["base"]["sha"] = "c" * 40 - if state["pr_reads"] >= 2 and scenario == "fresh-base-branch": - result["base"]["ref"] = "main" - elif state["pr_reads"] >= 2 and scenario == "fresh-head-repository": - result["head"]["repo"]["full_name"] = "other-owner/firemud" -elif endpoint.endswith(f"/actions/runs/{target_id}/attempts/1/jobs") or (admission_scenario and any(endpoint.endswith(f"/actions/runs/{run_id}/attempts/1/jobs") for run_id in (200, 201))): - requested_target = int(endpoint.split("/")[-4]) - assert "--paginate" in args and "--slurp" in args - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "success"}] - if scenario.startswith("publisher-"): - if scenario == "publisher-unassessed": - steps[0]["conclusion"] = "failure" - steps.append({"name": "Publish pending required gate status", "status": "completed", - "conclusion": "cancelled" if scenario == "publisher-cancelled" else "skipped" if scenario == "publisher-unassessed" else "failure"}) - if scenario != "ordinary-failure": - steps.append({"name": "Report dependency-deferred required gate", "status": "completed", - "conclusion": "skipped" if scenario == "publisher-cancelled" else "failure"}) - result = [{"total_count": 1, "jobs": [{"id": 2001 if requested_target == 201 else 2000, "run_id": requested_target, "head_sha": head, "status": "completed", "conclusion": "failure", - "name": "Validation Gate", "steps": steps}]}] - if scenario == "publisher-cancelled": - result[0]["jobs"][0]["conclusion"] = "cancelled" - if scenario.startswith("target-jobs-"): - gate = result[0]["jobs"][0] - if scenario == "target-jobs-truncated": - # A second gate job is omitted, so uniqueness is unproved. - result[0]["total_count"] = 2 - elif scenario == "target-jobs-missing-total": - result[0].pop("total_count") - elif scenario == "target-jobs-malformed-total": - result[0]["total_count"] = "1" - elif scenario == "target-jobs-overcount": - result[0]["total_count"] = 0 - elif scenario == "target-jobs-invalid-id": - gate["id"] = "2000" - elif scenario == "target-jobs-empty-pages": - result = [] - elif scenario == "target-jobs-zero": - result = [{"total_count": 0, "jobs": []}] - elif scenario == "target-jobs-duplicate": - result = [{"total_count": 2, "jobs": [gate]}, {"total_count": 2, "jobs": [gate]}] - elif scenario in {"target-jobs-multi", "target-jobs-inconsistent-total"}: - other = dict(gate, id=2002, name="Other job") - result = [{"total_count": 2, "jobs": [other]}, - {"total_count": 3 if scenario.endswith("inconsistent-total") else 2, "jobs": [gate]}] - else: - raise AssertionError(scenario) -elif endpoint.endswith(f"/actions/runs/{target_id}") or (admission_scenario and any(endpoint.endswith(f"/actions/runs/{run_id}") for run_id in (200, 201))): - requested_target = int(endpoint.rsplit("/", 1)[1]) - state["target_reads"] = state.get("target_reads", 0) + 1 - state.setdefault("target_reads_by_id", {})[str(requested_target)] = state.get("target_reads_by_id", {}).get(str(requested_target), 0) + 1 - result = run(requested_target) - if scenario == "window-new-target" and requested_target == 201 and not state.get("history_pages"): - result["status"] = "queued" - if scenario == "chronology-missing-created": - result.pop("created_at") - elif scenario == "chronology-invalid-created": - result["created_at"] = "not-a-timestamp" - elif scenario == "chronology-fresh-created" and state["target_reads"] >= 2: - result["created_at"] = "2026-07-30T03:01:00Z" - elif scenario == "consumed": - result["run_attempt"] = 2 - elif scenario == "fresh-changed" and state["target_reads"] >= 2: - result["status"] = "queued" - elif scenario == "wrong-tuple": - result["display_title"] = title.replace(base, "c" * 40) - elif scenario == "wrong-association": - result["pull_requests"] = [{"number": 456}] - elif scenario == "malformed-path": - result["path"] += "@" -elif endpoint.endswith("/actions/runs/100"): - result = run(100) -else: - raise AssertionError(endpoint) -state_path.write_text(json.dumps(state)) -if result is not None: - print(json.dumps(result)) -sys.exit(exit_status) -PY -EOF -chmod +x "$tmp_dir/resolver-bin/gh" -cat >"$tmp_dir/resolver-bin/sleep" <<'EOF' -#!/usr/bin/env python3 -import json -import os -from pathlib import Path -import sys -state_path = Path(os.environ["RESOLVER_STATE"]) -state = json.loads(state_path.read_text()) -state.setdefault("source_listing_waits", []).append(int(sys.argv[1])) -state_path.write_text(json.dumps(state)) -EOF -chmod +x "$tmp_dir/resolver-bin/sleep" - -run_resolver() { - local scenario="$1" source_id="${2:-100}" original_scenario="${3:-no-local-workflow-file}" - local phase="${4:-admit}" - local resolver_id="${5:-9000}" - local event_file="$tmp_dir/resolver-event-$scenario" - local result_status=0 - : >"$tmp_dir/resolver-output-$scenario" - printf '{"action":"completed","workflow_run":{"id":%s,"workflow_id":42,"head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","event":"pull_request"}}\n' \ - "$source_id" >"$event_file" - PATH="$tmp_dir/resolver-bin:$PATH" MOCK_ORIGINAL_GH="$tmp_dir/gh" \ - RESOLVER_STATE="$tmp_dir/resolver-state-$scenario" \ - GITHUB_EVENT_NAME=workflow_run GITHUB_EVENT_PATH="$event_file" GITHUB_RUN_ID="$resolver_id" \ - GITHUB_OUTPUT="$tmp_dir/resolver-output-$scenario" \ - GITHUB_REPOSITORY=example/firemud GH_TOKEN=test-token \ - GH_RETRY_COUNT_FILE="$tmp_dir/resolver-proof-count-$scenario" \ - GH_CALL_COUNT_DIR="$tmp_dir/resolver-proof-calls-$scenario" GH_SCENARIO="$original_scenario" \ - GH_FAILURE_MODE=none bash "$RESOLVER" "$phase" >"$tmp_dir/resolver-log-$scenario" 2>&1 || result_status=$? - if [[ "$phase" == admit ]]; then - python3 - "$tmp_dir/resolver-state-$scenario" "$tmp_dir/resolver-output-$scenario" "$resolver_id" "$result_status" <<'PY' -import json -from pathlib import Path -import sys -state_path, output_path = map(Path, sys.argv[1:3]) -run_id, result = sys.argv[3], int(sys.argv[4]) -state = json.loads(state_path.read_text()) -outputs = dict(line.split("=", 1) for line in output_path.read_text().splitlines()) -encoded_ids = outputs.get("accepted_job_ids", "") -confirmations = [] -if result == 0: - # Emulate the following native confirmation step from the actual output. - json.loads(encoded_ids) - confirmation = {"name": "Confirm admitted deferred gate jobs " + encoded_ids, - "status": "completed", "conclusion": "success"} - scenario = state["scenario"] - if scenario == "admission-marker-failed": - confirmation["conclusion"] = "failure" - elif scenario == "admission-marker-cancelled": - confirmation["conclusion"] = "cancelled" - elif scenario == "admission-marker-incomplete": - confirmation.update(status="in_progress", conclusion=None) - elif scenario == "admission-marker-malformed": - confirmation["name"] = "Confirm admitted deferred gate jobs not-json" - elif scenario == "admission-marker-duplicate-ids": - confirmation["name"] = "Confirm admitted deferred gate jobs [2000,2000]" - elif scenario == "admission-marker-string-id": - confirmation["name"] = 'Confirm admitted deferred gate jobs ["2000"]' - elif scenario == "admission-marker-oversized": - confirmation["name"] = "Confirm admitted deferred gate jobs " + json.dumps(list(range(1, 22)), separators=(",", ":")) - confirmations.append(confirmation) - if scenario == "admission-marker-missing": - confirmations = [] - elif scenario == "admission-marker-duplicate-step": - confirmations.append(confirmation.copy()) -else: - assert "accepted_job_ids" not in outputs, "uncertain admission published acknowledged IDs" -state.setdefault("native_admissions", {})[run_id] = { - "admission_conclusion": "success" if result == 0 else "failure", "confirmations": confirmations, -} -state_path.write_text(json.dumps(state)) -PY - fi - return "$result_status" -} -# Source completion can arrive after publication but before metadata completes. -printf '{"scenario":"bridge-running"}\n' >"$tmp_dir/resolver-state-bridge-running" -run_resolver bridge-running 100 pending-predecessor reconcile -python3 - "$tmp_dir/resolver-state-bridge-running" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -path = Path(sys.argv[1]) -state = json.loads(path.read_text()) -assert not state.get("status_posts"), state -state["metadata_completed"] = True -path.write_text(json.dumps(state)) -PY_BRIDGE -run_resolver bridge-running 200 no-local-workflow-file reconcile -python3 - "$tmp_dir/resolver-state-bridge-running" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("status_posts", [])) == 1 and state["status_posts"][0]["state"] == "success", state -PY_BRIDGE - -# A cancellation-only original leaves the owned barrier pending; the existing -# independently verified successful replacement callback can later settle it. -printf '{"scenario":"bridge-retry"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 100 cancellation-pending reconcile -[[ "$(jq '.status_posts // [] | length' "$tmp_dir/resolver-state-bridge-retry")" == 0 ]] || exit 1 -run_resolver bridge-retry 101 retry-success reconcile -[[ "$(jq -c '[.status_posts[].state]' "$tmp_dir/resolver-state-bridge-retry")" == '["success"]' ]] || { - echo "cancelled original did not recover through existing callback" >&2; exit 1; -} - -# Support is dormant until a producer publishes the exact recognizable barrier. -for scenario in bridge-success bridge-failed-producer bridge-failed-preservation bridge-empty-association bridge-fork bridge-pending bridge-failed bridge-cancelled bridge-replaced bridge-pr-changed bridge-foreign bridge-wrong-url bridge-terminal bridge-absent; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-pending ]] || original=pending-predecessor - [[ "$scenario" != bridge-failed ]] || original=failed-predecessor - # Both substantive-first and metadata-first callbacks use the same target. - source_id=100 - [[ "$scenario" != bridge-empty-association ]] || source_id=200 - run_resolver "$scenario" "$source_id" "$original" reconcile - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[2] -posts = state.get("status_posts", []) -expected = "success" if scenario in {"bridge-success", "bridge-failed-producer", "bridge-failed-preservation", "bridge-empty-association", "bridge-fork", "bridge-cancelled"} else "failure" if scenario in {"bridge-failed"} else None -assert len(posts) == (1 if expected else 0), state -if expected: - assert posts[0]["state"] == expected, state -assert not state.get("posts"), "bridge entered legacy rerun admission" -PY_BRIDGE -done -for scenario in bridge-running-wrong-app bridge-no-producer bridge-incomplete-status bridge-incomplete-jobs bridge-wrong-app bridge-wrong-attempt bridge-wrong-title bridge-cross-metadata-attempt-mismatch bridge-write-denied; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - if run_resolver "$scenario" 100 no-local-workflow-file reconcile; then - echo "unproved bridge settlement succeeded: $scenario" >&2; exit 1 - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_BRIDGE' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("status_posts", [])) == (1 if sys.argv[2] == "bridge-write-denied" else 0), state -PY_BRIDGE -done - -# Mirrors the observed Security ordering: metadata38678293269/1 published -# pending56392930570 before original38678278927 completed successfully; callback -#38678584212 executed reconciliation. Normalized identities below must now recover -# using rich creator evidence, while combined records omit that evidence. -for history_case in latest-owned latest-foreign null-actor missing-actor unknown-state page-two-owned page-two-absent budget unavailable-page duplicate-page wrong-head-url same-second foreign-same-second first-page-stop ignore-old-malformed overfull scalar malformed-row; do - scenario="bridge-history-$history_case" - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - case "$history_case" in - budget|unavailable-page|duplicate-page|wrong-head-url|overfull|scalar|malformed-row) - if run_resolver "$scenario" 100 no-local-workflow-file reconcile; then - echo "invalid rich resolver history qualified: $history_case" >&2; exit 1 - fi ;; - *) run_resolver "$scenario" 100 no-local-workflow-file reconcile ;; - esac - python3 - "$tmp_dir/resolver-state-$scenario" "$history_case" <<'PY_HISTORY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -case = sys.argv[2] -assert len(state.get("status_posts", [])) == (1 if case in {"latest-owned", "page-two-owned", "same-second", "first-page-stop", "ignore-old-malformed"} else 0), state -assert not any("/commits/" in call and call.endswith("/status") for call in state["calls"]), state -if case.startswith("page-two-"): assert 2 in state["status_pages"], state -if case == "first-page-stop": assert all(page == 1 for page in state["status_pages"]), state -if case == "budget": assert state["status_pages"] == list(range(1, 11)), state -PY_HISTORY -done - -# Same-head base advancement uses historical ownership and CURRENT proof. -for scenario in bridge-cross-success bridge-cross-attempt-two bridge-cross-source-null-steps bridge-cross-running bridge-cross-earlier-attempt bridge-cross-no-proof bridge-cross-failure bridge-cross-foreign bridge-cross-replaced bridge-cross-obsolete bridge-cross-cancelled-selection; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-cross-no-proof ]] || original=no-prior - [[ "$scenario" != bridge-cross-failure ]] || original=failed-predecessor - [[ "$scenario" != bridge-cross-cancelled-selection ]] || original=completed-cancelled-missing-step - [[ "$scenario" != bridge-cross-attempt-two ]] || original=attempt-fallback-attempt-two - if ! run_resolver "$scenario" 100 "$original" reconcile; then - cat "$tmp_dir/resolver-log-$scenario" >&2; exit 1 - fi - # A later old-base metadata completion cannot reclaim current-base authority. - if [[ "$scenario" != bridge-cross-obsolete ]]; then - jq '.metadata_completed = true' "$tmp_dir/resolver-state-$scenario" >"$tmp_dir/recovery-state-update" - mv "$tmp_dir/recovery-state-update" "$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" 200 no-local-workflow-file reconcile - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -expected = "success" if sys.argv[2] in {"bridge-cross-success", "bridge-cross-attempt-two", "bridge-cross-source-null-steps", "bridge-cross-running", "bridge-cross-earlier-attempt", "bridge-cross-cancelled-selection"} else "failure" if sys.argv[2] == "bridge-cross-failure" else None -posts = state.get("status_posts", []) -assert len(posts) == (1 if expected else 0), state -if expected: - assert posts[0]["state"] == expected, state - if sys.argv[2] == "bridge-cross-attempt-two": - assert posts[0]["target_url"].endswith("/200/attempts/2"), state - calls = state["calls"] - for path in ("/actions/runs/100/attempts/2/jobs", "/actions/runs/200/attempts/2", - "/actions/runs/200/attempts/2/jobs"): - assert any(path in call for call in calls), (path, calls) - assert sum("/actions/runs/100/attempts/2/jobs" in call for call in calls) == 2, state - assert sum("/actions/runs/200/attempts/2/jobs" in call for call in calls) == 2, state - elif sys.argv[2] == "bridge-cross-success": - assert posts[0]["target_url"].endswith("/200/attempts/1"), state - assert not any("/actions/runs/100/attempts/1/jobs" in call for call in state["calls"]), state - elif sys.argv[2] == "bridge-cross-source-null-steps": - assert posts[0]["target_url"].endswith("/200/attempts/1"), state - assert sum("/actions/runs/100/attempts/1/jobs" in call for call in state["calls"]) == 2, state - assert sum("/actions/runs/200/attempts/1/jobs" in call for call in state["calls"]) == 2, state - else: - assert posts[0]["target_url"].endswith("/200/attempts/1"), state -PY_RECOVERY -done -for scenario in bridge-cross-source-wrong-app bridge-cross-source-wrong-title bridge-cross-source-metadata bridge-cross-source-changed bridge-cross-source-attempt-mismatch bridge-cross-source-attempt-changed; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - original=no-local-workflow-file - [[ "$scenario" != bridge-cross-source-attempt-mismatch ]] || original=attempt-fallback-attempt-two - if run_resolver "$scenario" 100 "$original" reconcile; then - echo "invalid independent current-base source accepted: $scenario" >&2; exit 1 - fi - [[ "$(jq '.status_posts // [] | length' "$tmp_dir/resolver-state-$scenario")" == 0 ]] || exit 1 - if [[ "$scenario" == bridge-cross-source-attempt-changed ]]; then - [[ "$(jq '.selected_attempt_jobs_reads // 0' "$tmp_dir/resolver-state-$scenario")" == 2 ]] || { - echo "selected sparse source was not independently revalidated before publication" >&2; exit 1; - } - fi -done -printf '{"scenario":"bridge-retry"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 100 failed-predecessor reconcile -run_resolver bridge-retry 101 retry-success reconcile -python3 - "$tmp_dir/resolver-state-bridge-retry" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert [post["state"] for post in state["status_posts"]] == ["failure", "success"], state -PY_RECOVERY -printf '{"scenario":"bridge-retry","barrier_state":"error"}\n' >"$tmp_dir/resolver-state-bridge-retry" -run_resolver bridge-retry 101 retry-success reconcile -python3 - "$tmp_dir/resolver-state-bridge-retry" <<'PY_RECOVERY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert [post["state"] for post in state["status_posts"]] == ["success"], state -PY_RECOVERY - -resolver_posts() { - jq -r '.posts // 0' "$tmp_dir/resolver-state-$1" -} -resolver_source_listing_reads() { - jq -r '.source_listing_reads // 0' "$tmp_dir/resolver-state-$1" -} -resolver_source_listing_waits() { - jq -c '.source_listing_waits // []' "$tmp_dir/resolver-state-$1" -} -for scenario in success metadata-last metadata-first consumed fresh-changed fresh-base-branch fresh-head-repository ordinary-failure stale-pr wrong-tuple wrong-association malformed-path fork-empty ambiguous-post original-failure preflight prior-noop prior-cancelled-between-steps prior-cancelled-admission prior-ambiguous prior-unavailable prior-incomplete prior-missing-step prior-oversized source-oversized source-transient-row-count source-transient-missing-source source-empty-then-complete source-third-read-complete source-incomplete-then-malformed source-persistent-incomplete source-empty-persistent source-malformed-schema source-identity-mismatch source-malformed-row source-malformed-repository source-scalar-response source-array-response same-id-rerun prior-rerun-skipped queued-callback queued-new-revision queued-equal queued-equal-started queued-equal-missing queued-equal-malformed queued-equal-incomplete queued-equal-wrong-job prior-queued-old pending-callback pending-new-revision pending-equal pending-equal-started pending-equal-missing pending-equal-malformed pending-equal-incomplete pending-equal-wrong-job pending-equal-started-step pending-callback-started pending-callback-malformed pending-callback-attempt pending-callback-concluded prior-pending-old history-multi history-ceiling history-ambiguous-tail history-duplicate history-missing-current history-before-floor history-overcap history-incomplete history-missing-total history-malformed-total history-inconsistent-total history-malformed-page history-unavailable-page admission-delayed admission-zero admission-distinct admission-marker-failed admission-marker-cancelled admission-marker-incomplete admission-marker-missing admission-marker-malformed admission-marker-duplicate-ids admission-marker-string-id admission-marker-oversized admission-marker-duplicate-step partial-admission cancelled-pending-zero cancelled-pending-nonempty cancelled-pending-incomplete cancelled-pending-malformed cancelled-pending-missing cancelled-pending-unknown cancelled-pending-rerun cancelled-pending-started; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" -done -for target_coverage_case in truncated missing-total malformed-total overcount invalid-id empty-pages duplicate inconsistent-total zero multi; do - target_coverage_scenario="target-jobs-$target_coverage_case" - printf '{"scenario":"%s"}\n' "$target_coverage_scenario" >"$tmp_dir/resolver-state-$target_coverage_scenario" - case "$target_coverage_case" in - zero|multi) - run_resolver "$target_coverage_scenario" - expected_posts=0 - [[ "$target_coverage_case" != multi ]] || expected_posts=1 - [[ "$(resolver_posts "$target_coverage_scenario")" == "$expected_posts" ]] || { - echo "complete target job coverage selected the wrong gate: $target_coverage_case" >&2 - exit 1 - } - ;; - *) - if run_resolver "$target_coverage_scenario"; then - echo "resolver accepted invalid target job coverage: $target_coverage_case" >&2 - exit 1 - fi - [[ "$(resolver_posts "$target_coverage_scenario")" == 0 ]] || { - echo "invalid target job coverage admitted a POST: $target_coverage_case" >&2 - exit 1 - } - grep -Fq 'malformed or incomplete target jobs' "$tmp_dir/resolver-log-$target_coverage_scenario" || { - echo "invalid target job coverage did not fail at coverage validation: $target_coverage_case" >&2 - exit 1 - } - ;; - esac -done - -# A queued resolver cannot admit a target created after its own callback. -# The target's later callback remains eligible; no external receipt is needed. -for chronology_case in before-target missing-created invalid-created fresh-created; do - chronology_scenario="chronology-$chronology_case" - printf '{"scenario":"%s"}\n' "$chronology_scenario" >"$tmp_dir/resolver-state-$chronology_scenario" - run_resolver "$chronology_scenario" - [[ "$(resolver_posts "$chronology_scenario")" == 0 && "$(<"$tmp_dir/resolver-output-$chronology_scenario")" == 'accepted_job_ids=[]' ]] || { - echo "unproved target creation chronology admitted a POST: $chronology_case" >&2; exit 1; - } -done -[[ "$(jq '.target_reads' "$tmp_dir/resolver-state-chronology-fresh-created")" == 2 ]] || { - echo "target chronology was not rechecked immediately before admission" >&2; exit 1; -} -run_resolver chronology-before-target 200 no-local-workflow-file admit 9001 -[[ "$(resolver_posts chronology-before-target)" == 1 ]] || { - echo "target's later callback did not resolve a target refused by the earlier queued resolver" >&2; exit 1; -} - -# A denied or ambiguous publisher stays failed, but the non-cancelled guard -# exposes existing legacy recovery after independent original success. -for scenario in publisher-denied publisher-ambiguous publisher-cancelled publisher-unassessed; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" 200 pending-predecessor - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "publisher failure bypassed pending original proof: $scenario" >&2; exit 1; } - run_resolver "$scenario" - expected_posts=1 - [[ "$scenario" != publisher-cancelled && "$scenario" != publisher-unassessed ]] || expected_posts=0 - [[ "$(resolver_posts "$scenario")" == "$expected_posts" ]] || { echo "publisher legacy recovery violated native outcome: $scenario" >&2; exit 1; } -done - -run_resolver success -run_resolver success -[[ "$(resolver_posts success)" == 1 ]] || { echo "duplicate completion replayed a targeted rerun" >&2; exit 1; } -run_resolver metadata-last 200 -[[ "$(resolver_posts metadata-last)" == 1 ]] || { echo "metadata completion after original success was not resolved" >&2; exit 1; } -run_resolver metadata-first 200 pending-predecessor -[[ "$(resolver_posts metadata-first)" == 0 ]] || { echo "pending original admitted a rerun" >&2; exit 1; } -run_resolver metadata-first 100 pending-predecessor -[[ "$(resolver_posts metadata-first)" == 1 ]] || { echo "later original completion did not resolve metadata deferral" >&2; exit 1; } -for scenario in consumed fresh-changed fresh-base-branch fresh-head-repository ordinary-failure stale-pr wrong-tuple wrong-association malformed-path; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "resolver reran rejected target: $scenario" >&2; exit 1; } -done -for scenario in source-transient-row-count source-transient-missing-source source-empty-then-complete; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 && "$(resolver_source_listing_reads "$scenario")" == 2 && - "$(resolver_source_listing_waits "$scenario")" == '[1]' ]] || { - echo "valid incomplete source listing was not reread before admission: $scenario" >&2; exit 1; - } - grep -F "Exact-head source listing is incomplete (read 1/3):" "$tmp_dir/resolver-log-$scenario" >/dev/null || { - echo "source-list retry diagnostic was missing: $scenario" >&2; exit 1; - } -done -run_resolver source-third-read-complete -[[ "$(resolver_posts source-third-read-complete)" == 1 && - "$(resolver_source_listing_reads source-third-read-complete)" == 3 && - "$(resolver_source_listing_waits source-third-read-complete)" == '[1,2]' ]] || { - echo "third-read source recovery exceeded or bypassed the read/wait budget" >&2; exit 1; -} -if run_resolver source-incomplete-then-malformed; then - echo "source listing that became malformed did not fail closed" >&2; exit 1 -fi -[[ "$(resolver_posts source-incomplete-then-malformed)" == 0 && - "$(resolver_source_listing_reads source-incomplete-then-malformed)" == 2 && - "$(resolver_source_listing_waits source-incomplete-then-malformed)" == '[1]' ]] || { - echo "source listing retried after becoming malformed" >&2; exit 1; -} -grep -F 'Exact-head source coverage rejected: classification=malformed-row, total_count=1, returned_rows=1, source_present=false, limit=20.' \ - "$tmp_dir/resolver-log-source-incomplete-then-malformed" >/dev/null || { - echo "source listing that became malformed lost its classification" >&2; exit 1; -} -for scenario in source-persistent-incomplete source-empty-persistent; do - if run_resolver "$scenario"; then - echo "persistent exact-head source undercoverage did not fail closed: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 && "$(resolver_source_listing_reads "$scenario")" == 3 && - "$(resolver_source_listing_waits "$scenario")" == '[1,2]' ]] || { - echo "persistent source undercoverage exceeded or bypassed the read budget: $scenario" >&2; exit 1; - } -done -grep -F 'Exact-head source coverage remains incomplete after 3 reads: classification=incomplete-row-count, total_count=3, returned_rows=2, source_present=true, limit=20.' \ - "$tmp_dir/resolver-log-source-persistent-incomplete" >/dev/null || { - echo "persistent source undercoverage diagnostic did not report exact counts" >&2; exit 1; -} -grep -F 'Exact-head source coverage remains incomplete after 3 reads: classification=incomplete-missing-source, total_count=0, returned_rows=0, source_present=false, limit=20.' \ - "$tmp_dir/resolver-log-source-empty-persistent" >/dev/null || { - echo "persistent empty source listing was not reported as missing its event source" >&2; exit 1; -} -for scenario in source-malformed-schema source-identity-mismatch source-oversized source-malformed-row source-malformed-repository source-scalar-response source-array-response; do - if run_resolver "$scenario"; then - echo "malformed, misattributed, or over-limit source listing was accepted: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 && "$(resolver_source_listing_reads "$scenario")" == 1 && - "$(resolver_source_listing_waits "$scenario")" == '[]' ]] || { - echo "malformed, misattributed, or over-limit source listing was retried or admitted: $scenario" >&2; exit 1; - } - case "$scenario" in - source-malformed-schema) expected_diagnostic='classification=malformed-created-at, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-identity-mismatch) expected_diagnostic='classification=identity-mismatch, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-oversized) expected_diagnostic='classification=overflow-total-count, total_count=21, returned_rows=2, source_present=true, limit=20.' ;; - source-malformed-row) expected_diagnostic='classification=malformed-row, total_count=1, returned_rows=1, source_present=false, limit=20.' ;; - source-malformed-repository) expected_diagnostic='classification=malformed-row-repository, total_count=2, returned_rows=2, source_present=true, limit=20.' ;; - source-scalar-response|source-array-response) expected_diagnostic='classification=malformed-response, total_count=unknown, returned_rows=unknown, source_present=false, limit=20.' ;; - esac - grep -F "Exact-head source coverage rejected: $expected_diagnostic" "$tmp_dir/resolver-log-$scenario" >/dev/null || { - echo "source-list rejection omitted its cause or bounded numeric evidence: $scenario" >&2; exit 1; - } -done -run_resolver fork-empty 100 fork-empty-association -[[ "$(resolver_posts fork-empty)" == 1 ]] || { echo "resolver lost fork/empty-association attribution" >&2; exit 1; } -if run_resolver ambiguous-post; then - echo "ambiguous rerun POST did not fail closed" >&2 - exit 1 -fi -[[ "$(resolver_posts ambiguous-post)" == 1 ]] || { echo "ambiguous POST was replayed" >&2; exit 1; } -if run_resolver ambiguous-post; then - echo "a prior ambiguous admission with a still-visible attempt 1 did not require recovery" >&2 - exit 1 -fi -[[ "$(resolver_posts ambiguous-post)" == 1 ]] || { echo "later completion replayed an ambiguous POST" >&2; exit 1; } -if run_resolver same-id-rerun; then - echo "initial ambiguous same-ID admission did not fail closed" >&2; exit 1 -fi -jq '.resolver_attempt = 2' "$tmp_dir/resolver-state-same-id-rerun" >"$tmp_dir/resolver-state-update" -mv "$tmp_dir/resolver-state-update" "$tmp_dir/resolver-state-same-id-rerun" -if run_resolver same-id-rerun; then - echo "current resolver rerun hid its ambiguous first attempt" >&2; exit 1 -fi -[[ "$(resolver_posts same-id-rerun)" == 1 ]] || { echo "same-ID resolver rerun replayed admission" >&2; exit 1; } -for scenario in queued-callback queued-new-revision queued-equal pending-callback pending-new-revision pending-equal; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "later waiting callback poisoned current resolution: $scenario" >&2; exit 1; } - run_resolver "$scenario" 200 no-local-workflow-file admit 9001 - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "successor callback repeated consumed admission: $scenario" >&2; exit 1; } -done -run_resolver preflight 100 no-local-workflow-file preflight -[[ "$(resolver_posts preflight)" == 0 && "$(<"$tmp_dir/resolver-output-preflight")" == 'eligible=true' ]] || { - echo "preflight performed admission or lost native eligibility output" >&2; exit 1; -} -for scenario in prior-noop prior-cancelled-between-steps; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "clean skipped admission blocked resolution" >&2; exit 1; } -done -for scenario in prior-ambiguous prior-cancelled-admission prior-unavailable prior-incomplete prior-missing-step prior-oversized source-oversized prior-rerun-skipped prior-queued-old queued-equal-started queued-equal-missing queued-equal-malformed queued-equal-incomplete queued-equal-wrong-job pending-equal-started pending-equal-missing pending-equal-malformed pending-equal-incomplete pending-equal-wrong-job pending-equal-started-step pending-callback-started pending-callback-malformed pending-callback-attempt pending-callback-concluded prior-pending-old history-ambiguous-tail history-duplicate history-missing-current history-before-floor history-overcap history-incomplete history-missing-total history-malformed-total history-inconsistent-total history-malformed-page history-unavailable-page; do - if run_resolver "$scenario"; then - echo "unproved prior admission did not require recovery: $scenario" >&2; exit 1 - fi - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "unproved prior admission was replayed" >&2; exit 1; } -done -for scenario in history-multi history-ceiling; do - run_resolver "$scenario" - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "complete resolver history did not admit once: $scenario" >&2; exit 1; } - expected_pages=3 - [[ "$scenario" != history-ceiling ]] || expected_pages=10 - jq -e --argjson pages "$expected_pages" '.history_pages == [range(1; $pages + 1)]' \ - "$tmp_dir/resolver-state-$scenario" >/dev/null || { echo "resolver history pagination was incomplete: $scenario" >&2; exit 1; } -done -for scenario in prior-oversized history-overcap; do - [[ "$(jq '.history_pages | length' "$tmp_dir/resolver-state-$scenario")" == 1 ]] || { - echo "resolver fetched more history after observing the API ceiling: $scenario" >&2; exit 1; - } -done -[[ "$(jq '[.calls[] | select(endswith("/actions/runs/9001/attempts/1/jobs"))] | length' "$tmp_dir/resolver-state-prior-rerun-skipped")" == 0 ]] || { - echo "historical rerun relied on a latest skipped snapshot over its ambiguous first attempt" >&2; exit 1; -} -run_resolver admission-delayed -[[ "$(<"$tmp_dir/resolver-output-admission-delayed")" == 'accepted_job_ids=[2000]' ]] || { - echo "acknowledged POST did not publish its exact job ID" >&2; exit 1; -} -run_resolver admission-delayed 200 no-local-workflow-file admit 9001 -[[ "$(resolver_posts admission-delayed)" == 1 && "$(<"$tmp_dir/resolver-output-admission-delayed")" == 'accepted_job_ids=[]' ]] || { - echo "confirmed admission replayed while target attempt remained one" >&2; exit 1; -} -run_resolver admission-zero 200 pending-predecessor -[[ "$(resolver_posts admission-zero)" == 0 && "$(<"$tmp_dir/resolver-output-admission-zero")" == 'accepted_job_ids=[]' ]] || { - echo "successful zero-POST admission did not publish an empty set" >&2; exit 1; -} -run_resolver admission-zero 100 no-local-workflow-file admit 9001 -[[ "$(resolver_posts admission-zero)" == 1 ]] || { echo "confirmed zero-POST no-op poisoned later admission" >&2; exit 1; } -run_resolver admission-distinct -run_resolver admission-distinct 201 no-local-workflow-file admit 9001 -jq -e '.post_jobs == [2000,2001]' "$tmp_dir/resolver-state-admission-distinct" >/dev/null || { - echo "one acknowledged job blocked a distinct eligible gate or replayed itself" >&2; exit 1; -} -[[ "$(<"$tmp_dir/resolver-output-admission-distinct")" == 'accepted_job_ids=[2001]' ]] || { - echo "admission output included a previously acknowledged job" >&2; exit 1; -} -for scenario in admission-marker-failed admission-marker-cancelled admission-marker-incomplete admission-marker-missing admission-marker-malformed admission-marker-duplicate-ids admission-marker-string-id admission-marker-oversized admission-marker-duplicate-step; do - run_resolver "$scenario" - if run_resolver "$scenario" 200 no-local-workflow-file admit 9001; then - echo "uncertain native confirmation allowed a later admission: $scenario" >&2; exit 1; - fi - [[ "$(resolver_posts "$scenario")" == 1 ]] || { echo "uncertain confirmation replayed a POST: $scenario" >&2; exit 1; } -done -if run_resolver partial-admission; then - echo "partial admission did not fail closed" >&2; exit 1; -fi -if run_resolver partial-admission 200 no-local-workflow-file admit 9001; then - echo "partial admission did not require explicit recovery" >&2; exit 1; -fi -[[ "$(resolver_posts partial-admission)" == 2 ]] || { echo "partial admission replayed a POST" >&2; exit 1; } -run_resolver cancelled-pending-zero -[[ "$(resolver_posts cancelled-pending-zero)" == 1 ]] || { echo "cancelled-before-start zero-job callback blocked admission" >&2; exit 1; } -for scenario in cancelled-pending-nonempty cancelled-pending-incomplete cancelled-pending-malformed cancelled-pending-missing cancelled-pending-unknown cancelled-pending-rerun cancelled-pending-started; do - if run_resolver "$scenario"; then - echo "uncertain cancelled callback was treated as never admitted: $scenario" >&2; exit 1; - fi - [[ "$(resolver_posts "$scenario")" == 0 ]] || { echo "uncertain cancelled callback admitted a POST: $scenario" >&2; exit 1; } -done -if run_resolver original-failure 100 failed-predecessor; then - echo "resolver accepted failed original proof" >&2 - exit 1 -fi -[[ "$(resolver_posts original-failure)" == 0 ]] || { echo "failed original admitted a rerun" >&2; exit 1; } - -# History starts at the earliest frozen eligible target, including ties. Old -# substantive evidence and unrelated earlier traffic do not widen that window. -for scenario in window-old-source window-boundary-admitted window-boundary-ambiguous window-final-admitted window-final-ambiguous window-source-expiry window-ties window-new-target; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - source_id=100 - [[ "$scenario" != window-source-expiry ]] || source_id=200 - if [[ "$scenario" == *ambiguous ]]; then - if run_resolver "$scenario" "$source_id"; then - echo "target-boundary ambiguous admission was ignored: $scenario" >&2; exit 1 - fi - else - run_resolver "$scenario" "$source_id" - fi - python3 - "$tmp_dir/resolver-state-$scenario" "$scenario" <<'PY_WINDOW' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[2] -assert state["history_floor"] == "2026-07-30T02:00:00Z" -expected = [2000] if scenario in {"window-old-source", "window-new-target"} else [2001] if scenario == "window-ties" else [] -assert state.get("post_jobs", []) == expected, (scenario, state) -if "final" in scenario: - assert state["history_pages"] == [1, 2, 3], state -if scenario == "window-new-target": - assert state["target_reads_by_id"]["201"] == 1, state -PY_WINDOW -done -# Ineligible or consumed targets need neither history nor recovery inference. -for scenario in ordinary-failure consumed chronology-missing-created chronology-invalid-created; do - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/resolver-state-$scenario" - run_resolver "$scenario" - python3 - "$tmp_dir/resolver-state-$scenario" <<'PY_WINDOW' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert not state.get("history_pages") and not state.get("posts"), state -PY_WINDOW -done - -echo "PR required-gate context contract checks passed" - -# Activated callers preserve native proof and require acknowledged pending barriers. -PUBLISH_SCRIPT="$ROOT_DIR/.github/actions/publish-required-gate-status/publish-required-gate-status.sh" -python3 - "$ROOT_DIR" <<'PY_PUBLISH' -from pathlib import Path -import os -import subprocess -import sys -import yaml -root = Path(sys.argv[1]) -action = yaml.load((root / ".github/actions/publish-required-gate-status/action.yml").read_text(), Loader=yaml.BaseLoader) -assert set(action["inputs"]) == {"assessment", "gate-name", "workflow-name", "workflow-file", "workflow-path"} -assert all(value["required"] == "true" for value in action["inputs"].values()) -assert action["outputs"]["publication"]["value"] == "${{ steps.publish.outputs.publication }}" -callers = ( - ("ci.yml", "validation-gate", "Validation Gate", "CI — Validation"), - ("security.yml", "security-gate", "Security Gate", "Security Gate"), - ("codeql.yml", "codeql-gate", "CodeQL Gate", "CodeQL Analysis"), - ("license-scan.yml", "license-gate", "License Gate", "License Gate"), - ("smoke.yml", "smoke-gate", "Smoke Gate", "PR Smoke Gate"), -) -for filename, job_id, gate, workflow_name in callers: - data = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) - job = data["jobs"][job_id] - assert job["permissions"] == {"contents": "read", "checks": "read", "actions": "read", "pull-requests": "read", "statuses": "write"} - # The new write permission is confined to the required gate job. - assert "statuses" not in data.get("permissions", {}) - assert all("statuses" not in value.get("permissions", {}) for key, value in data["jobs"].items() if key != job_id) - steps = job["steps"] - preserve = next(step for step in steps if step.get("id") == "preserved_gate") - publishers = [step for step in steps if step.get("uses") == "./.github/actions/publish-required-gate-status"] - assert len(publishers) == 1 - publisher = publishers[0] - assert publisher["name"] == "Publish pending required gate status" - assert publisher["id"] == "publish-pending-status" - assert publisher["if"] == preserve["if"] - assert publisher["with"] == { - "assessment": "${{ steps.preserved_gate.outputs.assessment }}", "gate-name": gate, - "workflow-name": workflow_name, "workflow-file": filename, "workflow-path": f".github/workflows/{filename}", - } - guard = next(step for step in steps if step.get("name") == "Report dependency-deferred required gate") - assert guard["if"] == preserve["if"].replace("${{ ", "${{ !cancelled() && ", 1) - assert guard["env"] == {"PUBLISHER_OUTCOME": "${{ steps.publish-pending-status.outcome }}", "ASSESSMENT": "${{ steps.preserved_gate.outputs.assessment }}", "PUBLICATION": "${{ steps.publish-pending-status.outputs.publication }}"} - assert steps.index(publisher) == steps.index(preserve) + 1 - assert steps.index(guard) == steps.index(publisher) + 1 - assert not any("continue-on-error" in step for step in (preserve, publisher, guard)) - # Execute each actual caller guard: only these complete outcome pairs pass. - allowed = {("dependency-deferred", "pending-acknowledged"), ("success", "unchanged"), - ("success", "success-acknowledged"), ("success", "pending-acknowledged")} - for outcome in ("success", "failure", "skipped", "cancelled", ""): - for assessment in ("dependency-deferred", "success", "failure", "", "unknown"): - for publication in ("pending-acknowledged", "success-acknowledged", "unchanged", "", "unknown"): - result = subprocess.run(["bash", "-e", "-c", guard["run"]], - env={**os.environ, "PUBLISHER_OUTCOME": outcome, "ASSESSMENT": assessment, "PUBLICATION": publication}, - capture_output=True, text=True, check=False) - expected = 0 if outcome == "success" and (assessment, publication) in allowed else 1 - assert result.returncode == expected, (filename, outcome, assessment, publication, result) - -PY_PUBLISH -mkdir "$tmp_dir/producer-bin" -cat >"$tmp_dir/producer-bin/gh" <<'EOF_PRODUCER_GH' -#!/usr/bin/env bash -set -euo pipefail -if [[ "${GITHUB_OUTPUT}" != "${PRODUCER_OUTPUT_PATH}" ]]; then - exec "${MOCK_ORIGINAL_GH}" "$@" -fi -python3 - "$@" <<'PY_PRODUCER_GH' -import json -import os -from pathlib import Path -import sys -args = sys.argv[1:] -state_path = Path(os.environ["PRODUCER_STATE"]) -state = json.loads(state_path.read_text()) -scenario = state["scenario"] -method = args[args.index("--method") + 1] -endpoint = next(arg for arg in args if arg.startswith("/repos/")) -head, base, old_base = "a" * 40, "b" * 40, "c" * 40 -repo = "example/firemud" -head_repo = "fork-owner/firemud" if scenario == "deferred-fork" else repo -current_attempt = 2 if scenario == "deferred-owned-earlier-attempt" else 1 -api_url = f"https://api.github.com/repos/{repo}/statuses/{head}" -run_url = f"https://github.com/{repo}/actions/runs/" -creator = {"id": 41898282, "login": "github-actions[bot]", "type": "Bot"} -state.setdefault("calls", []).append(f"{method} {endpoint}") - -def rich_history_case(scenario, barrier, page): - # Native GET /statuses/ is a newest-first array with creator; the - # combined projection above has the same IDs but deliberately no creator. - case = scenario.removeprefix("bridge-").removeprefix("history-") - older = {**barrier, "id": 499, "created_at": "2026-10-14T00:00:00Z", - "creator": {"id": 99, "login": "foreign", "type": "User"}} - unrelated = [{**barrier, "id": 1000 + (page - 1) * 100 + index, "context": f"other-{page}-{index}", - "created_at": "2026-10-15T01:00:00Z"} for index in range(100)] - if case == "latest-owned": return [barrier, older] - if case == "latest-foreign": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"]}] - if case == "null-actor": return [{**barrier, "creator": None}] - if case == "missing-actor": return [{key: value for key, value in barrier.items() if key != "creator"}] - if case == "unknown-state": return [{**barrier, "state": "unknown"}] - if case == "page-two-owned": return unrelated if page == 1 else [barrier, older] - if case == "page-two-absent": return unrelated if page == 1 else [] - if case == "budget": return unrelated - if case == "unavailable-page": - if page == 1: return unrelated - raise RuntimeError("status page unavailable") - if case == "duplicate-page": return unrelated if page == 1 else [{**unrelated[0], "id": 1000}] - if case == "wrong-head-url": return [{**barrier, "url": barrier["url"].replace("a" * 40, "b" * 40)}] - if case == "same-second": return [barrier, {**older, "created_at": barrier["created_at"]}] - if case == "foreign-same-second": return [{**barrier, "creator": older["creator"]}, {**older, "creator": barrier["creator"], "created_at": barrier["created_at"]}] - if case == "first-page-stop": - if page != 1: raise RuntimeError("older pages must not be read") - return [barrier] + unrelated[:99] - if case == "ignore-old-malformed": return [barrier, "bad"] - if case == "overfull": return unrelated + [barrier] - if case == "scalar": return "bad" - if case == "malformed-row": return ["bad"] - raise AssertionError(case) - -result = None -exit_status = 0 -if method == "POST": - assert endpoint == f"/repos/{repo}/statuses/{head}", endpoint - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - state.setdefault("posts", []).append(fields) - result = {"id": 501, "url": api_url, "creator": creator, - "state": fields["state"], "context": fields["context"], "target_url": fields["target_url"], - "created_at": "2026-10-15T00:00:00Z", "updated_at": "2026-10-15T00:00:00Z"} - # Deliberately no sha/app_id: those fields do not exist in native statuses. - if scenario in {"ack-denied", "ack-ambiguous"}: - exit_status = 1 - elif scenario == "ack-wrong-url": - result["url"] = api_url.replace(head, base) - elif scenario == "ack-missing-creator": - result.pop("creator") - elif scenario == "ack-missing-id": - result.pop("id") - elif scenario == "ack-bad-timestamp": - result["created_at"] = "unknown" - elif scenario == "ack-wrong-state": - result["state"] = "success" -elif endpoint.endswith("/actions/workflows/ci.yml"): - result = {"id": 42, "name": "CI — Validation", "path": ".github/workflows/ci.yml"} -elif endpoint.endswith("/pulls/123"): - state["pr_reads"] = state.get("pr_reads", 0) + 1 - result = {"number": 123, "state": "open", "base": {"sha": base, "ref": "develop", "repo": {"full_name": repo}}, - "head": {"sha": head, "ref": "proof-branch", "repo": {"full_name": head_repo}}} - if scenario in {"tuple-replaced", "durable-tuple-replaced"} and state["pr_reads"] > 1: - result["base"]["sha"] = old_base -elif endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/statuses/{head}"): - state["status_reads"] = state.get("status_reads", 0) + 1 - barrier_state = "pending" - if scenario in {"deferred-owned-failure", "success-owned-failure"}: - barrier_state = "failure" - elif scenario in {"deferred-owned-error", "success-owned-error"}: - barrier_state = "error" - elif scenario in {"deferred-owned-success", "success-owned-success"}: - barrier_state = "success" - barrier = {"id": 500, "url": api_url, "created_at": "2026-10-15T00:00:00Z", "context": "Validation Gate", "state": barrier_state, - "target_url": f"{run_url}{300 if current_attempt == 2 else 200}/attempts/1", "creator": creator} - if scenario.endswith("foreign"): - barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} - if scenario == "status-replaced" and state["status_reads"] > 1: - barrier["id"] = 999 - if scenario == "durable-status-replaced" and state["status_reads"] > 1: - barrier["id"] = 999 - if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"}: - barrier["target_url"] = f"{run_url}200/attempts/1" - if scenario == "status-arrived-current-foreign": - barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} - absent = scenario in {"deferred-absent", "deferred-fork", "success-absent"} or scenario.startswith("ack-") or scenario.startswith("current-") - rich = [] if absent else [barrier] - if scenario in {"status-arrived-current-pending", "status-arrived-stale-pending", "status-arrived-current-foreign"} and state["status_reads"] == 1: - rich = [] - combined = {"sha": head, "total_count": len(rich), "statuses": [{key: value for key, value in row.items() if key != "creator"} for row in rich]} - assert all("creator" not in row for row in combined["statuses"]) - if endpoint.endswith("/status"): - result = combined # Actual combined projection deliberately omits creator. - else: - fields = dict(arg.split("=", 1) for arg in args if "=" in arg) - assert fields["per_page"] == "100" and "--paginate" not in args - page = int(fields["page"]) - state.setdefault("status_pages", []).append(page) - result = rich - if scenario.startswith("history-"): - try: - result = rich_history_case(scenario, barrier, page) - except RuntimeError: - result = None - exit_status = 1 - if scenario == "incomplete-status": - result = combined # Wrong endpoint shape must never qualify. -elif "/actions/runs/" in endpoint and not endpoint.endswith("/jobs"): - historical = "/attempts/" in endpoint - run_id = int(endpoint.split("/")[-3] if historical else endpoint.rsplit("/", 1)[1]) - assert run_id in {200, 300}, endpoint - old = historical - attempt = int(endpoint.rsplit("/", 1)[1]) if historical else current_attempt - running = not old or scenario == "deferred-owned-running" - run_base = base if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"} else old_base if run_id == 200 else base - result = {"id": run_id, "run_attempt": attempt, "run_number": 2 if run_id == 200 else 3, "workflow_id": 42, "event": "pull_request", - "repository": {"full_name": repo}, "head_repository": {"full_name": head_repo}, - "head_sha": head, "head_branch": "proof-branch", "name": "CI — Validation", - "path": ".github/workflows/ci.yml", "pull_requests": [], - "display_title": f"CI — Validation pr-123 base-{run_base} head-{head}", - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success"} - if old and scenario == "deferred-owned-newer": - result["run_number"] = 4 - if old and scenario == "deferred-old-equal-number": - result["run_number"] = 3 - if old and scenario == "deferred-old-missing-number": - result.pop("run_number") - if old and scenario == "deferred-old-wrong-title": - result["display_title"] = result["display_title"].replace("pr-123", "pr-456") - if not old and scenario == "current-wrong-tuple": - result["head_sha"] = old_base -elif endpoint.endswith("/jobs"): - run_id = int(endpoint.split("/")[-4]) - attempt = int(endpoint.split("/")[-2]) - old = run_id == 200 or (current_attempt == 2 and attempt == 1) - running = not old or scenario == "deferred-owned-running" - native_id = run_id * 10 + attempt if current_attempt == 2 else run_id * 10 - publisher = {"name": "Publish pending required gate status", "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "skipped" if scenario == "deferred-old-skipped" else "success"} - steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "success"}, publisher] - if old and running: - steps = [publisher] - if not old and scenario == "durable-current-missing-publisher": - steps = steps[:1] - job = {"id": native_id, "run_id": run_id, "name": "Validation Gate", "head_sha": head, - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", - "check_run_url": f"https://api.github.com/repos/{repo}/check-runs/{native_id}", "steps": steps} - result = {"total_count": 1, "jobs": [job]} - if scenario == "current-incomplete-jobs" and not old: - result["total_count"] = 2 -elif "/check-runs/" in endpoint: - check_id = int(endpoint.rsplit("/", 1)[1]) - old = check_id == 2000 or (current_attempt == 2 and check_id == 3001) - running = not old or scenario == "deferred-owned-running" - result = {"id": check_id, "name": "Validation Gate", "head_sha": head, - "status": "in_progress" if running else "completed", - "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", - "app": {"id": 99 if scenario == "deferred-old-wrong-app" or (not old and scenario in {"current-wrong-app", "durable-current-wrong-app"}) else 15368, "slug": "github-actions"}} -else: - raise AssertionError(endpoint) -state_path.write_text(json.dumps(state)) -if result is not None: - print(json.dumps(result)) - if scenario == "ack-multiple" and method == "POST": - print(json.dumps(result)) -sys.exit(exit_status) -PY_PRODUCER_GH -EOF_PRODUCER_GH -chmod +x "$tmp_dir/producer-bin/gh" -run_producer() { - local scenario="$1" assessment="$2" original="${3:-no-local-workflow-file}" - local event_file="$tmp_dir/producer-event-$scenario" head_repository=example/firemud current_attempt=1 - [[ "$scenario" != deferred-owned-earlier-attempt ]] || current_attempt=2 - [[ "$scenario" != deferred-fork ]] || head_repository=fork-owner/firemud - jq -n --arg head_repo "$head_repository" '{action: "edited", number: 123, repository: {full_name: "example/firemud"}, changes: {title: {from: "old"}}, - pull_request: {number: 123, base: {sha: ("b" * 40), ref: "develop", repo: {full_name: "example/firemud"}}, - head: {sha: ("a" * 40), ref: "proof-branch", repo: {full_name: $head_repo}}}}' >"$event_file" - printf '{"scenario":"%s"}\n' "$scenario" >"$tmp_dir/producer-state-$scenario" - : >"$tmp_dir/producer-output-$scenario" - PATH="$tmp_dir/producer-bin:$PATH" GH_TOKEN=test-token GITHUB_REPOSITORY=example/firemud \ - GITHUB_EVENT_NAME=pull_request GITHUB_EVENT_PATH="$event_file" GITHUB_RUN_ID=300 GITHUB_RUN_ATTEMPT="$current_attempt" \ - GITHUB_OUTPUT="$tmp_dir/producer-output-$scenario" PRODUCER_OUTPUT_PATH="$tmp_dir/producer-output-$scenario" \ - PRODUCER_STATE="$tmp_dir/producer-state-$scenario" MOCK_ORIGINAL_GH="$tmp_dir/gh" \ - GH_SCENARIO="$original" GH_FAILURE_MODE=none GH_RETRY_COUNT_FILE="$tmp_dir/producer-proof-count-$scenario" \ - BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - PR_NUMBER=123 ASSESSMENT="$assessment" REQUIRED_GATE_NAME='Validation Gate' EXPECTED_WORKFLOW_NAME='CI — Validation' \ - EXPECTED_WORKFLOW_FILE=ci.yml EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml \ - bash "$PUBLISH_SCRIPT" >"$tmp_dir/producer-log-$scenario" 2>&1 -} -for scenario in deferred-absent deferred-fork deferred-owned-pending deferred-owned-current-pending deferred-owned-earlier-attempt deferred-owned-newer deferred-old-equal-number deferred-old-missing-number deferred-owned-failure deferred-owned-error deferred-owned-success deferred-owned-running deferred-owned-cancelled deferred-owned-step-failed success-owned-pending success-owned-failure success-owned-error success-assessment-pending status-replaced status-arrived-current-pending status-arrived-stale-pending status-arrived-current-foreign tuple-replaced durable-tuple-replaced durable-status-replaced deferred-foreign deferred-old-wrong-app deferred-old-wrong-title deferred-old-skipped success-absent success-owned-success success-foreign; do - assessment=dependency-deferred - [[ "$scenario" != success-* ]] || assessment=success - original=no-local-workflow-file - [[ "$scenario" != success-assessment-pending ]] || original=pending-predecessor - if ! run_producer "$scenario" "$assessment" "$original"; then - cat "$tmp_dir/producer-log-$scenario" >&2; exit 1 - fi - python3 - "$tmp_dir/producer-state-$scenario" "$tmp_dir/producer-output-$scenario" "$scenario" <<'PY_PUBLISH' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -scenario = sys.argv[3] -unchanged = scenario in {"status-replaced", "status-arrived-stale-pending", "status-arrived-current-foreign", "tuple-replaced", "durable-tuple-replaced", "durable-status-replaced", "deferred-owned-newer", "deferred-old-equal-number", "deferred-old-missing-number", "deferred-foreign", "deferred-old-wrong-app", "deferred-old-wrong-title", "deferred-old-skipped", "success-absent", "success-owned-success", "success-foreign"} -expected = "unchanged" if unchanged else "success-acknowledged" if scenario in {"success-owned-pending", "success-owned-failure", "success-owned-error"} else "pending-acknowledged" -assert Path(sys.argv[2]).read_text().strip() == f"publication={expected}", (scenario, state) -already_durable = scenario in {"deferred-owned-current-pending", "deferred-owned-earlier-attempt", "status-arrived-current-pending"} -assert len(state.get("posts", [])) == (0 if unchanged or already_durable else 1), state -if not unchanged and not already_durable: - assert state["posts"][0]["target_url"] == f"https://github.com/example/firemud/actions/runs/300/attempts/{2 if scenario == 'deferred-owned-earlier-attempt' else 1}", state - assert state["posts"][0]["state"] == expected.split("-")[0], state -PY_PUBLISH -done -# Refreshed cancellation-only proof must acknowledge a pending status, even -# when the caller originally assessed success. It never acknowledges success. -run_producer success-assessment-pending success cancellation-pending -[[ "$(<"$tmp_dir/producer-output-success-assessment-pending")" == publication=pending-acknowledged ]] || exit 1 -[[ "$(jq -r '.posts[0].state' "$tmp_dir/producer-state-success-assessment-pending")" == pending ]] || exit 1 - -for history_case in latest-owned latest-foreign null-actor missing-actor unknown-state page-two-owned page-two-absent budget unavailable-page duplicate-page wrong-head-url same-second foreign-same-second first-page-stop ignore-old-malformed overfull scalar malformed-row; do - scenario="history-$history_case" - case "$history_case" in - budget|unavailable-page|duplicate-page|wrong-head-url|overfull|scalar|malformed-row) - if run_producer "$scenario" success; then - echo "invalid rich producer history qualified: $history_case" >&2; exit 1 - fi ;; - *) run_producer "$scenario" success ;; - esac - python3 - "$tmp_dir/producer-state-$scenario" "$tmp_dir/producer-output-$scenario" "$history_case" <<'PY_HISTORY' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -case = sys.argv[3] -expected = "success-acknowledged" if case in {"latest-owned", "page-two-owned", "same-second", "first-page-stop", "ignore-old-malformed"} else "unchanged" if case in {"latest-foreign", "foreign-same-second", "null-actor", "missing-actor", "unknown-state", "page-two-absent"} else None -assert Path(sys.argv[2]).read_text().strip() == (f"publication={expected}" if expected else ""), state -assert len(state.get("posts", [])) == (1 if expected == "success-acknowledged" else 0), state -assert not any("/commits/" in call and call.endswith("/status") for call in state["calls"]), state -if case.startswith("page-two-"): assert 2 in state["status_pages"], state -if case == "first-page-stop": assert all(page == 1 for page in state["status_pages"]), state -if case == "budget": assert state["status_pages"] == list(range(1, 11)), state -PY_HISTORY -done - -for scenario in success-assessment-failed incomplete-status current-wrong-app current-wrong-tuple current-incomplete-jobs durable-current-wrong-app durable-current-missing-publisher ack-denied ack-ambiguous ack-wrong-url ack-missing-creator ack-missing-id ack-bad-timestamp ack-wrong-state ack-multiple; do - assessment=dependency-deferred - original=no-local-workflow-file - if [[ "$scenario" == success-assessment-failed ]]; then assessment=success; original=failed-predecessor; fi - if run_producer "$scenario" "$assessment" "$original"; then - echo "invalid publication succeeded: $scenario" >&2; exit 1 - fi - [[ ! -s "$tmp_dir/producer-output-$scenario" ]] || { echo "failed publication emitted native-success allowance" >&2; exit 1; } - python3 - "$tmp_dir/producer-state-$scenario" "$scenario" <<'PY_PUBLISH' -import json -from pathlib import Path -import sys -state = json.loads(Path(sys.argv[1]).read_text()) -assert len(state.get("posts", [])) == (1 if sys.argv[2].startswith("ack-") else 0), state -PY_PUBLISH -done - -echo "Required-gate status producer contract checks passed" - # Exercise the temporary failed-producer verifier separately: passing producer # proof above is unchanged and remains the only runtime qualification path. node - "$smoke_clock_fixture" "$ROOT_DIR/.github/workflows/smoke.yml" <<'NODE' diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index b47d12f249..1aac58fb7a 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -362,7 +362,7 @@ for filename in ("ci.yml", "security.yml", "license-scan.yml", "codeql.yml"): expected_events.add("schedule") if events["schedule"] != [{"cron": "0 0 * * 0"}]: raise SystemExit("CodeQL must retain its weekly full-analysis schedule") - if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' }}": + if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}": raise SystemExit("CodeQL Gate must cover every PR base and remain PR-only") if set(events) != expected_events: raise SystemExit(f"{filename} must retain exactly its supported events") @@ -552,9 +552,11 @@ PYTHON # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. assert_job_contains security.yml security-summary "name: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Security Summary)' || 'Security Summary' }}" assert_job_contains smoke.yml smoke-summary "name: \${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Summary)' || 'Smoke Summary' }}" -# A metadata-only edit must retain the required gate name. Its preservation -# action verifies prior proof before reporting success for the unchanged tuple. -assert_job_contains smoke.yml smoke-gate 'name: Smoke Gate' +# A metadata-only edit skips the required gate under a non-required name so the +# earlier substantive result stands; pr-required-gate-context-contract.sh owns +# the full gate-condition matrix. +# shellcheck disable=SC2016 # Assert literal GitHub expression syntax. +assert_job_contains smoke.yml smoke-gate "name: \${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }}" assert_job_contains smoke.yml smoke-summary-pending 'name: Smoke Summary (Pending)' assert_job_contains smoke.yml smoke-summary-pending 'tracked-by-smoke-gate' assert_job_contains smoke.yml smoke-summary 'needs: [changes, smoke-gate, smoke-summary-pending]' @@ -648,8 +650,8 @@ assert "branches" not in runtime["on"]["workflow_run"] PYTHON # Reproduce the metadata-edit sequence structurally: the edit has its own -# concurrency namespace, all runtime construction jobs remain skipped, and no -# dispatch-capable step exists in Smoke Gate. The original event tuple remains +# concurrency namespace, all runtime construction jobs remain skipped, and Smoke +# Gate skips under a non-required name. The original event tuple remains # valid for merge gating while trusted image publication and preview continue # to require current-base provenance. python3 - "$smoke_path" "$runtime_images_path" <<'PY' @@ -663,8 +665,11 @@ smoke_path, runtime_path = map(Path, sys.argv[1:]) smoke = yaml.load(smoke_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) runtime = yaml.load(runtime_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) -if smoke["jobs"]["smoke-gate"].get("name") != "Smoke Gate": - raise SystemExit("metadata-only smoke must retain its required gate context") +if smoke["jobs"]["smoke-gate"].get("name") != ( + "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && " + "github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }}" +): + raise SystemExit("metadata-only smoke must skip under a non-required name and keep Smoke Gate otherwise") runtime_jobs = runtime["jobs"] metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" @@ -934,7 +939,6 @@ async function runDispatcher({ 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" }, ], ...(ciEvidence.gate ?? {}), @@ -1124,14 +1128,12 @@ async function runDispatcher({ const emptyBranch = await runDispatcher({ tuples: [child], callback: { ...prCallback, head_branch: "" } }); assert.equal(emptyBranch.dispatches.length, 0); assert.equal(emptyBranch.refRequests.length, 0, "empty callback branch must be rejected before ref lookup"); - const preservationStep = { name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: "skipped" }; const enforcementStep = { name: "Enforce validation success", status: "completed", conclusion: "success" }; for (const [label, ciEvidence] of [ - ["metadata preservation executed", { gate: { steps: [{ ...preservationStep, conclusion: "success" }, { ...enforcementStep, conclusion: "skipped" }] } }], - ["failed metadata preservation", { gate: { steps: [{ ...preservationStep, conclusion: "failure" }, { ...enforcementStep, conclusion: "skipped" }] } }], - ["missing preservation", { gate: { steps: [enforcementStep] } }], - ["ambiguous preservation", { gate: { steps: [preservationStep, preservationStep, enforcementStep] } }], - ["skipped enforcement", { gate: { steps: [preservationStep, { ...enforcementStep, conclusion: "skipped" }] } }], + ["metadata-only edit gate", { gate: { name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: [] } }], + ["legacy metadata gate with skipped enforcement", { gate: { steps: [{ ...enforcementStep, conclusion: "skipped" }] } }], + ["missing enforcement", { gate: { steps: [] } }], + ["ambiguous enforcement", { gate: { steps: [enforcementStep, enforcementStep] } }], ["old native attempt job", { gate: { run_attempt: 2 } }], ["wrong native job run", { gate: { run_id: 7002 } }], ["wrong native job head", { gate: { head_sha: sha("f") } }], @@ -1151,7 +1153,7 @@ async function runDispatcher({ } const failedSubstantive = await runDispatcher({ tuples: [child], sourceTuples: [source], callback: { ...prCallback, conclusion: "failure" }, - ciEvidence: { gate: { conclusion: "failure", steps: [preservationStep, { ...enforcementStep, conclusion: "failure" }] } }, + ciEvidence: { gate: { conclusion: "failure", steps: [{ ...enforcementStep, conclusion: "failure" }] } }, }); assert.equal(runtimeDispatches(failedSubstantive).length, 2, "failed substantive CI remains a reconcile signal requiring each source/child's independent runtime smoke"); @@ -2383,21 +2385,17 @@ require_ordered_sequence \ 'if (fullSmokeJob?.conclusion !== "success") {' \ 'PR Full-Stack Smoke job did not complete successfully:' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -require_contains "$smoke_path" 'SMOKE_GATE_REQUIRED: ${{ github.event.action != '\''edited'\'' || github.event.changes.base.ref != null }}' -# shellcheck disable=SC2016 # Assert literal GitHub expression syntax. require_contains "$smoke_path" 'CHANGES_RESULT: ${{ needs.changes.result }}' # shellcheck disable=SC2016 # Assert literal shell source. -require_contains "$smoke_path" 'echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT"' -# shellcheck disable=SC2016 # Assert literal shell source. -require_contains "$smoke_path" 'if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then' +require_contains "$smoke_path" 'if [ "$CHANGES_RESULT" = "success" ]; then' # shellcheck disable=SC2016 # Assert literal shell source. require_contains "$smoke_path" 'echo "execute=true" >> "$GITHUB_OUTPUT"' # shellcheck disable=SC2016 # Assert literal shell source. require_contains "$smoke_path" 'echo "execute=false" >> "$GITHUB_OUTPUT"' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -require_contains "$smoke_path" 'if: ${{ steps.smoke_gate_context.outputs.required == '\''true'\'' && steps.smoke_gate_context.outputs.execute != '\''true'\'' }}' +require_contains "$smoke_path" 'if: ${{ steps.smoke_gate_context.outputs.execute != '\''true'\'' }}' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -if grep -Fq 'echo "required=${{' "$smoke_path" || grep -Fq 'echo "execute=${{' "$smoke_path"; then +if grep -Fq 'echo "execute=${{' "$smoke_path"; then echo "smoke_gate_context must pass expressions through step env" >&2 exit 1 fi diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index fb98491bc3..4ff857b43d 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -15,8 +15,8 @@ if ! awk ' fi grep -Fq 'github.paginate(github.rest.actions.listWorkflowRuns' "$workflow" -grep -Fq 'workflowRunFor("codeql.yml")' "$workflow" -grep -Fq 'workflowRunFor("license-scan.yml")' "$workflow" +grep -Fq 'workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns)' "$workflow" +grep -Fq 'workflowRunFor("license-scan.yml", "License Gate", checkRuns)' "$workflow" grep -Fq 'head_sha: headSha,' "$workflow" grep -Fq 'return "skipped";' "$workflow" grep -Fq 'run_attempt' "$workflow" @@ -137,6 +137,18 @@ const github = { status: "completed", conclusion: "failure", }, + { + // A later metadata-only edit run: its gate is skipped under a + // non-required name and must not mask the substantive failure. + id: 270, + event: "pull_request", + head_sha: headSha, + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + created_at: "2026-09-20T12:00:00Z", + run_attempt: 1, + status: "completed", + conclusion: "success", + }, { id: 250, event: "pull_request", @@ -183,6 +195,15 @@ const github = { completed_at: "2026-09-19T00:02:00Z", details_url: "https://github.example/actions/runs/100/job/1001", }, + { + id: 2701, + name: "PR Metadata Edit (CodeQL Gate)", + status: "completed", + conclusion: "skipped", + created_at: "2026-09-20T12:00:01Z", + completed_at: "2026-09-20T12:00:01Z", + details_url: "https://github.example/actions/runs/270/job/2701", + }, { id: 2001, name: "CodeQL Gate", From 5847cb149cb4a2ed72447903b17e00a8e6474091 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:26:14 +1300 Subject: [PATCH 040/199] Match native skipped-job names when excluding metadata runs GitHub leaves a skipped job's name expression unevaluated, so the metadata gate check run carries the expression text rather than the evaluated 'PR Metadata Edit (...)' label. Match the label inside the name. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/static-analysis-summary.yml | 4 +++- design/architecture/system-architecture-cicd.md | 4 ++-- dev-tools/tests/static-analysis-summary-contract.sh | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 3efcb75a9e..23dbb56c22 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -133,10 +133,12 @@ jobs: // Metadata-only edits skip their gate under a non-required name; the // earlier substantive run for the same title remains the result. + // GitHub leaves a skipped job's name expression unevaluated, so match + // the metadata label inside it. const workflowRunFor = async (workflowId, gateName, checkRuns) => { const workflowName = workflowId === "codeql.yml" ? "CodeQL Analysis" : "License Gate"; const metadataRunIds = new Set((Array.isArray(checkRuns) ? checkRuns : []) - .filter((checkRun) => checkRun?.name === `PR Metadata Edit (${gateName})`) + .filter((checkRun) => String(checkRun?.name || "").includes(`'PR Metadata Edit (${gateName})'`)) .map(checkRunWorkflowId) .filter(Boolean)); const expectedTitle = `${workflowName} pr-${issueNumber} base-${baseSha} head-${headSha}`; diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index bc350ac3fd..07f170384e 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -36,9 +36,9 @@ The manual [Game Session factory inventory qualification workflow](../../.github The Validation, Security, CodeQL, License, and Smoke gates keep their exact branch-protection names for every substantive pull-request event: open, new commits, reopen, and a base-branch change. Their workflows still listen to `edited`, because GitHub reports a retarget as an `edited` event and cannot filter it by field before starting a run. -A metadata-only edit is an `edited` event whose `changes.base` is absent, such as a title or description change. On that event every job in the five workflows is skipped, and each gate job is skipped under a non-required name, `PR Metadata Edit ()`. The edit therefore produces no check run under a required name, so the latest required check run for the head stays the earlier substantive result. A failing or pending gate stays failing or pending, and an edit cannot turn a pull request green. A skipped job under a required name would count as passing, which is why the gate must never skip under its required name. +A metadata-only edit is an `edited` event whose `changes.base` is absent, such as a title or description change. On that event every job in the five workflows is skipped, and each gate job is skipped under a non-required name. The name expression selects `PR Metadata Edit ()`; GitHub does not evaluate a skipped job's name, so the check run shows the whole expression text instead, which is still not a required name. The edit therefore produces no check run under a required name, so the latest required check run for the head stays the earlier substantive result. A failing or pending gate stays failing or pending, and an edit cannot turn a pull request green. A skipped job under a required name would count as passing, which is why the gate must never skip under its required name. -Metadata runs use their own concurrency namespace, so an edit cannot cancel or replace an in-progress substantive run. Completion callbacks that read gate results, such as the [runtime-image refresh](#pull-request-runtime-and-preview-chain), the detached Validation Summary and the Static Analysis Summary, ignore metadata runs: they require the required-name gate job, or exclude runs whose gate carries the metadata name. +Metadata runs use their own concurrency namespace, so an edit cannot cancel or replace an in-progress substantive run. Completion callbacks that read gate results, such as the [runtime-image refresh](#pull-request-runtime-and-preview-chain), the detached Validation Summary and the Static Analysis Summary, ignore metadata runs: they require the required-name gate job, or exclude runs whose gate check name contains the metadata label. The [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) checks the gate names, job conditions and concurrency namespaces for all five workflows. diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 4ff857b43d..e3e5976ea2 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -197,7 +197,8 @@ const github = { }, { id: 2701, - name: "PR Metadata Edit (CodeQL Gate)", + // Native skipped-job name: GitHub leaves the expression unevaluated. + name: "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'", status: "completed", conclusion: "skipped", created_at: "2026-09-20T12:00:01Z", From 30f030e4d99f127a1f9d21f993d8300762763688 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:39:54 +1300 Subject: [PATCH 041/199] Record native proof for metadata-edit gate skip Co-Authored-By: Claude Opus 5.5 --- .../implementation-tracking/platform-operations-and-delivery.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 843e6da456..6fc9587fad 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -138,7 +138,7 @@ World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeed ### Required CI Gates on Metadata Edits -A title or description edit skips every job in the five required-gate workflows, and each gate is skipped under a non-required `PR Metadata Edit ()` name, so the earlier substantive result stands and an edit cannot turn a failing PR green. Base retargets still run the full gates. This replaced the earlier metadata preservation machinery (shared preservation and status-publisher actions, the Resolve Required Gates callback and their supplementary pending statuses), which is removed. Disposable proof PRs #3056 and #3081 belonged to that retired design; neither may be merged. Native proof on a disposable PR is pending: a body edit must leave the five required checks unchanged, and a retarget must rerun them. [CI/CD: Required Gates on Metadata Edits](../../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits) owns the contract. +A title or description edit skips every job in the five required-gate workflows, and each gate is skipped under a non-required `PR Metadata Edit ()` name, so the earlier substantive result stands and an edit cannot turn a failing PR green. Base retargets still run the full gates. This replaced the earlier metadata preservation machinery (shared preservation and status-publisher actions, the Resolve Required Gates callback and their supplementary pending statuses), which is removed. Disposable proof PRs #3056 and #3081 belonged to that retired design; neither may be merged. Native proof on disposable [PR #3467](https://github.com/benhook1013/FireMUD/pull/3467) (closed): a body edit created only skipped metadata-named gate checks and left the five required checks unchanged, and a retarget reran all five under their required names. GitHub shows a skipped job's unevaluated name expression rather than the evaluated `PR Metadata Edit (...)` label; it is still not a required name. [CI/CD: Required Gates on Metadata Edits](../../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits) owns the contract. The PR runtime producer and Smoke Gate now provide an affirmative native producer guarantee for unavailable GitHub step metadata, with an immutable whole-workflow fingerprint and exact run/job/attempt attribution. The existing required-gate contract exercises successful PR/typed-refresh attribution, native smoke/cleanup outcome failures, altered or unavailable definitions, and older producer fail-closed behavior. Native GitHub execution of this new path remains unproved; the successful runtime run for PR #3200 exposed empty step metadata and its earlier producer cannot qualify retroactively. The [CI/CD workflow owner](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) defines the proof contract and fingerprint upkeep. From f04d60ec6c4880a6e3a0af5fe0d70eddffc8b45a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:01:22 +1300 Subject: [PATCH 042/199] fix: enforce retained recovery tuple and preview test contracts --- .../tests/preview-runtime-refresh.test.cjs | 21 +++++-- .../InitialGameplayReleaseTupleCodec.java | 1 + .../model/InitialGameplayReleaseModel.java | 3 + .../InitialGameplayReleaseModelTest.java | 60 ++++++++++++++++--- 4 files changed, 71 insertions(+), 14 deletions(-) diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 02cd35196b..a7335ca95b 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -23,8 +23,7 @@ function fixture() { base: {object: {sha: B}}, merge: {sha: A, parents: [{sha: B}, {sha: C}]}, }; } -async function execute(f) { - const sent = []; +async function execute(f, sent = []) { const github = {request: async (route, args) => { assert.equal(route, 'GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs'); assert.equal(args.run_id, 99); assert.equal(args.attempt_number, 2); @@ -42,7 +41,10 @@ async function execute(f) { (f.producers ?? []).filter(run => run.status === args.status)}}; }, }, - pulls: {get: async () => ({data: f.pr})}, + pulls: {get: async ({pull_number}) => { + assert.equal(pull_number, f.pr.number); + return {data: f.pr}; + }}, git: {getRef: async ({ref}) => { assert.equal(ref, 'heads/' + f.pr.base.ref); return {data: f.base}; @@ -135,7 +137,10 @@ test('canonical non-runtime base image selection does not dispatch', async () => const f = fixture(); f.imageTag = B; assert.deepEqual(await execute(f), []); }); test('unexpected canonical image selection fails closed', async () => { - const f = fixture(); f.imageTag = 'untrusted'; await assert.rejects(execute(f), /Unexpected image/); + const f = fixture(); f.imageTag = 'untrusted'; + const sent = []; + await assert.rejects(execute(f, sent), /Unexpected image/); + assert.deepEqual(sent, []); }); test('qualified canonical workflow path remains eligible', async () => { @@ -224,7 +229,9 @@ for (const [name, mutate] of Object.entries({ }); test('bounded inventory saturation fails without dispatch or polling', async () => { const f = fixture(); f.fullInventory = Array.from({length: 100}, () => ({})); - await assert.rejects(execute(f), /exceeds bounded lookup/); + const sent = []; + await assert.rejects(execute(f, sent), /exceeds bounded lookup/); + assert.deepEqual(sent, []); assert.equal(f.lookups, 3); }); test('qualified trusted default workflow path suppresses exact dispatch', async () => { @@ -257,6 +264,8 @@ test('immutable title repairs base despite current mutable association', async ( test('truncated or oversized attempt inventory is refused', async () => { for (const inventory of [{total_count: 301, jobs: []}, {total_count: 2, jobs: []}]) { const f = fixture(); f.inventory = inventory; - await assert.rejects(execute(f), /inventory/); + const sent = []; + await assert.rejects(execute(f, sent), /inventory/); + assert.deepEqual(sent, []); } }); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index ec8bb24b15..43b330ec87 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -24,6 +24,7 @@ public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { Objects.requireNonNull(objectMapper, "objectMapper must not be null") .rebuild() .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(tools.jackson.databind.DeserializationFeature.ACCEPT_FLOAT_AS_INT) .build(); this.digestMapper = this.objectMapper.writer().with(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java index 912f46c967..fc0765303e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java @@ -779,6 +779,9 @@ public static String requiredText(String value, String name) { if (value.isBlank()) { throw new IllegalArgumentException(name + " must not be blank"); } + if (value.indexOf(0) >= 0) { + throw new IllegalArgumentException(name + " must not contain NUL"); + } return value; } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index b2bf954244..4cb0b34bf4 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterInventory; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; class InitialGameplayReleaseModelTest { private static final String DIGEST = "a".repeat(64); @@ -478,15 +479,58 @@ void noEffectReadbackRequiresClosedAttemptRatherThanObservedAbsence() { @Test void persistedPartitionAcknowledgementRequiresExplicitNonNullPartitionId() { - InitialGameplayReleaseTupleCodec codec = - new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); - String json = codec.toJson(evidence(scope(UUID.randomUUID()))); - assertThat(json).contains("\"partitionId\":0"); - assertThatThrownBy(() -> codec.readEvidence(json.replace("\"partitionId\":0,", ""))) - .isInstanceOf(RuntimeException.class); + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); + var original = evidence(scope(UUID.randomUUID())); + String json = codec.toJson(original); + assertThat(codec.readEvidence(json)).isEqualTo(original); + ObjectNode missing = (ObjectNode) mapper.readTree(json); + ObjectNode explicitNull = missing.deepCopy(); + ((ObjectNode) missing.at("/issuerLayout/acknowledgements/0")).remove("partitionId"); + ((ObjectNode) explicitNull.at("/issuerLayout/acknowledgements/0")).putNull("partitionId"); + String missingJson = mapper.writeValueAsString(missing); + String nullJson = mapper.writeValueAsString(explicitNull); + + assertThatThrownBy(() -> codec.readEvidence(missingJson)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> codec.readEvidence(nullJson)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void persistedEvidenceRejectsFractionalOperationFence() { + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); + var original = evidence(scope(UUID.randomUUID())); + String json = codec.toJson(original); + assertThat(codec.readEvidence(json)).isEqualTo(original); + ObjectNode altered = (ObjectNode) mapper.readTree(json); + ((ObjectNode) altered.get("issuerLayout")).put("operationFence", 21.9); + String fractionalJson = mapper.writeValueAsString(altered); + + assertThatThrownBy(() -> codec.readEvidence(fractionalJson)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void journalReadbackRejectsNulInIdentityBeforePersistence() { assertThatThrownBy( - () -> codec.readEvidence(json.replace("\"partitionId\":0", "\"partitionId\":null"))) - .isInstanceOf(RuntimeException.class); + () -> + new InitialGameplayReleaseModel.EffectReadback( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, + DIGEST, + DIGEST, + InitialGameplayReleaseModel.EffectReadbackState.PREPARED_FENCED, + InitialGameplayReleaseModel.EffectReadbackAuthority + .GAME_SESSION_DURABLE_CURRENT_STATE, + "readback" + Character.toString(0) + "identity", + java.time.Instant.EPOCH)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readbackIdentity") + .hasMessageContaining("NUL"); } private static Scope scope(UUID playableNamespace) { From 0cb835a8aa665f9d1aa9418d93bb7548d3e7b2ec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:06:24 +1300 Subject: [PATCH 043/199] fix: refuse future-dated new recovery readbacks --- .../JooqInitialGameplayReleaseJournal.java | 3 +++ ...ReleaseJournalPostgresIntegrationTest.java | 27 +++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 9c2f1be77f..1f280f10a0 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -365,6 +365,9 @@ public Operation recordEffectReadback( } throw conflict("effect readback changed after acknowledgement"); } + if (readback.observedAt().isAfter(now)) { + throw conflict("effect readback observation is in the future"); + } if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { throw conflict("effect readback belongs to another attempt"); } diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 9b705d55f1..04620c14df 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -159,6 +159,21 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() "gamesession-preparation-readback-1", base.plusSeconds(6)); UUID prepareEffectId = prepare.effect().effectId(); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + prepareEffectId, + prepareAttempt, + prepareReadback, + base.plusSeconds(5))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("observation is in the future"); + assertThat(journal.find(scope.operationId())).contains(authorized); + assertThat(journal.findEffect(scope.operationId(), EffectKind.PREPARE_PLAYABLE_STATE_FENCED)) + .contains(prepare); + assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isEmpty(); EffectReadback otherAttempt = new EffectReadback( scope.operationId(), @@ -185,15 +200,23 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() prepare.effect().effectId(), prepareAttempt, "TRANSPORT_OUTCOME_UNKNOWN", - base.plusSeconds(7)); + base.plusSeconds(5)); Operation releasing = journal.recordEffectReadback( scope.operationId(), prepare.effect().effectId(), prepareAttempt, prepareReadback, - base.plusSeconds(7)); + prepareReadback.observedAt()); assertThat(releasing.phase()).isEqualTo(Phase.RELEASING); + assertThat( + journal.recordEffectReadback( + scope.operationId(), + prepareEffectId, + prepareAttempt, + prepareReadback, + base.plusSeconds(5))) + .isEqualTo(releasing); assertThat( journal .recordAmbiguousEffect( From 9d8a2928d664f7aff27c3cfdb97a8890b70a367e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:17:02 +1300 Subject: [PATCH 044/199] fix: preserve durable recovery outcomes on repeated observation --- .../pr-required-gate-context-contract.sh | 23 ++- .../pr-runtime-image-publication-contract.sh | 3 + .../preview-runner-isolation-contract.sh | 21 ++- .../InitialGameplayReleaseTupleCodec.java | 9 + .../JooqInitialGameplayReleaseJournal.java | 61 +++++-- ...ReleaseJournalPostgresIntegrationTest.java | 167 ++++++++++++++++++ 6 files changed, 270 insertions(+), 14 deletions(-) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8ea400266b..f6973ff2b0 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3517,6 +3517,18 @@ const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set(JSON.parse( script.match(/const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set\((\[[\s\S]*?\])\);/)[1] .replace(/,\s*\]/, "]"))); +for (const fingerprint of [ + "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", + "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", +]) assert.ok(outgoingTrustedRefreshRuntimeWorkflowSha256.has(fingerprint), + `outgoing trusted refresh fingerprint missing: ${fingerprint}`); +const outgoingRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Outgoing trusted refresh fixture\n")]); +const outgoingRefreshFixtureSha256 = require("node:crypto").createHash("sha256") + .update(outgoingRefreshBytes).digest("hex"); +assert.ok(![canonicalRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, + canonicalLegacyRuntimeWorkflowSha256].includes(outgoingRefreshFixtureSha256)); +assert.ok(!outgoingTrustedRefreshRuntimeWorkflowSha256.has(outgoingRefreshFixtureSha256)); + 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); @@ -3573,7 +3585,7 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, - outgoingTrustedRefreshRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + new Set([...outgoingTrustedRefreshRuntimeWorkflowSha256, outgoingRefreshFixtureSha256]), 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); @@ -3697,6 +3709,15 @@ function markerAccepted(overrides = {}) { assert.equal(await verify(usePreviousRefresh, "pull_request", knownPlay), false, "the previous successful definition cannot attest a PR producer"); } + const useOutgoingRefresh = data => Object.assign(data.definitions[workflowPath], { + content: outgoingRefreshBytes.toString("base64"), size: outgoingRefreshBytes.length, + }); + for (const knownPlay of [true, false]) { + assert.equal(await verify(useOutgoingRefresh, "repository_dispatch", knownPlay), true, + "trusted refresh may retain an outgoing producer proof"); + assert.equal(await verify(useOutgoingRefresh, "pull_request", knownPlay), false, + "an outgoing definition cannot attest a PR producer"); + } for (const path of Object.keys(classifierDefinitions)) { assert.equal(await verify(d => { const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index e0cbad03cd..893b621ace 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -6,6 +6,9 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" WORKFLOW="$ROOT_DIR/.github/workflows/publish-pr-runtime-images.yml" RUNTIME_WORKFLOW="$ROOT_DIR/.github/workflows/runtime-images.yml" +# The contract intentionally uses Python assertions; never report success when disabled. +python3 -c 'import sys; sys.exit(0 if __debug__ else "Runtime image publication contract requires Python assertions; unset PYTHONOPTIMIZE.")' + # Evaluate the workflow's actual string/boolean concurrency expression against fixed event fixtures. # This bounded expression uses only property reads, equality, boolean operators and format. python3 - "$RUNTIME_WORKFLOW" <<'PY_CONCURRENCY' diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 7f3ad49bda..237e2d7ffb 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -460,8 +460,25 @@ if len(plan_checkouts) != 1 or plan_checkouts[0].get("with", {}).get("ref") != " render_checkouts = checkouts(preview_jobs["preview-render"]) if len(render_checkouts) != 2: raise AssertionError("preview render must isolate trusted tools and candidate chart checkouts") -if render_checkouts[0].get("with", {}).get("ref") != "${{ github.event.repository.default_branch }}" or render_checkouts[0].get("with", {}).get("path") is not None: - raise AssertionError("preview render tools must remain rooted at the trusted default branch") +def check_render_tools_checkout(checkout: dict[str, Any]) -> None: + options = checkout.get("with", {}) + if options.get("ref") != "${{ github.event.repository.default_branch }}" or options.get("path") is not None: + raise AssertionError("preview render tools must remain rooted at the trusted default branch") + if "repository" in options and options["repository"] != "${{ github.repository }}": + raise AssertionError("preview render tools must check out the current repository") + +check_render_tools_checkout(render_checkouts[0]) +foreign_tools_checkout = { + **render_checkouts[0], + "with": {**render_checkouts[0]["with"], "repository": "other-owner/other-repo"}, +} +try: + check_render_tools_checkout(foreign_tools_checkout) +except AssertionError as error: + if str(error) != "preview render tools must check out the current repository": + raise +else: + raise AssertionError("foreign render tools checkout escaped repository checking") if render_checkouts[1].get("with", {}).get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or render_checkouts[1].get("with", {}).get("path") != "candidate": raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") def check_trusted_working_directories(workflow: dict[str, Any], job: dict[str, Any]) -> None: diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 43b330ec87..51bc2fc19e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -97,6 +97,15 @@ public InitialGameplayReleaseModel.InitialGameplayReleaseEvidence readEvidence(S } } + InitialGameplayReleaseModel.EffectReadback readEffectReadback(String json) { + try { + return objectMapper.readValue(json, InitialGameplayReleaseModel.EffectReadback.class); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Unable to read persisted initial gameplay release effect readback", exception); + } + } + public InitialGameplayReleaseModel.TypedEffect readEffect(String kind, String json) { try { if (InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 1f280f10a0..38681ac0af 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -312,7 +312,11 @@ private OutboxEntry recordNonterminalEffectOutcome( if (current.lastAttemptId() != null && !current.lastAttemptId().equals(attemptId)) { throw conflict("effect attempt identity changed"); } - if (current.state() == resultState || current.state() == EffectOutboxState.ACKNOWLEDGED) { + if (current.state() == resultState + || current.state() == EffectOutboxState.ACKNOWLEDGED + || (current.lastAttemptId() != null + && current.state() == EffectOutboxState.RETRYABLE + && resultState == EffectOutboxState.AMBIGUOUS)) { return current; } if (current.state() != EffectOutboxState.DISPATCHED @@ -348,29 +352,39 @@ public Operation recordEffectReadback( Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); requireReadbackMatches(readback, current, operationId, effectId); + if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { + throw conflict("effect readback belongs to another attempt"); + } String readbackDigest = tupleCodec.digest(readback); - if (current.state() == EffectOutboxState.ACKNOWLEDGED) { + if (current.state() == EffectOutboxState.ACKNOWLEDGED + || current.state() == EffectOutboxState.RETRYABLE) { Record stored = tx.fetchOne( - "SELECT readback_digest FROM " + "SELECT readback_digest, readback_payload FROM " + OUTBOX_TABLE + " WHERE operation_id = ? AND effect_id = ?", operationId, effectId); - if (current.lastAttemptId() != null - && current.lastAttemptId().equals(attemptId) - && stored != null - && readbackDigest.equals(stored.get("readback_digest", String.class))) { + String storedDigest = + stored == null ? null : stored.get("readback_digest", String.class); + if (current.state() == EffectOutboxState.ACKNOWLEDGED) { + if (readbackDigest.equals(storedDigest) + || (stored != null + && !readback.observedAt().isAfter(now) + && sameAcknowledgedOutcome(readback, stored, storedDigest))) { + return operation; + } + throw conflict("effect readback changed after acknowledgement"); + } + if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT + && readbackDigest.equals(storedDigest)) { return operation; } - throw conflict("effect readback changed after acknowledgement"); + throw conflict("effect readback changed after definitive no effect"); } if (readback.observedAt().isAfter(now)) { throw conflict("effect readback observation is in the future"); } - if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { - throw conflict("effect readback belongs to another attempt"); - } if (current.state() != EffectOutboxState.DISPATCHED && current.state() != EffectOutboxState.AMBIGUOUS) { throw conflict("effect is not awaiting readback reconciliation"); @@ -650,6 +664,31 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private boolean sameAcknowledgedOutcome( + EffectReadback readback, Record stored, String storedDigest) { + JSONB payload = stored.get("readback_payload", JSONB.class); + if (payload == null || storedDigest == null) { + return false; + } + EffectReadback acknowledged = tupleCodec.readEffectReadback(payload.data()); + if (!storedDigest.equals(tupleCodec.digest(acknowledged))) { + return false; + } + // A new observation time does not replace the first durable receipt. + return acknowledged.equals( + new EffectReadback( + readback.operationId(), + readback.effectId(), + readback.attemptId(), + readback.effectKind(), + readback.operationTupleDigest(), + readback.payloadDigest(), + readback.state(), + readback.authority(), + readback.readbackIdentity(), + acknowledged.observedAt())); + } + private void requireReadbackMatches( EffectReadback readback, OutboxEntry outbox, UUID operationId, UUID effectId) { if (!readback.operationId().equals(operationId) diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 04620c14df..7ecfecae7f 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -228,6 +228,51 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() .state()) .isEqualTo(EffectOutboxState.ACKNOWLEDGED); UUID preparedEffectId = prepare.effect().effectId(); + String retainedAcknowledgement = storedOutbox(scope.operationId(), preparedEffectId); + EffectReadback laterObservation = + readbackFor( + prepare, + prepareAttempt, + EffectReadbackState.PREPARED_FENCED, + prepareReadback.readbackIdentity(), + base.plusSeconds(8)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + preparedEffectId, + prepareAttempt, + laterObservation, + base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(scope.operationId(), preparedEffectId)) + .isEqualTo(retainedAcknowledgement); + assertThat( + journal.recordEffectReadback( + scope.operationId(), + preparedEffectId, + prepareAttempt, + laterObservation, + base.plusSeconds(9))) + .isEqualTo(releasing); + EffectReadback changedReceipt = + readbackFor( + prepare, + prepareAttempt, + EffectReadbackState.PREPARED_FENCED, + "different-durable-receipt", + base.plusSeconds(8)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + preparedEffectId, + prepareAttempt, + changedReceipt, + base.plusSeconds(9))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(scope.operationId(), preparedEffectId)) + .isEqualTo(retainedAcknowledgement); assertThatThrownBy( () -> journal.recordAmbiguousEffect( @@ -356,6 +401,128 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(next.attemptCount()).isEqualTo(2); } + @Test + void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + Scope scope = scope(); + journal.create(scope, UUID.randomUUID()); + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base.plusSeconds(1)); + Operation awaitingResume = + journal.transition( + transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base.plusSeconds(2)); + Operation authorized = + journal.transition( + transitionTuple(awaitingResume, TransitionVerb.RESUME), base.plusSeconds(3)); + UUID effectId = + journal + .findEffect(scope.operationId(), EffectKind.PREPARE_PLAYABLE_STATE_FENCED) + .orElseThrow() + .effect() + .effectId(); + UUID firstAttempt = UUID.randomUUID(); + OutboxEntry dispatched = + journal.claimEffect(scope.operationId(), effectId, firstAttempt, base.plusSeconds(4)); + EffectReadback terminal = + readbackFor( + dispatched, + firstAttempt, + EffectReadbackState.PROVEN_NO_EFFECT, + "durable-closure", + base.plusSeconds(5)); + assertThat( + journal.recordEffectReadback( + scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(6))) + .isEqualTo(authorized); + String retained = storedOutbox(scope.operationId(), effectId); + + assertThat( + journal.recordEffectReadback( + scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(7))) + .isEqualTo(authorized); + assertThat( + journal + .recordAmbiguousEffect( + scope.operationId(), + effectId, + firstAttempt, + "LATE_TIMEOUT", + base.plusSeconds(7)) + .state()) + .isEqualTo(EffectOutboxState.RETRYABLE); + assertThatThrownBy( + () -> + journal.recordAmbiguousEffect( + scope.operationId(), + effectId, + UUID.randomUUID(), + "WRONG_ATTEMPT", + base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + EffectReadback changed = + readbackFor( + dispatched, + firstAttempt, + EffectReadbackState.PROVEN_NO_EFFECT, + "durable-closure", + base.plusSeconds(6)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), effectId, firstAttempt, changed, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); + + UUID replacementAttempt = UUID.randomUUID(); + assertThat( + journal + .claimEffect(scope.operationId(), effectId, replacementAttempt, base.plusSeconds(8)) + .lastAttemptId()) + .isEqualTo(replacementAttempt); + String replacement = storedOutbox(scope.operationId(), effectId); + assertThat(replacement) + .contains( + "\"readback_identity\":null", "\"readback_payload\":null", "\"readback_digest\":null"); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(9))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(replacement); + } + + private static String storedOutbox(UUID operationId, UUID effectId) { + return dsl.fetchOne( + "SELECT row_to_json(o)::text AS row_json FROM recovery_control.initial_gameplay_release_outbox o" + + " WHERE operation_id = ? AND effect_id = ?", + operationId, + effectId) + .get("row_json", String.class); + } + + private static EffectReadback readbackFor( + OutboxEntry entry, + UUID attempt, + EffectReadbackState state, + String identity, + Instant observedAt) { + return new EffectReadback( + entry.effect().operationId(), + entry.effect().effectId(), + attempt, + entry.effect().kind(), + entry.effect().operationTupleDigest(), + entry.payloadDigest(), + state, + state == EffectReadbackState.PROVEN_NO_EFFECT + ? EffectReadbackAuthority.GAME_SESSION_DURABLE_CLOSED_ATTEMPT + : EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + identity, + observedAt); + } + @Test void createRetryWithChangedCanonicalTenantConflicts() { Scope original = scope(); From c64bca9b48b2971fede723662df04ebea8ea0b5d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:28:41 +1300 Subject: [PATCH 045/199] fix: reload recovery state and bind readback timestamps --- .../tests/static-analysis-summary-contract.sh | 26 ++++-- .../InitialGameplayReleaseController.java | 4 +- .../InitialGameplayReleaseEffectPort.java | 5 +- .../InitialGameplayReleaseControllerTest.java | 84 +++++++++++++++++++ 4 files changed, 107 insertions(+), 12 deletions(-) diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index f9d558effd..99ffba4c07 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -285,6 +285,7 @@ const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); // Model the two serialized workflow_run callbacks against a persistent comment store. async function assertCompletionOrders() { + const advancedHeadSha = "f".repeat(40); const originalPaginate = github.paginate; const originalIssues = github.rest.issues; const originalTimeout = global.setTimeout; @@ -316,24 +317,29 @@ async function assertCompletionOrders() { github.paginate = async (method, input) => { const rows = await originalPaginate(method, input); if (method === commentsList) return comments; + const requestedHead = method === codeqlListWorkflowRuns ? input.head_sha : input.ref; + const liveHead = requestedHead === advancedHeadSha; + const proofHead = liveHead ? advancedHeadSha : headSha; + const runOffset = (currentBaseSha === baseSha ? 0 : 1000) + (liveHead ? 2000 : 0); if (method === codeqlListWorkflowRuns) { if (!currentTuplePublished) return rows; const key = input.workflow_id === "codeql.yml" ? "codeql" : "license"; if (!completed.has(key) && absentCounterpart) return []; return rows.filter((row) => [100, 200, 300].includes(row.id)).map((row) => ({ ...row, - id: row.id + (currentBaseSha === baseSha ? 0 : 1000), - head_sha: currentHeadSha, - display_title: row.display_title.replace(`base-${baseSha}`, `base-${currentBaseSha}`).replace(`head-${headSha}`, `head-${currentHeadSha}`), + id: row.id + runOffset, + head_sha: proofHead, + display_title: row.display_title.replace(`base-${baseSha}`, `base-${currentBaseSha}`).replace(`head-${headSha}`, `head-${proofHead}`), status: completed.has(key) ? "completed" : "in_progress", conclusion: completed.has(key) ? "success" : null, })); } return rows.filter((row) => !absentCounterpart || completed.has(row.id === 3001 ? "license" : "codeql")) .map((row) => ({ ...row, - details_url: row.details_url.replace(/runs\/(\d+)/, (_, id) => `runs/${Number(id) + (currentBaseSha === baseSha ? 0 : 1000)}`), + id: row.id + runOffset, + details_url: row.details_url.replace(/runs\/(\d+)/, (_, id) => `runs/${Number(id) + runOffset}`), status: completed.has(row.id === 3001 ? "license" : "codeql") ? "completed" : "in_progress", conclusion: completed.has(row.id === 3001 ? "license" : "codeql") - ? (currentBaseSha !== baseSha && row.id === 2001 ? "failure" : "success") : null, + ? (!liveHead && currentBaseSha !== baseSha && row.id === 2001 ? "failure" : "success") : null, })); }; const callback = async (key) => { @@ -378,17 +384,21 @@ async function assertCompletionOrders() { } // Both producer orders must recover current-head proof even if the // final wake is an obsolete head and all current-head wakes coalesced. - currentHeadSha = "f".repeat(40); + currentHeadSha = advancedHeadSha; const writesBeforeHeadAdvance = updates; await callback(first); if (updates !== writesBeforeHeadAdvance + 1 || !comments[0].body.includes(currentHeadSha)) { throw new Error("older-head wake must publish new head identity in the existing comment"); } - if (!comments[0].body.includes("CodeQL gate: `failure`")) { - throw new Error("stale-head wake must reconcile live-head failure"); + if (!comments[0].body.includes("CodeQL gate: `success`")) { + throw new Error("stale-head wake must replace the old failure with live-head success"); } + const writesAfterHeadAdvance = updates; await callback(counterpart); + if (updates !== writesAfterHeadAdvance || creates !== 1 || comments.length !== 1) { + throw new Error("counterpart callback must leave the live-head summary unchanged"); + } currentHeadSha = headSha; currentBaseSha = "e".repeat(40); currentTuplePublished = false; diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index 2df4beb588..69f9145374 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -181,10 +181,10 @@ private Operation readBackEffect(Operation operation, OutboxEntry outbox, UUID a try { resolution = effectPort.readback(outbox.effect(), attemptId); } catch (RuntimeException exception) { - return operation; + return requireOperation(operation.scope().operationId()); } if (resolution.status() != InitialGameplayReleaseEffectPort.ReadbackStatus.AVAILABLE) { - return operation; + return requireOperation(operation.scope().operationId()); } EffectReadback readback = resolution.readback(); Instant now = clock.instant(); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 6787f63100..5d6b2ef16d 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -58,8 +58,9 @@ record EffectReadbackResolution( if ((status == ReadbackStatus.AVAILABLE) != (readback != null)) { throw new IllegalArgumentException("readback must be present exactly for AVAILABLE"); } - if (status == ReadbackStatus.AVAILABLE && observedAt == null) { - throw new IllegalArgumentException("available readback requires observation time"); + if (status == ReadbackStatus.AVAILABLE && !readback.observedAt().equals(observedAt)) { + throw new IllegalArgumentException( + "available readback observation time must match receipt"); } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 3380ebbc92..1f49092af2 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -191,6 +191,90 @@ void emptyOutboxReloadsLatestOperation() { assertThat(controller.reconcileNextEffect(operationId)).isSameAs(after); } + @Test + void unavailableReadbackReloadsLatestOperation() { + assertReadbackFailureReloadsLatestOperation(false); + } + + @Test + void failedReadbackReloadsLatestOperation() { + assertReadbackFailureReloadsLatestOperation(true); + } + + private void assertReadbackFailureReloadsLatestOperation(boolean throwsException) { + var journal = mock(InitialGameplayReleaseJournal.class); + var effectPort = mock(InitialGameplayReleaseEffectPort.class); + var scope = + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-1", "recovery-peer", "storage-1", "revision-1", DIGEST), + "evidence"); + var before = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + var after = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation.class); + when(before.scope()).thenReturn(scope); + var effect = + new PreparePlayableStateFencedEffect( + scope.operationId(), UUID.randomUUID(), UUID.randomUUID(), scope, DIGEST, "proof"); + var attempt = UUID.randomUUID(); + var outbox = + new net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry( + UUID.randomUUID(), + effect, + DIGEST, + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState + .DISPATCHED, + 1, + attempt, + null, + null); + when(journal.find(scope.operationId())) + .thenReturn(java.util.Optional.of(before), java.util.Optional.of(after)); + when(journal.findNextEffect(scope.operationId())).thenReturn(java.util.Optional.of(outbox)); + if (throwsException) { + when(effectPort.readback(effect, attempt)) + .thenThrow(new IllegalStateException("owner readback failed")); + } else { + when(effectPort.readback(effect, attempt)) + .thenReturn(InitialGameplayReleaseEffectPort.EffectReadbackResolution.unavailable()); + } + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + mock(InitialGameplayReleaseEvidenceProvider.class), + effectPort); + + assertThat(controller.reconcileNextEffect(scope.operationId())).isSameAs(after); + verify(effectPort).readback(effect, attempt); + verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); + } + + @Test + void availableReadbackRequiresReceiptObservationTime() { + var readback = + mock( + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback.class); + var observedAt = java.time.Instant.parse("2026-11-18T12:00:00Z"); + when(readback.observedAt()).thenReturn(observedAt); + var status = InitialGameplayReleaseEffectPort.ReadbackStatus.AVAILABLE; + assertThat( + new InitialGameplayReleaseEffectPort.EffectReadbackResolution( + status, readback, observedAt)) + .isEqualTo(InitialGameplayReleaseEffectPort.EffectReadbackResolution.available(readback)); + assertThatThrownBy( + () -> + new InitialGameplayReleaseEffectPort.EffectReadbackResolution( + status, readback, observedAt.plusSeconds(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must match receipt"); + } + @Test void futureDatedOwnerReadbackCannotAdvanceJournal() { var journal = mock(InitialGameplayReleaseJournal.class); From a077cf763002e8e2e413725cedd46f36c8262730 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:45:32 +1300 Subject: [PATCH 046/199] fix: complete recovery wiring and isolate workflow review failures --- .github/scripts/classify-change-scope.cjs | 2 + .github/workflows/ci.yml | 3 + .../protected-pod-admission-proof.yml | 34 ++++++-- .github/workflows/runtime-images.yml | 3 +- .github/workflows/smoke.yml | 2 +- .github/workflows/static-analysis-summary.yml | 56 ++++++++++--- .../architecture/system-architecture-cicd.md | 4 +- .../tests/ci-lightweight-scope-contract.sh | 65 +++++++++------ .../tests/pr-retarget-workflow-contract.sh | 4 +- .../pr-runtime-image-publication-contract.sh | 13 ++- ...otected-pod-admission-workflow-contract.sh | 48 +++++++++++ .../tests/static-analysis-summary-contract.sh | 65 ++++++++++++++- dev-tools/validation/check-flyway-versions.py | 18 +++- ...untGameSessionAbortCompositionFixture.java | 17 +++- ...eniedInitialGameplayReleaseEffectPort.java | 2 +- .../InitialGameplayReleaseController.java | 15 +++- .../InitialGameplayReleaseEffectPort.java | 11 ++- .../src/main/resources/application.yml | 1 + ...overyControllerOwnerConfigurationTest.java | 6 +- .../RecoveryControllerPackagedWiringTest.java | 57 +++++++++++++ .../InitialGameplayReleaseControllerTest.java | 82 ++++++++++++++++++- 21 files changed, 441 insertions(+), 67 deletions(-) create mode 100644 dev-tools/tests/protected-pod-admission-workflow-contract.sh create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerPackagedWiringTest.java diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 252d85791d..eed27687cd 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -17,6 +17,7 @@ const ALL_SERVICES = [ const ALL_MODULES = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -52,6 +53,7 @@ const SHARED_PREFIXES = [ "services/common-library/", "services/common-data-runtime/", "services/common-platform-core/", + "services/common-redis-contracts/", "services/common-saga/", "services/common-temporal/", "services/common-security/", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f941e7a40..c254967e99 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,6 +69,7 @@ jobs: const completeModules = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -441,6 +442,8 @@ jobs: time bash ./dev-tools/tests/cloc-report-contract.sh TIMEFORMAT='bash ./dev-tools/tests/ci-lightweight-scope-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/ci-lightweight-scope-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/protected-pod-admission-workflow-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/protected-pod-admission-workflow-contract.sh TIMEFORMAT='bash ./dev-tools/tests/gradle-dependency-recovery-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/gradle-dependency-recovery-contract.sh TIMEFORMAT='bash ./dev-tools/tests/workflow-version-authority-contract.sh: real=%3R user=%3U sys=%3S' diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 6b941e9c52..9b6d7888d7 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -122,12 +122,12 @@ jobs: elif ! actual_claim="$(cat "$claim")" || [[ "$actual_claim" != "$expected_claim" ]]; then printf 'cleanup=refused_invalid_ownership_claim\n' status=1 - elif ! node_names="$(docker ps -a --format '{{.Names}}')"; then + elif ! node_names="$(timeout --signal=TERM --kill-after=5s 15s docker ps -a --format '{{.Names}}')"; then printf 'cleanup=failed_node_lookup\n' status=1 elif grep -Fxq "$node" <<<"$node_names"; then local owner_label - owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" + owner_label="$(timeout --signal=TERM --kill-after=5s 15s docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null)" || owner_label="" if [[ "$owner_label" == "$KIND_CLUSTER_NAME" ]]; then kind delete cluster --name "$KIND_CLUSTER_NAME" --kubeconfig "$KUBECONFIG" || status=$? else @@ -176,7 +176,7 @@ jobs: echo "created kubeconfig did not select the exact run-owned context" >&2 exit 1 } - node_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' \ + node_label="$(timeout --signal=TERM --kill-after=5s 15s docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' \ "${KIND_CLUSTER_NAME}-control-plane")" [[ "$node_label" == "$KIND_CLUSTER_NAME" ]] || { echo "kind node ownership label did not match this run" >&2 @@ -212,6 +212,30 @@ jobs: | kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" create -f - elapsed policy_and_fixture_creation "$phase_started" + # Policy admission status is asynchronous; readiness is not proof of + # current-generation type checking. The pinned probe still verifies + # exact policy/binding contents after this bounded readiness wait. + policy_deadline="$(( $(date +%s) + 90 ))" + for policy in firemud-trust-runtime-namespace-boundary firemud-trust-runtime-binding-boundary firemud-trust-runtime-pod-boundary firemud-trust-runtime-pod-identity; do + while true; do + policy_json="$(kubectl --request-timeout=5s --kubeconfig "$KUBECONFIG" --context "$expected_context" get validatingadmissionpolicy "$policy" -o json)" || policy_json='{}' + if jq -e ' + (.metadata.generation | type) == "number" and + .status.observedGeneration == .metadata.generation and + (.status.typeChecking | type) == "object" and + (.status.typeChecking.expressionWarnings // []) == [] and + .spec.failurePolicy == "Fail" + ' <<<"$policy_json" >/dev/null; then + break + fi + if (( $(date +%s) >= policy_deadline )); then + printf 'policy_readiness=timeout policy=%s\n' "$policy" >&2 + return 1 + fi + sleep 2 + done + done + phase_started="$(date +%s)" for app in account-service game-session-service; do kubectl --kubeconfig "$KUBECONFIG" --context "$expected_context" -n dev \ @@ -260,11 +284,11 @@ jobs: printf 'cleanup=refused_invalid_ownership_claim\n' | tee -a "$evidence" exit 1 fi - if ! node_names="$(docker ps -a --format '{{.Names}}')"; then + if ! node_names="$(timeout --signal=TERM --kill-after=5s 15s docker ps -a --format '{{.Names}}')"; then printf 'cleanup=failed_node_lookup\n' | tee -a "$evidence" exit 1 elif grep -Fxq "$node" <<<"$node_names"; then - owner_label="$(docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null || true)" + owner_label="$(timeout --signal=TERM --kill-after=5s 15s docker inspect --format '{{ index .Config.Labels "io.x-k8s.kind.cluster" }}' "$node" 2>/dev/null)" || owner_label="" if [[ "$owner_label" != "$KIND_CLUSTER_NAME" ]]; then printf 'cleanup=refused_unverified_node_identity node=%s label=%s\n' "$node" "$owner_label" \ | tee -a "$evidence" diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index c86bf16c90..25edcdeb9c 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -58,7 +58,8 @@ permissions: # let an existing producer finish when duplicate requests arrive. 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: false + # Only protected-branch publications supersede older branch commits. + cancel-in-progress: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }} jobs: image-meta: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e7aeff2d5f..203c734346 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -561,7 +561,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "57c30607a72672c5cab5c2d1701a648425cf013ec61d2da0397cf04e3cdec512"; + const canonicalRuntimeWorkflowSha256 = "4b97e52230413781c32db8fea21f94e46d7e2610346508cfc60adc972eb7dc7c"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index bfc429fae6..ec300dc16e 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -13,21 +13,53 @@ permissions: actions: read pull-requests: write -concurrency: - group: static-analysis-summary-source-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }} - # Serialize by native source repository and branch, independent of association - # ordering or the producer workflow. Shared-branch PRs conservatively serialize. - # Publication below requires this identity still matches the live PR. - # Serialize the CodeQL and license completion events so a pending summary - # cannot race a terminal summary into creating two comments. Every validated - # callback snapshots the live tuple, so an older-head wake can replace pending - # work without losing current-head reconciliation. Never cancel active writes. - cancel-in-progress: false - jobs: + resolve-summary-target: + name: Resolve Summary Target + if: ${{ github.event.workflow_run.event == 'pull_request' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: {} + outputs: + pull-number: ${{ steps.target.outputs.pull-number }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Resolve validated summary target + id: target + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const source = context.payload.workflow_run; + if (source?.event !== "pull_request") return; + const workflowName = ({ + ".github/workflows/codeql.yml": "CodeQL Analysis", + ".github/workflows/license-scan.yml": "License Gate", + })[source.path]; + const title = String(source.display_title || "").match( + /^(CodeQL Analysis|License Gate) pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/ + ); + if (!title || title[1] !== workflowName || title[4] !== source.head_sha || + ![workflowName, source.display_title].includes(source.name) || + !Number.isSafeInteger(source.head_repository?.id) || source.head_repository.id <= 0 || + typeof source.head_branch !== "string" || !source.head_branch.trim()) return; + const number = Number(title[2]); + if (!Number.isSafeInteger(number) || !Array.isArray(source.pull_requests) || + source.pull_requests.filter(pr => pr?.number === number).length !== 1) return; + core.setOutput("pull-number", String(number)); + publish-summary: name: Static Analysis Summary - if: ${{ github.event.workflow_run.event == 'pull_request' }} + needs: [resolve-summary-target] + if: ${{ needs.resolve-summary-target.outputs.pull-number != '' }} + # Only validated PR callbacks enter this queue. Old heads refresh the same + # live PR; other PRs and skipped push callbacks cannot replace its pending work. + concurrency: + group: static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }} + cancel-in-progress: false runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index dbf3657349..9822b1c79d 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -50,7 +50,7 @@ Workflows live in the `.github/workflows/` directory. A typical pipeline runs on The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account, Game Session, or World Management module. World requires its native two-partition declaration; historical World full-check jobs remain valid without an aggregate. Account and Game Session retain attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. -The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. Serialization uses branch and immutable head SHA so superseded heads cannot evict current-head pending callbacks. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. +The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. A no-checkout resolver without write permissions validates the PR callback identity before publication enters a PR-number queue. CodeQL and License callbacks for the same PR serialize across heads; different PRs sharing a branch and skipped push callbacks cannot replace that PR’s pending work. An older-head callback may replace pending work for the same PR because publication snapshots the live PR tuple. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. ### Pull Request Runtime And Preview Chain @@ -226,7 +226,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata, binds the unique tuple step to the native run head and uniquely matching PR association, checks the recorded merge parents, and compares its recorded base with the current branch ref instead of treating mutable API association fields as event history. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. -This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate policy removal (restoring GitHub default protections) or replacement with only `pull_request` and `repository_dispatch`, then verify natural PR/manual-dispatch paths against the merged code. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. +This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate the additive path-specific policy update: retain `pull_request_target` and `repository_dispatch` and add `pull_request`. Verify fresh natural PR and manual-dispatch events against the merged code; the documentation change itself neither grants authorization nor changes that policy. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 37868bee60..2d5e78789f 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -11,6 +11,44 @@ MODULE_CHECK_WRAPPER="$ROOT_DIR/.github/scripts/run-gradle-module-checks.sh" node --test "$ROOT_DIR/.github/scripts/classify-change-scope.test.cjs" +node - "$CI_WORKFLOW" "$CLASSIFIER" <<'JS_SCOPE' +const assert = require("node:assert/strict"); +const {execFileSync} = require("node:child_process"); +const workflow = JSON.parse(execFileSync("python3", ["-c", + "import json,sys,yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))", + process.argv[2]], {encoding: "utf8"})); +const compute = workflow.jobs.changes.steps.find(step => step.id === "compute").with.script; +const {ALL_MODULES, BOOTABLE_MODULES, classifyChangeScope} = require(process.argv[3]); +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const execute = new AsyncFunction("require", "github", "context", "core", compute); +(async () => { + for (const [available, modules, compatible] of [ + [false, undefined, false], + [true, undefined, false], + [true, ALL_MODULES.filter(module => module !== "recovery-controller-service"), false], + [true, ALL_MODULES.filter(module => module !== "common-redis-contracts"), false], + [true, ALL_MODULES, true], + ]) { + const outputs = {}; + await execute(name => name === "node:fs" ? {existsSync: () => available} : { + ALL_MODULES: modules, + classifyGithubChangeScope: async () => ({ + runAll: false, affectedModules: ["account-service"], bootableModules: ["account-service"], + affectedServices: ["account-service"], lightweightOnly: true, + }), + }, {}, {}, {setOutput: (name, value) => outputs[name] = value, warning() {}}); + assert.equal(outputs.run_all, String(!compatible)); + assert.equal(outputs.lightweight_only, String(compatible)); + assert.deepEqual(JSON.parse(outputs.affected_modules), compatible ? ["account-service"] : ALL_MODULES); + assert.deepEqual(JSON.parse(outputs.bootable_modules), + compatible ? ["account-service"] : [...BOOTABLE_MODULES]); + } + const shared = classifyChangeScope(["services/common-redis-contracts/src/main/java/Example.java"]); + assert.deepEqual(shared.affectedModules, ALL_MODULES); + assert.ok(!shared.bootableModules.includes("common-redis-contracts")); +})().catch(error => { console.error(error); process.exitCode = 1; }); +JS_SCOPE + require_contains() { local path="$1" local expected="$2" @@ -381,6 +419,7 @@ DEV_TOOLS_TEST_DISCOVERY_COMMAND = "python3 -m unittest discover -s dev-tools/te REMAINING_FULL_RUN_COMMANDS = ( 'bash ./dev-tools/tests/cloc-report-contract.sh', 'bash ./dev-tools/tests/ci-lightweight-scope-contract.sh', + 'bash ./dev-tools/tests/protected-pod-admission-workflow-contract.sh', 'bash ./dev-tools/tests/gradle-dependency-recovery-contract.sh', 'bash ./dev-tools/tests/workflow-version-authority-contract.sh', 'bash ./dev-tools/tests/workflow-tool-updater-contract.sh', @@ -1469,32 +1508,6 @@ require_equal( "ci workflow", ) ci_compute_step = find_step(ci, "changes", "Compute affected jobs", "ci workflow") -for guard in ( - "completeModules.every(module => ALL_MODULES.includes(module))", - "run_all: scope.runAll || !moduleScopeAvailable", - "affected_modules: moduleScopeAvailable ? scope.affectedModules : completeModules", - "bootable_modules: moduleScopeAvailable ? scope.bootableModules : completeBootableModules", - "lightweight_only: moduleScopeAvailable && scope.lightweightOnly", -): - require_contains(ci_compute_step, ("with", "script"), guard, "ci workflow") -require_contains( - ci_compute_step, - ("with", "script"), - "const { classifyGithubChangeScope, ALL_MODULES } = require(classifierPath)", - "ci workflow", -) -require_contains( - ci_compute_step, - ("with", "script"), - "await classifyGithubChangeScope(github, context)", - "ci workflow", -) -require_contains( - ci_compute_step, - ("with", "script"), - "Base revision predates the change classifier; using complete validation scope.", - "ci workflow", -) classifier_inventories = load_classifier_module_inventories(sys.argv[5]) for output_key, constant_name, inventory_key in ( ("affected_modules", "completeModules", "allModules"), diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index d4ae3d549b..9233ef0af5 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -705,7 +705,7 @@ if "github.sha" in concurrency_group.split("github.event_name == 'repository_dis raise SystemExit("repository_dispatch concurrency must not use the default-branch github.sha") # Execute the workflow-level selector before its dispatcher can classify a CI # callback. A title/body CI completion must not evict substantive reconciliation. -assert runtime["concurrency"]["cancel-in-progress"] == "false", "duplicate requests must not cancel a useful running producer" +assert runtime["concurrency"]["cancel-in-progress"] == "${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }}" def callback_group(branch, source_id, source_attempt, source_event="pull_request", head="a" * 40): values = { @@ -1562,7 +1562,7 @@ require_contains "$runtime_images_path" 'types: [opened, synchronize, reopened, require_contains "$runtime_images_path" 'types: [pr-runtime-base-refresh]' require_contains "$runtime_images_path" 'repository_dispatch:' require_contains "$runtime_images_path" "&& 'metadata' || 'required' }}" -require_contains "$runtime_images_path" ' cancel-in-progress: false' +require_contains "$runtime_images_path" " cancel-in-progress: \${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }}" require_contains "$runtime_images_path" 'run-name: Build Runtime Images ' require_contains "$runtime_images_path" "format('secure-pr-artifact pr-{0}" require_contains "$runtime_images_path" 'github.event.pull_request.base.sha' diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 893b621ace..29db237995 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -19,7 +19,7 @@ from pathlib import Path source = Path(sys.argv[1]).read_text() group = re.search(r"^ group: (runtime-images-.*)$", source, re.MULTILINE).group(1) -assert re.search(r"^ cancel-in-progress: false$", source, re.MULTILINE) +cancel = re.search(r"^ cancel-in-progress: (.*)$", source, re.MULTILINE).group(1) class Context: def __init__(self, value=None): @@ -53,14 +53,14 @@ base = { "head": {"sha": "head1", "repo": {"full_name": "owner/repo"}}}}, } -def evaluate(event): +def evaluate(event, expression_source=group): def expression(match): code = match.group(1).replace("&&", " and ").replace("||", " or ") code = re.sub(r"\bnull\b", "None", code) # Only the checked-in expression is code; event values remain data. return str(eval(code, {"__builtins__": {}}, { "github": Context(event), "format": lambda template, *args: template.format(*args)})) - return re.sub(r"\$\{\{(.*?)\}\}", expression, group) + return re.sub(r"\$\{\{(.*?)\}\}", expression, expression_source) def check(event, suffix): expected = "runtime-images-Build Runtime Images-" + suffix @@ -93,6 +93,13 @@ dispatch = {**base, "event_name": "repository_dispatch", "event": { "action": "pr-runtime-base-refresh", "client_payload": { "pr_number": 7, "base_sha": "base1", "head_sha": "head1", "merge_sha": "merge1"}}} check(dispatch, "pr-7-base-base1-head-head1-merge-merge1-required") +for event in [base, dispatch, {"event_name": "workflow_dispatch"}, + {"event_name": "workflow_run", "event": {"workflow_run": {"event": "pull_request", "head_branch": "develop"}}}]: + assert evaluate(event, cancel) == "False", event +for branch in ["main", "develop", "feature/x"]: + event = {"event_name": "workflow_run", "event": {"workflow_run": {"event": "push", "head_branch": branch}}} + assert evaluate(event, cancel) == str(branch in ["main", "develop"]), event + for value in [0, False, "", None]: invalid = copy.deepcopy(dispatch) invalid["event"]["client_payload"]["pr_number"] = value diff --git a/dev-tools/tests/protected-pod-admission-workflow-contract.sh b/dev-tools/tests/protected-pod-admission-workflow-contract.sh new file mode 100644 index 0000000000..1a8e7b55c2 --- /dev/null +++ b/dev-tools/tests/protected-pod-admission-workflow-contract.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 - "$ROOT_DIR" <<'PY' +import json, os, pathlib, subprocess, sys, tempfile +import yaml +root = pathlib.Path(sys.argv[1]) +workflow = yaml.safe_load((root / ".github/workflows/protected-pod-admission-proof.yml").read_text()) +steps = workflow["jobs"]["admission-only"]["steps"] +runs = [step.get("run", "") for step in steps] +lookups = [line for script in runs for line in script.splitlines() if "node_names=" in line] +assert len(lookups) == 2 +assert all("timeout --signal=TERM --kill-after=5s 15s docker ps -a" in line for line in lookups) +inspects = [line for script in runs for line in script.splitlines() if 'owner_label="$(timeout' in line] +assert len(inspects) == 2 +assert all('15s docker inspect' in line and '|| owner_label=""' in line for line in inspects) +proof = next(script for script in runs if "policy_deadline=" in script) +wait = proof[proof.index('policy_deadline='):proof.index('elapsed fixture_rollout')] +wait = wait[:wait.index('phase_started=')] +# Execute the real wait body against bounded fake API/time, never a cluster. +with tempfile.TemporaryDirectory(prefix="firemud-policy-wait-") as directory: + tmp = pathlib.Path(directory) + def command(name, source): + file = tmp / name + file.write_text("#!/usr/bin/env python3\n" + source) + file.chmod(0o700) + command("date", 'import os,pathlib\np=pathlib.Path(os.environ["CLOCK"]);n=int(p.read_text()) if p.exists() else 0;p.write_text(str(n+30));print(n)\n') + command("sleep", 'pass\n') + command("kubectl", '''import os,pathlib,json,sys +p=pathlib.Path(os.environ["CALLS"]);n=int(p.read_text()) if p.exists() else 0;p.write_text(str(n+1)) +if os.environ["CASE"]=="api-error":sys.exit(1) +ready=os.environ["CASE"]=="ready" or (os.environ["CASE"]=="late" and n>0) +print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Fail"},"status":{"observedGeneration":2 if ready else 1,"typeChecking":{"expressionWarnings":["bad"] if os.environ["CASE"]=="warnings" else []}}})) +''') + for case, success in [("ready", True), ("late", True), ("stale", False), ("warnings", False), ("api-error", False)]: + for name in ("clock", "calls"): + (tmp/name).unlink(missing_ok=True) + env = dict(os.environ, PATH=str(tmp)+":"+os.environ["PATH"], CASE=case, + CLOCK=str(tmp/"clock"), CALLS=str(tmp/"calls"), + KUBECONFIG="/not-a-live-config", expected_context="fixture") + result = subprocess.run(["bash", "-c", "set -euo pipefail\nrun_wait() {\n"+wait+"\n}\nrun_wait"], env=env, capture_output=True, text=True, timeout=10) + assert (result.returncode == 0) == success, (case, result.stderr) + if success: + assert int((tmp/"calls").read_text()) >= 4 + else: + assert "policy_readiness=timeout" in result.stderr +print("Protected Pod workflow bounded cleanup/readiness contract passed") +PY diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 0b478a08f5..4277c45ebb 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -27,7 +27,7 @@ grep -Fq 'per_page: 100' "$workflow" grep -Fq 'cancel-in-progress: false' "$workflow" # GitHub expressions are literal workflow text, not shell expansions. # shellcheck disable=SC2016 -grep -Fq 'group: static-analysis-summary-source-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }}' "$workflow" +grep -Fq 'group: static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }}' "$workflow" grep -Fq 'const headSha = currentPullRequest.head?.sha;' "$workflow" grep -Fq 'context.payload.workflow_run.display_title !== expectedSourceTitle' "$workflow" grep -Fq 'finalPullRequest.base?.sha !== baseSha' "$workflow" @@ -77,6 +77,69 @@ for line in lines[start + 1 :]: script_path.write_text(textwrap.dedent("\n".join(body)) + "\n", encoding="utf-8") PY +# Execute the actual pre-queue resolver and verify the job-level lock boundary. +python3 - "$workflow" "$test_root/summary-target.js" <<'PY_TARGET' +import sys +from pathlib import Path +import yaml +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +assert "concurrency" not in workflow, "unvalidated callbacks must not share a workflow queue" +resolver = workflow["jobs"]["resolve-summary-target"] +publisher = workflow["jobs"]["publish-summary"] +assert resolver["permissions"] == {}, "resolver must not receive write authority" +assert resolver["if"] == "${{ github.event.workflow_run.event == 'pull_request' }}" +assert publisher["needs"] == ["resolve-summary-target"] +assert publisher["if"] == "${{ needs.resolve-summary-target.outputs.pull-number != '' }}" +assert publisher["concurrency"] == { + "group": "static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }}", + "cancel-in-progress": "false", +} +step = next(step for step in resolver["steps"] if step.get("id") == "target") +assert resolver["outputs"]["pull-number"] == "${{ steps.target.outputs.pull-number }}" +Path(sys.argv[2]).write_text(step["with"]["script"]) +PY_TARGET +node - "$test_root/summary-target.js" <<'NODE_TARGET' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const resolve = new Function("context", "core", fs.readFileSync(process.argv[2], "utf8")); +const head = "a".repeat(40), base = "b".repeat(40); +function source(number = 42, workflow = "CodeQL Analysis", sha = head) { + return {event: "pull_request", name: workflow, + path: workflow === "CodeQL Analysis" ? ".github/workflows/codeql.yml" : ".github/workflows/license-scan.yml", + display_title: `${workflow} pr-${number} base-${base} head-${sha}`, head_sha: sha, + head_repository: {id: 123}, head_branch: "shared", pull_requests: [{number}]}; +} +function group(run) { + const outputs = {}; + resolve({payload: {workflow_run: run}}, {setOutput: (key, value) => { outputs[key] = value; }}); + return outputs["pull-number"] ? `static-analysis-summary-pr-${outputs["pull-number"]}` : null; +} +const a = group(source()), b = group(source(99)); +assert.notEqual(a, b, "same source branch must not couple different PR queues"); +assert.equal(a, group(source(42, "License Gate")), "producer channels must serialize per PR"); +assert.equal(a, group(source(42, "CodeQL Analysis", "c".repeat(40))), "head advance must keep the PR queue"); +for (const pull_requests of [[{number: 99}, {number: 42}], [{number: 42}, {number: 99}]]) { + assert.equal(group({...source(), pull_requests}), a, "association order must not select another PR"); +} +for (const override of [ + {event: "push"}, {event: "schedule"}, {display_title: "malformed"}, + {head_sha: "d".repeat(40)}, {path: ".github/workflows/unrelated.yml"}, {name: "forged"}, + {head_repository: {id: 0}}, {head_repository: null}, {head_branch: ""}, + {pull_requests: null}, {pull_requests: [{number: 99}]}, + {pull_requests: [{number: 42}, {number: 42}]}, +]) assert.equal(group({...source(), ...override}), null, JSON.stringify(override)); +// Fork identity is not authority: keep a valid association routable; the existing +// publisher independently verifies the live PR repository/branch before any write. +assert.equal(group({...source(), head_repository: {id: 456}}), a); +const pending = new Map(); +pending.set(a, "42-final"); pending.set(b, "99-old"); +const push = group({...source(), event: "push"}); +if (push) pending.set(push, "push"); +assert.equal(pending.get(a), "42-final", "other PR and push cannot replace PR42 pending work"); +assert.equal(pending.get(b), "99-old"); +console.log("static summary target and queue isolation contract passed"); +NODE_TARGET + node - "$script_path" <<'NODE' const fs = require("node:fs"); const script = fs.readFileSync(process.argv[2], "utf8"); diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 91f3f20330..aa60119f6b 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -12,7 +12,7 @@ from pathlib import Path VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") -MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/migration/") +MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/(?:migration|recovery-control-migration)/") RUNTIME_DEPENDENCY_RE = re.compile( r'(?:implementation|api|runtimeOnly)\s*\(\s*project\(\s*":([^\"]+)"' r'|dependencies\.add\(\s*"(?:implementation|api|runtimeOnly)"\s*,\s*project\.project\(\s*":([^\"]+)"' @@ -52,6 +52,8 @@ def current_snapshot(repo_root: Path) -> Snapshot: *repo_root.glob("services/*/src/main/resources/application*.y*ml"), *repo_root.glob("services/*/src/main/resources/db/migration/**/*"), *repo_root.glob("services/*/src/main/java/db/migration/**/*"), + *repo_root.glob("services/*/src/main/resources/db/recovery-control-migration/**/*"), + *repo_root.glob("services/*/src/main/java/db/recovery-control-migration/**/*"), *repo_root.glob("buildSrc/**/*.kt"), *repo_root.glob("buildSrc/**/*.kts")] return {path.relative_to(repo_root).as_posix(): path.read_bytes() for path in paths if path.is_file()} @@ -262,6 +264,20 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str check("removed history", {path: data for path, data in history.items() if path != local + "V1__init.sql"}, history, "removed or renamed") check("java/sql duplicate", {**history, "services/example-service/src/main/java/db/migration/V1__dup.java": b"// dup"}, history, "duplicate version V1") + recovery = "services/recovery-controller-service/src/main/resources/db/recovery-control-migration/" + recovery_history = {recovery + "V1__journal.sql": b"-- journal"} + check("unchanged isolated recovery history", recovery_history, recovery_history, None) + check("duplicate recovery version", {**recovery_history, recovery + "V1__duplicate.sql": b"-- duplicate"}, + recovery_history, "duplicate version V1") + check("changed recovery history", {recovery + "V1__journal.sql": b"-- rewritten"}, + recovery_history, "content changed") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / recovery).mkdir(parents=True) + (root / recovery / "V1__journal.sql").write_bytes(b"-- journal") + if current_snapshot(root) != recovery_history or not all(map(relevant_path, recovery_history)): + raise AssertionError("isolated recovery history is not selected for both snapshots") + # Exercise the actual composed convention wiring and exclude test-only dependencies. conventions = { "buildSrc/build.gradle.kts": b'id = "base"\nimplementationClass = "example.Base"\nid = "composed"\nimplementationClass = "example.Composed"', diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java index 4f2c46b27a..b816ffeb2d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java @@ -90,7 +90,7 @@ Session openNeverAdmitted(boolean installedBootstrap) throws Exception { final class Session implements AutoCloseable { private long phaseStartedAt = System.nanoTime(); private boolean setupComplete; - private final PhysicalRedisFixture redis = PhysicalRedisFixture.start(); + private final PhysicalRedisFixture redis; final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture accountFixture; final CanonicalGameplayAdmissionAbortCompositionFixture gs; final LoopbackMtlsTestPki.Pki pki; @@ -123,8 +123,8 @@ private Session( boolean installedBootstrap, boolean includeWrongPeerIdentity) throws Exception { + redis = startRedis(); try { - markPhase("redis_start"); accountFixture = accountFixtures.newFixture(redis.client()); markPhase("account_fixture"); var issuance = accountFixture.committedCandidate.identity(); @@ -422,6 +422,19 @@ CanonicalGameplayAdmissionAbortOutcome abortWith(String callerToken) { .abortFirstNew(gs.transitionId(), callerToken); } + private PhysicalRedisFixture startRedis() throws Exception { + try { + try { + return PhysicalRedisFixture.start(); + } finally { + markPhase("redis_start"); + } + } catch (Exception | Error setupFailure) { + markPhase("setup_failed"); + throw setupFailure; + } + } + private void markPhase(String phase) { long now = System.nanoTime(); if (Boolean.getBoolean("firemud.gameplay.fixture-phase-diagnostics")) { diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java index 1f204e70dc..03fe0a9094 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java @@ -9,7 +9,7 @@ public class DeniedInitialGameplayReleaseEffectPort implements InitialGameplayReleaseEffectPort { @Override public EffectApplyResult apply(TypedEffect effect, UUID attemptId) { - return EffectApplyResult.retryableNoEffect("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); + return EffectApplyResult.notDispatched("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); } @Override diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index 69f9145374..0049cf6451 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -151,7 +151,8 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { clock.instant()); return requireOperation(operation.scope().operationId()); } - if (applyResult.status() == ApplyStatus.RETRYABLE_NO_EFFECT) { + if (applyResult.status() == ApplyStatus.RETRYABLE_NO_EFFECT + || applyResult.status() == ApplyStatus.NOT_DISPATCHED) { journal.recordRetryableEffect( operation.scope().operationId(), dispatched.effect().effectId(), @@ -227,12 +228,18 @@ private Operation transition( if (prior.isPresent()) { return prior.orElseThrow(); } - verifyFreshEvidence(operation); + EvidenceResolution resolution = evidenceProvider.read(operation.scope()); + if (resolution.status() == ResolutionStatus.UNAVAILABLE) { + Optional committedWhileReading = journal.findTransition(tuple); + if (committedWhileReading.isPresent()) { + return committedWhileReading.orElseThrow(); + } + } + verifyFreshEvidence(operation, resolution); return journal.transition(tuple, clock.instant()); } - private void verifyFreshEvidence(Operation operation) { - EvidenceResolution resolution = evidenceProvider.read(operation.scope()); + private void verifyFreshEvidence(Operation operation, EvidenceResolution resolution) { if (resolution.status() != ResolutionStatus.AVAILABLE) { throw unavailable("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_" + resolution.status().name()); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 5d6b2ef16d..1f429409a6 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -12,7 +12,9 @@ public interface InitialGameplayReleaseEffectPort { /** * RETRYABLE_NO_EFFECT is a definitive owner rejection for this exact attempt, never a timeout or - * absence observation. The owner must not apply the rejected attempt later. + * absence observation. The owner must not apply the rejected attempt later. NOT_DISPATCHED means + * the local adapter can prove it never sent this attempt; it is retryable without owner evidence. + * A possibly transmitted request must not be classified as NOT_DISPATCHED. */ EffectApplyResult apply(TypedEffect effect, UUID attemptId); @@ -26,7 +28,7 @@ public interface InitialGameplayReleaseEffectPort { record EffectApplyResult(ApplyStatus status, String outcomeCode) { public EffectApplyResult { Objects.requireNonNull(status, "status"); - if (status == ApplyStatus.RETRYABLE_NO_EFFECT || status == ApplyStatus.AMBIGUOUS) { + if (status != ApplyStatus.APPLIED) { net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.requiredOutcomeCode( outcomeCode); } @@ -36,6 +38,10 @@ public static EffectApplyResult applied() { return new EffectApplyResult(ApplyStatus.APPLIED, null); } + public static EffectApplyResult notDispatched(String outcomeCode) { + return new EffectApplyResult(ApplyStatus.NOT_DISPATCHED, outcomeCode); + } + public static EffectApplyResult retryableNoEffect(String outcomeCode) { return new EffectApplyResult(ApplyStatus.RETRYABLE_NO_EFFECT, outcomeCode); } @@ -47,6 +53,7 @@ public static EffectApplyResult ambiguous(String outcomeCode) { enum ApplyStatus { APPLIED, + NOT_DISPATCHED, RETRYABLE_NO_EFFECT, AMBIGUOUS } diff --git a/services/recovery-controller-service/src/main/resources/application.yml b/services/recovery-controller-service/src/main/resources/application.yml index 0aa86d87a9..7edc1dd4f8 100644 --- a/services/recovery-controller-service/src/main/resources/application.yml +++ b/services/recovery-controller-service/src/main/resources/application.yml @@ -2,6 +2,7 @@ spring: autoconfigure: exclude: - net.firedevops.firemud.common.config.DatabaseAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration application: name: recovery-controller-service datasource: diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java index 5e49a77525..b2df419e9f 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java @@ -27,9 +27,10 @@ import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; import org.springframework.boot.jooq.autoconfigure.JooqAutoConfiguration; +import org.springframework.boot.test.context.TestComponent; +import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import tools.jackson.databind.json.JsonMapper; @@ -127,7 +128,7 @@ void dedicatedDatasourceOwnsFlywayAndJooq() { }); } - @Configuration(proxyBeanMethods = false) + @TestConfiguration(proxyBeanMethods = false) @ImportAutoConfiguration({ DatabaseAutoConfiguration.class, DataSourceAutoConfiguration.class, @@ -136,6 +137,7 @@ void dedicatedDatasourceOwnsFlywayAndJooq() { }) static class DatabaseWiring {} + @TestComponent @AutoConfiguration static class Replacements { @Bean diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerPackagedWiringTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerPackagedWiringTest.java new file mode 100644 index 0000000000..e4d676cfb2 --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerPackagedWiringTest.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.recovery.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import javax.sql.DataSource; +import net.firedevops.firemud.recovery.RecoveryControllerServiceApplication; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.JooqInitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.DeniedInitialGameplayReleaseEvidenceProvider; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseController; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.util.ClassUtils; + +@SpringBootTest( + classes = RecoveryControllerServiceApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.NONE, + properties = { + "FIREMUD_RECOVERY_CONTROL_DB_HOST=recovery-control.invalid", + "FIREMUD_RECOVERY_CONTROL_DB_USER=recovery", + "FIREMUD_RECOVERY_CONTROL_DB_PASSWORD=test-only", + "spring.jooq.sql-dialect=POSTGRES", + "spring.flyway.enabled=false", + "spring.grpc.server.enabled=false", + "spring.ssl.bundle.pem.firemud-grpc.keystore.certificate=classpath:certs/dev-cert.pem", + "spring.ssl.bundle.pem.firemud-grpc.keystore.private-key=classpath:certs/dev-key.pem", + "spring.ssl.bundle.pem.firemud-grpc.truststore.certificate=classpath:certs/dev-ca.pem" + }) +class RecoveryControllerPackagedWiringTest { + @Autowired private ApplicationContext context; + + @Test + void packagedApplicationDiscoversDeniedOwnerAndIsolatedJournalWithoutRedis() { + assertThat(context.getBean(InitialGameplayReleaseEvidenceProvider.class)) + .isInstanceOf(DeniedInitialGameplayReleaseEvidenceProvider.class); + assertThat(context.getBean(InitialGameplayReleaseEffectPort.class)) + .isInstanceOf(DeniedInitialGameplayReleaseEffectPort.class); + assertThat(context.getBean(InitialGameplayReleaseJournal.class)) + .isInstanceOf(JooqInitialGameplayReleaseJournal.class); + assertThat(context.getBeansOfType(InitialGameplayReleaseController.class)).hasSize(1); + assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); + String redisConnectionFactory = + "org.springframework.data.redis.connection.RedisConnectionFactory"; + ClassLoader loader = context.getClassLoader(); + // common-data-runtime puts Redis on the runtime classpath, not the test compile classpath. + if (ClassUtils.isPresent(redisConnectionFactory, loader)) { + assertThat( + context.getBeansOfType(ClassUtils.resolveClassName(redisConnectionFactory, loader))) + .isEmpty(); + } + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 1f49092af2..d6bb47610b 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -19,9 +19,16 @@ import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Target; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.Resume; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Operation; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PeerStorageBinding; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Phase; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PreparePlayableStateFencedEffect; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.PublicTransitionTuple; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; +import net.firedevops.firemud.recovery.model.MaintenanceLockCredential; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; @@ -148,8 +155,10 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { DIGEST, "proof-identity-1"); - assertThat(port.apply(effect, UUID.randomUUID()).status()) - .isEqualTo(InitialGameplayReleaseEffectPort.ApplyStatus.RETRYABLE_NO_EFFECT); + var result = port.apply(effect, UUID.randomUUID()); + assertThat(result.status()) + .isEqualTo(InitialGameplayReleaseEffectPort.ApplyStatus.NOT_DISPATCHED); + assertThat(result.outcomeCode()).isEqualTo("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); assertThat(port.readback(effect, UUID.randomUUID()).status()) .isEqualTo(InitialGameplayReleaseEffectPort.ReadbackStatus.UNAVAILABLE); } @@ -161,6 +170,9 @@ void applyOutcomeCodesUseJournalContract() { assertThatThrownBy( () -> InitialGameplayReleaseEffectPort.EffectApplyResult.retryableNoEffect(invalid)) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> InitialGameplayReleaseEffectPort.EffectApplyResult.notDispatched(invalid)) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> InitialGameplayReleaseEffectPort.EffectApplyResult.ambiguous(invalid)) .isInstanceOf(IllegalArgumentException.class); @@ -171,6 +183,72 @@ void applyOutcomeCodesUseJournalContract() { .isEqualTo("OWNER_BUSY"); } + @Test + void unavailableOwnerEvidenceReturnsConcurrentExactCommittedTransition() { + assertUnavailableTransition(true); + } + + @Test + void unavailableOwnerEvidenceWithoutCommittedTransitionStillFailsClosed() { + assertUnavailableTransition(false); + } + + private void assertUnavailableTransition(boolean committed) { + var journal = mock(InitialGameplayReleaseJournal.class); + var codec = mock(InitialGameplayReleaseTupleCodec.class); + var provider = mock(InitialGameplayReleaseEvidenceProvider.class); + var scope = + new Scope( + UUID.randomUUID(), + UUID.randomUUID(), + "release-target", + UUID.randomUUID(), + new PeerStorageBinding( + "release-target", "cluster-1", "recovery-peer", "storage-1", "revision-1", DIGEST), + "evidence"); + var before = mock(Operation.class); + var after = mock(Operation.class); + var evidence = mock(InitialGameplayReleaseEvidence.class); + var lock = MaintenanceLockCredential.issue(UUID.randomUUID()); + when(before.scope()).thenReturn(scope); + when(before.maintenanceLockIdentity()).thenReturn(lock.identity()); + when(before.evidence()).thenReturn(evidence); + when(evidence.evidenceIdentity()).thenReturn("proof"); + when(codec.digest(scope)).thenReturn(DIGEST); + when(codec.digest(evidence)).thenReturn(DIGEST); + when(journal.find(scope.operationId())).thenReturn(java.util.Optional.of(before)); + var tuple = + new PublicTransitionTuple( + scope.operationId(), + DIGEST, + TransitionVerb.RESUME, + Phase.AWAITING_RESUME, + lock.identity(), + scope.evidenceRef(), + "proof", + DIGEST); + when(journal.findTransition(tuple)) + .thenReturn( + java.util.Optional.empty(), + committed ? java.util.Optional.of(after) : java.util.Optional.empty()); + when(provider.read(scope)) + .thenReturn(InitialGameplayReleaseEvidenceProvider.EvidenceResolution.unavailable()); + var controller = + new InitialGameplayReleaseController( + journal, codec, provider, mock(InitialGameplayReleaseEffectPort.class)); + var command = new Resume(scope.operationId(), Phase.AWAITING_RESUME, lock, scope.evidenceRef()); + + if (committed) { + assertThat(controller.resume(command)).isSameAs(after); + } else { + assertThatThrownBy(() -> controller.resume(command)) + .isInstanceOf(OwnerBoundaryUnavailableException.class) + .hasMessage("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_UNAVAILABLE"); + } + verify(journal, org.mockito.Mockito.times(2)).findTransition(tuple); + verify(journal, never()).transition(any(), any()); + } + @Test void emptyOutboxReloadsLatestOperation() { var journal = mock(InitialGameplayReleaseJournal.class); From 2f3b3ca772a5168206c626d3b25e76a477bc4003 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:03:12 +1300 Subject: [PATCH 047/199] fix: finish retained preview and recovery review findings --- .github/workflows/hosted-identity-request.yml | 19 +++- .github/workflows/preview-reconciler.yml | 49 +++++++- .github/workflows/preview-runtime-refresh.yml | 56 +++++++-- .github/workflows/smoke.yml | 25 +++++ .../hosted/shared/wait-for-runtime-images.sh | 68 ++++++++++- ...d-identity-controller-workflow-contract.sh | 17 ++- .../tests/pr-retarget-workflow-contract.sh | 106 ++++++++++++++++++ dev-tools/tests/preview-priority-contract.sh | 100 ++++++++++------- .../tests/preview-runtime-refresh.test.cjs | 28 ++++- .../recovery/InitialGameplayRecoverCodec.java | 29 +++-- .../InitialGameplayRecoverCodecTest.java | 15 +++ 11 files changed, 437 insertions(+), 75 deletions(-) diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index bfe8cf49cd..b022e690c1 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -131,13 +131,26 @@ jobs: } SOURCE_RUN_ID="$WORKFLOW_RUN_ID" workflow_run_json="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}")" - require_source_field path '.github/workflows/preview.yml' "$(jq -r '.path // empty' <<<"$workflow_run_json")" + SOURCE_EVENT="$(jq -r '.event // empty' <<<"$workflow_run_json")" + source_path="$(jq -r '.path // empty' <<<"$workflow_run_json")" + source_path_pr="" + if [[ "$SOURCE_EVENT" == pull_request && + "$source_path" =~ ^[.]github/workflows/preview[.]yml@refs/pull/([1-9][0-9]{0,50})/merge$ ]]; then + source_path_pr="${BASH_REMATCH[1]}" + jq -e --arg pr "$source_path_pr" ' + .head_sha as $head | + ([.pull_requests[]? | select((.number | tostring) == $pr)] | + length == 1 and .[0].head.sha == $head) + ' <<<"$workflow_run_json" >/dev/null || + emit_no_action "Ignoring qualified source path without a matching pull request and head." + else + require_source_field path '.github/workflows/preview.yml' "$source_path" + fi require_source_field conclusion success "$(jq -r '.conclusion // empty' <<<"$workflow_run_json")" require_source_field repository "$GITHUB_REPOSITORY" \ "$(jq -r '.repository.full_name // empty' <<<"$workflow_run_json")" require_source_field head "$WORKFLOW_RUN_HEAD_SHA" \ "$(jq -r '.head_sha // empty' <<<"$workflow_run_json")" - SOURCE_EVENT="$(jq -r '.event // empty' <<<"$workflow_run_json")" [[ "$SOURCE_EVENT" == pull_request || "$SOURCE_EVENT" == repository_dispatch ]] || emit_no_action "Ignoring source run with unsupported event ${SOURCE_EVENT}." if [[ "$SOURCE_EVENT" == pull_request ]]; then @@ -183,6 +196,8 @@ jobs: PR_NUMBER="$(jq -er '.prNumber | select(type == "number" and floor == .)' "$ARTIFACT_DIRECTORY/preview-metadata.json")" EXPECTED_HEAD_SHA="$(jq -er '.headSha | select(type == "string")' "$ARTIFACT_DIRECTORY/preview-metadata.json")" if [[ "$SOURCE_EVENT" == pull_request ]]; then + [[ -z "$source_path_pr" || "$source_path_pr" == "$PR_NUMBER" ]] || + emit_no_action "Ignoring artifact not bound to the qualified source path pull request." jq -e --argjson pr "$PR_NUMBER" --arg head "$EXPECTED_HEAD_SHA" \ '.head_sha == $head and ([.pull_requests[] | select(.number == $pr)] | length) == 1 and ([.pull_requests[] | select(.number == $pr)][0].head.sha == $head)' \ <<<"$workflow_run_json" >/dev/null || diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 45a3678ef8..f0555686b8 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -340,6 +340,29 @@ jobs: active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" available_slots=$((max_active - active_count)) dispatch_sent=false + automatic_preview_has_tuple() { + local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" jobs latest + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" \ + --arg head "$head" --arg tuple "$tuple" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) + and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) + and any($jobs[]; + .name == "Preview Plan" and .run_id == $id and .run_attempt == $attempt + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and ([.steps[]? | select(.name | startswith("Preview event tuple "))] | length == 1) + and any(.steps[]?; .name == $tuple and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null || return 1 + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 1 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" ' + .id == $id and .run_attempt == $attempt and .head_sha == $head + and .event == "pull_request" + and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge")) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) + ' <<<"$latest" >/dev/null + } + dispatch_candidates() { while IFS=$'\t' read -r _ pr_number head_sha pr_author pr_base_ref pr_state labels_json_base64; do if ! labels_json="$(printf '%s' "$labels_json_base64" | base64 --decode 2>/dev/null)" || @@ -517,8 +540,8 @@ jobs: fi fi - if ! active_preview_run_id="$( - jq -r \ + if ! preview_candidates="$( + jq -c \ --arg workflow_name "${preview_workflow_name}" \ --arg trusted_workflow_name "Trusted Hosted Identity Request" \ --arg default_branch "${DEFAULT_BRANCH}" \ @@ -554,7 +577,11 @@ jobs: ) and ( .display_title == $run_name - or (.display_title == $pr_title + or (.name == $workflow_name and .event == "pull_request" + and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) + and .display_title == $pr_title + and (.id > 0 and .id == (.id | floor)) + and ((.run_attempt | type) == "number" and .run_attempt > 0 and .run_attempt == (.run_attempt | floor)) and .head_sha == $head_sha and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) ) @@ -566,7 +593,8 @@ jobs: or .status == "pending" ) ) - | .id + | if .display_title == $run_name then {id, exact: true} + else {id, run_attempt, exact: false} end end end ' <<<"${active_preview_runs_json}" @@ -575,6 +603,19 @@ jobs: exit 1 fi + active_preview_run_id="$(jq -rs '[.[] | select(.exact)][0].id // empty' <<<"$preview_candidates")" + if [[ -z "$active_preview_run_id" ]]; then + # A same-head title is not proof: the base can move independently. + tuple_step="Preview event tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + while IFS=$'\t' read -r run_id run_attempt; do + [[ -n "$run_id" ]] || continue + if automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number"; then + active_preview_run_id="$run_id" + break + fi + done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt] | @tsv' <<<"$preview_candidates") + fi + if [[ -n "${active_preview_run_id}" ]]; then echo "Skipping proof retry for PR #${pr_number}: preview source or trusted consumer run ${active_preview_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." continue diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index bdb4b5009e..3cea49c900 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -76,7 +76,9 @@ jobs: } const plans = jobs.filter(job => job.name === 'Preview Plan'); if (plans.length !== 1) { - core.info('Missing or ambiguous Preview Plan metadata; await a fresh preview render.'); + core.info(plans.length === 0 && attempt > 1 + ? 'Preview Plan is absent from this rerun attempt. Use Re-run all jobs so a fresh plan proves this render.' + : 'Missing or ambiguous Preview Plan metadata; await a fresh preview render.'); return; } const plan = plans[0]; @@ -109,7 +111,7 @@ jobs: ...context.repo, ref: recorded[4], }); if (recordedMerge.sha !== recorded[4] || recordedMerge.parents?.length !== 2 || - recordedMerge.parents[0].sha !== recorded[2] || + !sha.test(recordedMerge.parents[0].sha) || recordedMerge.parents[1].sha !== recorded[3]) { core.info('Recorded preview merge does not prove its base/head tuple; no dispatch.'); return; @@ -118,16 +120,20 @@ jobs: ...context.repo, pull_number: source.number, }); // Execute only the checked-out default-branch eligibility policy. - try { - require('node:child_process').execFileSync('python3', [ - './dev-tools/hosted/preview/preview-eligibility.py', '--revalidate-deploy', - '--expected-repository', repository, '--expected-head-sha', run.head_sha, - ], {encoding: 'utf8', input: JSON.stringify(pr)}); - } catch (error) { - if (error.status !== 1) throw error; - core.info('Canonical preview eligibility refused the current PR; no dispatch.'); - return; - } + const isEligible = (pull) => { + try { + require('node:child_process').execFileSync('python3', [ + './dev-tools/hosted/preview/preview-eligibility.py', '--revalidate-deploy', + '--expected-repository', repository, '--expected-head-sha', run.head_sha, + ], {encoding: 'utf8', input: JSON.stringify(pull)}); + return true; + } catch (error) { + if (error.status !== 1) throw error; + core.info('Canonical preview eligibility refused the current PR; no dispatch.'); + return false; + } + }; + if (!isEligible(pr)) return; const isIntegrationBase = ['main', 'develop'].includes(pr.base?.ref); if (pr.state !== 'open' || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || @@ -153,6 +159,14 @@ jobs: core.info('Current merge is not the exact current base/head tuple; no dispatch.'); return; } + // An event can retain an older base while its merge SHA already + // identifies the current test merge. Admit that mismatch only when + // both independent GitHub reads prove the exact same current merge. + if (recordedMerge.parents[0].sha !== recorded[2] && + (recordedMerge.sha !== merge.sha || recordedMerge.parents[0].sha !== base.object.sha)) { + core.info('Recorded preview merge does not prove its base/head tuple; no dispatch.'); + return; + } // Reuse the canonical default-branch path classifier rather than // trusting source outputs or maintaining a second image policy. const imageTag = require('node:child_process').execFileSync('bash', [ @@ -212,6 +226,24 @@ jobs: if (page === 3) throw new Error('Active runtime inventory exceeds bounded lookup'); } } + const {data: latestPr} = await github.rest.pulls.get({ + ...context.repo, pull_number: source.number, + }); + if (!isEligible(latestPr) || latestPr.number !== pr.number || + latestPr.state !== 'open' || latestPr.head?.repo?.full_name !== repository || + latestPr.base?.repo?.full_name !== repository || + latestPr.head?.sha !== pr.head.sha || latestPr.base?.ref !== pr.base.ref || + latestPr.merge_commit_sha !== merge.sha) { + core.info('Preview eligibility or exact tuple changed during runtime lookup; no dispatch.'); + return; + } + const {data: latestBase} = await github.rest.git.getRef({ + ...context.repo, ref: `heads/${pr.base.ref}`, + }); + if (latestBase.object?.sha !== base.object.sha) { + core.info('Preview base changed during runtime lookup; no dispatch.'); + return; + } await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: 'pr-runtime-base-refresh', client_payload: { diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 203c734346..d973463d34 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -987,6 +987,31 @@ jobs: newestPreExecutionCancellation ??= run; continue; } + if (run.status !== "completed") { + const completed = matchingRuns.filter(({run: older}) => + older.id !== run.id && older.status === "completed" && older.conclusion === "success"); + for (const {run: older} of completed.slice(0, 3)) { + try { + const jobs = await withTransientGitHubRetry("duplicate runtime attempt jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: older.id, attempt_number: older.run_attempt, per_page: 100, + }) + ); + const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); + const smoke = (producers[0]?.steps ?? []).filter((step) => + step.name === "Run credential-free full-stack smoke"); + if (producers.length === 1 && smoke.length === 1 && + smoke[0].status === "completed" && smoke[0].conclusion === "success" && + await verifyCanonicalSmokeProducer(older, producers[0], identity)) { + core.info("A verified completed exact runtime producer precedes the pending duplicate."); + return older; + } + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.info("Older runtime producer proof is unavailable; retain the existing wait."); + } + } + } return run; } return newestPreExecutionCancellation; diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 7c84d3bb13..d6ef3bc348 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -62,7 +62,8 @@ 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 = sys.argv[1:6] +exclude_pending_id = sys.argv[6] if len(sys.argv) > 6 else "" try: payload = json.load(sys.stdin) except json.JSONDecodeError: @@ -108,6 +109,9 @@ def is_matching_run(run): ) matching_runs = [run for run in workflow_runs if is_matching_run(run)] +if exclude_pending_id: + matching_runs = [run for run in matching_runs if str(run.get("id")) != exclude_pending_id + and run.get("status") == "completed" and run.get("conclusion") == "success"] if not matching_runs: print("missing") raise SystemExit(0) @@ -148,7 +152,7 @@ print( created_at, ) ) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" +' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" } fetch_publisher_runs() { @@ -219,7 +223,7 @@ import json import re import sys -wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id = sys.argv[1:] +wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id = sys.argv[1:7] if not re.fullmatch(r"[1-9][0-9]*", source_run_id): raise SystemExit(1) try: @@ -258,6 +262,9 @@ if wait_mode == "pull-request": ] else: matching_runs = [] +if len(sys.argv) > 7: + matching_runs = [run for run in matching_runs if run.get("event") == "repository_dispatch" + and run.get("status") == "completed" and run.get("conclusion") == "success"] if not matching_runs: print("missing") raise SystemExit(0) @@ -271,7 +278,54 @@ print( run.get("html_url", ""), ) ) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$1" +' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" +} + +# Only a source-ID-bound typed callback with positive native publication proof +# can finish the wait ahead of a pending producer. Skipped publication cannot. +use_completed_duplicate_publication() { + local state older_id older_created inventory upper line publisher_id run attempt jobs latest + IFS=$'\t' read -r state older_id _ _ _ _ older_created <<<"$1" + [[ "$state" == "found" ]] || return 1 + local source source_attempt source_latest + source="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source" | read_run_state)" == "$1" ]] || return 1 + source_attempt="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' + select(.repository.full_name == $repo and .head_repository.full_name == $repo) + | .run_attempt | select(type == "number" and . >= 1 and floor == .) + ' <<<"$source")" || return 1 + upper="$(date -u +%Y-%m-%dT%H:%M:%SZ)" || return 1 + inventory="$(fetch_publisher_runs repository_dispatch "$older_created" "$upper")" || return 1 + line="$(read_publisher_state "$older_id" completed-typed <<<"$inventory")" || return 1 + IFS=$'\t' read -r state publisher_id _ <<<"$line" + [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ ]] || return 1 + run="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 + attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" \ + --arg title "Publish PR Runtime Images source-run-${older_id}" ' + select(.id == $id and .event == "repository_dispatch" and .display_title == $title + and .path == ".github/workflows/publish-pr-runtime-images.yml" + and .repository.full_name == $repo and .head_repository.full_name == $repo + and .status == "completed" and .conclusion == "success") + | .run_attempt | select(type == "number" and . >= 1 and floor == .) + ' <<<"$run")" || return 1 + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' + (.jobs | type == "array") and (.total_count == (.jobs | length)) and + ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | + ($jobs | length) == 1 and ($jobs[0] | + .run_id == $id and .run_attempt == $attempt and + .status == "completed" and .conclusion == "success" and + ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | + ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) + ' <<<"$jobs" >/dev/null || return 1 + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' + .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" + ' <<<"$latest" >/dev/null || return 1 + source_latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 + jq -e --argjson attempt "$source_attempt" '.run_attempt == $attempt' <<<"$source_latest" >/dev/null || return 1 + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$1" ]] || return 1 + printf 'Trusted PR image publisher %s succeeded for %s before a duplicate producer.\n' "$publisher_id" "$image_tag" } wait_for_pr_publisher() { @@ -386,6 +440,12 @@ while (( SECONDS < deadline )); do continue fi + if [[ "$wait_mode" == "pull-request" && "$run_status" != "completed" ]] && + older_state="$(read_run_state "$run_id" <<<"$workflow_payload")" && + use_completed_duplicate_publication "$older_state"; then + exit 0 + fi + if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then printf 'Matching runtime-images workflow %s succeeded for %s after %ss.\n' \ "${run_id}" "${image_tag}" "$((SECONDS - start_epoch))" diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index ea291d777c..9e11b57e34 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6724,7 +6724,7 @@ target_real_python3="$(command -v python3)" canonical_artifact_name='preview-render-pr-900-cccccccccccccccccccccccccccccccccccccccc' valid_workflow_run_json='{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"cccccccccccccccccccccccccccccccccccccccc"}}]}' distinct_source_sha=dddddddddddddddddddddddddddddddddddddddd -distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"dddddddddddddddddddddddddddddddddddddddd"}}]}' +distinct_source_workflow_run_json='{"conclusion":"success","head_sha":"dddddddddddddddddddddddddddddddddddddddd","path":".github/workflows/preview.yml@refs/pull/900/merge","event":"pull_request","repository":{"full_name":"example/FireMUD"},"pull_requests":[{"number":900,"head":{"sha":"dddddddddddddddddddddddddddddddddddddddd"}}]}' valid_artifacts_json='[{"artifacts":[{"name":"'"$canonical_artifact_name"'","expired":false},{"name":"old-preview","expired":true},{"name":"unrelated-artifact","expired":false}]}]' run_deploy_target_fixture() { @@ -6791,6 +6791,17 @@ run_deploy_target_fixture() { run_deploy_target_fixture valid 0 'action=deploy' grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-valid.output" +qualified_source_run_json="$(jq -c '.path += "@refs/pull/900/merge"' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$qualified_source_run_json" \ + run_deploy_target_fixture qualified-source-deploy 0 'action=deploy' +grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-qualified-source-deploy.output" +cross_pr_qualified_source_run_json="$(jq -c ' + .path += "@refs/pull/901/merge" | .pull_requests += [{number:901,head:{sha:.head_sha}}] +' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$cross_pr_qualified_source_run_json" \ + run_deploy_target_fixture qualified-source-cross-pr 0 'Ignoring artifact not bound to the qualified source path pull request.' +grep -Fxq 'action=none' "$TEMP_DIR/deploy-target-qualified-source-cross-pr.output" + FAKE_FIXTURE_PR_FILES_JSON='[[{"filename":"services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql"}]]' \ run_deploy_target_fixture v2-schema-migration 0 'v2_schema_migration_change=true' FAKE_FIXTURE_PR_FILES_JSON='[[{"filename":"services/game-session-service/src/main/resources/db/migration/R__refresh_runtime_views.sql"}]]' \ @@ -6992,6 +7003,10 @@ run_invalid_source_field \ path \ '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/other.yml","event":"pull_request","repository":{"full_name":"example/FireMUD"}}' \ '::error title=Unexpected source run path::Expected .github/workflows/preview.yml; actual .github/workflows/other.yml.' +run_invalid_source_field \ + dispatch-qualified-path \ + '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml@refs/pull/7/merge","event":"repository_dispatch","repository":{"full_name":"example/FireMUD"}}' \ + '::error title=Unexpected source run path::Expected .github/workflows/preview.yml; actual .github/workflows/preview.yml@refs/pull/7/merge.' run_invalid_source_field \ repository \ '{"conclusion":"success","head_sha":"cccccccccccccccccccccccccccccccccccccccc","path":".github/workflows/preview.yml","event":"pull_request","repository":{"full_name":"fork/FireMUD"}}' \ diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 9233ef0af5..580f938790 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2154,6 +2154,15 @@ if [[ -n "${CONTRACT_GH_STATE_FILE:-}" ]]; then fi fi +if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then + case "$*" in + *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source.json"; exit 0 ;; + *actions/runs/202) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher.json"; exit 0 ;; + *actions/runs/202/attempts/2/jobs?per_page=100) + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-$CONTRACT_DUPLICATE_JOB.json"; exit 0 ;; + esac +fi + if [[ "$*" == *"publish-pr-runtime-images.yml"* ]]; then [[ "$*" != *"--paginate"* ]] || { echo 'publisher inventory must be bounded' >&2; exit 1; } if [[ -n "${CONTRACT_PUBLISHER_PAYLOAD:-}" ]]; then @@ -2238,6 +2247,20 @@ for created_at in [source["created_at"], "2026-02-31T00:01:00Z", "2026-07-24T00: def parse_source(run): return subprocess.run([sys.executable, "-c", source_parser, "pull-request", "pr-merge-" + "c" * 40, "c" * 40, "b" * 40, "a" * 40], input=json.dumps({"workflow_runs": [run]}), capture_output=True, text=True) +pending_duplicate = {**source, "id": 104, "status": "in_progress", + "conclusion": None, "created_at": "2026-07-24T00:05:00Z"} +source_argv = [sys.executable, "-c", source_parser, "pull-request", "pr-merge-" + "c" * 40, + "c" * 40, "b" * 40, "a" * 40] +def parse_duplicates(*duplicate_runs, completed_alternative=False): + return subprocess.run(source_argv + (["104"] if completed_alternative else []), + input=json.dumps({"workflow_runs": list(duplicate_runs)}), + capture_output=True, text=True, check=True).stdout.split("\t") + +assert parse_duplicates(pending_duplicate, source)[1] == "104" +assert parse_duplicates(pending_duplicate, source, completed_alternative=True)[1] == "101" +wrong_tuple = {**source, "display_title": source["display_title"].replace("merge-" + "c" * 40, "merge-" + "d" * 40)} +assert parse_duplicates(pending_duplicate, wrong_tuple, completed_alternative=True) == ["missing\n"] + for field, values in {"id": [None, 0, True, "101"], "status": [None, "", "completed\t"], "html_url": [None, "", "https://example.test/\t101"], "conclusion": [None, "", "success\n"]}.items(): for value in values: assert parse_source({**source, field: value}).returncode != 0, f"malformed source {field} must be rejected" @@ -2251,6 +2274,20 @@ for conclusion in [None, ""]: assert split.stdout.splitlines() == ["found", "101", "in_progress", "pending", source["html_url"], source["event"], source["created_at"]], "optional conclusion must preserve Bash field positions" base = {"id": 202, "event": "repository_dispatch", "status": "completed", "conclusion": "success", "html_url": "https://example.test/publisher/202", "display_title": "Publish PR Runtime Images source-run-101", "created_at": "2026-07-24T00:04:00Z"} +repository = {"full_name": "example/FireMUD"} +(root / "duplicate-inventory.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, source]})) +(root / "duplicate-source.json").write_text(json.dumps({**source, "run_attempt": 1, + "repository": repository, "head_repository": repository})) +(root / "duplicate-publisher.json").write_text(json.dumps({**base, "run_attempt": 2, + "path": ".github/workflows/publish-pr-runtime-images.yml", "repository": repository, + "head_repository": repository})) +for conclusion in ["success", "skipped"]: + (root / f"duplicate-jobs-{conclusion}.json").write_text(json.dumps({"total_count": 1, "jobs": [ + {"name": "Publish Fixed PR Merge Image Tags", "run_id": 202, "run_attempt": 2, + "status": "completed", "conclusion": "success", "steps": [ + {"name": "Publish fixed PR image tags", "status": "completed", "conclusion": conclusion} + ]} + ]})) fixtures = { "dispatch-success": base, "dispatch-wrong-source": {**base, "display_title": "Publish PR Runtime Images source-run-999"}, @@ -2270,6 +2307,22 @@ many = [{**base, "id": 300 + index, "display_title": f"Publish PR Runtime Images (root / "dispatch-outside-window.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-07-23T00:00:00Z"}]})) (root / "dispatch-invalid-date.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-02-31T00:00:00Z"}]})) PY_FIXTURES +for conclusion in success skipped; do + if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB="$conclusion" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/duplicate-$conclusion.output" 2>"$contract_fixture_dir/duplicate-$conclusion.error"; then + [[ "$conclusion" == "success" ]] || { echo "Skipped publication step bypassed duplicate wait" >&2; exit 1; } + require_contains "$contract_fixture_dir/duplicate-$conclusion.output" 'Trusted PR image publisher 202 succeeded' + else + [[ "$conclusion" == "skipped" ]] || { cat "$contract_fixture_dir/duplicate-$conclusion.error" >&2; exit 1; } + require_contains "$contract_fixture_dir/duplicate-$conclusion.output" 'Waiting for runtime-images workflow 104' + fi +done for fixture in missing-url empty-url; do if CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$fixture.json" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ @@ -2722,6 +2775,59 @@ script_path.write_text(textwrap.dedent("\n".join(body)) + "\n", encoding="utf-8" PY # Exercise the checked-in retry/cache functions without live GitHub requests. +node - "$smoke_gate_script" <<'NODE_DUPLICATE_SMOKE' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const script = fs.readFileSync(process.argv[2], "utf8"); +const start = script.indexOf("async function findMatchingRuntimeImagesRun("); +const end = script.indexOf("async function resolveCurrentIdentity(", start); +assert.ok(start >= 0 && end > start); +const source = script.slice(start, end); +const identity = {baseSha: "a".repeat(40), headSha: "b".repeat(40), mergeSha: "c".repeat(40)}; +const title = "exact runtime producer"; +const name = "PR Full-Stack Smoke (runtime-required=true)"; +const pending = {id: 10, event: "pull_request", head_sha: identity.headSha, display_title: title, + status: "in_progress", run_attempt: 1, created_at: "2026-07-24T00:10:00Z"}; +const older = id => ({...pending, id, status: "completed", conclusion: "success", + created_at: "2026-07-24T00:01:00Z"}); +async function choose(runs, verifiedId, smokeConclusion = "success") { + const lookedUp = []; + const paginate = async (route, args) => { + assert.match(route, /\/attempts\/\{attempt_number\}\/jobs$/); + assert.equal(args.attempt_number, 1); + lookedUp.push(args.run_id); + return [{id: args.run_id, name, steps: [{name: "Run credential-free full-stack smoke", + status: "completed", conclusion: smokeConclusion}]}]; + }; + paginate.iterator = async function* (_method, query) { + assert.equal(query.head_sha, identity.headSha); + yield {data: runs}; + }; + const github = {paginate, rest: {actions: {listWorkflowRuns() {}}}}; + const execute = new Function("owner", "repo", "prNumber", "github", "context", "core", + "withTransientGitHubRetry", "positiveInteger", "isPreExecutionCancelledAttempt", + "canonicalSmokeJobName", "verifyCanonicalSmokeProducer", "TerminalGitHubRequestError", + "identity", "title", source + "\nreturn findMatchingRuntimeImagesRun('pull_request', title, identity);"); + const selected = await execute("example", "repo", "7", github, {}, {info() {}}, + (_label, run) => run(), n => Number.isInteger(n) && n > 0, async () => false, name, + async (run, job, tuple) => { + assert.equal(job.id, run.id); + assert.equal(tuple, identity); + return run.id === verifiedId; + }, class extends Error {}, identity, title); + return {id: selected.id, lookedUp}; +} +(async () => { + assert.deepEqual(await choose([pending, older(3)], 3), {id: 3, lookedUp: [3]}); + assert.deepEqual(await choose([pending, older(3)], 9), {id: 10, lookedUp: [3]}); + assert.deepEqual(await choose([pending, older(3)], 3, "skipped"), {id: 10, lookedUp: [3]}); + assert.deepEqual(await choose([pending, {...older(3), display_title: "wrong tuple"}], 3), + {id: 10, lookedUp: []}); + assert.deepEqual(await choose([pending, older(4), older(3), older(2), older(1)], 1), + {id: 10, lookedUp: [4, 3, 2]}); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE_DUPLICATE_SMOKE + node - "$smoke_gate_script" <<'NODE' const assert = require("node:assert/strict"); const fs = require("node:fs"); diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index a3ee3aa6f9..c59164a5c9 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -443,6 +443,14 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == fi exit 0 fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254/attempts/2/jobs?per_page=100' ]]; then + printf '%s' "${FAKE_PREVIEW_PLAN_JOBS_JSON:-null}" + exit 0 +fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254' ]]; then + printf '%s' "${FAKE_PREVIEW_SOURCE_LATEST_JSON:-null}" + exit 0 +fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then printf '%s\n' "$*" >> "$FAKE_DISPATCH_LOG" exit 0 @@ -2515,7 +2523,7 @@ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" reset_case -reconciler_source_title_consumer_output="$TEMP_DIR/reconciler-source-title-consumer.out" +reconciler_source_title_consumer_output="$TEMP_DIR/reconciler-unqualified-consumer.out" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -2527,46 +2535,52 @@ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_source_title_consumer_output" grep -Fqx \ - "Skipping proof retry for PR #901: preview source or trusted consumer run 5253 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ + "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ "$reconciler_source_title_consumer_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" - -reset_case -reconciler_pull_request_target_output="$TEMP_DIR/reconciler-pull-request-target.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5254,"path":".github/workflows/preview.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"name":"PR Preview Environment","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_pull_request_target_output" -grep -Fqx \ - "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ - "$reconciler_pull_request_target_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" +test -s "$FAKE_DISPATCH_LOG" -reset_case -reconciler_workflow_run_output="$TEMP_DIR/reconciler-workflow-run.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5255,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"}]}]' \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_workflow_run_output" -grep -Fqx \ - "Skipping proof retry for PR #901: preview source or trusted consumer run 5255 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ - "$reconciler_workflow_run_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" +# An automatic run must prove exactly this tuple in its current native attempt. +for tuple_case in current qualified old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path; do + reset_case + reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" + tuple_name="Preview event tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" + old_tuple_name="Preview event tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-dddddddddddddddddddddddddddddddddddddddd" + plan_jobs="$(jq -cn --arg tuple "$tuple_name" --arg old "$old_tuple_name" \ + --arg head "$preview_head_sha" --arg variant "$tuple_case" ' + def step($name): {name:$name,status:"completed",conclusion:"success"}; + [{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head,status:"completed",conclusion:"success", + steps:(if $variant == "old_merge" then [step($old)] + elif $variant == "ambiguous" then [step($tuple),step($old)] + else [step($tuple)] end)}] | + if $variant == "missing" then {jobs:[],total_count:0} else {jobs:.,total_count:length} end')" + latest_source="$(jq -cn --arg head "$preview_head_sha" --arg variant "$tuple_case" ' + {id:5254,run_attempt:(if $variant == "stale_attempt" then 3 else 2 end), + head_sha:$head,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"}')" + ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PREVIEW_PLAN_JOBS_JSON="$plan_jobs" \ + FAKE_PREVIEW_SOURCE_LATEST_JSON="$latest_source" \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$reconciler_pull_request_output" + if [[ "$tuple_case" == current || "$tuple_case" == qualified ]]; then + grep -Fqx \ + "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ + "$reconciler_pull_request_output" + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" + else + grep -Fqx \ + "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ + "$reconciler_pull_request_output" + test -s "$FAKE_DISPATCH_LOG" + fi +done reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance.out" @@ -2576,8 +2590,12 @@ reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-adva FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[{"id":5256,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"branch","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"queued"},{"id":5256,"path":".github/workflows/hosted-identity-request.yml","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","pull_requests":[{"number":901}],"event":"workflow_run","name":"Trusted Hosted Identity Request","head_branch":"feature-preview","display_title":"PR preview 901","status":"in_progress"}]}]' \ -PREVIEW_MAX_ACTIVE=2 \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ + --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" ' + [{workflow_runs:([{id:5256,path:".github/workflows/hosted-identity-request.yml", + name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title} + | . + {event:"branch",status:"queued"}, . + {event:"workflow_run",status:"in_progress"}])}]')" \ + PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" grep -Fqx \ diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index a7335ca95b..255cc9052b 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -43,7 +43,8 @@ async function execute(f, sent = []) { }, pulls: {get: async ({pull_number}) => { assert.equal(pull_number, f.pr.number); - return {data: f.pr}; + f.pullReads = (f.pullReads ?? 0) + 1; + return {data: f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr}; }}, git: {getRef: async ({ref}) => { assert.equal(ref, 'heads/' + f.pr.base.ref); @@ -52,14 +53,14 @@ async function execute(f, sent = []) { repos: {getCommit: async ({ref}) => ({data: ref === E ? f.recordedMerge : f.merge}), createDispatchEvent: async p => sent.push(p)}, }}; await new AsyncFunction('github', 'context', 'core', 'require', script)(github, - {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99, run_attempt: 2}, repository: {default_branch: 'develop'}}}, {info() {}}, name => { + {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99, run_attempt: 2}, repository: {default_branch: 'develop'}}}, {info(message) {(f.messages ??= []).push(message);}}, name => { assert.equal(name, 'node:child_process'); return {execFileSync(command, args, options) { if (command === 'python3') { assert.deepEqual(args, ['./dev-tools/hosted/preview/preview-eligibility.py', '--revalidate-deploy', '--expected-repository', 'example/FireMUD', '--expected-head-sha', f.run.head_sha]); - assert.deepEqual(JSON.parse(options.input), f.pr); + assert.deepEqual(JSON.parse(options.input), f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr); return execFileSync(command, args, {...options, cwd: root}); } assert.equal(command, 'bash'); @@ -261,6 +262,27 @@ test('immutable title repairs base despite current mutable association', async ( assert.equal((await execute(f)).length, 1); }); +test('partial rerun without an exact-attempt plan gives safe full-rerun guidance', async () => { + const f = fixture(); f.jobs = []; + assert.deepEqual(await execute(f), []); + assert.ok(f.messages.some(message => message.includes('Re-run all jobs'))); +}); + +test('priority removed during active lookup refuses dispatch', async () => { + const f = fixture(); + f.pr.base.ref = 'feature/stack'; + f.pr.labels = [{name: 'preview:priority'}]; + f.latestPr = {...f.pr, labels: []}; + assert.deepEqual(await execute(f), []); + assert.equal(f.pullReads, 2); +}); + +test('event base drift can repair the independently revalidated current merge', async () => { + const f = fixture(); + f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${D} head-${C} merge-${A}`; + assert.equal((await execute(f)).length, 1); +}); + test('truncated or oversized attempt inventory is refused', async () => { for (const inventory of [{total_count: 301, jobs: []}, {total_count: 2, jobs: []}]) { const f = fixture(); f.inventory = inventory; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java index fb1ca618fc..3adea73dca 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodec.java @@ -32,8 +32,17 @@ * The request identity and fixed target owner are context, deliberately outside the digest. */ public final class InitialGameplayRecoverCodec { + /** Raw request limit; every encoded JSON token inherits this same 16,384-byte ceiling. */ public static final int MAX_RAW_BYTES = 16384; - public static final int MAX_RAW_STRING_CHARACTERS = 4096; + + public static final int MAX_DECODED_STRING_UTF16_UNITS = 4096; + + /** + * @deprecated This historically named limit measures decoded text, not raw JSON token bytes. + */ + @Deprecated public static final int MAX_RAW_STRING_CHARACTERS = MAX_DECODED_STRING_UTF16_UNITS; + + private static final int MAX_DECODED_STRING_UTF8_BYTES = 4096; public static final int MAX_DEPTH = 4; public static final int MAX_OBJECT_MEMBERS = 8; public static final int MAX_CANONICAL_SEGMENT_BYTES = 8192; @@ -45,7 +54,7 @@ public final class InitialGameplayRecoverCodec { .streamReadConstraints( StreamReadConstraints.builder() .maxNestingDepth(MAX_DEPTH) - .maxStringLength(MAX_RAW_STRING_CHARACTERS) + .maxStringLength(MAX_DECODED_STRING_UTF16_UNITS) .maxNumberLength(1) .build()) .build(); @@ -53,8 +62,12 @@ public final class InitialGameplayRecoverCodec { private InitialGameplayRecoverCodec() {} /** - * Reads bounded raw UTF-8 in the declared member order without a generic tree/map decoder. - * Original bytes are validated before normalization; no replacement-character repair is used. + * Reads bounded raw UTF-8 in the declared member order without a generic tree/map decoder. The + * complete byte array is checked before UTF-8 decoding or parser allocation. Because each encoded + * token is part of that array, it cannot exceed 16,384 raw bytes. There is no separate raw-token + * check: the 4,096 limits apply to decoded string length and UTF-8 bytes, not its escaped JSON + * spelling. Malformed UTF-8 is rejected, not repaired. Field-specific text limits still apply + * before and after NFC. */ public static InitialGameplayRecoverRequest decode(byte[] raw) { Objects.requireNonNull(raw, "raw"); @@ -275,10 +288,10 @@ private static void segment(ByteArrayOutputStream output, byte[] bytes) { private static String string(JsonParser parser, String name) throws IOException { member(parser, name); require(parser.nextToken(), JsonToken.VALUE_STRING); - String raw = parser.getText(); - InitialGameplayRecoverRequest.text(raw, MAX_RAW_STRING_CHARACTERS); - // Field constructors must see the original value to enforce their raw byte limits. - return raw; + String decoded = parser.getText(); + InitialGameplayRecoverRequest.text(decoded, MAX_DECODED_STRING_UTF8_BYTES); + // Field constructors need the original decoded value to enforce pre-NFC byte limits. + return decoded; } private static void literal(JsonParser parser, String name, String value) throws IOException { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java index c6388e77a7..6e34fd4aa9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/recovery/InitialGameplayRecoverCodecTest.java @@ -154,6 +154,21 @@ void rejectsNoncanonicalIdsWrongTypesMalformedUnicodeAndOverlimits() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void encodedTokenCanExceedDecodedStringLimitWithinRawRequestCeiling() { + String detail = "a".repeat(700); + String escaped = "\\u0061".repeat(700); + assertThat(escaped.getBytes(StandardCharsets.UTF_8).length).isGreaterThan(4096); + String wire = WIRE.replace("\"initial\"", "\"" + escaped + "\""); + int paddingBytes = + InitialGameplayRecoverCodec.MAX_RAW_BYTES - wire.getBytes(StandardCharsets.UTF_8).length; + String atRawLimit = wire + " ".repeat(paddingBytes); + + assertThat(decode(atRawLimit)) + .isEqualTo(decode(WIRE.replace("\"initial\"", "\"" + detail + "\""))); + rejects(atRawLimit + " "); + } + @Test void rejectsRawFieldsThatShrinkBelowTheirLimitOnlyAfterNormalization() { rejects(WIRE.replace("\"world\"", "\"" + "e\u0301".repeat(43) + "\"")); From fc756464004563bb9997388717686b87315f0697 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:19:08 +1300 Subject: [PATCH 048/199] fix: retain summary callbacks and prove ambiguous recovery isolation --- .github/actionlint.yaml | 5 ++++- .github/workflows/static-analysis-summary.yml | 6 ++++-- dev-tools/tests/static-analysis-summary-contract.sh | 1 + ...tialGameplayReleaseJournalPostgresIntegrationTest.java | 8 +++++--- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index a9dd088ee8..1783aa6378 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -4,8 +4,11 @@ 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. +# only in workflows explicitly using this documented queue option. paths: + .github/workflows/static-analysis-summary.yml: + ignore: + - 'unexpected key "queue" for "concurrency" section' .github/workflows/preview.yml: ignore: - 'unexpected key "queue" for "concurrency" section' diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index ec300dc16e..efe1c5780c 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -56,10 +56,12 @@ jobs: needs: [resolve-summary-target] if: ${{ needs.resolve-summary-target.outputs.pull-number != '' }} # Only validated PR callbacks enter this queue. Old heads refresh the same - # live PR; other PRs and skipped push callbacks cannot replace its pending work. + # live PR. Retain up to 100 pending callbacks, so a failing late callback + # cannot replace the pending terminal update; other PRs have separate queues. concurrency: group: static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }} cancel-in-progress: false + queue: max runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -107,7 +109,7 @@ jobs: ".github/workflows/license-scan.yml": "License Gate", })[sourceWorkflowPath]; // The completion is a wake signal, never proof for the current base. - // An older-head or older-base callback may replace pending work for this PR. + // An older-head or older-base callback may run after newer work for this PR. // Validate its original identity, then derive proof only from the live tuple. const sourceBaseSha = String(context.payload.workflow_run.display_title || "") .match(/ base-([0-9a-f]{40}) head-/)?.[1]; diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 4277c45ebb..eb7e768585 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -93,6 +93,7 @@ assert publisher["if"] == "${{ needs.resolve-summary-target.outputs.pull-number assert publisher["concurrency"] == { "group": "static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }}", "cancel-in-progress": "false", + "queue": "max", } step = next(step for step in resolver["steps"] if step.get("id") == "target") assert resolver["outputs"]["pull-number"] == "${{ steps.target.outputs.pull-number }}" diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 7ecfecae7f..82608ca3ca 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -360,7 +360,8 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { Operation awaiting = journal.transition( transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base.plusSeconds(3)); - journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(4)); + Operation authorized = + journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(4)); OutboxEntry prepare = journal.findNextEffect(scope.operationId()).orElseThrow(); UUID attemptId = UUID.randomUUID(); OutboxEntry dispatched = @@ -383,8 +384,9 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(retryRead.state()).isEqualTo(EffectOutboxState.AMBIGUOUS); assertThat(retryRead.lastAttemptId()).isEqualTo(attemptId); assertThat(retryRead.attemptCount()).isEqualTo(1); - assertThat(journal.find(scope.operationId()).orElseThrow().phase()) - .isEqualTo(Phase.RESUME_AUTHORIZED); + assertThat(journal.find(scope.operationId())).contains(authorized); + assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isEmpty(); OutboxEntry definitiveNoEffect = journal.recordRetryableEffect( scope.operationId(), From 75c78d335f3200d2d323a2b3f6a52cb5a85012ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:39:03 +1300 Subject: [PATCH 049/199] fix: reconcile review proof fixtures and native summary classification --- .github/workflows/static-analysis-summary.yml | 58 +++++++++---------- .github/workflows/validation-summary.yml | 1 + .../preview/validate-preview-artifact.py | 5 ++ .../tests/ci-validation-summary-contract.sh | 5 ++ .../pr-required-gate-context-contract.sh | 46 ++++++++++++++- .../preview-runner-isolation-contract.sh | 5 +- ...otected-pod-admission-workflow-contract.sh | 6 +- .../tests/static-analysis-summary-contract.sh | 35 +++++++++-- .../test_validate_preview_artifact.py | 23 ++++++++ 9 files changed, 144 insertions(+), 40 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index efe1c5780c..c317d2e129 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -161,19 +161,6 @@ jobs: return numericIdentity(left?.id) - numericIdentity(right?.id); }; - const selectLatestWorkflowRun = (workflowRuns) => { - const candidates = (Array.isArray(workflowRuns) ? workflowRuns : []).filter( - (workflowRun) => - workflowRun?.event === "pull_request" && - workflowRun?.head_sha === headSha - ); - return candidates.reduce( - (latest, candidate) => - !latest || compareWorkflowRuns(candidate, latest) > 0 ? candidate : latest, - null - ); - }; - const checkRunWorkflowId = (checkRun) => { const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); return match?.[1] || null; @@ -183,17 +170,8 @@ jobs: // earlier substantive run for the same title remains the result. // GitHub leaves a skipped job's name expression unevaluated, so match // the metadata label inside it. - const workflowRunFor = async (workflowId, gateName, checkRuns) => { + const workflowRunFor = async (workflowId, gateName) => { const workflowName = workflowId === "codeql.yml" ? "CodeQL Analysis" : "License Gate"; - const metadataRunIds = new Set((Array.isArray(checkRuns) ? checkRuns : []) - .filter((checkRun) => { - if (checkRun?.status !== "completed" || checkRun?.conclusion !== "skipped") return false; - const name = String(checkRun.name || ""); - const metadataName = `PR Metadata Edit (${gateName})`; - return name === metadataName || name.includes(`'${metadataName}'`); - }) - .map(checkRunWorkflowId) - .filter(Boolean)); const expectedTitle = `${workflowName} pr-${issueNumber} base-${baseSha} head-${headSha}`; const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, { ...context.repo, @@ -202,10 +180,32 @@ jobs: head_sha: headSha, per_page: 100, }); - return selectLatestWorkflowRun( - workflowRuns.filter((workflowRun) => - workflowRun?.display_title === expectedTitle && !metadataRunIds.has(String(workflowRun.id))) - ); + const candidates = workflowRuns.filter((run) => + run?.display_title === expectedTitle && run.event === "pull_request" && + run.head_sha === headSha).sort((a, b) => compareWorkflowRuns(b, a)); + for (const candidate of candidates) { + if (!Number.isSafeInteger(candidate.id) || candidate.id <= 0 || + !Number.isSafeInteger(candidate.run_attempt) || candidate.run_attempt <= 0) { + throw new Error("Static summary candidate identity is unavailable."); + } + const { data } = await github.request( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + { ...context.repo, run_id: candidate.id, attempt_number: candidate.run_attempt, per_page: 100 } + ); + if (!Array.isArray(data.jobs) || !Number.isSafeInteger(data.total_count) || + data.total_count !== data.jobs.length || data.total_count >= 100) { + throw new Error("Static summary candidate jobs are incomplete."); + } + const metadataName = `PR Metadata Edit (${gateName})`; + const metadata = data.jobs.some(job => job.status === "completed" && + job.conclusion === "skipped" && + (job.name === metadataName || String(job.name || "").includes("'" + metadataName + "'"))); + const substantive = data.jobs.some(job => job.name === gateName); + if (metadata && !substantive) continue; + if (!substantive) return { ...candidate, status: "in_progress", conclusion: null }; + return candidate; + } + return null; }; const compareCheckRuns = (left, right) => { @@ -282,8 +282,8 @@ jobs: const checkRuns = await loadChecks(); const workflowRuns = { - codeql: await workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns), - license: await workflowRunFor("license-scan.yml", "License Gate", checkRuns), + codeql: await workflowRunFor("codeql.yml", "CodeQL Gate"), + license: await workflowRunFor("license-scan.yml", "License Gate"), }; // Each serialized producer completion publishes one bounded snapshot. // A running counterpart stays pending until its completion callback refreshes this comment. diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index 45562f14a2..54be516d9c 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -172,6 +172,7 @@ jobs: "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", "hosted-environment-identity-controller", "load-testing", + "recovery-controller-service", "common-redis-contracts", ]); const placeholders = new Map([ ["Build and Test ($" + "{{ matrix.module }})", "legacy"], diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 72860658bd..5212ba9b34 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -881,6 +881,11 @@ def _expected_gateway_container_env(expected_namespace: str) -> list[dict]: {"name": "SPRING_PROFILES_ACTIVE", "value": "prod"}, {"name": "SPRING_FLYWAY_TABLE", "value": "flyway_schema_history_gateway"}, {"name": "SERVICE_SCHEMA", "value": "gateway"}, + { + "name": "JAVA_TOOL_OPTIONS", + "value": "-XX:TieredStopAtLevel=1 -XX:ReservedCodeCacheSize=64m -Xss512k", + }, + {"name": "MALLOC_ARENA_MAX", "value": "2"}, { "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index dce9757e88..dcc36bb166 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -183,6 +183,11 @@ async function noWrites(config, reject = false) { + ': `' + conclusion + '`')); } } + const newModules = harness({jobs: [...clone(jobs), + row('Build and Test (recovery-controller-service / full)', 995), + row('Build and Test (common-redis-contracts / full)', 996)]}); + await newModules.run(); + assert.match(newModules.calls.creates[0].body, /All validation checks passed/); const metadataSplit = clone(jobs); for (const job of metadataSplit) { job.conclusion = 'skipped'; job.steps = []; } assert.equal((await noWrites({ jobs: metadataSplit })).comments.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 0391dd8d15..4810fc176b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -50,6 +50,50 @@ def evaluate(expression, action, base_ref, event="pull_request"): return eval(body, {"__builtins__": {}}) +def excludes_metadata(expression): + body = expression.strip() + if body.startswith("${{") and body.endswith("}}"): + body = body[3:-2].strip() + if body == SUBSTANTIVE[1:-1] or body == PR_SUBSTANTIVE[1:-1]: + return True + # Only a required top-level conjunction can enforce the exclusion. + # Parenthesized additional conditions may contain OR without bypassing it. + depth = 0 + quoted = False + start = 0 + terms = [] + index = 0 + while index < len(body): + char = body[index] + if char == "'": + if quoted and index + 1 < len(body) and body[index + 1] == "'": + index += 2 + continue + quoted = not quoted + elif not quoted: + if char == "(": + depth += 1 + elif char == ")": + depth -= 1 + if depth < 0: + return False + elif depth == 0 and body[index:index + 2] == "||": + return False + elif depth == 0 and body[index:index + 2] == "&&": + terms.append(body[start:index].strip()) + start = index + 2 + index += 1 + index += 1 + terms.append(body[start:].strip()) + return not quoted and depth == 0 and any(term in (SUBSTANTIVE, PR_SUBSTANTIVE) for term in terms) + + +assert excludes_metadata("${{ " + SUBSTANTIVE + " && needs.changes.result == 'success' }}") +assert excludes_metadata("${{ always() && " + PR_SUBSTANTIVE + " && (true || false) }}") +assert not excludes_metadata("${{ github.event_name == 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null }}") +assert not excludes_metadata("${{ " + SUBSTANTIVE + " || always() }}") +assert not excludes_metadata("${{ (" + SUBSTANTIVE + " || always()) }}") + for directory in (".github/actions/preserve-required-gate", ".github/actions/publish-required-gate-status"): if (root / directory).exists(): raise SystemExit(f"retired metadata preservation machinery must stay deleted: {directory}") @@ -108,7 +152,7 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o if job_id == gate_job: continue condition = job.get("if", "") - if "github.event.action != 'edited' || github.event.changes.base.ref != null" not in condition: + if not excludes_metadata(condition): raise SystemExit(f"{workflow} job {job_id} can run for a metadata-only edit") if job.get("name") in {name for _, _, name, *_ in gates.values()}: raise SystemExit(f"{workflow} job {job_id} must not reuse a required gate name") diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 237e2d7ffb..d1f0548154 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -110,15 +110,16 @@ def active_ids(row: dict[str, Any]) -> str: "--arg", "default_branch", "develop", "--arg", "pr_title", "PR preview 7", "--argjson", "pr_number", "7", "--arg", "head_sha", "a" * 40, "--arg", "run_name", "Preview dispatch pr-7-base-b-head-a-merge-c", - active_filter, + "(" + active_filter + ") | .id", ], input=json.dumps([row]), text=True).strip() active_run = { "id": 1, "name": "PR Preview Environment", "path": ".github/workflows/preview.yml", "head_branch": "feature", "head_sha": "a" * 40, "pull_requests": [{"number": 7}], - "display_title": "PR preview 7", "status": "in_progress", + "display_title": "PR preview 7", "status": "in_progress", "run_attempt": 1, "event": "pull_request", "firemud_reconciler_branch_filtered": False, } assert active_ids(active_run) == "1" +assert active_ids({key: value for key, value in active_run.items() if key != "run_attempt"}) == "" assert active_ids({**active_run, "pull_requests": [{"number": 8}, {"number": 7}]}) == "1" assert active_ids({**active_run, "pull_requests": [{"number": 7}, {"number": 7}]}) == "" for fields in ( diff --git a/dev-tools/tests/protected-pod-admission-workflow-contract.sh b/dev-tools/tests/protected-pod-admission-workflow-contract.sh index 1a8e7b55c2..a9c8911d1b 100644 --- a/dev-tools/tests/protected-pod-admission-workflow-contract.sh +++ b/dev-tools/tests/protected-pod-admission-workflow-contract.sh @@ -29,10 +29,10 @@ with tempfile.TemporaryDirectory(prefix="firemud-policy-wait-") as directory: command("kubectl", '''import os,pathlib,json,sys p=pathlib.Path(os.environ["CALLS"]);n=int(p.read_text()) if p.exists() else 0;p.write_text(str(n+1)) if os.environ["CASE"]=="api-error":sys.exit(1) -ready=os.environ["CASE"]=="ready" or (os.environ["CASE"]=="late" and n>0) -print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Fail"},"status":{"observedGeneration":2 if ready else 1,"typeChecking":{"expressionWarnings":["bad"] if os.environ["CASE"]=="warnings" else []}}})) +ready=os.environ["CASE"] in ("ready", "warnings", "ignore") or (os.environ["CASE"]=="late" and n>0) +print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Ignore" if os.environ["CASE"]=="ignore" else "Fail"},"status":{"observedGeneration":2 if ready else 1,"typeChecking":{"expressionWarnings":["bad"] if os.environ["CASE"]=="warnings" else []}}})) ''') - for case, success in [("ready", True), ("late", True), ("stale", False), ("warnings", False), ("api-error", False)]: + for case, success in [("ready", True), ("late", True), ("stale", False), ("warnings", False), ("ignore", False), ("api-error", False)]: for name in ("clock", "calls"): (tmp/name).unlink(missing_ok=True) env = dict(os.environ, PATH=str(tmp)+":"+os.environ["PATH"], CASE=case, diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index eb7e768585..5892050b7c 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -15,8 +15,8 @@ if ! awk ' fi grep -Fq 'github.paginate(github.rest.actions.listWorkflowRuns' "$workflow" -grep -Fq 'workflowRunFor("codeql.yml", "CodeQL Gate", checkRuns)' "$workflow" -grep -Fq 'workflowRunFor("license-scan.yml", "License Gate", checkRuns)' "$workflow" +grep -Fq 'workflowRunFor("codeql.yml", "CodeQL Gate")' "$workflow" +grep -Fq 'workflowRunFor("license-scan.yml", "License Gate")' "$workflow" grep -Fq 'head_sha: headSha,' "$workflow" grep -Fq 'return "skipped";' "$workflow" grep -Fq 'run_attempt' "$workflow" @@ -31,7 +31,7 @@ grep -Fq 'group: static-analysis-summary-pr-${{ needs.resolve-summary-target.out grep -Fq 'const headSha = currentPullRequest.head?.sha;' "$workflow" grep -Fq 'context.payload.workflow_run.display_title !== expectedSourceTitle' "$workflow" grep -Fq 'finalPullRequest.base?.sha !== baseSha' "$workflow" -grep -Fq 'workflowRun?.display_title === expectedTitle' "$workflow" +grep -Fq 'run?.display_title === expectedTitle' "$workflow" grep -Fq 'comment.user?.login === "github-actions[bot]"' "$workflow" grep -Fq 'if (comment.id === existing?.id) continue;' "$workflow" @@ -159,7 +159,17 @@ const calls = { paginate: [], deleted: [], updated: [], created: [] }; const codeqlListWorkflowRuns = async () => undefined; const checksListForRef = async () => undefined; const commentsList = async () => undefined; +const jobRequests = []; const github = { + request: async (route, input) => { + if (route !== "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs") throw new Error("unexpected native request"); + jobRequests.push(input); + if (input.attempt_number !== 1 || input.per_page !== 100) throw new Error("candidate must use exact attempt and bounded jobs"); + const metadata = input.run_id === 270; + const name = metadata ? "github.event.action == 'edited' && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'" : + input.run_id % 1000 === 300 ? "License Gate" : "CodeQL Gate"; + return { data: { total_count: 1, jobs: [{ name, status: "completed", conclusion: metadata ? "skipped" : "success" }] } }; + }, rest: { pulls: { get: async () => { pullRequestReads += 1; @@ -264,8 +274,8 @@ const github = { }, { id: 2701, - // Native skipped-job name: GitHub leaves the expression unevaluated. - name: "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'", + // Initial checks precede the new metadata run; candidate jobs classify it later. + name: "Unrelated earlier snapshot", status: "completed", conclusion: "skipped", created_at: "2026-09-20T12:00:01Z", @@ -653,6 +663,21 @@ run(github, context, core).then(async () => { await assertCompletionOrders(); await assertInterruptedRecovery(); await assertAssociationSelection(); + if (!jobRequests.some(input => input.run_id === 270)) throw new Error("metadata race was not classified from candidate jobs"); + const savedRequest = github.request; + github.request = async () => ({ data: { total_count: 1, jobs: [{ name: "Unrelated job", status: "completed", conclusion: "success" }] } }); + const unknownStart = calls.updated.length; + await run(github, context, core); + const unknownWrites = calls.updated.slice(unknownStart); + if (!unknownWrites.length || unknownWrites.some(row => row.body.includes("checks passed"))) throw new Error("unclassified successful jobs must not yield a green summary"); + if (!unknownWrites.some(row => row.body.includes("in_progress"))) throw new Error("unclassified candidate must remain pending"); + const writesBefore = calls.updated.length + calls.created.length; + github.request = async () => ({ data: { total_count: 101, jobs: [] } }); + let refused = false; + try { await run(github, context, core); } catch (error) { + refused = error.message.includes("jobs are incomplete"); + } finally { github.request = savedRequest; } + if (!refused || calls.updated.length + calls.created.length !== writesBefore) throw new Error("incomplete candidate jobs must not publish success"); console.log("static analysis summary behavioral contract passed"); }, ); diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index ce24c62801..58fa060525 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -2689,6 +2689,29 @@ def test_gateway_rejects_extra_gameplay_client_tls_item(self): ): self.validator.validate_service_consumers([document], "pr-42") + def test_gateway_jvm_profile_matches_chart_and_rejects_value_changes(self): + defaults = yaml.safe_load((ROOT / "k8s/helm/firemud/values.yaml").read_text()) + expected = { + "JAVA_TOOL_OPTIONS": defaults["previewStack"]["jvm"]["javaToolOptions"], + "MALLOC_ARENA_MAX": defaults["previewStack"]["jvm"]["mallocArenaMax"], + } + env = self.validator._expected_gateway_container_env("pr-42") + self.assertEqual( + {row["name"]: row["value"] for row in env if row["name"] in expected}, + expected, + ) + for name in expected: + with self.subTest(name=name): + document = self._gateway_document() + for row in document["spec"]["template"]["spec"]["containers"][0]["env"]: + if row["name"] == name: + row["value"] = "unapproved" + with ( + patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}), + self.assertRaisesRegex(ValueError, "unsafe container env"), + ): + self.validator.validate_service_consumers([document], "pr-42") + def test_gateway_rejects_redirect_and_jvm_environment_injection(self): for injected in ( { From 6496d6defd019a3d146858dfff21795b08bf6016 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:44:54 +1300 Subject: [PATCH 050/199] fix: preserve native callback compatibility and recovery proof checks --- .github/workflows/ci.yml | 6 ++ .../architecture/system-architecture-cicd.md | 2 + .../pr-required-gate-context-contract.sh | 4 + .../tests/pr-retarget-workflow-contract.sh | 26 +++++- ...ReleaseJournalPostgresIntegrationTest.java | 12 +-- .../InitialGameplayReleaseControllerTest.java | 89 +++++++++++++++++++ 6 files changed, 132 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c254967e99..a7e5d3e5de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1407,6 +1407,12 @@ jobs: - name: Declare dev tool contract split run: ':' + # Transitional native marker for the currently deployed workflow_run reader. + # It never executes or preserves a status; metadata edits skip this whole job. + - name: Preserve successful required gate on metadata-only edit + if: ${{ !always() }} + run: ':' + - name: Enforce validation success env: DOCS_CHANGED: ${{ needs.changes.outputs.docs_changed }} diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 9822b1c79d..ba06b3bf95 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -40,6 +40,8 @@ A metadata-only edit is an `edited` event whose `changes.base` is absent, such a Metadata runs use their own concurrency namespace, so an edit cannot cancel or replace an in-progress substantive run. Completion callbacks that read gate results, such as the [runtime-image refresh](#pull-request-runtime-and-preview-chain), the detached Validation Summary and the Static Analysis Summary, ignore metadata runs: they require the required-name gate job, or exclude runs whose gate check name contains the metadata label. +The Validation Gate temporarily retains one inert, unconditionally skipped native step named `Preserve successful required gate on metadata-only edit` for the default-branch runtime callback that still expects that marker. It does not execute the retired status-preservation machinery or change any check result. Metadata edits skip the entire gate under its non-required name, so the marker cannot qualify them. Remove this marker only after the default-branch callback no longer requires it. + The [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) checks the gate names, job conditions and concurrency namespaces for all five workflows. Account Service and Game Session validation each use four independent matrix partitions. Account retains two test forks per partition. On Linux, Game Session caps `integrationTest` at two JVM forks, bounded by Gradle’s worker count; JUnit methods within each suite remain serial, and other platforms retain their existing single-fork behavior. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the module’s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. World Management uses the same provenance and aggregation contract with two whole-class partitions balanced collectively across its unit, integration, and cross-service tasks. The existing Validation Gate requires every selected module matrix group and the corresponding coverage aggregate when any of the three slow services is affected. Ordinary local checks for all three services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 4810fc176b..e0468a3a50 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -140,6 +140,10 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o needs = gate.get("needs") if "changes" not in (needs if isinstance(needs, list) else [needs]): raise SystemExit(f"{workflow} {gate_name} must depend on change detection") + compatibility = [step for step in gate.get("steps", []) if step.get("name") == "Preserve successful required gate on metadata-only edit"] + expected_compatibility = [{"name": "Preserve successful required gate on metadata-only edit", "if": "${{ !always() }}", "run": ":"}] if workflow == "ci.yml" else [] + if compatibility != expected_compatibility: + raise SystemExit(f"{workflow} must retain only the inert CI callback compatibility marker") result_steps = [step for step in gate.get("steps", []) if step.get("name") == result_step] if len(result_steps) != 1 or result_steps[0].get("env", {}).get("CHANGES_RESULT") != "${{ needs.changes.result }}": raise SystemExit(f"{workflow} {gate_name} must enforce through one {result_step!r} step reading CHANGES_RESULT") diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 580f938790..9843472fd2 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -902,7 +902,7 @@ const assertCompleteRefinementPreservesEligibleInitialRuns = (initialRuns, cutof async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, - branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, + branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, legacyMarkerReader = false, }) { const dispatches = []; const errors = []; @@ -939,6 +939,7 @@ async function runDispatcher({ 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" }, ], ...(ciEvidence.gate ?? {}), @@ -1048,7 +1049,16 @@ async function runDispatcher({ global.setTimeout = (resolve) => { resolve(); }; Date.now = () => Date.parse("2026-01-08T00:00:00Z"); try { - await new AsyncFunction("github", "context", "core", dispatcherScript)(github, context, core); + // Default-branch reader at 3474c809 additionally requires this skipped marker. + // Run the identical identity/enforcement/dispatch checks with that historical predicate. + const script = legacyMarkerReader ? dispatcherScript.replace( + "enforcement.length !== 1", + "(gate?.steps?.filter(step => step.name === 'Preserve successful required gate on metadata-only edit').length !== 1 || " + + "gate.steps.find(step => step.name === 'Preserve successful required gate on metadata-only edit').status !== 'completed' || " + + "gate.steps.find(step => step.name === 'Preserve successful required gate on metadata-only edit').conclusion !== 'skipped') || enforcement.length !== 1" + ) : dispatcherScript; + if (legacyMarkerReader) assert.notEqual(script, dispatcherScript); + await new AsyncFunction("github", "context", "core", script)(github, context, core); } finally { Date.now = originalDateNow; global.setTimeout = originalSetTimeout; @@ -1128,6 +1138,18 @@ async function runDispatcher({ const emptyBranch = await runDispatcher({ tuples: [child], callback: { ...prCallback, head_branch: "" } }); assert.equal(emptyBranch.dispatches.length, 0); assert.equal(emptyBranch.refRequests.length, 0, "empty callback branch must be rejected before ref lookup"); + for (const legacyMarkerReader of [false, true]) { + const compatible = await runDispatcher({tuples:[child], sourceTuples:[source], callback:prCallback, legacyMarkerReader}); + assert.equal(runtimeDispatches(compatible).length, 2, "substantive attempt works with both reader versions"); + for (const gate of [ + {name:"PR Metadata Edit (Validation Gate)", conclusion:"skipped", steps:[]}, + {run_attempt:2}, {head_sha:sha("f")}, {run_id:7002}, + ]) { + const invalid = await runDispatcher({tuples:[child], sourceTuples:[source], callback:prCallback, + legacyMarkerReader, ciEvidence:{gate}}); + assert.equal(invalid.dispatches.length, 0, "compatibility marker cannot authorize metadata or wrong native identity"); + } + } const enforcementStep = { name: "Enforce validation success", status: "completed", conclusion: "success" }; for (const [label, ciEvidence] of [ ["metadata-only edit gate", { gate: { name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: [] } }], diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 82608ca3ca..d88df2e866 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -496,11 +496,13 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { } private static String storedOutbox(UUID operationId, UUID effectId) { - return dsl.fetchOne( - "SELECT row_to_json(o)::text AS row_json FROM recovery_control.initial_gameplay_release_outbox o" - + " WHERE operation_id = ? AND effect_id = ?", - operationId, - effectId) + return java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(o)::text AS row_json FROM recovery_control.initial_gameplay_release_outbox o" + + " WHERE operation_id = ? AND effect_id = ?", + operationId, + effectId), + "expected persisted outbox row") .get("row_json", String.class); } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index d6bb47610b..d2ed2c693a 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -163,6 +163,95 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { .isEqualTo(InitialGameplayReleaseEffectPort.ReadbackStatus.UNAVAILABLE); } + @Test + void pendingEffectClaimedByAnotherAttemptDoesNotDispatch() { + assertPendingClaimHandling(false); + } + + @Test + void pendingEffectApplyExceptionRecordsAmbiguousNotRetryable() { + assertPendingClaimHandling(true); + } + + private void assertPendingClaimHandling(boolean ownsClaim) { + var journal = mock(InitialGameplayReleaseJournal.class); + var port = mock(InitialGameplayReleaseEffectPort.class); + var operation = mock(Operation.class); + var after = mock(Operation.class); + var scope = mock(Scope.class); + var operationId = UUID.randomUUID(); + var effect = mock(PreparePlayableStateFencedEffect.class); + var effectId = UUID.randomUUID(); + when(scope.operationId()).thenReturn(operationId); + when(operation.scope()).thenReturn(scope); + when(effect.effectId()).thenReturn(effectId); + var pending = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry.class); + when(pending.effect()).thenReturn(effect); + when(pending.state()) + .thenReturn( + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectOutboxState + .PENDING); + when(journal.find(operationId)) + .thenReturn(java.util.Optional.of(operation), java.util.Optional.of(after)); + when(journal.findNextEffect(operationId)).thenReturn(java.util.Optional.of(pending)); + var claimedAttempt = new java.util.concurrent.atomic.AtomicReference(); + when(journal.claimEffect( + org.mockito.ArgumentMatchers.eq(operationId), + org.mockito.ArgumentMatchers.eq(effectId), + any(), + any())) + .thenAnswer( + invocation -> { + UUID requested = invocation.getArgument(2); + claimedAttempt.set(requested); + var claimed = + mock( + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry + .class); + when(claimed.state()) + .thenReturn( + net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel + .EffectOutboxState.DISPATCHED); + when(claimed.lastAttemptId()) + .thenReturn( + ownsClaim + ? requested + : new UUID( + ~requested.getMostSignificantBits(), + requested.getLeastSignificantBits())); + if (ownsClaim) when(claimed.effect()).thenReturn(effect); + return claimed; + }); + if (ownsClaim) + when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) + .thenThrow(new IllegalStateException("response lost after possible owner send")); + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + mock(InitialGameplayReleaseEvidenceProvider.class), + port); + assertThat(controller.reconcileNextEffect(operationId)).isSameAs(after); + assertThat(claimedAttempt.get()).isNotNull(); + verify(journal, never()).recordRetryableEffect(any(), any(), any(), any(), any()); + verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); + if (ownsClaim) { + verify(port).apply(effect, claimedAttempt.get()); + verify(port, never()).readback(any(), any()); + verify(journal) + .recordAmbiguousEffect( + org.mockito.ArgumentMatchers.eq(operationId), + org.mockito.ArgumentMatchers.eq(effectId), + org.mockito.ArgumentMatchers.eq(claimedAttempt.get()), + org.mockito.ArgumentMatchers.eq("EFFECT_CALL_OUTCOME_UNKNOWN"), + any()); + } else { + verifyNoInteractions(port); + verify(journal, never()).recordAmbiguousEffect(any(), any(), any(), any(), any()); + } + } + @Test void applyOutcomeCodesUseJournalContract() { for (String invalid : From 252cd6f3414f39966d248c90909d43c16e51a117 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:54:42 +1300 Subject: [PATCH 051/199] fix: bind smoke proofs to exact completed runtime attempts --- .github/workflows/smoke.yml | 61 +++++++++++++++---- .../pr-required-gate-context-contract.sh | 39 +++++++++--- .../tests/pr-retarget-workflow-contract.sh | 29 +++++++-- 3 files changed, 104 insertions(+), 25 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index d973463d34..c2a45b9bae 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -919,6 +919,22 @@ jobs: return `${identity.sourceEvent}:${identity.baseRef}@${identity.baseSha}...${identity.headSha}#${identity.mergeSha}`; } + async function verifyCompletedCanonicalRuntime(run, identity) { + if (run?.status !== "completed" || run.conclusion !== "success" || + !positiveInteger(run.run_attempt)) return false; + const jobs = await withTransientGitHubRetry("canonical runtime attempt jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, + }) + ); + const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); + const smoke = (producers[0]?.steps ?? []).filter((step) => + step.name === "Run credential-free full-stack smoke"); + return producers.length === 1 && smoke.length <= 1 && + (smoke.length === 0 || smoke[0].status !== "completed" || smoke[0].conclusion === "success") && + await verifyCanonicalSmokeProducer(run, producers[0], identity); + } + async function findMatchingRuntimeImagesRun(sourceEvent, expectedDisplayTitle, identity) { const workflowRunQuery = { owner, @@ -992,17 +1008,7 @@ jobs: older.id !== run.id && older.status === "completed" && older.conclusion === "success"); for (const {run: older} of completed.slice(0, 3)) { try { - const jobs = await withTransientGitHubRetry("duplicate runtime attempt jobs lookup", () => - github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { - owner, repo, run_id: older.id, attempt_number: older.run_attempt, per_page: 100, - }) - ); - const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - const smoke = (producers[0]?.steps ?? []).filter((step) => - step.name === "Run credential-free full-stack smoke"); - if (producers.length === 1 && smoke.length === 1 && - smoke[0].status === "completed" && smoke[0].conclusion === "success" && - await verifyCanonicalSmokeProducer(older, producers[0], identity)) { + if (await verifyCompletedCanonicalRuntime(older, identity)) { core.info("A verified completed exact runtime producer precedes the pending duplicate."); return older; } @@ -1204,6 +1210,23 @@ jobs: ); matching = replacement; } + // A queued native run can share a tuple with a completed trusted refresh. + // It must not hide already verified smoke proof or cause a second dispatch. + if (currentIdentity.sourceEvent === "pull_request" && matching?.event === "pull_request" && + matching.status !== "completed") { + const replacement = await findMatchingRuntimeImagesRun( + "repository_dispatch", expectedDisplayTitle, currentIdentity + ); + try { + if (replacement && await verifyCompletedCanonicalRuntime(replacement, currentIdentity)) { + core.info("A completed verified exact trusted refresh supersedes the pending native wait."); + matching = replacement; + } + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.info("Trusted refresh proof is unavailable; retain the native wait."); + } + } if (matching) { core.info(`Found runtime-images run ${matching.id} with status=${matching.status} conclusion=${matching.conclusion}`); if (matching.status !== "completed") { @@ -1293,11 +1316,12 @@ jobs: const jobs = await withTransientGitHubRetry( "runtime-images job lookup", () => github.paginate( - github.rest.actions.listJobsForWorkflowRun, + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: matching.id, + attempt_number: matching.run_attempt, per_page: 100, } ) @@ -1431,6 +1455,19 @@ jobs: ); continue smokeGatePolling; } + // Job proof belongs to the selected immutable attempt, never the latest + // attempt's jobs. Recheck after mutable PR identity before accepting it. + const { data: currentAttempt } = await withTransientGitHubRetry( + "final successful runtime attempt lookup", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + ); + if (!positiveInteger(matching.run_attempt) || currentAttempt.id !== matching.id || + currentAttempt.run_attempt !== matching.run_attempt || + currentAttempt.status !== "completed" || currentAttempt.conclusion !== "success") { + core.info("Runtime attempt changed before smoke proof acceptance; resume exact selection."); + 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 e0468a3a50..850fba50d1 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -334,6 +334,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { let now = 1000; const start = now; const failures = []; + const cancelledReads = new Set(); 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", @@ -355,13 +356,15 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { 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"}}) }, + status: "completed", conclusion: cancelledReads.has(run_id) ? "cancelled" : "success"}}) }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); assert.equal(input.attempt_number, 1); + cancelledReads.add(input.run_id); return {data: cancelledSource(input.run_id)}; }, paginate: async (method, input) => { - if (method === listJobs) { + if (!cancelledReads.has(input.run_id)) { + assert.equal(input.attempt_number, 1); 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" }] }]; } @@ -503,7 +506,7 @@ const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defa 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 now = 1000, snapshots = 0, reads = 0, currentRunReads = 0; const failures = [], refs = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { repository: {default_branch: "develop"}, @@ -523,6 +526,10 @@ async function scenario(kind, event = "pull_request") { if (kind === "marker-success") job.steps[0].conclusion = "success"; if (kind.startsWith("legacy")) job.name = "PR Full-Stack Smoke"; if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; + if (kind === "duplicate-nonterminal-step") job.steps.push({name: "Run credential-free full-stack smoke", status: "in_progress", conclusion: null}); + if (["duplicate-terminal-skipped", "duplicate-terminal-failure"].includes(kind)) job.steps.push({name: "Run credential-free full-stack smoke", status: "completed", conclusion: kind.endsWith("failure") ? "failure" : "skipped"}); + if (kind === "pending-native-refresh-failed") source.conclusion = "failure"; + if (kind === "pending-native-refresh-skipped") job.steps.push({name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}); 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"}]; const sourceMutations = { @@ -552,7 +559,11 @@ 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 () => { + currentRunReads += 1; + const superseded = kind === "newer-attempt" || (kind === "rerun-after-proof" && currentRunReads > 1); + return {data: {...source, run_attempt: superseded ? 2 : 1, status: superseded ? "in_progress" : "completed"}}; + }, }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); @@ -567,14 +578,18 @@ async function scenario(kind, event = "pull_request") { "wrong-job-head": {head_sha: defaultSha}, "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] || {})}]; + snapshots += 1; + 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); if (event === "repository_dispatch" && input.event === "pull_request") { - yield {data: [{...source, event: "pull_request", head_sha: head, conclusion: "cancelled"}]}; return; + yield {data: [{...source, id: kind.startsWith("pending-native") ? 43 : source.id, event: "pull_request", head_sha: head, + status: kind.startsWith("pending-native") ? "queued" : "completed", + conclusion: kind.startsWith("pending-native") ? null : "cancelled"}]}; return; } - yield {data: [source]}; + yield {data: kind.startsWith("duplicate-") && !["duplicate-jobs", "duplicate-attempt-jobs"].includes(kind) + ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [source]}; }; const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, @@ -588,6 +603,16 @@ async function scenario(kind, event = "pull_request") { assert.deepEqual(success.refs, [event === "pull_request" ? merge : defaultSha], "immutable definition must come from actual source event revision"); } assert.deepEqual((await scenario("legacy-positive")).failures, []); + assert.deepEqual((await scenario("pending-native-refresh", "repository_dispatch")).failures, [], "trusted successful refresh releases queued native wait"); + for (const kind of ["pending-native-refresh-skipped", "pending-native-refresh-failed"]) { + assert.equal((await scenario(kind, "repository_dispatch")).failures.length, 1, `${kind} cannot release queued native wait`); + } + for (const kind of ["duplicate-missing-step", "duplicate-nonterminal-step"]) { + assert.deepEqual((await scenario(kind)).failures, [], `${kind} preserves canonical fallback`); + } + for (const kind of ["duplicate-terminal-skipped", "duplicate-terminal-failure", "rerun-after-proof"]) { + assert.equal((await scenario(kind)).failures.length, 1, `${kind} cannot supply successful proof`); + } 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", diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 9843472fd2..a4a652f881 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2446,7 +2446,7 @@ require_contains "$smoke_path" 'matching.conclusion === "cancelled"' require_contains "$smoke_path" 'waiting for an exact repository_dispatch replacement' require_contains "$smoke_path" 'const cancelledReplacementTimeoutMs = 5 * 60 * 1000;' require_contains "$smoke_path" 'Cancelled runtime-images run ${cancelledRunId} has no exact repository_dispatch replacement ' -require_contains "$smoke_path" 'github.rest.actions.listJobsForWorkflowRun' +require_contains "$smoke_path" 'attempt_number: matching.run_attempt,' require_contains "$smoke_path" 'job.name === "PR Full-Stack Smoke"' require_contains "$smoke_path" 'step.name === "Run credential-free full-stack smoke"' require_contains "$smoke_path" 'fullSmokeJob?.status === "completed"' @@ -2478,7 +2478,9 @@ require_contains "$smoke_path" 'Stopping obsolete completed smoke gate for' require_contains "$smoke_path" 'Stopping obsolete stale-snapshot smoke gate for' require_ordered_sequence \ "$smoke_path" \ - 'github.rest.actions.listJobsForWorkflowRun,' \ + '"runtime-images job lookup",' \ + '"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",' \ + 'attempt_number: matching.run_attempt,' \ 'if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) {' require_branch_return "$smoke_path" 'if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) {' require_ordered_sequence \ @@ -2801,7 +2803,7 @@ node - "$smoke_gate_script" <<'NODE_DUPLICATE_SMOKE' const assert = require("node:assert/strict"); const fs = require("node:fs"); const script = fs.readFileSync(process.argv[2], "utf8"); -const start = script.indexOf("async function findMatchingRuntimeImagesRun("); +const start = script.indexOf("async function verifyCompletedCanonicalRuntime("); const end = script.indexOf("async function resolveCurrentIdentity(", start); assert.ok(start >= 0 && end > start); const source = script.slice(start, end); @@ -3013,9 +3015,11 @@ function runtimeTitle(base, head, merge) { return `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; } +const knownRuns = new Map(); function runtimeRun(id, title) { return { id, + run_attempt: 1, event: "pull_request", head_sha: headSha, display_title: title, @@ -3092,10 +3096,20 @@ const github = { }; }, }, - actions: { listWorkflowRuns, listJobsForWorkflowRun }, + actions: { listWorkflowRuns, listJobsForWorkflowRun, + getWorkflowRun: async ({run_id}) => { + const source = availableRuns.find(run => run.id === run_id) ?? knownRuns.get(run_id); + if (!source) throw new Error(`unbound native run lookup ${run_id}`); + return {data: source}; + }, + }, }, paginate: async (method, input) => { - if (method === listJobsForWorkflowRun) { + if (method === "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs") { + if (input.attempt_number !== 1) throw new Error("jobs must bind to selected native attempt"); + const source = availableRuns.find(run => run.id === input.run_id) ?? knownRuns.get(input.run_id); + if (!source) throw new Error(`unbound attempt jobs lookup ${input.run_id}`); + if (source.conclusion === "cancelled") return []; // No complete cancellation inventory is supplied by this fixture. jobQueries.push(input); return [{ name: "PR Full-Stack Smoke", @@ -3121,6 +3135,7 @@ github.paginate.iterator = (method, input) => { onRepositoryDispatchQuery?.(repositoryDispatchQueryCount); } return (async function* workflowRunPages() { + for (const source of availableRuns) knownRuns.set(source.id, {...source}); yield { data: availableRuns }; })(); }; @@ -3159,7 +3174,9 @@ async function checkPartialPaginationRetry() { workflowRunQueries.push(input); return (async function* partialPages() { attempts++; - yield { data: [attempts === 1 ? stale : fresh] }; + const source = attempts === 1 ? stale : fresh; + knownRuns.set(source.id, {...source}); + yield { data: [source] }; if (attempts === 1) throw { status: 503, message: "controlled pagination interruption" }; })(); }; From de2bd36a9badc44a5eebbd1eeed80bc239a5bea8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:07:48 +1300 Subject: [PATCH 052/199] fix(recovery): retain definitive closure proof at database time precision --- .../JooqInitialGameplayReleaseJournal.java | 32 ++- ...ReleaseJournalPostgresIntegrationTest.java | 219 ++++++++++++++++++ 2 files changed, 248 insertions(+), 3 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 38681ac0af..a4afd9bf61 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -272,7 +272,9 @@ public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, WHERE operation_id = ? AND effect_id = ? AND state IN ('pending', 'retryable') """, attemptId, - toOffsetDateTime(now), + // PostgreSQL stores microseconds; truncate explicitly rather than rounding + // the dispatch floor upward beyond an observation of this same instant. + toOffsetDateTime(now.truncatedTo(java.time.temporal.ChronoUnit.MICROS)), toOffsetDateTime(now), operationId, effectId); @@ -380,13 +382,21 @@ && sameAcknowledgedOutcome(readback, stored, storedDigest))) { && readbackDigest.equals(storedDigest)) { return operation; } - throw conflict("effect readback changed after definitive no effect"); + if (readback.state() != EffectReadbackState.PROVEN_NO_EFFECT + || ((storedDigest != null + || (stored != null && stored.get("readback_payload", JSONB.class) != null)) + && !hasValidatedUnknownReadback(stored, storedDigest, current))) { + throw conflict("effect readback changed after definitive no effect"); + } + // A definitive apply rejection may precede its first durable closure receipt. + // Keep normal attempt and observation fences before retaining that receipt. } if (readback.observedAt().isAfter(now)) { throw conflict("effect readback observation is in the future"); } if (current.state() != EffectOutboxState.DISPATCHED - && current.state() != EffectOutboxState.AMBIGUOUS) { + && current.state() != EffectOutboxState.AMBIGUOUS + && current.state() != EffectOutboxState.RETRYABLE) { throw conflict("effect is not awaiting readback reconciliation"); } Record timestamps = @@ -664,6 +674,22 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private boolean hasValidatedUnknownReadback( + Record stored, String storedDigest, OutboxEntry current) { + JSONB payload = stored == null ? null : stored.get("readback_payload", JSONB.class); + if (payload == null || storedDigest == null) { + return false; + } + EffectReadback previous = tupleCodec.readEffectReadback(payload.data()); + if (!storedDigest.equals(tupleCodec.digest(previous)) + || previous.state() != EffectReadbackState.UNKNOWN_OR_PARTIAL) { + return false; + } + requireReadbackMatches( + previous, current, current.effect().operationId(), current.effect().effectId()); + return true; + } + private boolean sameAcknowledgedOutcome( EffectReadback readback, Record stored, String storedDigest) { JSONB payload = stored.get("readback_payload", JSONB.class); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index d88df2e866..1e1d3cfea7 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -495,6 +495,225 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(replacement); } + @Test + void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + journal.recordRetryableEffect( + operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(5)); + String before = storedOutbox(operationId, effectId); + EffectReadback stale = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PROVEN_NO_EFFECT, + "closure", + base.plusSeconds(3)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, stale, base.plusSeconds(6))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + EffectReadback future = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PROVEN_NO_EFFECT, + "closure", + base.plusSeconds(7)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, future, base.plusSeconds(6))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + EffectReadback closure = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PROVEN_NO_EFFECT, + "closure", + base.plusSeconds(6)); + journal.recordEffectReadback(operationId, effectId, attemptId, closure, base.plusSeconds(6)); + String retained = storedOutbox(operationId, effectId); + assertThat(retained).contains(tupleCodec.digest(closure)); + journal.recordEffectReadback(operationId, effectId, attemptId, closure, base.plusSeconds(7)); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, future, base.plusSeconds(8))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + UUID nextAttempt = UUID.randomUUID(); + journal.claimEffect(operationId, effectId, nextAttempt, base.plusSeconds(8)); + String replaced = storedOutbox(operationId, effectId); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, closure, base.plusSeconds(9))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(replaced); + } + + @Test + void unknownReadbackBeforeDefinitiveRejectionAllowsOnlyValidatedSameAttemptClosure() { + for (String variant : List.of("valid", "corrupt-digest", "other-attempt", "missing-digest")) { + clearJournal(); + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + EffectReadback unknown = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "unknown", + base.plusSeconds(5)); + journal.recordEffectReadback(operationId, effectId, attemptId, unknown, base.plusSeconds(5)); + journal.recordRetryableEffect( + operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(6)); + if (variant.equals("missing-digest")) { + String retained = storedOutbox(operationId, effectId); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET readback_digest=NULL WHERE effect_id=?", + effectId)) + .isInstanceOf(org.jooq.exception.IntegrityConstraintViolationException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); + continue; + } + if (!variant.equals("valid")) { + EffectReadback stored = + variant.equals("other-attempt") + ? readbackFor( + dispatched, + UUID.randomUUID(), + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "unknown", + base.plusSeconds(5)) + : unknown; + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET readback_payload=CAST(? AS jsonb), readback_digest=? WHERE effect_id=?", + tupleCodec.toJson(stored), + variant.equals("missing-digest") + ? null + : variant.equals("corrupt-digest") ? "a".repeat(64) : tupleCodec.digest(stored), + effectId); + } + String before = storedOutbox(operationId, effectId); + EffectReadback stale = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PROVEN_NO_EFFECT, + "closure", + base.plusSeconds(3)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, stale, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + EffectReadback closure = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PROVEN_NO_EFFECT, + "closure", + base.plusSeconds(7)); + if (variant.equals("valid")) { + journal.recordEffectReadback( + operationId, effectId, attemptId, closure, base.plusSeconds(7)); + String retained = storedOutbox(operationId, effectId); + assertThat(retained).contains(tupleCodec.digest(closure)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, unknown, base.plusSeconds(8))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); + } else { + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, closure, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + } + } + } + + @Test + void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrecision() { + for (int nanos : new int[] {499, 999, 999_999_999}) { + clearJournal(); + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60).plusNanos(nanos); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + Instant dispatchInstant = base.plusSeconds(4); + Instant floor = dispatchInstant.truncatedTo(ChronoUnit.MICROS); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_dispatched_at FROM recovery_control.initial_gameplay_release_outbox WHERE effect_id = ?", + effectId)) + .get("last_dispatched_at", java.time.OffsetDateTime.class) + .toInstant()) + .isEqualTo(floor); + String before = storedOutbox(operationId, effectId); + EffectReadback stale = + readbackFor( + dispatched, + dispatched.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "before-dispatch-floor", + floor.minusNanos(1)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, + effectId, + dispatched.lastAttemptId(), + stale, + base.plusSeconds(5))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + EffectReadback closure = + readbackFor( + dispatched, + dispatched.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "same-instant", + dispatchInstant); + journal.recordEffectReadback( + operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(5)); + assertThat(storedOutbox(operationId, effectId)).contains(tupleCodec.digest(closure)); + } + } + + private static OutboxEntry authorizedDispatch(Instant base) { + Scope scope = scope(); + journal.create(scope, UUID.randomUUID()); + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base.plusSeconds(1)); + Operation awaiting = + journal.transition( + transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base.plusSeconds(2)); + journal.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base.plusSeconds(3)); + OutboxEntry pending = journal.findNextEffect(scope.operationId()).orElseThrow(); + return journal.claimEffect( + scope.operationId(), pending.effect().effectId(), UUID.randomUUID(), base.plusSeconds(4)); + } + private static String storedOutbox(UUID operationId, UUID effectId) { return java.util.Objects.requireNonNull( dsl.fetchOne( From 03dc808a705dc2c7d8b165859f929a72f070a966 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:27:46 +1300 Subject: [PATCH 053/199] test(ci): strengthen retained review source and timeout proofs --- .../scripts/classify-change-scope.test.cjs | 10 ++++++++ .../tests/ci-validation-summary-contract.sh | 23 ++++++++++++++++--- ...d-identity-controller-workflow-contract.sh | 2 ++ .../tests/pr-retarget-workflow-contract.sh | 8 ++----- dev-tools/tests/preview-priority-contract.sh | 8 +++++-- .../preview-runner-isolation-contract.sh | 21 +++++++++++++++-- 6 files changed, 59 insertions(+), 13 deletions(-) diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index c22afdf752..47cb2fd2fe 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -536,6 +536,16 @@ test("shared modules force every Gradle module, including common-temporal", () = assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("recovery-controller-service", "hosted-environment-identity-controller")); }); +test("shared modules force every Gradle module, including common-redis-contracts", () => { + const result = classifyChangeScope([ + "services/common-redis-contracts/src/main/java/example/RedisContract.java", + ]); + + assert.equal(result.runAll, true); + assert.deepEqual(result.affectedModules, ALL_MODULES); + assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("recovery-controller-service", "hosted-environment-identity-controller")); +}); + test("controller and load-testing changes receive their own module checks", () => { const controllerResult = classifyChangeScope([ "services/hosted-environment-identity-controller/src/main/java/example/Controller.java", diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index dcc36bb166..68dfe1ac3e 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -56,9 +56,26 @@ split_markers = [step for step in ci['jobs']['validation-gate']['steps'] if split_markers != [{'name': 'Declare dev tool contract split', 'run': ':'}]: raise SystemExit('Split contract inventory must retain its unconditional native source marker') def substantive_name(name): - # Metadata-only edits rename a job; substantive runs use the fallback name. - match = re.fullmatch(r"\$\{\{ .* && 'PR Metadata Edit \((.+)\)' \|\| '\1' \}\}", name) - return match[1] if match else name + # Metadata wrappers must normalize to an explicitly covered substantive name. + match = re.fullmatch(r"\$\{\{\s+.*\s+&&\s+'PR Metadata Edit \((.+)\)'\s+\|\|\s+'\1'\s+\}\}", name) + if match: + return match[1] + if "PR Metadata Edit" in name: + raise ValueError(f"Unrecognized metadata job wrapper: {name}") + return name + +assert substantive_name("${{ condition && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate' }}") == "Validation Gate" +for malformed in [ + "${{ condition && 'PR Metadata Edit (Validation Gate)' || 'Wrong Gate' }}", + "${{ condition && 'PR Metadata Edit (Validation Gate)' }}", +]: + try: + substantive_name(malformed) + except ValueError: + pass + else: + raise AssertionError("Unrecognized metadata wrapper escaped normalization") + names = [substantive_name(job['name']) for job in ci['jobs'].values()] for name in names: if '${{' not in name and json.dumps(name, ensure_ascii=False) not in script: diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 9e11b57e34..c55cd1bd2c 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6794,6 +6794,7 @@ grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-va qualified_source_run_json="$(jq -c '.path += "@refs/pull/900/merge"' <<<"$valid_workflow_run_json")" FAKE_FIXTURE_WORKFLOW_RUN_JSON="$qualified_source_run_json" \ run_deploy_target_fixture qualified-source-deploy 0 'action=deploy' +grep -Fxq 'action=deploy' "$TEMP_DIR/deploy-target-qualified-source-deploy.output" grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-qualified-source-deploy.output" cross_pr_qualified_source_run_json="$(jq -c ' .path += "@refs/pull/901/merge" | .pull_requests += [{number:901,head:{sha:.head_sha}}] @@ -6867,6 +6868,7 @@ for association_order in before after; do else .pull_requests + [{number:901,head:{sha:.head_sha}}] end)' <<<"$valid_workflow_run_json")" FAKE_FIXTURE_WORKFLOW_RUN_JSON="$multiple_association_json" \ run_deploy_target_fixture "multiple-associations-${association_order}" 0 'action=deploy' + grep -Fxq 'action=deploy' "$TEMP_DIR/deploy-target-multiple-associations-${association_order}.output" done duplicate_target_json="$(jq -c '.pull_requests += .pull_requests' <<<"$valid_workflow_run_json")" FAKE_FIXTURE_WORKFLOW_RUN_JSON="$duplicate_target_json" \ diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index a4a652f881..83b05672f9 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -556,7 +556,6 @@ assert_job_contains smoke.yml smoke-summary "name: \${{ github.event.action == ' # earlier substantive result stands; pr-required-gate-context-contract.sh owns # the full gate-condition matrix. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. -assert_job_contains smoke.yml smoke-gate "name: \${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }}" assert_job_contains smoke.yml smoke-summary-pending 'name: Smoke Summary (Pending)' assert_job_contains smoke.yml smoke-summary-pending 'tracked-by-smoke-gate' assert_job_contains smoke.yml smoke-summary 'needs: [changes, smoke-gate, smoke-summary-pending]' @@ -665,11 +664,7 @@ smoke_path, runtime_path = map(Path, sys.argv[1:]) smoke = yaml.load(smoke_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) runtime = yaml.load(runtime_path.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) -if smoke["jobs"]["smoke-gate"].get("name") != ( - "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && " - "github.event.changes.base.ref == null && 'PR Metadata Edit (Smoke Gate)' || 'Smoke Gate' }}" -): - raise SystemExit("metadata-only smoke must skip under a non-required name and keep Smoke Gate otherwise") +# Required gate names are asserted in pr-required-gate-context-contract.sh. runtime_jobs = runtime["jobs"] metadata_guard = "github.event.action != 'edited' || github.event.changes.base.ref != null" @@ -2343,6 +2338,7 @@ for conclusion in success skipped; do else [[ "$conclusion" == "skipped" ]] || { cat "$contract_fixture_dir/duplicate-$conclusion.error" >&2; exit 1; } require_contains "$contract_fixture_dir/duplicate-$conclusion.output" 'Waiting for runtime-images workflow 104' + require_contains "$contract_fixture_dir/duplicate-$conclusion.error" 'Timed out waiting for runtime-images workflow' fi done for fixture in missing-url empty-url; do diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index c59164a5c9..8af01c1869 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -2582,8 +2582,9 @@ for tuple_case in current qualified old_merge missing ambiguous stale_attempt wr fi done +for observation_case in duplicate-rows workflow-run-only; do reset_case -reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance.out" +reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -2591,10 +2592,11 @@ reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-adva FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ + --arg observation "$observation_case" \ --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" ' [{workflow_runs:([{id:5256,path:".github/workflows/hosted-identity-request.yml", name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title} - | . + {event:"branch",status:"queued"}, . + {event:"workflow_run",status:"in_progress"}])}]')" \ + | if $observation == "duplicate-rows" then . + {event:"branch",status:"queued"}, . + {event:"workflow_run",status:"in_progress"} else . + {event:"workflow_run",status:"in_progress"} end])}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" @@ -2604,6 +2606,8 @@ grep -Fqx \ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +done + reset_case reconciler_first_proof_retry_output="$TEMP_DIR/reconciler-first-proof-retry.out" ( diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index d1f0548154..be84968da5 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -480,8 +480,25 @@ except AssertionError as error: raise else: raise AssertionError("foreign render tools checkout escaped repository checking") -if render_checkouts[1].get("with", {}).get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or render_checkouts[1].get("with", {}).get("path") != "candidate": - raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") +def check_candidate_checkout(step: dict[str, Any]) -> None: + options = step.get("with", {}) + if options.get("repository", "$"+"{{ github.repository }}") != "$"+"{{ github.repository }}": + raise AssertionError("preview candidate must check out the current repository") + if options.get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or options.get("path") != "candidate": + raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") + +check_candidate_checkout(render_checkouts[1]) +try: + check_candidate_checkout({ + **render_checkouts[1], + "with": {**render_checkouts[1].get("with", {}), "repository": "other-owner/other-repo"}, + }) +except AssertionError as error: + if str(error) != "preview candidate must check out the current repository": + raise +else: + raise AssertionError("foreign candidate checkout escaped repository checking") + def check_trusted_working_directories(workflow: dict[str, Any], job: dict[str, Any]) -> None: inherited = workflow.get("defaults", {}).get("run", {}).get("working-directory", ".") inherited = job.get("defaults", {}).get("run", {}).get("working-directory", inherited) From db87b82f47a2fa43d0092bbb966abc5896b844f0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:33:21 +1300 Subject: [PATCH 054/199] fix(ci): preserve proven event-bound documentation-only scope --- .github/workflows/ci.yml | 44 +++++++++++++++++-- .../tests/ci-lightweight-scope-contract.sh | 33 ++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a7e5d3e5de..59464f8702 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,11 +112,47 @@ jobs: const moduleScopeAvailable = Array.isArray(scope.affectedModules) && Array.isArray(scope.bootableModules) && Array.isArray(ALL_MODULES) && completeModules.every(module => ALL_MODULES.includes(module)); + // An old module inventory must not turn proven documentation-only PRs + // into full builds. Re-read complete native paths rather than trusting + // an old classifier's module knowledge for new service directories. + let documentationOnly = false; + if (!moduleScopeAvailable && scope.lightweightOnly === true && + context.eventName === "pull_request") { + try { + const eventPr = context.payload.pull_request; + const exactEvent = pr => pr && /^[0-9a-f]{40}$/i.test(eventPr.head?.sha || "") && + /^[0-9a-f]{40}$/i.test(eventPr.base?.sha || "") && + pr.number === eventPr.number && pr.head?.sha === eventPr.head.sha && + pr.base?.sha === eventPr.base.sha && + pr.changed_files === eventPr.changed_files; + const before = (await github.rest.pulls.get({ + ...context.repo, pull_number: eventPr.number, + })).data; + const entries = await github.paginate(github.rest.pulls.listFiles, { + ...context.repo, pull_number: context.payload.pull_request.number, per_page: 100, + }, response => response.data); + const knownDoc = path => typeof path === "string" && + /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && + !path.split("/").includes(".."); + const after = (await github.rest.pulls.get({ + ...context.repo, pull_number: eventPr.number, + })).data; + documentationOnly = exactEvent(before) && exactEvent(after) && + Number.isInteger(context.payload.pull_request.changed_files) && + entries.length > 0 && entries.length === context.payload.pull_request.changed_files && + entries.every(entry => entry && knownDoc(entry.filename) && + ["added", "removed", "modified", "renamed"].includes(entry.status) && + (entry.status !== "renamed" || knownDoc(entry.previous_filename)) && + (entry.previous_filename === undefined || knownDoc(entry.previous_filename))); + } catch { + // Missing or incomplete native evidence keeps the full fallback. + } + } outputs = { - run_all: scope.runAll || !moduleScopeAvailable, + run_all: scope.runAll || (!moduleScopeAvailable && !documentationOnly), affected_services: scope.affectedServices, - affected_modules: moduleScopeAvailable ? scope.affectedModules : completeModules, - bootable_modules: moduleScopeAvailable ? scope.bootableModules : completeBootableModules, + affected_modules: documentationOnly ? [] : (moduleScopeAvailable ? scope.affectedModules : completeModules), + bootable_modules: documentationOnly ? [] : (moduleScopeAvailable ? scope.bootableModules : completeBootableModules), docs_changed: scope.docsChanged, frontend_changed: scope.frontendChanged, python_changed: scope.pythonChanged, @@ -124,7 +160,7 @@ jobs: validation_python_changed: scope.validationPythonChanged, postgres_runtime_proof_changed: scope.postgresRuntimeProofChanged === undefined ? true : scope.postgresRuntimeProofChanged, - lightweight_only: moduleScopeAvailable && scope.lightweightOnly, + lightweight_only: (moduleScopeAvailable || documentationOnly) && scope.lightweightOnly, }; } else { core.warning("Base revision predates the change classifier; using complete validation scope."); diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 2d5e78789f..81fed32238 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -43,6 +43,39 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput assert.deepEqual(JSON.parse(outputs.bootable_modules), compatible ? ["account-service"] : [...BOOTABLE_MODULES]); } + for (const [entries, count, expected, drift] of [ + [[{filename: "design/README.md"}], 1, true], + [[{filename: "design/README.md"}], 1, false, "head-before"], + [[{filename: "design/README.md"}], 1, false, "head-after"], + [[{filename: "design/README.md"}], 1, false, "base-after"], + [[{filename: "design/README.md"}], 2, false], + [[{filename: "design/README.md", status: "renamed"}], 1, false], + [[{filename: "services/new-service/README.md"}], 1, false], + [[{filename: "design/README.md", previous_filename: "services/new-service/Main.java"}], 1, false], + [[{filename: "design/../services/Main.md"}], 1, false], + [[{filename: "design/README.md", previous_filename: "docs/old.md"}], 1, true], + ]) { + const outputs = {}; + await execute(name => name === "node:fs" ? {existsSync: () => true} : { + ALL_MODULES: ALL_MODULES.filter(module => module !== "recovery-controller-service"), + classifyGithubChangeScope: async () => ({runAll: false, affectedModules: [], + bootableModules: [], affectedServices: [], lightweightOnly: true}), + }, {rest: {pulls: {listFiles() {}, get: (() => { + let calls = 0; + return async () => { const call = calls++; return ({data: {number: 42, changed_files: count, + head: {sha: (drift === "head-before" || (drift === "head-after" && call > 0)) ? "c".repeat(40) : "a".repeat(40)}, + base: {sha: drift === "base-after" && call > 0 ? "c".repeat(40) : "b".repeat(40)}, + }}); }; + })()}}, paginate: async () => entries.map(entry => ({status: "modified", ...entry}))}, + {eventName: "pull_request", repo: {owner: "example", repo: "FireMUD"}, + payload: {pull_request: {number: 42, changed_files: count, + head: {sha: "a".repeat(40)}, base: {sha: "b".repeat(40)}}}}, + {setOutput: (name, value) => outputs[name] = value, warning() {}}); + assert.equal(outputs.lightweight_only, String(expected)); + assert.equal(outputs.run_all, String(!expected)); + assert.deepEqual(JSON.parse(outputs.affected_modules), expected ? [] : ALL_MODULES); + assert.deepEqual(JSON.parse(outputs.bootable_modules), expected ? [] : [...BOOTABLE_MODULES]); + } const shared = classifyChangeScope(["services/common-redis-contracts/src/main/java/Example.java"]); assert.deepEqual(shared.affectedModules, ALL_MODULES); assert.ok(!shared.bootableModules.includes("common-redis-contracts")); From efc028259e3bc193e6b0c8a5ced61fe2195a1a9a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:37:19 +1300 Subject: [PATCH 055/199] fix(preview): defer uncertain attempts and match resolved plan tuples --- .github/workflows/preview-reconciler.yml | 51 ++++++++++++++++---- .github/workflows/preview.yml | 4 ++ dev-tools/tests/preview-priority-contract.sh | 49 +++++++++++++++---- 3 files changed, 86 insertions(+), 18 deletions(-) diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index f0555686b8..95e90a9192 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -342,25 +342,48 @@ jobs: dispatch_sent=false automatic_preview_has_tuple() { local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" jobs latest - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 - jq -e --argjson id "$run_id" --argjson attempt "$attempt" \ - --arg head "$head" --arg tuple "$tuple" ' + # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 2 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' .jobs as $jobs | (($jobs | type) == "array") and (.total_count == ($jobs | length)) + and (.total_count < 100) and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) and any($jobs[]; .name == "Preview Plan" and .run_id == $id and .run_attempt == $attempt and .head_sha == $head and .status == "completed" and .conclusion == "success" - and ([.steps[]? | select(.name | startswith("Preview event tuple "))] | length == 1) - and any(.steps[]?; .name == $tuple and .status == "completed" and .conclusion == "success")) - ' <<<"$jobs" >/dev/null || return 1 - latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 1 + and ([.steps[]? | select(.name | startswith("Preview resolved tuple "))] | length == 1) + and any(.steps[]?; + (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null || return 2 + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 + jq -e ' + type == "object" + and (.id | type == "number" and . > 0 and . == floor) + and (.run_attempt | type == "number" and . > 0 and . == floor) + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.event | type == "string" and length > 0) + and (.path | type == "string" and length > 0) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) + ' <<<"$latest" >/dev/null || return 2 + if jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" ' + .id == $id and .run_attempt != $attempt and .head_sha == $head + and .event == "pull_request" + and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge")) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) + ' <<<"$latest" >/dev/null; then + return 2 + fi jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" ' .id == $id and .run_attempt == $attempt and .head_sha == $head and .event == "pull_request" and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge")) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) - ' <<<"$latest" >/dev/null + ' <<<"$latest" >/dev/null || return 1 + jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) + ' <<<"$jobs" >/dev/null || return 1 } dispatch_candidates() { @@ -604,14 +627,20 @@ jobs: fi active_preview_run_id="$(jq -rs '[.[] | select(.exact)][0].id // empty' <<<"$preview_candidates")" + active_preview_lookup_unknown=false if [[ -z "$active_preview_run_id" ]]; then # A same-head title is not proof: the base can move independently. - tuple_step="Preview event tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" while IFS=$'\t' read -r run_id run_attempt; do [[ -n "$run_id" ]] || continue if automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number"; then active_preview_run_id="$run_id" break + else + lookup_status=$? + if [[ "$lookup_status" -eq 2 ]]; then + active_preview_lookup_unknown=true + fi fi done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt] | @tsv' <<<"$preview_candidates") fi @@ -620,6 +649,10 @@ jobs: echo "Skipping proof retry for PR #${pr_number}: preview source or trusted consumer run ${active_preview_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." continue fi + if [[ "$active_preview_lookup_unknown" == true ]]; then + echo "Skipping proof retry for PR #${pr_number}: active preview tuple lookup unavailable; retry budget unchanged." + continue + fi if [[ "${namespace_exists}" == "true" && "${current_base_sha}" == "${base_sha}" && diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 23d88494e8..6336f67a10 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -375,6 +375,10 @@ jobs: --author "$TARGET_AUTHOR" \ --labels-json "$TARGET_LABELS_JSON" >> "$GITHUB_OUTPUT" + - name: Preview resolved tuple pr-${{ steps.derive.outputs.pr_number }} base-${{ steps.derive.outputs.base_sha }} head-${{ steps.derive.outputs.head_sha }} merge-${{ steps.derive.outputs.merge_sha }} + if: ${{ github.event_name == 'pull_request' && steps.derive.outputs.action == 'deploy' && steps.eligibility.outputs.eligible == 'true' }} + run: ':' + - name: Explain preview skip if: ${{ steps.eligibility.outputs.eligible != 'true' }} run: | diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 8af01c1869..fcee042e06 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -40,6 +40,20 @@ Path(sys.argv[3]).write_text(body, encoding="utf-8") PY } +python3 - "$ROOT_DIR/.github/workflows/preview.yml" <<'PY' +import sys, yaml +steps = yaml.safe_load(open(sys.argv[1]))["jobs"]["preview-plan"]["steps"] +resolved = [(i, s) for i, s in enumerate(steps) if s.get("name", "").startswith("Preview resolved tuple ")] +assert len(resolved) == 1 +index, marker = resolved[0] +assert marker["run"] == ":" +assert marker["if"] == "${{ github.event_name == 'pull_request' && steps.derive.outputs.action == 'deploy' && steps.eligibility.outputs.eligible == 'true' }}" +assert marker["name"] == "Preview resolved tuple pr-${{ steps.derive.outputs.pr_number }} base-${{ steps.derive.outputs.base_sha }} head-${{ steps.derive.outputs.head_sha }} merge-${{ steps.derive.outputs.merge_sha }}" +assert index > next(i for i,s in enumerate(steps) if s.get("id") == "derive") +assert index > next(i for i,s in enumerate(steps) if s.get("id") == "eligibility") +assert sum(s.get("name", "").startswith("Preview event tuple ") for s in steps) == 1 +PY + cardinality_workflow="$TEMP_DIR/step-cardinality.yml" cat >"$cardinality_workflow" <<'YAML' jobs: @@ -444,10 +458,12 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == exit 0 fi if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254/attempts/2/jobs?per_page=100' ]]; then + [[ "${FAKE_PREVIEW_PLAN_JOBS_FAIL:-false}" != true ]] || exit 1 printf '%s' "${FAKE_PREVIEW_PLAN_JOBS_JSON:-null}" exit 0 fi if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254' ]]; then + [[ "${FAKE_PREVIEW_SOURCE_LATEST_FAIL:-false}" != true ]] || exit 1 printf '%s' "${FAKE_PREVIEW_SOURCE_LATEST_JSON:-null}" exit 0 fi @@ -2540,40 +2556,55 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path; do +for tuple_case in current qualified old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" - tuple_name="Preview event tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" - old_tuple_name="Preview event tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-dddddddddddddddddddddddddddddddddddddddd" + tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" + old_tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-dddddddddddddddddddddddddddddddddddddddd" plan_jobs="$(jq -cn --arg tuple "$tuple_name" --arg old "$old_tuple_name" \ --arg head "$preview_head_sha" --arg variant "$tuple_case" ' def step($name): {name:$name,status:"completed",conclusion:"success"}; [{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head,status:"completed",conclusion:"success", - steps:(if $variant == "old_merge" then [step($old)] + steps:(if $variant == "old_merge" or $variant == "stale_attempt_old_tuple" then [step($old)] elif $variant == "ambiguous" then [step($tuple),step($old)] - else [step($tuple)] end)}] | - if $variant == "missing" then {jobs:[],total_count:0} else {jobs:.,total_count:length} end')" + elif $variant == "event_only" then [step($tuple | sub("resolved"; "event"))] + elif $variant == "old_event_current_plan" then [step($old | sub("resolved"; "event")),step($tuple)] + else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] | + if $variant == "missing" then {jobs:[],total_count:0} + elif $variant == "jobs_incomplete" then {jobs:.,total_count:2} + elif $variant == "jobs_malformed" then {jobs:null,total_count:1} + else {jobs:.,total_count:length} end')" latest_source="$(jq -cn --arg head "$preview_head_sha" --arg variant "$tuple_case" ' - {id:5254,run_attempt:(if $variant == "stale_attempt" then 3 else 2 end), - head_sha:$head,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"}')" + {id:5254,run_attempt:(if $variant == "stale_attempt" or $variant == "stale_attempt_old_tuple" then 3 else 2 end), + head_sha:$head,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} + | if $variant == "latest_missing_head" then del(.head_sha) + elif $variant == "latest_missing_path" then del(.path) else . end')" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PREVIEW_PLAN_JOBS_FAIL="$([[ "$tuple_case" == jobs_unavailable ]] && echo true || echo false)" \ + FAKE_PREVIEW_SOURCE_LATEST_FAIL="$([[ "$tuple_case" == latest_unavailable ]] && echo true || echo false)" \ FAKE_PREVIEW_PLAN_JOBS_JSON="$plan_jobs" \ FAKE_PREVIEW_SOURCE_LATEST_JSON="$latest_source" \ FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_output" - if [[ "$tuple_case" == current || "$tuple_case" == qualified ]]; then + if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == old_event_current_plan ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" + elif [[ "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple ]]; then + grep -Fqx \ + "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ + "$reconciler_pull_request_output" + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" else grep -Fqx \ "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ From 8e032a60499ae02db0826862b4d8379c1b024909 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:08:35 +1300 Subject: [PATCH 056/199] Strengthen required gate contract assertions --- .../tests/pr-required-gate-context-contract.sh | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) mode change 100644 => 100755 dev-tools/tests/pr-required-gate-context-contract.sh diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh old mode 100644 new mode 100755 index 850fba50d1..46e1274e28 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -147,6 +147,8 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o result_steps = [step for step in gate.get("steps", []) if step.get("name") == result_step] if len(result_steps) != 1 or result_steps[0].get("env", {}).get("CHANGES_RESULT") != "${{ needs.changes.result }}": raise SystemExit(f"{workflow} {gate_name} must enforce through one {result_step!r} step reading CHANGES_RESULT") + if "if" in result_steps[0]: + raise SystemExit(f"{workflow} {gate_name} result step must run unconditionally") if any("if" in step and "edited" in step["if"] for step in gate.get("steps", [])): raise SystemExit(f"{workflow} {gate_name} steps must not branch on edits; the job condition owns that") @@ -507,7 +509,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, currentRunReads = 0; - const failures = [], refs = []; + const failures = [], refs = [], info = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { repository: {default_branch: "develop"}, pull_request: {number: 42, head: {sha: head, repo: {full_name: repository}}, @@ -592,9 +594,9 @@ async function scenario(kind, event = "pull_request") { ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [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 => info.push(message), warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots}; + return {failures, refs, snapshots, info}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -605,7 +607,12 @@ async function scenario(kind, event = "pull_request") { assert.deepEqual((await scenario("legacy-positive")).failures, []); assert.deepEqual((await scenario("pending-native-refresh", "repository_dispatch")).failures, [], "trusted successful refresh releases queued native wait"); for (const kind of ["pending-native-refresh-skipped", "pending-native-refresh-failed"]) { - assert.equal((await scenario(kind, "repository_dispatch")).failures.length, 1, `${kind} cannot release queued native wait`); + const result = await scenario(kind, "repository_dispatch"); + assert.equal(result.failures.length, 1, `${kind} cannot release queued native wait`); + assert(result.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), + `${kind} must leave the native run selected`); + assert(!result.info.some(line => line.startsWith("Found runtime-images run 42 with status=")), + `${kind} must not select the refresh`); } for (const kind of ["duplicate-missing-step", "duplicate-nonterminal-step"]) { assert.deepEqual((await scenario(kind)).failures, [], `${kind} preserves canonical fallback`); From 9bf797eade6fdeaebb59128122b8d5ae6c282076 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:19:11 +1300 Subject: [PATCH 057/199] Retain native smoke wait during optional refresh lookup failures --- .github/workflows/smoke.yml | 18 +++++++++++++++--- .../tests/pr-required-gate-context-contract.sh | 16 ++++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c2a45b9bae..c8d549b282 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1214,9 +1214,21 @@ jobs: // It must not hide already verified smoke proof or cause a second dispatch. if (currentIdentity.sourceEvent === "pull_request" && matching?.event === "pull_request" && matching.status !== "completed") { - const replacement = await findMatchingRuntimeImagesRun( - "repository_dispatch", expectedDisplayTitle, currentIdentity - ); + let replacement; + try { + replacement = await findMatchingRuntimeImagesRun( + "repository_dispatch", expectedDisplayTitle, currentIdentity + ); + } catch (error) { + const status = error?.status ?? error?.response?.status; + const code = error?.code ?? error?.cause?.code; + const networkFailure = status == null && [ + "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", + "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", + ].includes(code); + if (!retryableStatuses.has(status) && !networkFailure) throw error; + core.warning("Trusted refresh inventory is unavailable; retain the native wait."); + } try { if (replacement && await verifyCompletedCanonicalRuntime(replacement, currentIdentity)) { core.info("A completed verified exact trusted refresh supersedes the pending native wait."); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 46e1274e28..8355b777c4 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -508,7 +508,7 @@ const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defa 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, currentRunReads = 0; + let now = 1000, snapshots = 0, reads = 0, currentRunReads = 0, refreshInventoryReads = 0; const failures = [], refs = [], info = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { repository: {default_branch: "develop"}, @@ -590,13 +590,19 @@ async function scenario(kind, event = "pull_request") { status: kind.startsWith("pending-native") ? "queued" : "completed", conclusion: kind.startsWith("pending-native") ? null : "cancelled"}]}; return; } + if (kind.startsWith("pending-native-inventory-") && input.event === "repository_dispatch") { + refreshInventoryReads += 1; + const forbidden = kind.endsWith("-forbidden"); + throw Object.assign(new Error(forbidden ? "optional inventory forbidden" : "optional inventory unavailable"), + {status: forbidden ? 403 : 503}); + } yield {data: kind.startsWith("duplicate-") && !["duplicate-jobs", "duplicate-attempt-jobs"].includes(kind) ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [source]}; }; const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: message => info.push(message), warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, info}; + return {failures, refs, snapshots, info, refreshInventoryReads}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -614,6 +620,12 @@ async function scenario(kind, event = "pull_request") { assert(!result.info.some(line => line.startsWith("Found runtime-images run 42 with status=")), `${kind} must not select the refresh`); } + const unavailable = await scenario("pending-native-inventory-unavailable", "repository_dispatch"); + assert(unavailable.refreshInventoryReads >= 4, "temporary inventory errors exhaust the normal retries"); + assert(unavailable.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), + "temporary inventory outage must leave the native run selected"); + assert.equal(unavailable.failures.length, 1, "a native run that never finishes still fails the gate"); + await assert.rejects(() => scenario("pending-native-inventory-forbidden", "repository_dispatch"), /inventory forbidden/); for (const kind of ["duplicate-missing-step", "duplicate-nonterminal-step"]) { assert.deepEqual((await scenario(kind)).failures, [], `${kind} preserves canonical fallback`); } From 7d9f7e050008a3c37dfdda818cfc3a0503c639c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:26:51 +1300 Subject: [PATCH 058/199] Recheck live smoke comparison after final attempt lookup --- .github/workflows/smoke.yml | 12 ++++++++++++ .../tests/pr-required-gate-context-contract.sh | 16 +++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c8d549b282..cc525354ab 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1480,6 +1480,18 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (currentIdentity.sourceEvent === "repository_dispatch") { + // A trusted refresh follows the live base, unlike immutable event proof. + const acceptanceIdentity = await resolveCurrentIdentity( + "Stopping stale current-base smoke gate after the final run lookup" + ); + if (acceptanceIdentity?.obsolete) return; + if (!acceptanceIdentity || identityKey(acceptanceIdentity) !== identityKey(currentIdentity)) { + currentIdentity = acceptanceIdentity; + core.info("Current-base identity changed after the final runtime attempt lookup; resume exact selection."); + 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 8355b777c4..8649a0deec 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -509,8 +509,11 @@ 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, currentRunReads = 0, refreshInventoryReads = 0; + const liveFallback = kind.startsWith("trusted-current-base"); + const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); + const tupleAdvanced = () => kind === "trusted-current-base-advances" && currentRunReads >= 2; const failures = [], refs = [], info = []; - const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { + const context = {repo: {owner: "example", repo: "firemud"}, sha: liveFallback ? 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"}, @@ -546,10 +549,11 @@ 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}}; + return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: tupleAdvanced() ? nextBase : base}, merge_commit_sha: tupleAdvanced() ? nextMerge : merge}}; }}, + git: {getRef: async () => ({data: {object: {sha: tupleAdvanced() ? nextBase : 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 === nextMerge ? nextBase : base}, {sha: head}]}}), getContent: async ({ref, path}) => { refs.push(ref); assert.equal(path, source.path); @@ -639,6 +643,12 @@ async function scenario(kind, event = "pull_request") { assert.equal((await scenario(kind)).failures.length, 1, `${kind} must not supply successful proof`); } assert.equal((await scenario("wrong-dispatch-branch", "repository_dispatch")).failures.length, 1); + const stableFallback = await scenario("trusted-current-base-stable", "repository_dispatch"); + assert.deepEqual(stableFallback.failures, [], "unchanged current-base tuple still accepts exact refresh proof"); + const advancedFallback = await scenario("trusted-current-base-advances", "repository_dispatch"); + assert(advancedFallback.info.some(line => line.includes("identity changed after the final runtime attempt lookup")), + "late base movement cannot accept the old trusted refresh"); + assert.match(advancedFallback.failures[0], /Timed out waiting for the exact runtime-images/); const stale = await scenario("stale-final"); assert.deepEqual(stale.failures, [], "obsolete gate exits without publishing proof for changed base ref"); console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); From 50523220656779f38f6ff3bba8c7ded289086573 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:04:21 +1300 Subject: [PATCH 059/199] Reselect newer attempts after incomplete smoke snapshots --- .github/workflows/smoke.yml | 13 ++++++++++ .../pr-required-gate-context-contract.sh | 25 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index cc525354ab..63b4b74a2f 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1388,6 +1388,19 @@ jobs: )); continue; } + // A rerun may have superseded the attempt whose snapshot never materialized. + // Only the same run's provably newer attempt warrants reselection. + const { data: latestSnapshotAttempt } = await withTransientGitHubRetry( + "runtime attempt lookup after incomplete smoke snapshot", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + ); + if (positiveInteger(matching.run_attempt) && latestSnapshotAttempt.id === matching.id && + positiveInteger(latestSnapshotAttempt.run_attempt) && + latestSnapshotAttempt.run_attempt > matching.run_attempt) { + core.info("Runtime attempt superseded the incomplete smoke snapshot; resume exact selection."); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const snapshotRetrySummary = maxCompletedJobSnapshotRetries === 0 ? "before the remaining workflow deadline allowed a retry" : `after ${maxCompletedJobSnapshotRetries} retries`; diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8649a0deec..6948523d94 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -523,6 +523,8 @@ async function scenario(kind, event = "pull_request") { 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: []}; + const incompleteSnapshot = kind.startsWith("incomplete-snapshot-"); + let snapshotRerunVisible = false; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, check_run_url: `https://api.github.com/repos/${repository}/check-runs/100`, name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", @@ -567,6 +569,10 @@ async function scenario(kind, event = "pull_request") { getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), getWorkflowRun: async () => { currentRunReads += 1; + if (incompleteSnapshot) { + snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; + return {data: {...source, run_attempt: snapshotRerunVisible ? 2 : 1}}; + } const superseded = kind === "newer-attempt" || (kind === "rerun-after-proof" && currentRunReads > 1); return {data: {...source, run_attempt: superseded ? 2 : 1, status: superseded ? "in_progress" : "completed"}}; }, @@ -578,7 +584,16 @@ async function scenario(kind, event = "pull_request") { }, paginate: async (method, input) => { 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); + assert.equal(input.run_id, 42); + if (incompleteSnapshot) { + snapshots += 1; + if (input.attempt_number === 1) return []; + assert.equal(input.attempt_number, 2); + return [{...job, run_attempt: 2, steps: [ + ...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}, + ]}]; + } + 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"}, @@ -600,6 +615,9 @@ async function scenario(kind, event = "pull_request") { throw Object.assign(new Error(forbidden ? "optional inventory forbidden" : "optional inventory unavailable"), {status: forbidden ? 403 : 503}); } + if (incompleteSnapshot) { + yield {data: [{...source, run_attempt: snapshotRerunVisible ? 2 : 1}]}; return; + } yield {data: kind.startsWith("duplicate-") && !["duplicate-jobs", "duplicate-attempt-jobs"].includes(kind) ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [source]}; }; @@ -643,6 +661,11 @@ async function scenario(kind, event = "pull_request") { assert.equal((await scenario(kind)).failures.length, 1, `${kind} must not supply successful proof`); } assert.equal((await scenario("wrong-dispatch-branch", "repository_dispatch")).failures.length, 1); + const supersededSnapshot = await scenario("incomplete-snapshot-superseded"); + assert(supersededSnapshot.info.some(line => line.includes("superseded the incomplete smoke snapshot"))); + assert.deepEqual(supersededSnapshot.failures, [], "reselection must qualify the newer attempt's own exact smoke evidence"); + const unchangedSnapshot = await scenario("incomplete-snapshot-unchanged"); + assert.match(unchangedSnapshot.failures[0], /did not expose a terminal PR Full-Stack Smoke job/); const stableFallback = await scenario("trusted-current-base-stable", "repository_dispatch"); assert.deepEqual(stableFallback.failures, [], "unchanged current-base tuple still accepts exact refresh proof"); const advancedFallback = await scenario("trusted-current-base-advances", "repository_dispatch"); From 3714e23afe6de2b52a2029945f1d2609f3721110 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:24:15 +1300 Subject: [PATCH 060/199] Bind static analysis summaries to exact workflow attempts --- .github/workflows/static-analysis-summary.yml | 91 +++++++---------- .../tests/static-analysis-summary-contract.sh | 98 ++++++++++++++++--- 2 files changed, 117 insertions(+), 72 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index c317d2e129..079ecce9cd 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -139,7 +139,7 @@ jobs: if (value === "success") return "✅"; if (value === "failure") return "❌"; if (value === "cancelled") return "⚪"; - if (value === "pending" || value === "in_progress" || value === "queued") return "⏳"; + if (value === "pending" || value === "in_progress" || value === "queued" || value === "unavailable") return "⏳"; return "⏭️"; }; @@ -161,11 +161,6 @@ jobs: return numericIdentity(left?.id) - numericIdentity(right?.id); }; - const checkRunWorkflowId = (checkRun) => { - const match = String(checkRun?.details_url || "").match(/\/actions\/runs\/(\d+)(?:\/|$)/); - return match?.[1] || null; - }; - // Metadata-only edits skip their gate under a non-required name; the // earlier substantive run for the same title remains the result. // GitHub leaves a skipped job's name expression unevaluated, so match @@ -196,48 +191,37 @@ jobs: data.total_count !== data.jobs.length || data.total_count >= 100) { throw new Error("Static summary candidate jobs are incomplete."); } + const mismatched = data.jobs.some(job => !Number.isSafeInteger(job?.id) || job.id <= 0 || + job.run_id !== candidate.id || job.run_attempt !== candidate.run_attempt || job.head_sha !== headSha); + const evidenceNames = [gateName, ...(workflowId === "codeql.yml" ? [ + ...detailChecks.map(([, name]) => name), "CodeQL Analysis ($" + "{{ matrix.language }})", + ] : [])]; + const duplicate = !mismatched && + evidenceNames.some(name => data.jobs.filter(job => job.name === name).length > 1); + if (mismatched || duplicate) { + // Do not replace a summary from a newer attempt with an older ambiguous snapshot. + const {data: currentRun} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: candidate.id, + }); + if (currentRun?.id !== candidate.id || currentRun.run_attempt !== candidate.run_attempt || + currentRun.event !== "pull_request" || currentRun.head_sha !== headSha || + currentRun.display_title !== expectedTitle) { + throw new Error("Static summary cannot confirm the current workflow attempt."); + } + return { status: "unavailable", conclusion: null, jobs: [] }; + } const metadataName = `PR Metadata Edit (${gateName})`; const metadata = data.jobs.some(job => job.status === "completed" && job.conclusion === "skipped" && (job.name === metadataName || String(job.name || "").includes("'" + metadataName + "'"))); const substantive = data.jobs.some(job => job.name === gateName); if (metadata && !substantive) continue; - if (!substantive) return { ...candidate, status: "in_progress", conclusion: null }; - return candidate; + if (!substantive) return { ...candidate, status: "in_progress", conclusion: null, jobs: data.jobs }; + return { ...candidate, jobs: data.jobs }; } return null; }; - const compareCheckRuns = (left, right) => { - const leftTimestamp = Math.max( - parseTimestamp(left?.completed_at), - parseTimestamp(left?.started_at), - parseTimestamp(left?.created_at) - ); - const rightTimestamp = Math.max( - parseTimestamp(right?.completed_at), - parseTimestamp(right?.started_at), - parseTimestamp(right?.created_at) - ); - if (leftTimestamp !== rightTimestamp) return leftTimestamp - rightTimestamp; - return numericIdentity(left?.id) - numericIdentity(right?.id); - }; - - const selectLatestCheckRun = (checkRuns, checkName, workflowRun) => { - if (!workflowRun?.id) return null; - const workflowRunId = String(workflowRun.id); - const candidates = (Array.isArray(checkRuns) ? checkRuns : []).filter( - (checkRun) => - checkRun?.name === checkName && - checkRunWorkflowId(checkRun) === workflowRunId - ); - return candidates.reduce( - (latest, candidate) => - !latest || compareCheckRuns(candidate, latest) > 0 ? candidate : latest, - null - ); - }; - const normalizeStatus = (checkRun, checkName, workflowRun) => { if (!checkRun) { if ( @@ -256,38 +240,27 @@ jobs: return checkRun.conclusion ?? "pending"; }; - const loadChecks = async () => { - return github.paginate(github.rest.checks.listForRef, { - ...context.repo, - ref: headSha, - per_page: 100, - }); - }; - - const resolveStatuses = (checkRuns, workflowRuns) => + const resolveStatuses = (workflowRuns) => [...gateChecks, ...detailChecks].map(([label, checkName, workflowKey]) => { const isCodeQlAnalysis = checkName.startsWith("CodeQL Analysis ("); const emptyMatrixCodeQlCheck = "CodeQL Analysis ($" + "{{ matrix.language }})"; const workflowRun = workflowRuns?.[workflowKey] || null; - const selectedCheckRun = selectLatestCheckRun( - checkRuns, - checkName, - workflowRun - ) || (isCodeQlAnalysis - ? selectLatestCheckRun(checkRuns, emptyMatrixCodeQlCheck, workflowRun) - : null); - return [label, normalizeStatus(selectedCheckRun, checkName, workflowRun)]; + const jobs = workflowRun?.jobs ?? []; + let candidates = jobs.filter(job => job.name === checkName); + if (!candidates.length && isCodeQlAnalysis) { + candidates = jobs.filter(job => job.name === emptyMatrixCodeQlCheck); + } + return [label, normalizeStatus(candidates[0], checkName, workflowRun)]; }); - const checkRuns = await loadChecks(); const workflowRuns = { codeql: await workflowRunFor("codeql.yml", "CodeQL Gate"), license: await workflowRunFor("license-scan.yml", "License Gate"), }; // Each serialized producer completion publishes one bounded snapshot. // A running counterpart stays pending until its completion callback refreshes this comment. - const checks = resolveStatuses(checkRuns, workflowRuns); + const checks = resolveStatuses(workflowRuns); const gateResults = checks.slice(0, gateChecks.length); const detailResults = checks.slice(gateChecks.length); @@ -299,9 +272,13 @@ jobs: ["pending", "in_progress", "queued"].includes(result) ); + const unavailableChecks = gateResults.filter(([, result]) => result === "unavailable"); + let headline = "✅ Static analysis checks passed"; if (failedChecks.length > 0) { headline = "❌ Static analysis checks failed"; + } else if (unavailableChecks.length > 0) { + headline = "⏳ Static analysis evidence is unavailable"; } else if (pendingChecks.length > 0) { headline = "⏳ Static analysis checks are still running"; } diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 5892050b7c..9271db0935 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -20,8 +20,11 @@ grep -Fq 'workflowRunFor("license-scan.yml", "License Gate")' "$workflow" grep -Fq 'head_sha: headSha,' "$workflow" grep -Fq 'return "skipped";' "$workflow" grep -Fq 'run_attempt' "$workflow" -grep -Fq 'checkRunWorkflowId' "$workflow" -grep -Fq 'github.paginate(github.rest.checks.listForRef' "$workflow" +grep -Fq 'job.run_attempt !== candidate.run_attempt' "$workflow" +if grep -Fq 'github.rest.checks.listForRef' "$workflow"; then + echo "static analysis summary must not reuse a head-level check snapshot across attempts" >&2 + exit 1 +fi grep -Fq 'github.paginate(github.rest.issues.listComments' "$workflow" grep -Fq 'per_page: 100' "$workflow" grep -Fq 'cancel-in-progress: false' "$workflow" @@ -164,11 +167,24 @@ const github = { request: async (route, input) => { if (route !== "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs") throw new Error("unexpected native request"); jobRequests.push(input); - if (input.attempt_number !== 1 || input.per_page !== 100) throw new Error("candidate must use exact attempt and bounded jobs"); - const metadata = input.run_id === 270; - const name = metadata ? "github.event.action == 'edited' && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'" : - input.run_id % 1000 === 300 ? "License Gate" : "CodeQL Gate"; - return { data: { total_count: 1, jobs: [{ name, status: "completed", conclusion: metadata ? "skipped" : "success" }] } }; + if (input.per_page !== 100) throw new Error("candidate must use bounded jobs"); + const fromAttempt = (row) => ({ + ...row, run_id: input.run_id, run_attempt: input.attempt_number, head_sha: currentHeadSha, + }); + if (input.run_id === 270) { + return {data: {total_count: 1, jobs: [fromAttempt({id: 2701, + name: "github.event.action == 'edited' && 'PR Metadata Edit (CodeQL Gate)' || 'CodeQL Gate'", + status: "completed", conclusion: "skipped"})]}}; + } + // Reuse the existing status fixtures as native jobs. Each callback reads them + // from this same selected-attempt response, not via a real head-check query. + const callCount = calls.paginate.length; + const fixtures = await github.paginate(checksListForRef, {ref: currentHeadSha, per_page: 100}); + calls.paginate.splice(callCount); + let jobs = fixtures.filter(row => row.details_url.includes(`/runs/${input.run_id}/`)).map(fromAttempt); + if (input.attempt_number === 2) jobs = jobs.map(job => ({...job, id: job.id + 10000, + status: "in_progress", conclusion: null})); + return {data: {total_count: jobs.length, jobs}}; }, rest: { pulls: { get: async () => { @@ -446,7 +462,7 @@ async function assertCompletionOrders() { }); calls.paginate.length = 0; await run(github, context, core); - if (calls.paginate.length !== 4) throw new Error("each callback must take exactly one snapshot of both producers, checks and comments"); + if (calls.paginate.length !== 3) throw new Error("each callback must take exactly one snapshot of both producers and comments"); }; await callback(first); if (creates !== 1 || updates !== 0 || comments.length !== 1 || !comments[0].body.includes("still running")) { @@ -586,7 +602,7 @@ async function assertInterruptedRecovery() { } } run(github, context, core).then(async () => { - if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); + if (calls.paginate.length !== 3) throw new Error(`expected three paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) throw new Error("only the later duplicate should be deleted"); @@ -596,13 +612,13 @@ run(github, context, core).then(async () => { const canonicalBody = calls.updated[0].body; context.payload.workflow_run.name = "Forged workflow name"; await run(github, context, core); - if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + if (calls.paginate.length !== 3 || calls.updated.length !== 1 || calls.deleted.length !== 1) { throw new Error("unrelated source names must not query runs or alter comments"); } context.payload.workflow_run.name = "CodeQL Analysis"; context.payload.workflow_run.head_sha = "invalid"; return run(github, context, core).then(() => { - if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + if (calls.paginate.length !== 3 || calls.updated.length !== 1 || calls.deleted.length !== 1) { throw new Error("malformed source head should not query runs or alter comments"); } context.payload.workflow_run.head_sha = headSha; @@ -611,20 +627,20 @@ run(github, context, core).then(async () => { pullRequestReads = 0; context.payload.workflow_run.display_title = `CodeQL Analysis pr-42 base-invalid head-${headSha}`; return run(github, context, core).then(() => { - if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + if (calls.paginate.length !== 3 || calls.updated.length !== 1 || calls.deleted.length !== 1) { throw new Error("source run with a malformed canonical title must not query runs or alter comments"); } context.payload.workflow_run.display_title = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; context.payload.workflow_run.path = ".github/workflows/unrelated.yml"; return run(github, context, core).then(() => { - if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + if (calls.paginate.length !== 3 || calls.updated.length !== 1 || calls.deleted.length !== 1) { throw new Error("an unrelated source workflow must not query runs or alter comments"); } context.payload.workflow_run.path = ".github/workflows/codeql.yml"; pullRequestReads = 0; changeBaseDuringRun = true; return run(github, context, core).then(() => { - if (calls.paginate.length !== 8 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + if (calls.paginate.length !== 6 || calls.updated.length !== 1 || calls.deleted.length !== 1) { throw new Error("base changes during summarization must not alter comments"); } currentHeadSha = headSha; @@ -665,12 +681,64 @@ run(github, context, core).then(async () => { await assertAssociationSelection(); if (!jobRequests.some(input => input.run_id === 270)) throw new Error("metadata race was not classified from candidate jobs"); const savedRequest = github.request; - github.request = async () => ({ data: { total_count: 1, jobs: [{ name: "Unrelated job", status: "completed", conclusion: "success" }] } }); + const savedPaginate = github.paginate; + github.paginate = async (method, input) => { + const rows = await savedPaginate(method, input); + return method === codeqlListWorkflowRuns && input.workflow_id === "codeql.yml" + ? rows.map(row => row.id === 200 ? {...row, run_attempt: 2, status: "in_progress", conclusion: null} : row) + : rows; + }; + const rerunStart = calls.updated.length; + await run(github, context, core); + const rerunWrites = calls.updated.slice(rerunStart); + github.paginate = savedPaginate; + if (!jobRequests.some(input => input.run_id === 200 && input.attempt_number === 2) || + !rerunWrites.some(row => row.body.includes("CodeQL gate: \`in_progress\`")) || + rerunWrites.some(row => row.body.includes("checks passed"))) { + throw new Error("a prior attempt's status cannot replace the selected running rerun"); + } + github.request = async (_, input) => ({ data: { total_count: 1, jobs: [{ + id: 1, run_id: input.run_id, run_attempt: input.attempt_number, head_sha: currentHeadSha, + name: "Unrelated job", status: "completed", conclusion: "success", + }] } }); const unknownStart = calls.updated.length; await run(github, context, core); const unknownWrites = calls.updated.slice(unknownStart); if (!unknownWrites.length || unknownWrites.some(row => row.body.includes("checks passed"))) throw new Error("unclassified successful jobs must not yield a green summary"); if (!unknownWrites.some(row => row.body.includes("in_progress"))) throw new Error("unclassified candidate must remain pending"); + const savedActions = github.rest.actions; + let currentAttempt = 1; + github.rest.actions = {...savedActions, getWorkflowRun: async ({run_id}) => ({data: { + id: run_id, run_attempt: currentAttempt, event: "pull_request", head_sha: currentHeadSha, + display_title: `CodeQL Analysis pr-42 base-${currentBaseSha} head-${currentHeadSha}`, + }})}; + for (const duplicate of [false, true]) { + github.request = async (route, input) => { + const response = await savedRequest(route, input); + if (input.run_id !== 200) return response; + const jobs = response.data.jobs; + const gate = jobs.find(job => job.name === "CodeQL Gate"); + if (duplicate) jobs.push({...gate, id: gate.id + 50000}); + else gate.run_attempt += 1; + return {data: {jobs, total_count: jobs.length}}; + }; + const unavailableStart = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(unavailableStart).some(row => + row.body.includes("Static analysis evidence is unavailable") && + row.body.includes("CodeQL gate: \`unavailable\`"))) { + throw new Error("untrustworthy exact-attempt inventory must not leave a green summary"); + } + } + currentAttempt = 2; + const staleAttemptWrites = calls.updated.length + calls.created.length; + let staleAttemptRefused = false; + try { await run(github, context, core); } catch (error) { + staleAttemptRefused = error.message.includes("cannot confirm the current workflow attempt"); + } finally { github.rest.actions = savedActions; } + if (!staleAttemptRefused || calls.updated.length + calls.created.length !== staleAttemptWrites) { + throw new Error("an older ambiguous snapshot must not overwrite a newer summary"); + } const writesBefore = calls.updated.length + calls.created.length; github.request = async () => ({ data: { total_count: 101, jobs: [] } }); let refused = false; From 606f93156e311df907d3485e0f410e237d2f41c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:52:10 +1300 Subject: [PATCH 061/199] Keep non-publishing callbacks outside runtime publication concurrency --- .github/workflows/runtime-images.yml | 6 +++--- .github/workflows/smoke.yml | 2 +- .../tests/pr-retarget-workflow-contract.sh | 21 ++++++++++++++----- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 25edcdeb9c..12813ac28b 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -57,9 +57,9 @@ permissions: # Cancellation precedes admission: isolate all PR inputs by exact tuple and # let an existing producer finish when duplicate requests arrive. 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' }} - # Only protected-branch publications supersede older branch commits. - cancel-in-progress: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }} + 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' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') && format('branch-{0}', github.event.workflow_run.head_branch)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('ci-push-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + # Only successful publication callbacks can displace a protected-branch publisher. + cancel-in-progress: ${{ 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') }} jobs: image-meta: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 63b4b74a2f..9cf412188c 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -561,7 +561,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "4b97e52230413781c32db8fea21f94e46d7e2610346508cfc60adc972eb7dc7c"; + const canonicalRuntimeWorkflowSha256 = "d104522a14446575e61675897a300e387b2f50f3d1c918509751aad3a150b057"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 83b05672f9..ed9614d62d 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -700,9 +700,9 @@ if "github.sha" in concurrency_group.split("github.event_name == 'repository_dis raise SystemExit("repository_dispatch concurrency must not use the default-branch github.sha") # Execute the workflow-level selector before its dispatcher can classify a CI # callback. A title/body CI completion must not evict substantive reconciliation. -assert runtime["concurrency"]["cancel-in-progress"] == "${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }}" +assert runtime["concurrency"]["cancel-in-progress"] == "${{ 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') }}" -def callback_group(branch, source_id, source_attempt, source_event="pull_request", head="a" * 40): +def callback_group(branch, source_id, source_attempt, source_event="pull_request", head="a" * 40, conclusion="success", selector=concurrency_group): values = { "github.workflow": "Build Runtime Images", "github.event_name": "workflow_run", @@ -710,6 +710,7 @@ def callback_group(branch, source_id, source_attempt, source_event="pull_request "github.event.workflow_run.id": source_id, "github.event.workflow_run.run_attempt": source_attempt, "github.event.workflow_run.head_branch": branch, + "github.event.workflow_run.conclusion": conclusion, "github.event.workflow_run.head_sha": head, "github.ref": "refs/heads/develop", "github.run_id": 9000 + source_id, @@ -721,7 +722,7 @@ def callback_group(branch, source_id, source_attempt, source_event="pull_request expression = expression.replace("&&", " and ").replace("||", " or ").replace("null", "None") return str(eval(expression, {"__builtins__": {}, "format": lambda pattern, *args: pattern.format(*args)})) - return re.sub(r"\$\{\{(.*?)\}\}", evaluate, concurrency_group) + return re.sub(r"\$\{\{(.*?)\}\}", evaluate, selector) for branch in ("main", "develop", "feature/parent"): substantive = callback_group(branch, 7001, 1) @@ -741,7 +742,17 @@ for branch in ("main", "develop", "feature/parent"): assert callback_group(branch, 7003, 1, "push") not in (substantive, metadata), "PR callback must not cancel branch publication" for branch in ("main", "develop"): - assert callback_group(branch, 7101, 1, "push") == callback_group(branch, 7102, 2, "push", "b" * 40), "protected push publication must retain branch serialization" + publisher = callback_group(branch, 7101, 1, "push") + assert publisher == callback_group(branch, 7102, 2, "push", "b" * 40), "protected push publication must retain branch serialization" + assert callback_group(branch, 7101, 1, "push", selector=runtime["concurrency"]["cancel-in-progress"]) == "True" + for conclusion in ("failure", "cancelled", "timed_out", "skipped", ""): + nonpublisher = callback_group(branch, 7101, 1, "push", conclusion=conclusion) + assert nonpublisher != publisher, "a non-publishing callback must not displace an active or pending publisher" + assert nonpublisher != callback_group(branch, 7101, 2, "push", conclusion=conclusion) + assert callback_group(branch, 7101, 1, "push", conclusion=conclusion, + selector=runtime["concurrency"]["cancel-in-progress"]) == "False" +assert callback_group("feature/parent", 7101, 1, "push") != callback_group("feature/parent", 7102, 1, "push") +assert callback_group("feature/parent", 7101, 1, "push", selector=runtime["concurrency"]["cancel-in-progress"]) == "False" assert callback_group("main", 7101, 1, "push") != callback_group("develop", 7102, 1, "push"), "protected publication branches must remain separate" PY @@ -1579,7 +1590,7 @@ require_contains "$runtime_images_path" 'types: [opened, synchronize, reopened, require_contains "$runtime_images_path" 'types: [pr-runtime-base-refresh]' require_contains "$runtime_images_path" 'repository_dispatch:' require_contains "$runtime_images_path" "&& 'metadata' || 'required' }}" -require_contains "$runtime_images_path" " cancel-in-progress: \${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') }}" +require_contains "$runtime_images_path" " cancel-in-progress: \${{ 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') }}" require_contains "$runtime_images_path" 'run-name: Build Runtime Images ' require_contains "$runtime_images_path" "format('secure-pr-artifact pr-{0}" require_contains "$runtime_images_path" 'github.event.pull_request.base.sha' From 8f0fa56dfe36e154e433643a1d1bb3f08aad9441 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:25:15 +1300 Subject: [PATCH 062/199] Clarify GitHub Actions pending queue behavior --- design/architecture/system-architecture-cicd.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index ba06b3bf95..8a3c633fd3 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -52,7 +52,7 @@ Workflows live in the `.github/workflows/` directory. A typical pipeline runs on The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account, Game Session, or World Management module. World requires its native two-partition declaration; historical World full-check jobs remain valid without an aggregate. Account and Game Session retain attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. -The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. A no-checkout resolver without write permissions validates the PR callback identity before publication enters a PR-number queue. CodeQL and License callbacks for the same PR serialize across heads; different PRs sharing a branch and skipped push callbacks cannot replace that PR’s pending work. An older-head callback may replace pending work for the same PR because publication snapshots the live PR tuple. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. +The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. A no-checkout resolver without write permissions validates the PR callback identity before publication enters a PR-number queue. CodeQL and License callbacks for the same PR serialize across heads; different PRs sharing a branch and skipped push callbacks cannot replace that PR’s pending work. An older-head callback for the same PR can join the queue without replacing a waiting publisher; GitHub cancels a new arrival if the queue is full. When it runs, publication snapshots the live PR tuple. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. ### Pull Request Runtime And Preview Chain @@ -64,7 +64,7 @@ The optional [Static Analysis Summary](../../.github/workflows/static-analysis-s | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -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 its executed substantive Validation Gate enforcement 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. Runtime producers use nonpreemptive exact PR/base/head/merge concurrency groups, so an old-head rerun or duplicate tuple cannot cancel a useful producer. The refresh observer checks a bounded inventory of active canonical runtime producers and reuses an exact current tuple rather than knowingly dispatching another; the inventory check and dispatch are not atomic. 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. +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 its executed substantive Validation Gate enforcement 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. Runtime producers group by exact PR/base/head/merge tuple. An old-head rerun uses a separate group, and a duplicate request cannot cancel an already-running producer. With the default GitHub single-pending queue, a later matching request can still replace a pending producer. The refresh observer checks a bounded inventory of active canonical runtime producers and reuses an exact current tuple rather than knowingly dispatching another; the inventory check and dispatch are not atomic. 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. From 44fc6c4366cdbd70cf23966cfe1ddd391838bd30 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:37:48 +1300 Subject: [PATCH 063/199] Test effective PR gate concurrency groups --- .../pr-required-gate-context-contract.sh | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 6948523d94..1b0fce6ff6 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -8,7 +8,9 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" # earlier substantive result stands and an edit can never turn a failing PR # green. Base retargets keep the required name and rerun the full gate. python3 - "$ROOT_DIR" <<'PY' +import ast from pathlib import Path +import re import sys import yaml @@ -50,6 +52,90 @@ def evaluate(expression, action, base_ref, event="pull_request"): return eval(body, {"__builtins__": {}}) + +def literal_format(pattern, *args): + if type(pattern) is not str: + raise ValueError("Concurrency format requires a literal string") + parts = [] + cursor = 0 + for match in re.finditer(r"\{([0-9]+)\}", pattern): + literal = pattern[cursor:match.start()] + if "{" in literal or "}" in literal: + raise ValueError("Unsupported concurrency format placeholder") + index = int(match[1]) + if index >= len(args): + raise ValueError("Concurrency format placeholder out of range") + parts.extend((literal, str(args[index]))) + cursor = match.end() + tail = pattern[cursor:] + if "{" in tail or "}" in tail: + raise ValueError("Unsupported concurrency format placeholder") + return "".join((*parts, tail)) + + +def interpret_selector(node): + if isinstance(node, ast.Constant) and type(node.value) in (str, int, bool, type(None)): + return node.value + if isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)): + # GitHub's boolean operators return operands and short-circuit. + value = interpret_selector(node.values[0]) + for operand in node.values[1:]: + if bool(value) == isinstance(node.op, ast.Or): + return value + value = interpret_selector(operand) + return value + if (isinstance(node, ast.Compare) and len(node.ops) == 1 + and isinstance(node.ops[0], (ast.Eq, ast.NotEq))): + values = interpret_selector(node.left), interpret_selector(node.comparators[0]) + return (values[0] == values[1]) == isinstance(node.ops[0], ast.Eq) + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id == "format" and not node.keywords and node.args + and isinstance(node.args[0], ast.Constant)): + return literal_format(*(interpret_selector(arg) for arg in node.args)) + raise ValueError("Unsupported concurrency selector") + + +assert literal_format("metadata-{0}", 123) == "metadata-123" +for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{1}"): + try: + literal_format(forbidden, 123) + except ValueError: + pass + else: + raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") + + +def effective_group(group, base_ref): + values = { + "github.event.changes.base.ref": repr(base_ref), + "github.event.pull_request.number": "42", + "github.event.action": "'edited'", + "github.event_name": "'pull_request'", + "github.workflow": "'Required Gate'", + "github.run_id": "123", + "github.ref": "'refs/pull/42/merge'", + } + + def render(match): + body = match[1].strip() + for key, value in values.items(): + body = body.replace(key, value) + body = body.replace("&&", " and ").replace("||", " or ") + body = re.sub(r"\b(null|true|false)\b", lambda token: { + "null": "None", "true": "True", "false": "False", + }[token[0]], body) + tree = ast.parse(body, mode="eval") + return str(interpret_selector(tree.body)) + return re.sub(r"\$\{\{(.*?)\}\}", render, group) + + +def isolates_metadata_group(group, run_scoped): + metadata = effective_group(group, None) + retarget = effective_group(group, "develop") + expected_suffix = "-metadata-123" if run_scoped else "-metadata" + return metadata != retarget and metadata.endswith(expected_suffix) and retarget.endswith("-required") + + def excludes_metadata(expression): body = expression.strip() if body.startswith("${{") and body.endswith("}}"): @@ -169,6 +255,14 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o suffix = "format('metadata-{0}', github.run_id) || 'required'" if run_scoped else "&& 'metadata' || 'required'" if "github.event.pull_request.number" not in group or META.split(" && ", 1)[1] not in group or suffix not in group: raise SystemExit(f"{workflow} concurrency group must keep metadata runs out of the PR's required namespace") + if not isolates_metadata_group(group, run_scoped): + raise SystemExit(f"{workflow} effective metadata and retarget groups must differ") + # The old substring guard would accept this expression despite its bypass. + bypassed = group.replace(META, "true && 'required' || " + META, 1) + assert bypassed != group and META in bypassed and suffix in bypassed + assert effective_group(bypassed, None) == effective_group(bypassed, "develop"), workflow + assert effective_group(bypassed, None).endswith("-required"), workflow + assert not isolates_metadata_group(bypassed, run_scoped), workflow if concurrency.get("cancel-in-progress") != "true": raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") PY From 3fe8e47b4d2d9c9178da7f11e5746f9ead32de72 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:41:46 +1300 Subject: [PATCH 064/199] Complete runtime callback concurrency fixtures --- .../pr-runtime-image-publication-contract.sh | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 29db237995..6b21dbc1ab 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -96,9 +96,24 @@ check(dispatch, "pr-7-base-base1-head-head1-merge-merge1-required") for event in [base, dispatch, {"event_name": "workflow_dispatch"}, {"event_name": "workflow_run", "event": {"workflow_run": {"event": "pull_request", "head_branch": "develop"}}}]: assert evaluate(event, cancel) == "False", event -for branch in ["main", "develop", "feature/x"]: - event = {"event_name": "workflow_run", "event": {"workflow_run": {"event": "push", "head_branch": branch}}} - assert evaluate(event, cancel) == str(branch in ["main", "develop"]), event +def push_callback(branch, conclusion, run_id, attempt): + return {**base, "event_name": "workflow_run", "event": {"workflow_run": { + "event": "push", "head_branch": branch, "conclusion": conclusion, + "id": run_id, "run_attempt": attempt}}} + +for branch in ("main", "develop"): + event = push_callback(branch, "success", 91, 2) + assert evaluate(event, cancel) == "True", event + check(event, f"branch-{branch}-required") + for conclusion, run_id, attempt in (("failure", 92, 1), ("cancelled", 93, 2), + ("timed_out", 94, 3), (None, 95, 1)): + event = push_callback(branch, conclusion, run_id, attempt) + assert evaluate(event, cancel) == "False", event + check(event, f"ci-push-run-{run_id}-attempt-{attempt}-required") + +nonprotected = push_callback("feature/x", "success", 96, 2) +assert evaluate(nonprotected, cancel) == "False", nonprotected +check(nonprotected, "ci-push-run-96-attempt-2-required") for value in [0, False, "", None]: invalid = copy.deepcopy(dispatch) @@ -116,8 +131,6 @@ check(dispatch, "pr-7-base-base1-head-head2-merge-merge1-required") callback = {**base, "event_name": "workflow_run", "event": { "workflow_run": {"event": "pull_request", "id": 90, "run_attempt": 2}}} check(callback, "ci-pr-run-90-attempt-2-required") -callback["event"]["workflow_run"] = {"event": "push", "head_branch": "develop"} -check(callback, "branch-develop-required") check({**base, "event_name": "push", "event": {}, "ref": "refs/heads/develop"}, "refs/heads/develop-required") print("Runtime concurrency: nonpreemptive exact PR/dispatch tuple and branch isolation passed") From 2fb9df8aadc4270b1664d4cb4d3efeed84ad745f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:45:59 +1300 Subject: [PATCH 065/199] Document fixed hosted preview Gateway JVM defaults --- .../microservices/spring-cloud-gateway/configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index d62e9ab4d6..fad32b6154 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -31,7 +31,7 @@ For the TCP Proxy -> Gateway WebSocket mTLS hop, the TCP Proxy client identity a The trusted default-branch workflow treats the hosted preview Gateway configuration as an exact contract. The rendered `firemud-config` must match the canonical `previewStack.sharedConfig` values from the trusted Helm values file; only the two source-only MinIO credential entries are removed before the artifact is applied. Unknown, missing, or changed shared configuration is rejected. In particular, Gateway bridge and route URI variables, `SPRING_APPLICATION_JSON`, and `JAVA_TOOL_OPTIONS` are not accepted through the shared ConfigMap. -The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. +The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. For hosted preview Gateway artifacts, `previewStack.jvm.javaToolOptions` and `previewStack.jvm.mallocArenaMax` are fixed to the canonical chart defaults; Helm overrides of either value are not supported for this artifact. The trusted validator requires the exact values, even though the shared chart exposes these keys for its other uses. Change the chart defaults and trusted validator together if the hosted preview Gateway settings need to change. The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Game Session on TCP/8444 for the dedicated authenticated mTLS WebSocket receiver at `/ws/game/tcp`, Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. From 92dcdc2eba88d5a54ddd083982bacd9fde6ac0d2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:49:36 +1300 Subject: [PATCH 066/199] Recheck refresh attempt after validating current smoke tuple --- .github/workflows/smoke.yml | 11 +++++++++++ dev-tools/tests/pr-required-gate-context-contract.sh | 10 +++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 9cf412188c..a7811ef7f7 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1504,6 +1504,17 @@ jobs: core.info("Current-base identity changed after the final runtime attempt lookup; resume exact selection."); continue smokeGatePolling; } + const { data: acceptanceAttempt } = await withTransientGitHubRetry( + "current-base runtime attempt lookup after live identity validation", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + ); + if (acceptanceAttempt.id !== matching.id || + acceptanceAttempt.run_attempt !== matching.run_attempt || + acceptanceAttempt.status !== "completed" || acceptanceAttempt.conclusion !== "success") { + core.info("Runtime attempt changed after current-base identity validation; resume exact selection."); + 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 1b0fce6ff6..f8540063de 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -606,6 +606,7 @@ async function scenario(kind, event = "pull_request") { const liveFallback = kind.startsWith("trusted-current-base"); const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); const tupleAdvanced = () => kind === "trusted-current-base-advances" && currentRunReads >= 2; + let rerunStartedDuringLatestIdentityRead = false; const failures = [], refs = [], info = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: liveFallback ? null : merge, payload: { repository: {default_branch: "develop"}, @@ -645,6 +646,9 @@ async function scenario(kind, event = "pull_request") { const github = {rest: { pulls: {get: async () => { reads += 1; + if (kind === "trusted-current-base-attempt-advances" && currentRunReads >= 2) { + rerunStartedDuringLatestIdentityRead = true; + } return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: tupleAdvanced() ? nextBase : base}, merge_commit_sha: tupleAdvanced() ? nextMerge : merge}}; }}, git: {getRef: async () => ({data: {object: {sha: tupleAdvanced() ? nextBase : base}}})}, @@ -667,7 +671,7 @@ async function scenario(kind, event = "pull_request") { snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; return {data: {...source, run_attempt: snapshotRerunVisible ? 2 : 1}}; } - const superseded = kind === "newer-attempt" || (kind === "rerun-after-proof" && currentRunReads > 1); + const superseded = kind === "newer-attempt" || rerunStartedDuringLatestIdentityRead || (kind === "rerun-after-proof" && currentRunReads > 1); return {data: {...source, run_attempt: superseded ? 2 : 1, status: superseded ? "in_progress" : "completed"}}; }, }, @@ -762,6 +766,10 @@ async function scenario(kind, event = "pull_request") { assert.match(unchangedSnapshot.failures[0], /did not expose a terminal PR Full-Stack Smoke job/); const stableFallback = await scenario("trusted-current-base-stable", "repository_dispatch"); assert.deepEqual(stableFallback.failures, [], "unchanged current-base tuple still accepts exact refresh proof"); + const rerunningFallback = await scenario("trusted-current-base-attempt-advances", "repository_dispatch"); + assert(rerunningFallback.info.some(line => line.includes("attempt changed after current-base identity validation")), + "rerunning the producer during the live tuple lookup cannot accept the old attempt"); + assert.equal(rerunningFallback.failures.length, 1, "no exact proof for the new attempt must not pass"); const advancedFallback = await scenario("trusted-current-base-advances", "repository_dispatch"); assert(advancedFallback.info.some(line => line.includes("identity changed after the final runtime attempt lookup")), "late base movement cannot accept the old trusted refresh"); From 142ff93928720022150aab730a1916d62f45e3de Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:06:56 +1300 Subject: [PATCH 067/199] Resume exact native smoke selection after transient alternate reads --- .github/workflows/smoke.yml | 68 ++++++++++++++----- .../pr-required-gate-context-contract.sh | 67 ++++++++++++++++-- 2 files changed, 112 insertions(+), 23 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a7811ef7f7..f35bb93050 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -521,6 +521,7 @@ jobs: const pullRequestCheckInterval = 2; const retryableStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); let pollIteration = 0; + let retryPrimary = null; let identityDiagnostic = "current PR identity has not been resolved"; class TerminalGitHubRequestError extends Error {} @@ -935,7 +936,13 @@ jobs: await verifyCanonicalSmokeProducer(run, producers[0], identity); } - async function findMatchingRuntimeImagesRun(sourceEvent, expectedDisplayTitle, identity) { + function isRetryPrimary(selection, run) { + return selection.retryPrimary?.id === run?.id && + selection.retryPrimary?.run_attempt === run?.run_attempt && + selection.retryPrimary != null; + } + + async function findMatchingRuntimeImagesRun(sourceEvent, expectedDisplayTitle, identity, selection = {}) { const workflowRunQuery = { owner, repo, @@ -1003,13 +1010,14 @@ jobs: newestPreExecutionCancellation ??= run; continue; } - if (run.status !== "completed") { + if (run.status !== "completed" && !isRetryPrimary(selection, run)) { const completed = matchingRuns.filter(({run: older}) => older.id !== run.id && older.status === "completed" && older.conclusion === "success"); for (const {run: older} of completed.slice(0, 3)) { try { if (await verifyCompletedCanonicalRuntime(older, identity)) { core.info("A verified completed exact runtime producer precedes the pending duplicate."); + selection.pendingPrimary = run; return older; } } catch (error) { @@ -1159,10 +1167,15 @@ jobs: `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${currentIdentity.baseSha} head-${currentIdentity.headSha} ` + `merge-${currentIdentity.mergeSha} mode-required`; + const selection = { + retryPrimary: retryPrimary?.identity === identityKey(currentIdentity) ? retryPrimary : null, + }; + retryPrimary = null; let matching = await findMatchingRuntimeImagesRun( currentIdentity.sourceEvent, expectedDisplayTitle, - currentIdentity + currentIdentity, + selection ); if ( currentIdentity.sourceEvent === "pull_request" && @@ -1212,8 +1225,8 @@ jobs: } // A queued native run can share a tuple with a completed trusted refresh. // It must not hide already verified smoke proof or cause a second dispatch. - if (currentIdentity.sourceEvent === "pull_request" && matching?.event === "pull_request" && - matching.status !== "completed") { + if (!isRetryPrimary(selection, matching) && currentIdentity.sourceEvent === "pull_request" && + matching?.event === "pull_request" && matching.status !== "completed") { let replacement; try { replacement = await findMatchingRuntimeImagesRun( @@ -1232,6 +1245,7 @@ jobs: try { if (replacement && await verifyCompletedCanonicalRuntime(replacement, currentIdentity)) { core.info("A completed verified exact trusted refresh supersedes the pending native wait."); + selection.pendingPrimary = matching; matching = replacement; } } catch (error) { @@ -1325,19 +1339,37 @@ jobs: await failNonTerminalSnapshot("before the workflow deadline"); return; } - const jobs = await withTransientGitHubRetry( - "runtime-images job lookup", - () => github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - { - owner, - repo, - run_id: matching.id, - attempt_number: matching.run_attempt, - per_page: 100, - } - ) - ); + let jobs; + try { + jobs = await withTransientGitHubRetry( + "runtime-images job lookup", + () => github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + { + owner, + repo, + run_id: matching.id, + attempt_number: matching.run_attempt, + per_page: 100, + } + ) + ); + } catch (error) { + const status = error?.status ?? error?.response?.status; + if (!selection.pendingPrimary || !retryableStatuses.has(status)) throw error; + // Re-read the pending comparison on the next bounded poll. No + // partial evidence from this alternative carries into that poll. + core.warning( + `Runtime alternative ${matching.id} jobs are temporarily unavailable; retry exact primary selection.` + ); + retryPrimary = { + id: selection.pendingPrimary.id, + run_attempt: selection.pendingPrimary.run_attempt, + identity: identityKey(currentIdentity), + }; + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) { return; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index f8540063de..8ab3f49491 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -601,9 +601,16 @@ 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", captureLookupFailure = false) { let now = 1000, snapshots = 0, reads = 0, currentRunReads = 0, refreshInventoryReads = 0; const liveFallback = kind.startsWith("trusted-current-base"); + const h0 = kind.startsWith("optional-final-read-"); + const cancelledPrimary = kind === "optional-final-read-cancelled-primary"; + const duplicatePrimary = kind === "optional-final-read-duplicate"; + const badStatus = kind.endsWith("-forbidden") ? 403 : kind.endsWith("-missing") ? 404 : 503; + const primaryCanRecover = h0 && !cancelledPrimary && badStatus === 503; + const primaryReady = () => primaryCanRecover && primaryInventoryReads > 1; + let alternativeJobsReads = 0, primaryInventoryReads = 0, lookupFailure; const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); const tupleAdvanced = () => kind === "trusted-current-base-advances" && currentRunReads >= 2; let rerunStartedDuringLatestIdentityRead = false; @@ -618,6 +625,8 @@ async function scenario(kind, event = "pull_request") { 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: []}; + const exactPrimary = {...source, id: 43, event: "pull_request", head_sha: head, + created_at: "2026-09-01T00:00:01Z"}; const incompleteSnapshot = kind.startsWith("incomplete-snapshot-"); let snapshotRerunVisible = false; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, @@ -665,7 +674,8 @@ 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 () => { + getWorkflowRun: async ({run_id: runId}) => { + if (runId === 43 && primaryReady()) return {data: exactPrimary}; currentRunReads += 1; if (incompleteSnapshot) { snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; @@ -677,12 +687,24 @@ 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}"); + if (input.run_id === 43 && primaryReady()) return {data: exactPrimary}; + if (cancelledPrimary && input.run_id === 43) { + return {data: {...source, id: 43, event: "pull_request", status: "completed", conclusion: "cancelled"}}; + } assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); return {data: {...source, ...(sourceMutations[kind] || {})}}; }, paginate: async (method, input) => { 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"); + if (input.run_id === 43 && primaryReady()) { + return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, + {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + } assert.equal(input.run_id, 42); + if (h0 && ++alternativeJobsReads > (cancelledPrimary ? 0 : 2)) { + if (kind.endsWith("-malformed")) return null; + throw Object.assign(new Error(`H0 alternative final attempt jobs HTTP ${badStatus}`), {status: badStatus}); + } if (incompleteSnapshot) { snapshots += 1; if (input.attempt_number === 1) return []; @@ -702,6 +724,13 @@ async function scenario(kind, event = "pull_request") { }}; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); + if (h0 && input.event === "pull_request") { + primaryInventoryReads += 1; + const primary = {...exactPrimary, status: cancelledPrimary || primaryReady() ? "completed" : "queued", + conclusion: cancelledPrimary ? "cancelled" : primaryReady() ? "success" : null}; + yield {data: duplicatePrimary ? [primary, source] : [primary]}; + return; + } if (event === "repository_dispatch" && input.event === "pull_request") { yield {data: [{...source, id: kind.startsWith("pending-native") ? 43 : source.id, event: "pull_request", head_sha: head, status: kind.startsWith("pending-native") ? "queued" : "completed", @@ -720,9 +749,14 @@ async function scenario(kind, event = "pull_request") { ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [source]}; }; const clock = {now: () => now, parse: Date.parse}; - await execute(github, context, {info: message => info.push(message), warning: () => {}, setFailed: message => failures.push(message)}, - clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, info, refreshInventoryReads}; + try { + await execute(github, context, {info: message => info.push(message), warning: () => {}, setFailed: message => failures.push(message)}, + clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); + } catch (error) { + if (!captureLookupFailure) throw error; + lookupFailure = error; + } + return {failures, refs, snapshots, info, refreshInventoryReads, alternativeJobsReads, primaryInventoryReads, lookupFailure}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -740,6 +774,29 @@ async function scenario(kind, event = "pull_request") { assert(!result.info.some(line => line.startsWith("Found runtime-images run 42 with status=")), `${kind} must not select the refresh`); } + for (const [kind, event, selectionMessage] of [ + ["optional-final-read-refresh", "repository_dispatch", "supersedes the pending native wait"], + ["optional-final-read-duplicate", "pull_request", "precedes the pending duplicate"], + ]) { + const result = await scenario(kind, event); + assert(result.info.some(line => line.includes(selectionMessage)), kind); + assert.equal(result.alternativeJobsReads, 6, kind); + assert.equal(result.primaryInventoryReads, 2, kind); + assert(result.info.some(line => line.includes("Found runtime-images run 43 with status=completed")), kind); + assert.deepEqual(result.failures, [], kind); + } + for (const [kind, expectedReads, status] of [ + ["optional-final-read-cancelled-primary", 4, 503], + ["optional-final-read-forbidden", 3, 403], + ["optional-final-read-missing", 3, 404], + ["optional-final-read-malformed", 3, undefined], + ]) { + const result = await scenario(kind, "repository_dispatch", true); + assert.equal(result.alternativeJobsReads, expectedReads, kind); + assert.equal(result.primaryInventoryReads, 1, kind); + assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, status, kind); + if (status === undefined) assert(result.lookupFailure instanceof TypeError, kind); + } const unavailable = await scenario("pending-native-inventory-unavailable", "repository_dispatch"); assert(unavailable.refreshInventoryReads >= 4, "temporary inventory errors exhaust the normal retries"); assert(unavailable.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), From b4f34822fb3072dcb2e0ff9541a37209593ae8a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:21:12 +1300 Subject: [PATCH 068/199] Reject regressing gameplay release owner readbacks --- .../JooqInitialGameplayReleaseJournal.java | 24 +++++++++- ...ReleaseJournalPostgresIntegrationTest.java | 48 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index a4afd9bf61..4c3d6c71f0 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -401,7 +401,7 @@ && sameAcknowledgedOutcome(readback, stored, storedDigest))) { } Record timestamps = tx.fetchOne( - "SELECT last_dispatched_at FROM " + "SELECT last_dispatched_at, readback_payload, readback_digest FROM " + OUTBOX_TABLE + " WHERE operation_id = ? AND effect_id = ?", operationId, @@ -417,6 +417,7 @@ && sameAcknowledgedOutcome(readback, stored, storedDigest))) { if (readback.observedAt().isBefore(dispatchedAt)) { throw conflict("effect readback is stale"); } + requireNonRegressingReadback(readback, timestamps, current); if (readback.state() == EffectReadbackState.UNKNOWN_OR_PARTIAL) { setReadbackState( tx, current, readback, readbackDigest, EffectOutboxState.AMBIGUOUS, now); @@ -674,6 +675,27 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private void requireNonRegressingReadback( + EffectReadback readback, Record stored, OutboxEntry current) { + JSONB payload = stored.get("readback_payload", JSONB.class); + String digest = stored.get("readback_digest", String.class); + if (payload == null && digest == null) { + return; + } + if (payload == null || digest == null) { + throw conflict("retained effect readback is incomplete"); + } + EffectReadback previous = tupleCodec.readEffectReadback(payload.data()); + if (!digest.equals(tupleCodec.digest(previous))) { + throw conflict("retained effect readback digest does not match"); + } + requireReadbackMatches( + previous, current, current.effect().operationId(), current.effect().effectId()); + if (readback.observedAt().isBefore(previous.observedAt())) { + throw conflict("effect readback predates the retained same-attempt observation"); + } + } + private boolean hasValidatedUnknownReadback( Record stored, String storedDigest, OutboxEntry current) { JSONB payload = stored == null ? null : stored.get("readback_payload", JSONB.class); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 1e1d3cfea7..09c22bc6dd 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -403,6 +403,54 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(next.attemptCount()).isEqualTo(2); } + @Test + void delayedSameAttemptPreparationCannotOverrideNewerAmbiguity() { + Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + Operation before = journal.find(operationId).orElseThrow(); + EffectReadback unknown = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "latest-unknown", + base.plusSeconds(6)); + journal.recordEffectReadback(operationId, effectId, attemptId, unknown, base.plusSeconds(6)); + String retained = storedOutbox(operationId, effectId); + + for (EffectReadbackState delayedState : + List.of(EffectReadbackState.UNKNOWN_OR_PARTIAL, EffectReadbackState.PREPARED_FENCED)) { + EffectReadback delayed = + readbackFor(dispatched, attemptId, delayedState, "delayed", base.plusSeconds(5)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, delayed, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("predates the retained same-attempt observation"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); + assertThat(journal.find(operationId)).contains(before); + assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isEmpty(); + } + + EffectReadback fresh = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PREPARED_FENCED, + "fresh-owner-proof", + base.plusSeconds(8)); + Operation advanced = + journal.recordEffectReadback(operationId, effectId, attemptId, fresh, base.plusSeconds(8)); + assertThat(advanced.phase()).isEqualTo(Phase.RELEASING); + assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isPresent(); + } + @Test void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); From 524f097dfb84f58f56a3e2909d6f76e23260a43b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:25:32 +1300 Subject: [PATCH 069/199] Verify recovery journal payload IDs against persisted row keys --- .../JooqInitialGameplayReleaseJournal.java | 11 ++- ...ReleaseJournalPostgresIntegrationTest.java | 78 +++++++++++++++++++ 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 4c3d6c71f0..35c198168b 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -234,7 +234,7 @@ public Optional findNextEffect(UUID operationId) { Record record = dsl.fetchOne( """ - SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + SELECT outbox_id, operation_id, effect_id, effect_kind, operation_tuple_digest, payload, payload_digest, state, attempt_count, last_attempt_id, last_outcome_code, acknowledged_at FROM recovery_control.initial_gameplay_release_outbox @@ -452,7 +452,7 @@ public Optional findEffect(UUID operationId, EffectKind effectKind) Record record = dsl.fetchOne( """ - SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + SELECT outbox_id, operation_id, effect_id, effect_kind, operation_tuple_digest, payload, payload_digest, state, attempt_count, last_attempt_id, last_outcome_code, acknowledged_at FROM recovery_control.initial_gameplay_release_outbox @@ -587,6 +587,7 @@ private Operation toOperation(Record record) { JSONB bindingJson = record.get("peer_storage_binding", JSONB.class); Scope scope = tupleCodec.readScope(scopeJson.data()); if (!"initial_gameplay_release".equals(record.get("operation_kind", String.class)) + || !scope.operationId().equals(record.get("operation_id", UUID.class)) || !scope.targetNamespace().equals(record.get("target_namespace", String.class)) || !scope .playableStateNamespaceId() @@ -620,7 +621,7 @@ private OutboxEntry selectOutbox( Record record = context.fetchOne( """ - SELECT outbox_id, effect_id, effect_kind, operation_tuple_digest, payload, + SELECT outbox_id, operation_id, effect_id, effect_kind, operation_tuple_digest, payload, payload_digest, state, attempt_count, last_attempt_id, last_outcome_code, acknowledged_at FROM recovery_control.initial_gameplay_release_outbox @@ -640,7 +641,9 @@ private OutboxEntry toOutboxEntry(Record record) { String effectKind = record.get("effect_kind", String.class); Instant acknowledgedAt = toInstant(record.get("acknowledged_at", OffsetDateTime.class)); TypedEffect effect = tupleCodec.readEffect(effectKind, payload.data()); - if (!tupleCodec.digest(effect).equals(record.get("payload_digest", String.class)) + if (!effect.operationId().equals(record.get("operation_id", UUID.class)) + || !effect.effectId().equals(record.get("effect_id", UUID.class)) + || !tupleCodec.digest(effect).equals(record.get("payload_digest", String.class)) || !effect .operationTupleDigest() .equals(record.get("operation_tuple_digest", String.class))) { diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 09c22bc6dd..51fd66cc4f 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -746,6 +746,84 @@ void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrec } } + @Test + void scopeReaderRejectsResealedScopeForAnotherRowKey() { + Scope original = scope(); + journal.create(original, UUID.randomUUID()); + Scope foreign = + new Scope( + UUID.randomUUID(), + original.canonicalTenantId(), + original.targetNamespace(), + original.playableStateNamespaceId(), + original.peerStorageBinding(), + original.evidenceRef()); + + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_operation SET scope_payload=CAST(? AS jsonb), scope_digest=? WHERE operation_id=?", + tupleCodec.toJson(foreign), + tupleCodec.digest(foreign), + original.operationId())) + .isEqualTo(1); + assertThatThrownBy(() -> journal.find(original.operationId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Persisted initial gameplay release scope is inconsistent"); + } + + @Test + void outboxReadersRejectResealedPayloadForAnotherOperationRowKey() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry original = authorizedDispatch(base); + OutboxEntry foreign = authorizedDispatch(base); + UUID originalOperationId = original.effect().operationId(); + UUID foreignEffectId = foreign.effect().effectId(); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET effect_id=?, payload=CAST(? AS jsonb), payload_digest=?, operation_tuple_digest=? WHERE operation_id=? AND effect_id=?", + foreignEffectId, + tupleCodec.toJson(foreign.effect()), + foreign.payloadDigest(), + foreign.effect().operationTupleDigest(), + originalOperationId, + original.effect().effectId())) + .isEqualTo(1); + assertOutboxReadersRejectMismatchedKey(originalOperationId, foreignEffectId, base); + } + + @Test + void outboxReadersRejectResealedPayloadForAnotherEffectRowKey() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry original = authorizedDispatch(base); + UUID operationId = original.effect().operationId(); + UUID wrongEffectId = UUID.randomUUID(); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET effect_id=? WHERE operation_id=? AND effect_id=?", + wrongEffectId, + operationId, + original.effect().effectId())) + .isEqualTo(1); + assertOutboxReadersRejectMismatchedKey(operationId, wrongEffectId, base); + } + + private static void assertOutboxReadersRejectMismatchedKey( + UUID operationId, UUID effectId, Instant base) { + String error = "Persisted initial gameplay release effect is inconsistent"; + assertThatThrownBy(() -> journal.findNextEffect(operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(error); + assertThatThrownBy( + () -> journal.findEffect(operationId, EffectKind.PREPARE_PLAYABLE_STATE_FENCED)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(error); + assertThatThrownBy( + () -> + journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(5))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(error); + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); From d4d4dbcd4d69b602cd50f2b0f2478616fd2ebf42 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:28:42 +1300 Subject: [PATCH 070/199] Verify retained gameplay release receipts on exact replay --- .../JooqInitialGameplayReleaseJournal.java | 26 ++++++++++-- ...ReleaseJournalPostgresIntegrationTest.java | 42 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 35c198168b..95fd6aaec5 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -370,16 +370,20 @@ public Operation recordEffectReadback( String storedDigest = stored == null ? null : stored.get("readback_digest", String.class); if (current.state() == EffectOutboxState.ACKNOWLEDGED) { - if (readbackDigest.equals(storedDigest) - || (stored != null - && !readback.observedAt().isAfter(now) - && sameAcknowledgedOutcome(readback, stored, storedDigest))) { + if (readbackDigest.equals(storedDigest)) { + requireValidExactStoredReadback(readback, stored, storedDigest, current); + return operation; + } + if (stored != null + && !readback.observedAt().isAfter(now) + && sameAcknowledgedOutcome(readback, stored, storedDigest)) { return operation; } throw conflict("effect readback changed after acknowledgement"); } if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT && readbackDigest.equals(storedDigest)) { + requireValidExactStoredReadback(readback, stored, storedDigest, current); return operation; } if (readback.state() != EffectReadbackState.PROVEN_NO_EFFECT @@ -678,6 +682,20 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private void requireValidExactStoredReadback( + EffectReadback replay, Record stored, String digest, OutboxEntry current) { + JSONB payload = stored.get("readback_payload", JSONB.class); + if (payload == null) { + throw conflict("retained effect readback is incomplete"); + } + EffectReadback saved = tupleCodec.readEffectReadback(payload.data()); + if (!digest.equals(tupleCodec.digest(saved)) || !saved.equals(replay)) { + throw conflict("retained effect readback does not match exact replay"); + } + requireReadbackMatches( + saved, current, current.effect().operationId(), current.effect().effectId()); + } + private void requireNonRegressingReadback( EffectReadback readback, Record stored, OutboxEntry current) { JSONB payload = stored.get("readback_payload", JSONB.class); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 51fd66cc4f..6d91a5da90 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -824,6 +824,48 @@ private static void assertOutboxReadersRejectMismatchedKey( .hasMessageContaining(error); } + @Test + void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { + for (EffectReadbackState state : + List.of(EffectReadbackState.PREPARED_FENCED, EffectReadbackState.PROVEN_NO_EFFECT)) { + clearJournal(); + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + EffectReadback valid = + readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(5)); + Operation settled = + journal.recordEffectReadback( + operationId, effectId, attemptId, valid, base.plusSeconds(6)); + String before = storedOutbox(operationId, effectId); + assertThat( + journal.recordEffectReadback( + operationId, effectId, attemptId, valid, base.plusSeconds(7))) + .isEqualTo(settled); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + + EffectReadback mismatched = + readbackFor(dispatched, UUID.randomUUID(), state, "terminal", base.plusSeconds(5)); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET readback_payload=CAST(? AS jsonb) WHERE effect_id=?", + tupleCodec.toJson(mismatched), + effectId)) + .isEqualTo(1); + String corrupt = storedOutbox(operationId, effectId); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, valid, base.plusSeconds(8))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("retained effect readback does not match exact replay"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(corrupt); + assertThat(journal.find(operationId)).contains(settled); + } + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); From 6cd18ed348bd4d892069c841959cb49a98cf06a6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:34:18 +1300 Subject: [PATCH 071/199] Require a new attempt after durable gameplay release closure --- .../JooqInitialGameplayReleaseJournal.java | 30 +++++++++++++++++++ ...ReleaseJournalPostgresIntegrationTest.java | 29 ++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 95fd6aaec5..326fabd8f3 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -260,6 +260,11 @@ public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, || current.state() == EffectOutboxState.ACKNOWLEDGED) { return current; } + if (current.state() == EffectOutboxState.RETRYABLE + && attemptId.equals(current.lastAttemptId()) + && hasDurableNoEffectClosure(tx, current)) { + throw conflict("a retry must use a new effect attempt identity"); + } requirePhaseForEffect(operation.phase(), current.effect().kind()); int changed = tx.execute( @@ -682,6 +687,31 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private boolean hasDurableNoEffectClosure(DSLContext tx, OutboxEntry current) { + Record stored = + tx.fetchOne( + "SELECT readback_payload, readback_digest FROM " + + OUTBOX_TABLE + + " WHERE operation_id = ? AND effect_id = ?", + current.effect().operationId(), + current.effect().effectId()); + JSONB payload = stored.get("readback_payload", JSONB.class); + String digest = stored.get("readback_digest", String.class); + if (payload == null && digest == null) { + return false; + } + if (payload == null || digest == null) { + throw conflict("retained effect readback is incomplete"); + } + EffectReadback saved = tupleCodec.readEffectReadback(payload.data()); + if (!digest.equals(tupleCodec.digest(saved))) { + throw conflict("retained effect readback digest does not match"); + } + requireReadbackMatches( + saved, current, current.effect().operationId(), current.effect().effectId()); + return saved.state() == EffectReadbackState.PROVEN_NO_EFFECT; + } + private void requireValidExactStoredReadback( EffectReadback replay, Record stored, String digest, OutboxEntry current) { JSONB payload = stored.get("readback_payload", JSONB.class); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 6d91a5da90..ebe8474dec 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -525,6 +525,14 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); + assertThatThrownBy( + () -> + journal.claimEffect( + scope.operationId(), effectId, firstAttempt, base.plusSeconds(8))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("a retry must use a new effect attempt identity"); + assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); + UUID replacementAttempt = UUID.randomUUID(); assertThat( journal @@ -866,6 +874,27 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { } } + @Test + void retryableEffectWithoutDurableClosurePreservesSameAttemptClaimBehavior() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + assertThat( + journal + .recordRetryableEffect( + operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(5)) + .state()) + .isEqualTo(EffectOutboxState.RETRYABLE); + assertThat(storedOutbox(operationId, effectId)).contains("\"readback_payload\":null"); + OutboxEntry retried = + journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(6)); + assertThat(retried.state()).isEqualTo(EffectOutboxState.DISPATCHED); + assertThat(retried.lastAttemptId()).isEqualTo(attemptId); + assertThat(retried.attemptCount()).isEqualTo(dispatched.attemptCount() + 1); + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); From 50b031c7417ec4eec924a846e9774676a5621987 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:30:47 +1300 Subject: [PATCH 072/199] Keep terminal owner receipt immutable across valid re-observations --- .../JooqInitialGameplayReleaseJournal.java | 35 +++++-- ...ReleaseJournalPostgresIntegrationTest.java | 93 +++++++++++++++++-- 2 files changed, 113 insertions(+), 15 deletions(-) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 326fabd8f3..1c69e0977f 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -367,7 +367,7 @@ public Operation recordEffectReadback( || current.state() == EffectOutboxState.RETRYABLE) { Record stored = tx.fetchOne( - "SELECT readback_digest, readback_payload FROM " + "SELECT readback_digest, readback_payload, last_dispatched_at FROM " + OUTBOX_TABLE + " WHERE operation_id = ? AND effect_id = ?", operationId, @@ -377,11 +377,11 @@ public Operation recordEffectReadback( if (current.state() == EffectOutboxState.ACKNOWLEDGED) { if (readbackDigest.equals(storedDigest)) { requireValidExactStoredReadback(readback, stored, storedDigest, current); + requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } - if (stored != null - && !readback.observedAt().isAfter(now) - && sameAcknowledgedOutcome(readback, stored, storedDigest)) { + if (stored != null && sameRetainedOutcome(readback, stored, storedDigest)) { + requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } throw conflict("effect readback changed after acknowledgement"); @@ -389,6 +389,13 @@ && sameAcknowledgedOutcome(readback, stored, storedDigest)) { if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT && readbackDigest.equals(storedDigest)) { requireValidExactStoredReadback(readback, stored, storedDigest, current); + requireTerminalReplayWithinAttempt(readback, stored, now); + return operation; + } + if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT + && stored != null + && sameRetainedOutcome(readback, stored, storedDigest)) { + requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } if (readback.state() != EffectReadbackState.PROVEN_NO_EFFECT @@ -763,8 +770,21 @@ private boolean hasValidatedUnknownReadback( return true; } - private boolean sameAcknowledgedOutcome( - EffectReadback readback, Record stored, String storedDigest) { + private void requireTerminalReplayWithinAttempt( + EffectReadback readback, Record stored, Instant now) { + OffsetDateTime dispatchTime = stored.get("last_dispatched_at", OffsetDateTime.class); + if (dispatchTime == null) { + throw conflict("effect dispatch timestamp is unavailable"); + } + if (readback.observedAt().isBefore(dispatchTime.toInstant())) { + throw conflict("effect readback is stale"); + } + if (readback.observedAt().isAfter(now)) { + throw conflict("effect readback observation is in the future"); + } + } + + private boolean sameRetainedOutcome(EffectReadback readback, Record stored, String storedDigest) { JSONB payload = stored.get("readback_payload", JSONB.class); if (payload == null || storedDigest == null) { return false; @@ -773,7 +793,8 @@ private boolean sameAcknowledgedOutcome( if (!storedDigest.equals(tupleCodec.digest(acknowledged))) { return false; } - // A new observation time does not replace the first durable receipt. + // The authenticated outcome identifies the durable closure, not the read clock. + // A valid new observation time never replaces the first durable receipt. return acknowledged.equals( new EffectReadback( readback.operationId(), diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index ebe8474dec..443bd4a2b8 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -209,14 +209,27 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() prepareReadback, prepareReadback.observedAt()); assertThat(releasing.phase()).isEqualTo(Phase.RELEASING); + String retainedPrepare = storedOutbox(scope.operationId(), prepareEffectId); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + prepareEffectId, + prepareAttempt, + prepareReadback, + base.plusSeconds(5))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback observation is in the future"); + assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); assertThat( journal.recordEffectReadback( scope.operationId(), prepareEffectId, prepareAttempt, prepareReadback, - base.plusSeconds(5))) + prepareReadback.observedAt())) .isEqualTo(releasing); + assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); assertThat( journal .recordAmbiguousEffect( @@ -511,17 +524,50 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { "WRONG_ATTEMPT", base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); - EffectReadback changed = + EffectReadback observedAgain = readbackFor( dispatched, firstAttempt, EffectReadbackState.PROVEN_NO_EFFECT, "durable-closure", base.plusSeconds(6)); + assertThat( + journal.recordEffectReadback( + scope.operationId(), effectId, firstAttempt, observedAgain, base.plusSeconds(7))) + .isEqualTo(authorized); + for (Instant invalid : List.of(base.plusSeconds(3), base.plusSeconds(8))) { + EffectReadback invalidObservation = + readbackFor( + dispatched, + firstAttempt, + EffectReadbackState.PROVEN_NO_EFFECT, + "durable-closure", + invalid); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + scope.operationId(), + effectId, + firstAttempt, + invalidObservation, + base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + } + EffectReadback differentClosure = + readbackFor( + dispatched, + firstAttempt, + EffectReadbackState.PROVEN_NO_EFFECT, + "different-closure", + base.plusSeconds(6)); assertThatThrownBy( () -> journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, changed, base.plusSeconds(7))) + scope.operationId(), + effectId, + firstAttempt, + differentClosure, + base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); @@ -598,11 +644,12 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { assertThat(retained).contains(tupleCodec.digest(closure)); journal.recordEffectReadback(operationId, effectId, attemptId, closure, base.plusSeconds(7)); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); - assertThatThrownBy( - () -> - journal.recordEffectReadback( - operationId, effectId, attemptId, future, base.plusSeconds(8))) - .isInstanceOf(InitialGameplayReleaseConflictException.class); + Operation beforeReplay = journal.find(operationId).orElseThrow(); + assertThat( + journal.recordEffectReadback( + operationId, effectId, attemptId, future, base.plusSeconds(8))) + .isEqualTo(beforeReplay); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); UUID nextAttempt = UUID.randomUUID(); journal.claimEffect(operationId, effectId, nextAttempt, base.plusSeconds(8)); String replaced = storedOutbox(operationId, effectId); @@ -853,6 +900,36 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { operationId, effectId, attemptId, valid, base.plusSeconds(7))) .isEqualTo(settled); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + EffectReadback observedAgain = + readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(6)); + assertThat( + journal.recordEffectReadback( + operationId, effectId, attemptId, observedAgain, base.plusSeconds(7))) + .isEqualTo(settled); + EffectReadback stale = + readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(3)); + EffectReadback future = + readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(8)); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, stale, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback is stale"); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, future, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback observation is in the future"); + assertThatThrownBy( + () -> + journal.recordEffectReadback( + operationId, effectId, attemptId, valid, base.plusSeconds(4))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback observation is in the future"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat(journal.find(operationId)).contains(settled); EffectReadback mismatched = readbackFor(dispatched, UUID.randomUUID(), state, "terminal", base.plusSeconds(5)); From d36e33c46d9df0a14f6e6032a3bbac6926f6b39f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:00:22 +1300 Subject: [PATCH 073/199] Fix recovery controller and workflow review findings --- .github/workflows/smoke.yml | 25 ++++-- .github/workflows/static-analysis-summary.yml | 17 +++- design/developer-workflows/pr-lifecycle.md | 2 +- ...d-identity-controller-workflow-contract.sh | 24 +++++- .../pr-required-gate-context-contract.sh | 86 +++++++++++++++++-- .../tests/static-analysis-summary-contract.sh | 40 +++++++-- .../JooqInitialGameplayReleaseJournal.java | 3 + .../InitialGameplayReleaseController.java | 7 +- ...ReleaseJournalPostgresIntegrationTest.java | 13 ++- .../InitialGameplayReleaseControllerTest.java | 35 ++++++++ 10 files changed, 222 insertions(+), 30 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index f35bb93050..37f29e56d6 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1199,7 +1199,8 @@ jobs: const replacement = await findMatchingRuntimeImagesRun( "repository_dispatch", expectedDisplayTitle, - currentIdentity + currentIdentity, + selection ); if (!replacement) { if (Date.now() - cancelledRunObservedAt >= cancelledReplacementTimeoutMs) { @@ -1514,10 +1515,24 @@ jobs: } // Job proof belongs to the selected immutable attempt, never the latest // attempt's jobs. Recheck after mutable PR identity before accepting it. - const { data: currentAttempt } = await withTransientGitHubRetry( - "final successful runtime attempt lookup", - () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) - ); + let currentAttempt; + try { + ({ data: currentAttempt } = await withTransientGitHubRetry( + "final successful runtime attempt lookup", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + )); + } catch (error) { + const status = error?.status ?? error?.response?.status; + if (!selection.pendingPrimary || !retryableStatuses.has(status)) throw error; + core.warning(`Runtime alternative ${matching.id} final attempt is temporarily unavailable; retry exact primary selection.`); + retryPrimary = { + id: selection.pendingPrimary.id, + run_attempt: selection.pendingPrimary.run_attempt, + identity: identityKey(currentIdentity), + }; + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (!positiveInteger(matching.run_attempt) || currentAttempt.id !== matching.id || currentAttempt.run_attempt !== matching.run_attempt || currentAttempt.status !== "completed" || currentAttempt.conclusion !== "success") { diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 079ecce9cd..28a6fdc899 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -135,10 +135,13 @@ jobs: ["CodeQL gate", "CodeQL Gate", "codeql"], ["License gate", "License Gate", "license"], ]; + const terminalFailure = new Set([ + "failure", "cancelled", "timed_out", "action_required", "startup_failure", + ]); const statusIcon = (value) => { if (value === "success") return "✅"; - if (value === "failure") return "❌"; if (value === "cancelled") return "⚪"; + if (terminalFailure.has(value)) return "❌"; if (value === "pending" || value === "in_progress" || value === "queued" || value === "unavailable") return "⏳"; return "⏭️"; }; @@ -216,7 +219,15 @@ jobs: (job.name === metadataName || String(job.name || "").includes("'" + metadataName + "'"))); const substantive = data.jobs.some(job => job.name === gateName); if (metadata && !substantive) continue; - if (!substantive) return { ...candidate, status: "in_progress", conclusion: null, jobs: data.jobs }; + if (!substantive) { + if (candidate.status === "completed" && terminalFailure.has(candidate.conclusion)) { + return { ...candidate, jobs: data.jobs }; + } + const status = ["queued", "in_progress", "pending", "requested", "waiting"].includes(candidate.status) + ? "in_progress" + : "unavailable"; + return { ...candidate, status, conclusion: null, jobs: data.jobs }; + } return { ...candidate, jobs: data.jobs }; } return null; @@ -266,7 +277,7 @@ jobs: const detailResults = checks.slice(gateChecks.length); const failedChecks = gateResults.filter(([, result]) => - ["failure", "cancelled", "timed_out", "action_required"].includes(result) + terminalFailure.has(result) ); const pendingChecks = gateResults.filter(([, result]) => ["pending", "in_progress", "queued"].includes(result) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 78e511e452..324572e04a 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -29,7 +29,7 @@ Rules for triage: - Verify a finding against the code before deciding. Summary-only and outside-diff findings get the same treatment as inline ones. - Judge suggestions by real benefit against cost and risk. A finding being correct does not by itself make it Fix now. - Do not resolve a thread to hide unresolved work. Keep the original finding and decision when correcting a disposition. -- Accepted findings remain source-owned until the exact correction is verified at the current published head and recorded. For rejection or withdrawal, record the concrete reason and current-head evidence that no actionable work remains. Report outdated unresolved threads separately. Missing, malformed, unattributed, or incomplete evidence fails closed; an acknowledgment or edited standing summary cannot prove completion or an empty inventory. +- Fix-now findings remain source-owned until the exact correction is verified at the current published head and recorded. Routed findings require a recorded handoff and retain an open obligation with the receiving owner, not a fix on the source head. For rejection or withdrawal, record the concrete reason and current-head evidence that no actionable work remains. Report outdated unresolved threads separately. Missing, malformed, unattributed, or incomplete evidence fails closed; an acknowledgment or edited standing summary cannot prove completion or an empty inventory. - Routed findings do not block this PR. The receiving owner decides on them independently, and routes arriving at this PR are dispositioned before it is ready. The Overseer, or the human, reviews the routed backlog at milestones so routes do not pile up unowned. - Retargeting a route preserves the original finding, its open obligation, and its prior ownership, including honest unassigned work. A route is not a claim that the recipient has accepted or fixed it. - Track whether each round's findings are new or repeats of earlier ones. Repeated serious findings call for investigating their shared cause, not another round. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index c55cd1bd2c..14a3a76769 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6624,11 +6624,12 @@ case "$resource" in --arg head "${TEST_PR_HEAD_SHA:-cccccccccccccccccccccccccccccccccccccccc}" \ --arg repository "${TEST_PR_HEAD_REPOSITORY:-example/FireMUD}" \ --arg base_ref "${TEST_PR_BASE_REF:-develop}" \ + --arg merge "${TEST_PR_MERGE_SHA:-cccccccccccccccccccccccccccccccccccccccc}" \ --argjson mergeable "${TEST_PR_MERGEABLE:-true}" \ --argjson mergeable_state "$mergeable_state_json" \ --argjson labels "${TEST_PR_LABELS_JSON:-[]}" \ --argjson changed_files "$changed_file_count" \ - '{state:$state,changed_files:$changed_files,head:{sha:$head,repo:{full_name:$repository}},base:{ref:$base_ref,sha:"dddddddddddddddddddddddddddddddddddddddd",repo:{full_name:"example/FireMUD"}},merge_commit_sha:"cccccccccccccccccccccccccccccccccccccccc",mergeable:$mergeable,mergeable_state:$mergeable_state,labels:$labels}' + '{state:$state,changed_files:$changed_files,head:{sha:$head,repo:{full_name:$repository}},base:{ref:$base_ref,sha:"dddddddddddddddddddddddddddddddddddddddd",repo:{full_name:"example/FireMUD"}},merge_commit_sha:$merge,mergeable:$mergeable,mergeable_state:$mergeable_state,labels:$labels}' ;; repos/example/FireMUD/git/ref/heads/*) printf '%s' '{"ref":"refs/heads/develop","object":{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}' @@ -6640,6 +6641,10 @@ case "$resource" in printf '%s' '{"sha":"cccccccccccccccccccccccccccccccccccccccc","parents":[{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},{"sha":"cccccccccccccccccccccccccccccccccccccccc"}]}' fi ;; + repos/example/FireMUD/commits/dddddddddddddddddddddddddddddddddddddddd) + [[ "${TEST_PR_MERGE_SHA:-}" == dddddddddddddddddddddddddddddddddddddddd ]] + printf '%s' '{"sha":"dddddddddddddddddddddddddddddddddddddddd","parents":[{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},{"sha":"cccccccccccccccccccccccccccccccccccccccc"}]}' + ;; repos/example/FireMUD/actions/runs/42/artifacts\?per_page=100) if [[ -n "${FAKE_ARTIFACTS_JSON:-}" ]]; then printf '%s' "$FAKE_ARTIFACTS_JSON" @@ -6844,6 +6849,23 @@ FAKE_FIXTURE_EXPOSURE_MODE=public \ FAKE_FIXTURE_CERTIFICATE_MODE=standalone FAKE_FIXTURE_EXPOSURE_MODE=public \ run_deploy_target_fixture standalone-public 0 'action=deploy' +# A real natural preview uses H in the REST run, its workflow_run callback and PR +# association; the sanitized artifact also records the different execution merge M. +native_merge_sha=dddddddddddddddddddddddddddddddddddddddd +native_source_run_json="$(jq -c '.pull_requests[0].base.sha = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"' <<<"$valid_workflow_run_json")" +TEST_PR_MERGE_SHA="$native_merge_sha" \ +FAKE_FIXTURE_METADATA_MERGE_SHA="$native_merge_sha" \ +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$native_source_run_json" \ + run_deploy_target_fixture native-distinct-merge 0 'action=deploy' +grep -Fxq 'head_sha=cccccccccccccccccccccccccccccccccccccccc' "$TEMP_DIR/deploy-target-native-distinct-merge.output" +grep -Fxq "merge_sha=$native_merge_sha" "$TEMP_DIR/deploy-target-native-distinct-merge.output" +TEST_PR_MERGE_SHA="$native_merge_sha" \ +FAKE_FIXTURE_METADATA_MERGE_SHA="$native_merge_sha" \ +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$native_source_run_json" \ +FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$native_merge_sha" \ + run_deploy_target_fixture native-distinct-merge-callback 1 'Unexpected source run head' +test ! -s "$TEMP_DIR/deploy-target-native-distinct-merge-callback.output" + # A PR source run must bind both its run head and uniquely selected PR association to the artifact head. FAKE_FIXTURE_WORKFLOW_RUN_JSON="$distinct_source_workflow_run_json" \ FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8ab3f49491..967c070070 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -129,6 +129,44 @@ def effective_group(group, base_ref): return re.sub(r"\$\{\{(.*?)\}\}", render, group) +def can_reuse_required_name(name, required_names): + if not name: + return False + # These current matrix templates have fixed delimiters that can never + # render any required context. Do not assume arbitrary dynamics are safe. + matrix_prefixes = ( + "Build and Test (${{ matrix.module }} / ${{ matrix.partition }})", + "Build and Test (account-service / ${{ matrix.partition }})", + "Build and Test (game-session-service / ${{ matrix.partition }})", + "Build and Test (world-management-service / ${{ matrix.partition }})", + "CodeQL Analysis (${{ matrix.language }})", + ) + if name in matrix_prefixes and all( + not gate.startswith(("Build and Test (", "CodeQL Analysis (")) for gate in required_names + ): + return False + dynamic = re.fullmatch(r"\$\{\{(.*?)\}\}", name) + if not dynamic: + return "${{" in name or name in required_names + body = dynamic[1].strip() + # Limit dynamic names to the existing exact metadata ternary shape or a + # constant literal; other shapes need an explicitly reviewed model. + if re.fullmatch(r"'[^']*'", body): + return body[1:-1] in required_names + summary = re.fullmatch( + re.escape("github.event.action == 'edited' && github.event.changes.base.ref == null") + + r" && '([^']*)' \|\| '([^']*)'", + body, + ) + return not summary or any(option in required_names for option in summary.groups()) + + +assert can_reuse_required_name("${{ 'CodeQL Gate' }}", {"CodeQL Gate"}) +assert not can_reuse_required_name("${{ 'Auxiliary Report' }}", {"CodeQL Gate"}) +assert can_reuse_required_name("${{ matrix.language }}", {"CodeQL Gate"}) +assert not can_reuse_required_name("CodeQL Analysis (${{ matrix.language }})", {"CodeQL Gate"}) + + def isolates_metadata_group(group, run_scoped): metadata = effective_group(group, None) retarget = effective_group(group, "develop") @@ -246,8 +284,8 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o condition = job.get("if", "") if not excludes_metadata(condition): raise SystemExit(f"{workflow} job {job_id} can run for a metadata-only edit") - if job.get("name") in {name for _, _, name, *_ in gates.values()}: - raise SystemExit(f"{workflow} job {job_id} must not reuse a required gate name") + if can_reuse_required_name(job.get("name", job_id), {name for _, _, name, *_ in gates.values()}): + raise SystemExit(f"{workflow} job {job_id} has a possible required gate name collision") # Metadata runs never cancel or replace the substantive run. concurrency = data["concurrency"] @@ -606,9 +644,11 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const liveFallback = kind.startsWith("trusted-current-base"); const h0 = kind.startsWith("optional-final-read-"); const cancelledPrimary = kind === "optional-final-read-cancelled-primary"; + const cancelledWithReplacement = kind === "optional-final-read-cancelled-with-replacement"; + const finalAttemptError = kind.startsWith("optional-final-read-attempt-"); const duplicatePrimary = kind === "optional-final-read-duplicate"; const badStatus = kind.endsWith("-forbidden") ? 403 : kind.endsWith("-missing") ? 404 : 503; - const primaryCanRecover = h0 && !cancelledPrimary && badStatus === 503; + const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && badStatus === 503; const primaryReady = () => primaryCanRecover && primaryInventoryReads > 1; let alternativeJobsReads = 0, primaryInventoryReads = 0, lookupFailure; const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); @@ -627,6 +667,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal status: "completed", conclusion: "success", pull_requests: []}; const exactPrimary = {...source, id: 43, event: "pull_request", head_sha: head, created_at: "2026-09-01T00:00:01Z"}; + const dispatchPrimary = {...source, id: 44, created_at: "2026-09-01T00:00:02Z"}; const incompleteSnapshot = kind.startsWith("incomplete-snapshot-"); let snapshotRerunVisible = false; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, @@ -676,7 +717,11 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), getWorkflowRun: async ({run_id: runId}) => { if (runId === 43 && primaryReady()) return {data: exactPrimary}; + if (runId === 44 && cancelledWithReplacement) return {data: dispatchPrimary}; currentRunReads += 1; + if (finalAttemptError && currentRunReads >= 2) { + throw Object.assign(new Error(`alternative final workflow-run HTTP ${badStatus}`), {status: badStatus}); + } if (incompleteSnapshot) { snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; return {data: {...source, run_attempt: snapshotRerunVisible ? 2 : 1}}; @@ -688,7 +733,8 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); if (input.run_id === 43 && primaryReady()) return {data: exactPrimary}; - if (cancelledPrimary && input.run_id === 43) { + if (cancelledWithReplacement && input.run_id === 44) return {data: dispatchPrimary}; + if ((cancelledPrimary || cancelledWithReplacement) && input.run_id === 43) { return {data: {...source, id: 43, event: "pull_request", status: "completed", conclusion: "cancelled"}}; } assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); @@ -700,11 +746,19 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } + if (cancelledWithReplacement && input.run_id === 44) { + return [{...job, run_id: 44, steps: [...job.steps, + {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + } assert.equal(input.run_id, 42); - if (h0 && ++alternativeJobsReads > (cancelledPrimary ? 0 : 2)) { + if (h0 && ++alternativeJobsReads > (cancelledPrimary ? 0 : 2) && !finalAttemptError) { if (kind.endsWith("-malformed")) return null; throw Object.assign(new Error(`H0 alternative final attempt jobs HTTP ${badStatus}`), {status: badStatus}); } + if (finalAttemptError && alternativeJobsReads > 2) { + return [{...job, steps: [...job.steps, + {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + } if (incompleteSnapshot) { snapshots += 1; if (input.attempt_number === 1) return []; @@ -726,11 +780,16 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert.equal(method, listRuns); if (h0 && input.event === "pull_request") { primaryInventoryReads += 1; - const primary = {...exactPrimary, status: cancelledPrimary || primaryReady() ? "completed" : "queued", - conclusion: cancelledPrimary ? "cancelled" : primaryReady() ? "success" : null}; + const primary = {...exactPrimary, status: cancelledPrimary || cancelledWithReplacement || primaryReady() ? "completed" : "queued", + conclusion: cancelledPrimary || cancelledWithReplacement ? "cancelled" : primaryReady() ? "success" : null}; yield {data: duplicatePrimary ? [primary, source] : [primary]}; return; } + if (cancelledWithReplacement && input.event === "repository_dispatch") { + refreshInventoryReads += 1; + const next = refreshInventoryReads > 1 ? dispatchPrimary : {...dispatchPrimary, status: "queued", conclusion: null}; + yield {data: [next, source]}; return; + } if (event === "repository_dispatch" && input.event === "pull_request") { yield {data: [{...source, id: kind.startsWith("pending-native") ? 43 : source.id, event: "pull_request", head_sha: head, status: kind.startsWith("pending-native") ? "queued" : "completed", @@ -797,6 +856,19 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, status, kind); if (status === undefined) assert(result.lookupFailure instanceof TypeError, kind); } + const cancelledReplacement = await scenario("optional-final-read-cancelled-with-replacement", "repository_dispatch"); + assert.equal(cancelledReplacement.alternativeJobsReads, 6, "old dispatch proof exhausts final jobs retries"); + assert(cancelledReplacement.info.some(line => line.includes("Found runtime-images run 44 with status=completed"))); + assert.deepEqual(cancelledReplacement.failures, []); + const finalAttempt = await scenario("optional-final-read-attempt-transient", "repository_dispatch"); + assert.equal(finalAttempt.primaryInventoryReads, 2, "failed final attempt read resumes the native producer"); + assert(finalAttempt.info.some(line => line.includes("Found runtime-images run 43 with status=completed"))); + assert.deepEqual(finalAttempt.failures, []); + for (const [kind, code] of [["optional-final-read-attempt-forbidden", 403], ["optional-final-read-attempt-missing", 404]]) { + const result = await scenario(kind, "repository_dispatch", true); + assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, code, kind); + assert.equal(result.primaryInventoryReads, 1, kind); + } const unavailable = await scenario("pending-native-inventory-unavailable", "repository_dispatch"); assert(unavailable.refreshInventoryReads >= 4, "temporary inventory errors exhaust the normal retries"); assert(unavailable.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 9271db0935..a1444e5f74 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -697,15 +697,37 @@ run(github, context, core).then(async () => { rerunWrites.some(row => row.body.includes("checks passed"))) { throw new Error("a prior attempt's status cannot replace the selected running rerun"); } - github.request = async (_, input) => ({ data: { total_count: 1, jobs: [{ - id: 1, run_id: input.run_id, run_attempt: input.attempt_number, head_sha: currentHeadSha, - name: "Unrelated job", status: "completed", conclusion: "success", - }] } }); - const unknownStart = calls.updated.length; - await run(github, context, core); - const unknownWrites = calls.updated.slice(unknownStart); - if (!unknownWrites.length || unknownWrites.some(row => row.body.includes("checks passed"))) throw new Error("unclassified successful jobs must not yield a green summary"); - if (!unknownWrites.some(row => row.body.includes("in_progress"))) throw new Error("unclassified candidate must remain pending"); + github.request = async (route, input) => { + if (input.run_id !== 270) return savedRequest(route, input); + return {data: {total_count: 1, jobs: [{ + id: 2701, run_id: input.run_id, run_attempt: input.attempt_number, + head_sha: currentHeadSha, name: "Unrelated job", + status: "completed", conclusion: "success", + }]}}; + }; + for (const [status, conclusion, shown, headline] of [ + ["in_progress", null, "in_progress", "still running"], + ["completed", "success", "unavailable", "evidence is unavailable"], + ["completed", "skipped", "unavailable", "evidence is unavailable"], + ["completed", null, "unavailable", "evidence is unavailable"], + ...["failure", "cancelled", "timed_out", "action_required", "startup_failure"] + .map(value => ["completed", value, value, "checks failed"]), + ]) { + github.paginate = async (method, input) => { + const rows = await savedPaginate(method, input); + return method === codeqlListWorkflowRuns && input.workflow_id === "codeql.yml" + ? rows.map(row => row.id === 270 ? {...row, status, conclusion} : row) + : rows; + }; + const start = calls.updated.length; + await run(github, context, core); + const writes = calls.updated.slice(start); + if (!writes.some(row => row.body.includes("CodeQL gate: \`" + shown + "\`") && row.body.includes(headline)) || + writes.some(row => row.body.includes("checks passed"))) { + throw new Error(`no-gate candidate ${status}/${conclusion} must display ${shown} and ${headline}`); + } + } + github.paginate = savedPaginate; const savedActions = github.rest.actions; let currentAttempt = 1; github.rest.actions = {...savedActions, getWorkflowRun: async ({run_id}) => ({data: { diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 1c69e0977f..a354390f81 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -702,6 +702,9 @@ private boolean hasDurableNoEffectClosure(DSLContext tx, OutboxEntry current) { + " WHERE operation_id = ? AND effect_id = ?", current.effect().operationId(), current.effect().effectId()); + if (stored == null) { + throw conflict("effect outbox row disappeared while checking retained readback"); + } JSONB payload = stored.get("readback_payload", JSONB.class); String digest = stored.get("readback_digest", String.class); if (payload == null && digest == null) { diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index 0049cf6451..b4a3c73b7c 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort.EffectReadbackResolution; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.EvidenceResolution; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Narrow initial-gameplay-release owner. It has no HTTP ingress or autonomous effect dispatcher. @@ -110,9 +111,13 @@ public Operation resume(Resume command) { /** * Performs one outbox attempt or reconciles its exact prior attempt by owner readback. This * method is deliberately not scheduled or exposed as a network endpoint in this source-only - * stage. + * stage. Reconciliation must run without a caller-owned transaction so a successful claim is + * durable before an owner effect can be dispatched. */ public Operation reconcileNextEffect(UUID operationId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable("INITIAL_GAMEPLAY_RELEASE_RECONCILIATION_REQUIRES_NO_CALLER_TRANSACTION"); + } Operation operation = requireOperation(operationId); Optional next = journal.findNextEffect(operationId); if (next.isEmpty()) { diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 443bd4a2b8..82f53235e1 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -795,9 +795,16 @@ void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrec EffectReadbackState.PROVEN_NO_EFFECT, "same-instant", dispatchInstant); - journal.recordEffectReadback( - operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(5)); - assertThat(storedOutbox(operationId, effectId)).contains(tupleCodec.digest(closure)); + Operation recorded = + journal.recordEffectReadback( + operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(5)); + String retained = storedOutbox(operationId, effectId); + assertThat(retained).contains(tupleCodec.digest(closure)); + assertThat( + journal.recordEffectReadback( + operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(6))) + .isEqualTo(recorded); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index d2ed2c693a..9117940677 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -9,7 +9,10 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.sql.Connection; +import java.sql.SQLException; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReason; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.AuditReasonCode; @@ -31,11 +34,43 @@ import net.firedevops.firemud.recovery.model.MaintenanceLockCredential; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.databind.json.JsonMapper; class InitialGameplayReleaseControllerTest { private static final String DIGEST = "c".repeat(64); + @Test + void reconcileRefusesCallerTransactionBeforeClaimOrOwnerInteraction() throws SQLException { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true); + var caller = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + var journal = mock(InitialGameplayReleaseJournal.class); + var evidence = mock(InitialGameplayReleaseEvidenceProvider.class); + var port = mock(InitialGameplayReleaseEffectPort.class); + var controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + evidence, + port); + + caller.executeWithoutResult( + status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThatThrownBy(() -> controller.reconcileNextEffect(UUID.randomUUID())) + .isInstanceOf(OwnerBoundaryUnavailableException.class) + .hasMessage("INITIAL_GAMEPLAY_RELEASE_RECONCILIATION_REQUIRES_NO_CALLER_TRANSACTION"); + status.setRollbackOnly(); + }); + verify(connection).rollback(); + verifyNoInteractions(journal, evidence, port); + } + @Test void ownerResultsRejectMissingStatus() { assertThatThrownBy( From fe3b7ca8e8f0f9b3d96dfb88301ccf7993bab4fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:27:17 +1300 Subject: [PATCH 074/199] Resolve retained Hosted preview and recovery ownership findings --- .github/workflows/preview-reconciler.yml | 76 ++++-- .../hosted/shared/wait-for-runtime-images.sh | 90 ++++--- .../pr-required-gate-context-contract.sh | 2 + .../tests/pr-retarget-workflow-contract.sh | 25 ++ .../preview-runner-isolation-contract.sh | 31 ++- .../InitialGameplayReleaseJournal.java | 3 + .../InitialGameplayReleaseTupleCodec.java | 14 + .../JooqInitialGameplayReleaseJournal.java | 163 ++++++++++-- .../InitialGameplayReleaseController.java | 9 +- ...itial_gameplay_release_attempt_closure.sql | 29 ++ ...ReleaseJournalPostgresIntegrationTest.java | 248 +++++++++++++++++- 11 files changed, 590 insertions(+), 100 deletions(-) create mode 100644 services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 95e90a9192..a441345709 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -341,7 +341,7 @@ jobs: available_slots=$((max_active - active_count)) dispatch_sent=false automatic_preview_has_tuple() { - local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" jobs latest + local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 2 jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' @@ -367,18 +367,22 @@ jobs: and (.path | type == "string" and length > 0) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) ' <<<"$latest" >/dev/null || return 2 - if jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" ' + if jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' .id == $id and .run_attempt != $attempt and .head_sha == $head - and .event == "pull_request" - and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge")) + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1) + and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) ' <<<"$latest" >/dev/null; then return 2 fi - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" ' + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' .id == $id and .run_attempt == $attempt and .head_sha == $head - and .event == "pull_request" - and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge")) + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1) + and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) ' <<<"$latest" >/dev/null || return 1 jq -e --arg tuple "$tuple" ' @@ -566,7 +570,8 @@ jobs: if ! preview_candidates="$( jq -c \ --arg workflow_name "${preview_workflow_name}" \ - --arg trusted_workflow_name "Trusted Hosted Identity Request" \ + --argjson workflow_id "$preview_workflow_id" \ + --arg repository "$GITHUB_REPOSITORY" \ --arg default_branch "${DEFAULT_BRANCH}" \ --arg pr_title "PR preview ${pr_number}" \ --argjson pr_number "$pr_number" \ @@ -586,28 +591,34 @@ jobs: ) then error("workflow run entry is malformed") else + def positive_int: type == "number" and . > 0 and . == floor; + def native_preview: + .workflow_id == $workflow_id + and .repository.full_name == $repository + and .head_repository.full_name == $repository + and (.id | positive_int) and (.run_attempt | positive_int) + and (.name == $workflow_name or .name == .display_title); + def trusted_dispatch: + native_preview and .event == "repository_dispatch" + and .head_branch == $default_branch + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@" + $default_branch) + or .path == (".github/workflows/preview.yml@refs/heads/" + $default_branch)) + and .display_title == $run_name; + def provisional_pr: + native_preview and (.event == "pull_request" or .event == "pull_request_target") + and (.path == ".github/workflows/preview.yml" + or (.event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge"))) + and (.display_title == $pr_title or (.event == "pull_request" and .display_title == $run_name)) + and .head_sha == $head_sha + and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1; .[] | select( ( - (.name == $workflow_name - and ((.path // "" | split("@")[0]) == ".github/workflows/preview.yml")) - or (.name == $trusted_workflow_name - and ((.path // "" | split("@")[0]) == ".github/workflows/hosted-identity-request.yml")) - ) - and ( (.firemud_reconciler_branch_filtered == false) or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) ) - and ( - .display_title == $run_name - or (.name == $workflow_name and .event == "pull_request" - and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) - and .display_title == $pr_title - and (.id > 0 and .id == (.id | floor)) - and ((.run_attempt | type) == "number" and .run_attempt > 0 and .run_attempt == (.run_attempt | floor)) - and .head_sha == $head_sha - and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) - ) + and (trusted_dispatch or provisional_pr) and ( .status == "requested" or .status == "queued" @@ -616,8 +627,8 @@ jobs: or .status == "pending" ) ) - | if .display_title == $run_name then {id, exact: true} - else {id, run_attempt, exact: false} end + | if trusted_dispatch then {id, exact: true} + else {id, run_attempt, event, exact: false} end end end ' <<<"${active_preview_runs_json}" @@ -631,9 +642,9 @@ jobs: if [[ -z "$active_preview_run_id" ]]; then # A same-head title is not proof: the base can move independently. tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" - while IFS=$'\t' read -r run_id run_attempt; do + while IFS=$'\t' read -r run_id run_attempt run_event; do [[ -n "$run_id" ]] || continue - if automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number"; then + if automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event"; then active_preview_run_id="$run_id" break else @@ -642,7 +653,7 @@ jobs: active_preview_lookup_unknown=true fi fi - done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt] | @tsv' <<<"$preview_candidates") + done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt, .event] | @tsv' <<<"$preview_candidates") fi if [[ -n "${active_preview_run_id}" ]]; then @@ -766,6 +777,13 @@ jobs: echo "Unable to merge active preview workflow runs; refusing preview reconcile." >&2 exit 1 fi + if ! preview_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/preview.yml" | jq -er --arg name "$preview_workflow_name" ' + select(.name == $name and .path == ".github/workflows/preview.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 + exit 1 + fi dispatch_candidates <<<"$candidate_rows" fi diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 3a98bc0b23..bf9daa6833 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -63,7 +63,8 @@ import re from datetime import datetime, timezone wait_mode, image_tag, merge_sha, base_sha, head_sha = sys.argv[1:6] -exclude_pending_id = sys.argv[6] if len(sys.argv) > 6 else "" +excluded_id = sys.argv[6] if len(sys.argv) > 6 else "" +alternates = len(sys.argv) > 7 and sys.argv[7] == "alternates" try: payload = json.load(sys.stdin) except json.JSONDecodeError: @@ -109,49 +110,58 @@ def is_matching_run(run): ) matching_runs = [run for run in workflow_runs if is_matching_run(run)] -if exclude_pending_id: - matching_runs = [run for run in matching_runs if str(run.get("id")) != exclude_pending_id +if excluded_id: + matching_runs = [run for run in matching_runs if str(run.get("id")) != excluded_id and run.get("status") == "completed" and run.get("conclusion") == "success"] if not matching_runs: print("missing") raise SystemExit(0) -run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True)[0] +ranked = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True) # Every tab-delimited field must be nonempty so Bash IFS cannot shift positions. 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_id = run.get("id") -if type(run_id) is not int or run_id <= 0: - raise SystemExit(1) -if not all(clean_field(run.get(field)) for field in ("status", "html_url", "event")): - raise SystemExit(1) -conclusion = run.get("conclusion") -if conclusion is None or conclusion == "": - if run["status"] == "completed": +def format_run(run): + run_id = run.get("id") + if type(run_id) is not int or run_id <= 0: raise SystemExit(1) - conclusion = "pending" -elif not clean_field(conclusion): - raise SystemExit(1) -created_at = run.get("created_at") -if not isinstance(created_at, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", created_at): - raise SystemExit(1) -try: - created = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) -except ValueError: - raise SystemExit(1) -if created > datetime.now(timezone.utc): - raise SystemExit(1) -print( - "found\t{}\t{}\t{}\t{}\t{}\t{}".format( - run_id, - run["status"], - conclusion, - run["html_url"], - run["event"], - created_at, + if not all(clean_field(run.get(field)) for field in ("status", "html_url", "event")): + raise SystemExit(1) + conclusion = run.get("conclusion") + if conclusion is None or conclusion == "": + if run["status"] == "completed": + raise SystemExit(1) + conclusion = "pending" + elif not clean_field(conclusion): + raise SystemExit(1) + created_at = run.get("created_at") + if not isinstance(created_at, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", created_at): + raise SystemExit(1) + try: + created = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) + except ValueError: + raise SystemExit(1) + if created > datetime.now(timezone.utc): + raise SystemExit(1) + return ( + "found\t{}\t{}\t{}\t{}\t{}\t{}".format( + run_id, + run["status"], + conclusion, + run["html_url"], + run["event"], + created_at, + ) ) -) + +# Bound positive native lookups per polling pass and avoid duplicate API work. +seen = set() +for run in ranked[:8] if alternates else ranked[:1]: + line = format_run(run) + if run["id"] not in seen: + print(line) + seen.add(run["id"]) ' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" } @@ -282,7 +292,7 @@ print( } # Only a source-ID-bound typed callback with positive native publication proof -# can finish the wait ahead of a pending producer. Skipped publication cannot. +# can finish the wait ahead of a competing producer. Skipped publication cannot. use_completed_duplicate_publication() { local state older_id older_created inventory upper line publisher_id run attempt jobs latest publisher_path default_branch repository_info IFS=$'\t' read -r state older_id _ _ _ _ older_created <<<"$1" @@ -454,10 +464,14 @@ while (( SECONDS < deadline )); do continue fi - if [[ "$wait_mode" == "pull-request" && "$run_status" != "completed" ]] && - older_state="$(read_run_state "$run_id" <<<"$workflow_payload")" && - use_completed_duplicate_publication "$older_state"; then - exit 0 + if [[ "$wait_mode" == "pull-request" && "$SECONDS" -lt "$deadline" ]] && + older_states="$(read_run_state "$run_id" alternates <<<"$workflow_payload")"; then + while IFS= read -r older_state; do + [[ "$SECONDS" -lt "$deadline" ]] || break + if use_completed_duplicate_publication "$older_state"; then + exit 0 + fi + done <<<"$older_states" fi if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 967c070070..bd70cd42dc 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -271,6 +271,8 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o result_steps = [step for step in gate.get("steps", []) if step.get("name") == result_step] if len(result_steps) != 1 or result_steps[0].get("env", {}).get("CHANGES_RESULT") != "${{ needs.changes.result }}": raise SystemExit(f"{workflow} {gate_name} must enforce through one {result_step!r} step reading CHANGES_RESULT") + if result_steps[0].get("continue-on-error", "false") != "false": + raise SystemExit(f"{workflow} {gate_name} result step cannot ignore failures") if "if" in result_steps[0]: raise SystemExit(f"{workflow} {gate_name} result step must run unconditionally") if any("if" in step and "edited" in step["if"] for step in gate.get("steps", [])): diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 9b3cc0e76f..45d8795e9c 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2305,6 +2305,15 @@ for conclusion in [None, ""]: base = {"id": 202, "event": "repository_dispatch", "status": "completed", "conclusion": "success", "html_url": "https://example.test/publisher/202", "display_title": "Publish PR Runtime Images source-run-101", "created_at": "2026-07-24T00:04:00Z"} repository = {"full_name": "example/FireMUD"} (root / "duplicate-inventory.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, source]})) +terminal_duplicate = {**pending_duplicate, "status": "completed", "conclusion": "failure"} +intermediate_duplicate = {**source, "id": 103, "created_at": "2026-07-24T00:04:30Z"} +for name, runs in { + "terminal": [terminal_duplicate, source], + "multi": [pending_duplicate, intermediate_duplicate, source], + "terminal-no-proof": [terminal_duplicate, intermediate_duplicate], +}.items(): + (root / f"duplicate-{name}.json").write_text(json.dumps({"workflow_runs": runs})) + (root / "duplicate-source.json").write_text(json.dumps({**source, "run_attempt": 1, "repository": repository, "head_repository": repository})) publisher_path = ".github/workflows/publish-pr-runtime-images.yml" @@ -2363,6 +2372,22 @@ for conclusion in success skipped; do require_contains "$contract_fixture_dir/duplicate-$conclusion.error" 'Timed out waiting for runtime-images workflow' fi done +for variant in terminal multi terminal-no-proof; do + if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-$variant.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=6 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/competing-$variant.output" 2>"$contract_fixture_dir/competing-$variant.error"; then + [[ "$variant" != "terminal-no-proof" ]] + require_contains "$contract_fixture_dir/competing-$variant.output" 'Trusted PR image publisher 202 succeeded' + else + [[ "$variant" == "terminal-no-proof" ]] || { cat "$contract_fixture_dir/competing-$variant.error" >&2; exit 1; } + require_contains "$contract_fixture_dir/competing-$variant.error" 'completed with failure' + fi +done for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success CONTRACT_DUPLICATE_PATH="$variant" \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index be84968da5..daf75e104b 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -106,30 +106,47 @@ active_filter = re.search( def active_ids(row: dict[str, Any]) -> str: return subprocess.check_output([ "jq", "-r", "--arg", "workflow_name", "PR Preview Environment", - "--arg", "trusted_workflow_name", "Trusted Hosted Identity Request", + "--argjson", "workflow_id", "173511323", "--arg", "repository", "benhook1013/FireMUD", "--arg", "default_branch", "develop", "--arg", "pr_title", "PR preview 7", "--argjson", "pr_number", "7", "--arg", "head_sha", "a" * 40, "--arg", "run_name", "Preview dispatch pr-7-base-b-head-a-merge-c", - "(" + active_filter + ") | .id", + "(" + active_filter + ") | [.id, .exact] | @tsv", ], input=json.dumps([row]), text=True).strip() active_run = { - "id": 1, "name": "PR Preview Environment", "path": ".github/workflows/preview.yml", + "id": 1, "name": "PR preview 7", "path": ".github/workflows/preview.yml", + "workflow_id": 173511323, "repository": {"full_name": "benhook1013/FireMUD"}, + "head_repository": {"full_name": "benhook1013/FireMUD"}, "head_branch": "feature", "head_sha": "a" * 40, "pull_requests": [{"number": 7}], "display_title": "PR preview 7", "status": "in_progress", "run_attempt": 1, "event": "pull_request", "firemud_reconciler_branch_filtered": False, } -assert active_ids(active_run) == "1" +assert active_ids(active_run) == "1\tfalse" assert active_ids({key: value for key, value in active_run.items() if key != "run_attempt"}) == "" -assert active_ids({**active_run, "pull_requests": [{"number": 8}, {"number": 7}]}) == "1" +assert active_ids({**active_run, "pull_requests": [{"number": 8}, {"number": 7}]}) == "1\tfalse" assert active_ids({**active_run, "pull_requests": [{"number": 7}, {"number": 7}]}) == "" for fields in ( {"path": ".github/workflows/unrelated.yml"}, {"head_sha": "b" * 40}, + {"workflow_id": 170000000}, + {"head_repository": {"full_name": "fork/FireMUD"}}, + {"repository": {"full_name": "fork/FireMUD"}}, {"pull_requests": [{"number": 8}]}, ): assert active_ids({**active_run, **fields}) == "" -assert active_ids({**active_run, "display_title": "Preview dispatch pr-7-base-b-head-a-merge-c", - "pull_requests": [], "head_branch": "develop"}) == "1" +assert active_ids({**active_run, "event": "pull_request_target"}) == "1\tfalse" +assert active_ids({**active_run, "event": "pull_request_target", "path": ".github/workflows/unrelated.yml"}) == "" +dispatch_title = "Preview dispatch pr-7-base-b-head-a-merge-c" +dispatch = {**active_run, "name": dispatch_title, "display_title": dispatch_title, + "pull_requests": [], "head_branch": "develop"} +assert active_ids(dispatch) == "" +assert active_ids({**dispatch, "pull_requests": [{"number": 7}]}) == "1\tfalse" +assert active_ids({**dispatch, "event": "repository_dispatch"}) == "1\ttrue" +assert active_ids({**dispatch, "event": "repository_dispatch", "head_branch": "feature"}) == "" +assert active_ids({**dispatch, "event": "repository_dispatch", "workflow_id": 170000000}) == "" +assert active_ids({**dispatch, "event": "repository_dispatch", "path": ".github/workflows/other.yml"}) == "" +assert active_ids({**dispatch, "event": "pull_request_target", "pull_requests": [{"number": 7}]}) == "" +assert active_ids({**dispatch, "event": "workflow_run", "name": "Trusted Hosted Identity Request", + "path": ".github/workflows/hosted-identity-request.yml"}) == "" preview = load(preview_path) trusted = load(trusted_path) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java index 4d2b027d0f..8c8de6132b 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java @@ -35,6 +35,9 @@ Operation bindVerifiedEvidence( OutboxEntry recordRetryableEffect( UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); + /** False only for an exact dispatch superseded after validated durable owner closure. */ + boolean recordRetryableEffectForDispatch(OutboxEntry dispatch, String outcomeCode, Instant now); + OutboxEntry recordAmbiguousEffect( UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 51bc2fc19e..c526b91b06 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -97,6 +97,20 @@ public InitialGameplayReleaseModel.InitialGameplayReleaseEvidence readEvidence(S } } + InitialGameplayReleaseModel.PublicTransitionTuple readPublicTransition(String json) { + try { + var tuple = + objectMapper.readValue(json, InitialGameplayReleaseModel.PublicTransitionTuple.class); + // JSONB may reorder object properties, but stored fields and JSON value types must be exact. + if (tuple == null || !objectMapper.readTree(json).equals(objectMapper.valueToTree(tuple))) { + throw new IllegalStateException("Persisted public transition has a noncanonical shape"); + } + return tuple; + } catch (JacksonException exception) { + throw new IllegalStateException("Unable to read persisted public transition", exception); + } + } + InitialGameplayReleaseModel.EffectReadback readEffectReadback(String json) { try { return objectMapper.readValue(json, InitialGameplayReleaseModel.EffectReadback.class); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index cc8ba651e2..6f4c9d0909 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -154,15 +154,13 @@ public Operation transition(PublicTransitionTuple tuple, Instant now) { requireTransitionMatchesOperation(tuple, current); Record previous = tx.fetchOne( - "SELECT tuple_digest FROM " + "SELECT tuple_digest, tuple_payload, expected_phase, result_phase FROM " + TRANSITION_TABLE + " WHERE operation_id = ? AND verb = ?", tuple.operationId(), tuple.verb().wireValue()); if (previous != null) { - if (!tupleDigest.equals(previous.get("tuple_digest", String.class))) { - throw conflict("public transition tuple changed"); - } + requireRetainedTransition(previous, tuple, tupleDigest); return current; } if (current.phase() != tuple.expectedPhase()) { @@ -208,7 +206,7 @@ public Optional findTransition(PublicTransitionTuple tuple) { Objects.requireNonNull(tuple, "tuple must not be null"); Record previous = dsl.fetchOne( - "SELECT o.*, t.tuple_digest AS transition_digest FROM recovery_control.initial_gameplay_release_operation o " + "SELECT o.*, t.tuple_digest, t.tuple_payload, t.expected_phase, t.result_phase FROM recovery_control.initial_gameplay_release_operation o " + "JOIN " + TRANSITION_TABLE + " t ON t.operation_id=o.operation_id " @@ -220,9 +218,7 @@ public Optional findTransition(PublicTransitionTuple tuple) { } Operation operation = toOperation(previous); requireTransitionMatchesOperation(tuple, operation); - if (!tupleCodec.digest(tuple).equals(previous.get("transition_digest", String.class))) { - throw conflict("public transition tuple changed"); - } + requireRetainedTransition(previous, tuple, tupleCodec.digest(tuple)); return Optional.of(operation); } @@ -251,15 +247,19 @@ public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, DSLContext tx = DSL.using(configuration); Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); + requireEffectMatchesOperation(current.effect(), operation); + if (hasRetainedClosure(tx, current, attemptId, null)) { + throw conflict("a retry must use a new effect attempt identity"); + } if (current.state() == EffectOutboxState.DISPATCHED || current.state() == EffectOutboxState.AMBIGUOUS || current.state() == EffectOutboxState.ACKNOWLEDGED) { return current; } if (current.state() == EffectOutboxState.RETRYABLE - && attemptId.equals(current.lastAttemptId()) - && hasDurableNoEffectClosure(tx, current)) { - throw conflict("a retry must use a new effect attempt identity"); + && hasDurableNoEffectClosure(tx, current) + && !hasRetainedClosure(tx, current, current.lastAttemptId(), current.attemptCount())) { + throw conflict("durable owner closure has no retained attempt identity"); } requirePhaseForEffect(operation.phase(), current.effect().kind()); int changed = @@ -290,36 +290,72 @@ && hasDurableNoEffectClosure(tx, current)) { public OutboxEntry recordRetryableEffect( UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { return recordNonterminalEffectOutcome( - operationId, effectId, attemptId, outcomeCode, EffectOutboxState.RETRYABLE, now); + operationId, effectId, attemptId, outcomeCode, EffectOutboxState.RETRYABLE, now, null) + .orElseThrow(); + } + + @Override + public boolean recordRetryableEffectForDispatch( + OutboxEntry dispatch, String outcomeCode, Instant now) { + Objects.requireNonNull(dispatch, "dispatch must not be null"); + return recordNonterminalEffectOutcome( + dispatch.effect().operationId(), + dispatch.effect().effectId(), + dispatch.lastAttemptId(), + outcomeCode, + EffectOutboxState.RETRYABLE, + now, + dispatch) + .isPresent(); } @Override public OutboxEntry recordAmbiguousEffect( UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { return recordNonterminalEffectOutcome( - operationId, effectId, attemptId, outcomeCode, EffectOutboxState.AMBIGUOUS, now); + operationId, effectId, attemptId, outcomeCode, EffectOutboxState.AMBIGUOUS, now, null) + .orElseThrow(); } - private OutboxEntry recordNonterminalEffectOutcome( + private Optional recordNonterminalEffectOutcome( UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, EffectOutboxState resultState, - Instant now) { + Instant now, + OutboxEntry dispatch) { InitialGameplayReleaseModel.requiredOutcomeCode(outcomeCode); return dsl.transactionResult(configuration -> { DSLContext tx = DSL.using(configuration); + Operation operation = dispatch == null ? null : selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); - if (current.lastAttemptId() != null && !current.lastAttemptId().equals(attemptId)) { + if (dispatch != null) { + requireEffectMatchesOperation(current.effect(), operation); + if (dispatch.state() != EffectOutboxState.DISPATCHED + || attemptId == null + || !dispatch.outboxId().equals(current.outboxId()) + || !dispatch.effect().equals(current.effect()) + || !dispatch.payloadDigest().equals(current.payloadDigest())) { + throw conflict("effect dispatch tuple changed"); + } + } + if (!Objects.equals(current.lastAttemptId(), attemptId)) { + if (dispatch != null + && hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { + return Optional.empty(); + } throw conflict("effect attempt identity changed"); } + if (dispatch != null && dispatch.attemptCount() != current.attemptCount()) { + throw conflict("effect dispatch generation changed"); + } if (current.state() == resultState || current.state() == EffectOutboxState.ACKNOWLEDGED || (current.lastAttemptId() != null && current.state() == EffectOutboxState.RETRYABLE && resultState == EffectOutboxState.AMBIGUOUS)) { - return current; + return Optional.of(current); } if (current.state() != EffectOutboxState.DISPATCHED && !(current.state() == EffectOutboxState.AMBIGUOUS @@ -339,7 +375,7 @@ private OutboxEntry recordNonterminalEffectOutcome( operationId, effectId, attemptId); - return selectOutbox(tx, operationId, effectId, false); + return Optional.of(selectOutbox(tx, operationId, effectId, false)); }); } @@ -352,6 +388,7 @@ public Operation recordEffectReadback( DSLContext tx = DSL.using(configuration); Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); + requireEffectMatchesOperation(current.effect(), operation); requireReadbackMatches(readback, current, operationId, effectId); if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { throw conflict("effect readback belongs to another attempt"); @@ -432,6 +469,22 @@ && sameRetainedOutcome(readback, stored, storedDigest)) { return operation; } if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT) { + if (hasRetainedClosure(tx, current, readback.attemptId(), null)) { + throw conflict("effect attempt closure already exists outside exact replay"); + } + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_attempt_closure + (outbox_id, attempt_id, attempt_ordinal, readback_payload, readback_digest, dispatched_at, recorded_at) + VALUES (?, ?, ?, CAST(? AS jsonb), ?, CAST(? AS timestamptz), CAST(? AS timestamptz)) + """, + current.outboxId(), + readback.attemptId(), + current.attemptCount(), + JSONB.valueOf(tupleCodec.toJson(readback)), + readbackDigest, + dispatchTime, + toOffsetDateTime(now)); setReadbackState(tx, current, readback, readbackDigest, EffectOutboxState.RETRYABLE, now); return operation; } @@ -672,6 +725,39 @@ private void requireSameScope(Scope actual, Scope requested, String expectedDige } } + private void requireRetainedTransition( + Record row, PublicTransitionTuple requested, String digest) { + JSONB payload = row.get("tuple_payload", JSONB.class); + PublicTransitionTuple retained; + try { + retained = payload == null ? null : tupleCodec.readPublicTransition(payload.data()); + } catch (IllegalStateException corrupted) { + throw conflict("retained public transition tuple changed"); + } + if (retained == null + || !requested.equals(retained) + || !digest.equals(row.get("tuple_digest", String.class)) + || !digest.equals(tupleCodec.digest(retained)) + || !retained.expectedPhase().databaseValue().equals(row.get("expected_phase", String.class)) + || !retained + .verb() + .resultPhase() + .databaseValue() + .equals(row.get("result_phase", String.class))) { + throw conflict("retained public transition tuple changed"); + } + } + + private void requireEffectMatchesOperation(TypedEffect effect, Operation operation) { + if (!effect.scope().equals(operation.scope()) + || !effect.maintenanceLockIdentity().equals(operation.maintenanceLockIdentity()) + || operation.evidence() == null + || !effect.evidenceIdentity().equals(operation.evidence().evidenceIdentity()) + || !effect.operationTupleDigest().equals(operationTupleDigest(operation))) { + throw conflict("retained effect does not match the operation-owned tuple"); + } + } + private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Operation operation) { if (!tuple.operationId().equals(operation.scope().operationId()) || !tuple.scopeDigest().equals(tupleCodec.digest(operation.scope())) @@ -684,6 +770,47 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper } } + private boolean hasRetainedClosure( + DSLContext tx, OutboxEntry current, UUID attemptId, Integer expectedOrdinal) { + Record row = + tx.fetchOne( + """ + SELECT attempt_ordinal, readback_payload, readback_digest, dispatched_at, recorded_at + FROM recovery_control.initial_gameplay_release_attempt_closure + WHERE outbox_id=? AND attempt_id=? + """, + current.outboxId(), + attemptId); + if (row == null) return false; + Integer ordinal = row.get("attempt_ordinal", Integer.class); + if (ordinal == null + || ordinal < 1 + || ordinal > current.attemptCount() + || (expectedOrdinal != null && !expectedOrdinal.equals(ordinal))) { + throw conflict("retained effect dispatch generation changed"); + } + EffectReadback retained = + tupleCodec.readEffectReadback(row.get("readback_payload", JSONB.class).data()); + if (retained.state() != EffectReadbackState.PROVEN_NO_EFFECT + || !current.effect().operationId().equals(retained.operationId()) + || !current.effect().effectId().equals(retained.effectId()) + || !attemptId.equals(retained.attemptId()) + || current.effect().kind() != retained.effectKind() + || !current.effect().operationTupleDigest().equals(retained.operationTupleDigest()) + || !current.payloadDigest().equals(retained.payloadDigest()) + || !tupleCodec.digest(retained).equals(row.get("readback_digest", String.class)) + || retained + .observedAt() + .isBefore(row.get("dispatched_at", OffsetDateTime.class).toInstant()) + || retained + .observedAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .isAfter(row.get("recorded_at", OffsetDateTime.class).toInstant())) { + throw conflict("retained attempt closure does not match the exact dispatched tuple"); + } + return true; + } + private boolean hasDurableNoEffectClosure(DSLContext tx, OutboxEntry current) { Record stored = tx.fetchOne( diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index b4a3c73b7c..98e10c4eae 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -158,12 +158,9 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { } if (applyResult.status() == ApplyStatus.RETRYABLE_NO_EFFECT || applyResult.status() == ApplyStatus.NOT_DISPATCHED) { - journal.recordRetryableEffect( - operation.scope().operationId(), - dispatched.effect().effectId(), - attemptId, - applyResult.outcomeCode(), - clock.instant()); + // An exact, durably closed prior dispatch can be superseded while the apply call was pending. + journal.recordRetryableEffectForDispatch( + dispatched, applyResult.outcomeCode(), clock.instant()); return requireOperation(operation.scope().operationId()); } if (applyResult.status() == ApplyStatus.AMBIGUOUS) { diff --git a/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql new file mode 100644 index 0000000000..d63df340f2 --- /dev/null +++ b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql @@ -0,0 +1,29 @@ +-- Source-only upgrade. Fence and drain all V1 writers before migration and rollout. +-- V1 could overwrite prior closure evidence; never synthesize missing history. +-- [jooq ignore start] +LOCK TABLE recovery_control.initial_gameplay_release_outbox IN ACCESS EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM recovery_control.initial_gameplay_release_outbox + WHERE attempt_count <> 0 OR last_attempt_id IS NOT NULL OR last_dispatched_at IS NOT NULL + OR readback_payload IS NOT NULL OR state <> 'pending' + ) THEN + RAISE EXCEPTION 'Initial gameplay recovery closure migration requires no prior claims'; + END IF; +END $$; +-- [jooq ignore stop] + +CREATE TABLE recovery_control.initial_gameplay_release_attempt_closure ( + outbox_id UUID NOT NULL + REFERENCES recovery_control.initial_gameplay_release_outbox(outbox_id) ON DELETE RESTRICT, + attempt_id UUID NOT NULL, + attempt_ordinal INTEGER NOT NULL CHECK (attempt_ordinal > 0), + readback_payload JSONB NOT NULL, + readback_digest CHAR(64) NOT NULL, + dispatched_at TIMESTAMPTZ NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL, + CHECK (recorded_at >= dispatched_at), + PRIMARY KEY (outbox_id, attempt_id) +); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 36150da83e..8409537636 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -80,7 +80,9 @@ static void setUp() throws Exception { .load(); assertThat(flyway.info().all()) .extracting(info -> info.getScript()) - .containsExactly("V1__initial_gameplay_release_journal.sql"); + .containsExactlyInAnyOrder( + "V1__initial_gameplay_release_journal.sql", + "V2__retain_initial_gameplay_release_attempt_closure.sql"); flyway.migrate(); connection = DriverManager.getConnection( @@ -101,7 +103,8 @@ static void tearDown() throws Exception { @BeforeEach void clearJournal() { dsl.execute( - "TRUNCATE TABLE recovery_control.initial_gameplay_release_outbox, " + "TRUNCATE TABLE recovery_control.initial_gameplay_release_attempt_closure, " + + "recovery_control.initial_gameplay_release_outbox, " + "recovery_control.initial_gameplay_release_transition, " + "recovery_control.initial_gameplay_release_operation"); } @@ -945,6 +948,247 @@ void retryableEffectWithoutDurableClosurePreservesSameAttemptClaimBehavior() { assertThat(retried.attemptCount()).isEqualTo(dispatched.attemptCount() + 1); } + @Test + void transitionReplaysRejectCorruptRetainedPayloadAndPhasesWithoutWrites() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + Scope scope = scope(); + journal.create(scope, UUID.randomUUID()); + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base); + PublicTransitionTuple continuing = transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY); + Operation awaiting = journal.transition(continuing, base.plusSeconds(1)); + PublicTransitionTuple resuming = transitionTuple(awaiting, TransitionVerb.RESUME); + Operation authorized = journal.transition(resuming, base.plusSeconds(2)); + OutboxEntry pending = journal.findNextEffect(scope.operationId()).orElseThrow(); + String outbox = storedOutbox(scope.operationId(), pending.effect().effectId()); + + for (PublicTransitionTuple tuple : List.of(continuing, resuming)) { + var canonical = tupleCodec.toJson(tuple); + var withExtra = canonical.substring(0, canonical.length() - 1) + ",\"unknownField\":true}"; + + assertThat(journal.findTransition(tuple)).contains(authorized); + assertThat(journal.transition(tuple, base.plusSeconds(3))).isEqualTo(authorized); + for (String corruption : + List.of( + "tuple_payload=jsonb_set(tuple_payload, '{maintenanceLockIdentity}', to_jsonb(CAST(? AS text)))", + "tuple_payload=CAST(? AS jsonb)", + "tuple_payload=tuple_payload || CAST(? AS jsonb)", + "expected_phase=?", + "result_phase=?")) { + Object broken = + corruption.contains("jsonb_set") + ? UUID.randomUUID().toString() + : corruption.contains("||") + ? withExtra + : corruption.contains("jsonb") ? "{}" : "collecting"; + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_transition SET " + + corruption + + " WHERE operation_id=? AND verb=?", + broken, + scope.operationId(), + tuple.verb().wireValue()); + assertThatThrownBy(() -> journal.findTransition(tuple)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("retained public transition tuple changed"); + assertThatThrownBy(() -> journal.transition(tuple, base.plusSeconds(4))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("retained public transition tuple changed"); + assertThat(journal.find(scope.operationId())).contains(authorized); + assertThat(storedOutbox(scope.operationId(), pending.effect().effectId())) + .isEqualTo(outbox); + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_transition " + + "SET tuple_payload=CAST(? AS jsonb), expected_phase=?, result_phase=? " + + "WHERE operation_id=? AND verb=?", + tupleCodec.toJson(tuple), + tuple.expectedPhase().databaseValue(), + tuple.verb().resultPhase().databaseValue(), + scope.operationId(), + tuple.verb().wireValue()); + } + } + } + + @Test + void claimAndReadbackRejectEffectFromAnotherMaintenanceLockWithoutWrites() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry dispatched = authorizedDispatch(base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + UUID attemptId = dispatched.lastAttemptId(); + EffectReadback readback = + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PREPARED_FENCED, + "prepared", + base.plusSeconds(5)); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_operation SET maintenance_lock_identity=? WHERE operation_id=?", + UUID.randomUUID(), + operationId)) + .isEqualTo(1); + Operation corrupted = journal.find(operationId).orElseThrow(); + String outbox = storedOutbox(operationId, effectId); + + assertThatThrownBy( + () -> journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(5))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("retained effect does not match the operation-owned tuple"); + assertThatThrownBy(() -> + journal.recordEffectReadback( + operationId, effectId, attemptId, readback, base.plusSeconds(6))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("retained effect does not match the operation-owned tuple"); + assertThat(journal.find(operationId)).contains(corrupted); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(outbox); + assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isEmpty(); + } + + @Test + void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry a = authorizedDispatch(base); + UUID operationId = a.effect().operationId(); + UUID effectId = a.effect().effectId(); + journal.recordEffectReadback( + operationId, + effectId, + a.lastAttemptId(), + readbackFor( + a, + a.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "closed-a", + base.plusSeconds(5)), + base.plusSeconds(5)); + OutboxEntry b = + journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(6)); + String before = storedOutbox(operationId, effectId); + assertThat( + journal.recordRetryableEffectForDispatch(a, "DELAYED_NO_EFFECT", base.plusSeconds(7))) + .isFalse(); + assertThatThrownBy(() -> + journal.claimEffect(operationId, effectId, a.lastAttemptId(), base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + journal.recordEffectReadback( + operationId, + effectId, + b.lastAttemptId(), + readbackFor( + b, + b.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "closed-b", + base.plusSeconds(8)), + base.plusSeconds(8)); + before = storedOutbox(operationId, effectId); + assertThatThrownBy(() -> + journal.claimEffect(operationId, effectId, a.lastAttemptId(), base.plusSeconds(9))) + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + OutboxEntry c = + journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(10)); + assertThat(c.state()).isEqualTo(EffectOutboxState.DISPATCHED); + assertThat(c.lastAttemptId()).isNotIn(a.lastAttemptId(), b.lastAttemptId()); + } + + @Test + void delayedTransportOnlyGenerationCannotMutateSameIdRetry() { + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry original = authorizedDispatch(base); + UUID operationId = original.effect().operationId(); + UUID effectId = original.effect().effectId(); + UUID attemptId = original.lastAttemptId(); + assertThat( + journal.recordRetryableEffectForDispatch( + original, "TRANSPORT_REFUSED", base.plusSeconds(5))) + .isTrue(); + OutboxEntry retry = journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(6)); + assertThat(retry.attemptCount()).isEqualTo(original.attemptCount() + 1); + String before = storedOutbox(operationId, effectId); + assertThatThrownBy(() -> + journal.recordRetryableEffectForDispatch( + original, "STALE_TRANSPORT_REFUSED", base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect dispatch generation changed"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat( + journal.recordRetryableEffectForDispatch( + retry, "CURRENT_TRANSPORT_REFUSED", base.plusSeconds(8))) + .isTrue(); + } + + @Test + void migrationRefusesClaimedLegacyOutboxAndRollsBack() throws Exception { + String database = "legacy_closure_" + UUID.randomUUID().toString().replace("-", ""); + dsl.execute("CREATE DATABASE " + database); + String canonicalUrl = POSTGRES.getJdbcUrl(); + String legacyUrl = canonicalUrl.substring(0, canonicalUrl.lastIndexOf('/') + 1) + database; + try { + Flyway.configure() + .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .locations("classpath:db/recovery-control-migration") + .target("1") + .load() + .migrate(); + try (Connection legacyConnection = + DriverManager.getConnection(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword())) { + DSLContext legacyDsl = DSL.using(legacyConnection, SQLDialect.POSTGRES); + InitialGameplayReleaseJournal legacy = + new JooqInitialGameplayReleaseJournal(legacyDsl, tupleCodec); + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + Scope scope = scope(); + legacy.create(scope, UUID.randomUUID()); + InitialGameplayReleaseEvidence proof = evidence(scope); + Operation ready = + legacy.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base); + Operation awaiting = + legacy.transition(transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base); + legacy.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base); + OutboxEntry pending = legacy.findNextEffect(scope.operationId()).orElseThrow(); + UUID legacyAttempt = UUID.randomUUID(); + assertThat( + legacyDsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox " + + "SET state='dispatched', attempt_count=1, last_attempt_id=?, " + + "last_dispatched_at=now() WHERE outbox_id=?", + legacyAttempt, + pending.outboxId())) + .isEqualTo(1); + OutboxEntry before = legacy.findNextEffect(scope.operationId()).orElseThrow(); + Flyway upgrade = + Flyway.configure() + .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .locations("classpath:db/recovery-control-migration") + .load(); + assertThatThrownBy(() -> upgrade.migrate()) + .hasStackTraceContaining("requires no prior claims"); + assertThat(legacy.findNextEffect(scope.operationId())).contains(before); + assertThat( + legacyDsl + .fetchSingle( + "SELECT to_regclass('recovery_control.initial_gameplay_release_attempt_closure')") + .get(0)) + .isNull(); + assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("1"); + } + } finally { + dsl.execute("DROP DATABASE " + database); + } + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); From 3ee65328e498a9cea9f15dd773eb76f632be81df Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:01:58 +1300 Subject: [PATCH 075/199] Align Preview priority fixture with native workflow identity --- dev-tools/tests/preview-priority-contract.sh | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index fcee042e06..29f175f981 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -426,6 +426,10 @@ fake_labels_json() { fi printf '%s' "$labels_json" } +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/preview.yml' ]]; then + printf '%s\n' '{"id":173511323,"name":"PR Preview Environment","path":".github/workflows/preview.yml"}' + exit 0 +fi if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request\&status=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then active_query_status="${resource##*&status=}" active_query_status="${active_query_status%%&*}" @@ -2576,7 +2580,7 @@ for tuple_case in current qualified old_merge missing ambiguous stale_attempt wr else {jobs:.,total_count:length} end')" latest_source="$(jq -cn --arg head "$preview_head_sha" --arg variant "$tuple_case" ' {id:5254,run_attempt:(if $variant == "stale_attempt" or $variant == "stale_attempt_old_tuple" then 3 else 2 end), - head_sha:$head,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} + head_sha:$head,event:"pull_request",workflow_id:173511323,repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) else . end')" ( @@ -2589,7 +2593,7 @@ for tuple_case in current qualified old_merge missing ambiguous stale_attempt wr FAKE_PREVIEW_SOURCE_LATEST_FAIL="$([[ "$tuple_case" == latest_unavailable ]] && echo true || echo false)" \ FAKE_PREVIEW_PLAN_JOBS_JSON="$plan_jobs" \ FAKE_PREVIEW_SOURCE_LATEST_JSON="$latest_source" \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:"pull_request",path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:"pull_request",workflow_id:173511323,repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_output" @@ -2765,7 +2769,7 @@ reconciler_paginated_active_output="$TEMP_DIR/reconciler-paginated-active.out" --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" \ '[ {workflow_runs: []}, - {workflow_runs: [{id: 4242, path: ".github/workflows/preview.yml", name: "PR Preview Environment", head_branch: "develop", display_title: $title, status: "queued"}]} + {workflow_runs: [{id: 4242, run_attempt: 1, workflow_id: 173511323, event: "repository_dispatch", path: ".github/workflows/preview.yml", name: $title, head_branch: "develop", head_sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", repository: {full_name: "example/FireMUD"}, head_repository: {full_name: "example/FireMUD"}, display_title: $title, status: "queued"}]} ]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" From 747dedbf09884e25ad0fa4788490a424c963128b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:21:11 +1300 Subject: [PATCH 076/199] Repair Preview native run proof and CI parity fixtures --- .github/workflows/preview-reconciler.yml | 4 +- dev-tools/tests/preview-priority-contract.sh | 69 ++++++++++++++------ 2 files changed, 50 insertions(+), 23 deletions(-) diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index a441345709..0a136385f9 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -371,7 +371,7 @@ jobs: .id == $id and .run_attempt != $attempt and .head_sha == $head and .event == $event and .workflow_id == $workflow_id and .repository.full_name == $repository and .head_repository.full_name == $repository - and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1) + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) ' <<<"$latest" >/dev/null; then @@ -381,7 +381,7 @@ jobs: .id == $id and .run_attempt == $attempt and .head_sha == $head and .event == $event and .workflow_id == $workflow_id and .repository.full_name == $repository and .head_repository.full_name == $repository - and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1) + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) ' <<<"$latest" >/dev/null || return 1 diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 29f175f981..496caf4e7b 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash set -euo pipefail +trap 'rc=$?; printf "Preview priority contract failed at line %s (exit %s)\n" "$LINENO" "$rc" >&2' ERR ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" ALLOCATOR="$ROOT_DIR/dev-tools/hosted/preview/allocate-preview-capacity.sh" @@ -451,13 +452,19 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == jq -c \ --arg requested_status "$active_query_status" \ --arg requested_scope "$active_query_scope" \ - '[.[] | .workflow_runs = [.workflow_runs[] | select(.status == $requested_status) | select((.event // $requested_scope) == $requested_scope)]]' \ + '[.[] | .workflow_runs = [.workflow_runs[] | select(.status == $requested_status) | select((.event // $requested_scope) == $requested_scope or ($requested_scope == "branch" and .event == "repository_dispatch"))]]' \ <<<"$FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON" else jq -cn \ --argjson runs "${FAKE_ACTIVE_PREVIEW_RUNS_JSON:-[]}" \ --arg requested_status "$active_query_status" \ - '[{workflow_runs:[$runs[] | select(.status == $requested_status) | {id:.databaseId,path:".github/workflows/preview.yml",name:"PR Preview Environment",head_branch:"develop",display_title:.displayTitle,status:.status}]}]' + --arg requested_scope "$active_query_scope" \ + '[{workflow_runs:[$runs[] | select(.status == $requested_status and $requested_scope == "branch") | { + id:.databaseId,run_attempt:1,workflow_id:173511323,event:"repository_dispatch", + path:".github/workflows/preview.yml",name:.displayTitle,head_branch:"develop", + head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + display_title:.displayTitle,status:.status}]}]' fi exit 0 fi @@ -2523,7 +2530,7 @@ grep -Fqx \ grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" reset_case -reconciler_trusted_consumer_output="$TEMP_DIR/reconciler-trusted-consumer.out" +reconciler_unrelated_consumer_output="$TEMP_DIR/reconciler-trusted-consumer.out" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -2535,12 +2542,11 @@ reconciler_trusted_consumer_output="$TEMP_DIR/reconciler-trusted-consumer.out" '[{workflow_runs:[{id:5252,path:".github/workflows/hosted-identity-request.yml",name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title,status:"in_progress"}]}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" -) > "$reconciler_trusted_consumer_output" +) > "$reconciler_unrelated_consumer_output" grep -Fqx \ - "Skipping proof retry for PR #901: preview source or trusted consumer run 5252 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ - "$reconciler_trusted_consumer_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" + "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ + "$reconciler_unrelated_consumer_output" +test -s "$FAKE_DISPATCH_LOG" reset_case reconciler_source_title_consumer_output="$TEMP_DIR/reconciler-unqualified-consumer.out" @@ -2560,7 +2566,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2580,7 +2586,7 @@ for tuple_case in current qualified old_merge missing ambiguous stale_attempt wr else {jobs:.,total_count:length} end')" latest_source="$(jq -cn --arg head "$preview_head_sha" --arg variant "$tuple_case" ' {id:5254,run_attempt:(if $variant == "stale_attempt" or $variant == "stale_attempt_old_tuple" then 3 else 2 end), - head_sha:$head,event:"pull_request",workflow_id:173511323,repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} + head_sha:$head,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:173511323,repository:{full_name:(if $variant == "wrong_latest_repo" then "example/Other" else "example/FireMUD" end)},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) else . end')" ( @@ -2593,11 +2599,11 @@ for tuple_case in current qualified old_merge missing ambiguous stale_attempt wr FAKE_PREVIEW_SOURCE_LATEST_FAIL="$([[ "$tuple_case" == latest_unavailable ]] && echo true || echo false)" \ FAKE_PREVIEW_PLAN_JOBS_JSON="$plan_jobs" \ FAKE_PREVIEW_SOURCE_LATEST_JSON="$latest_source" \ - FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:"pull_request",workflow_id:173511323,repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg variant "$tuple_case" '[{workflow_runs:[{id:5254,run_attempt:2,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:(if $variant == "wrong_list_id" then 1 else 173511323 end),repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_list_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",pull_requests:[{number:901}],name:"PR Preview Environment",head_branch:"feature-preview",display_title:"PR preview 901",status:"in_progress"}]}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_output" - if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == old_event_current_plan ]]; then + if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == target || "$tuple_case" == old_event_current_plan ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_pull_request_output" @@ -2629,17 +2635,33 @@ reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-adva FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ --arg observation "$observation_case" \ --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" ' - [{workflow_runs:([{id:5256,path:".github/workflows/hosted-identity-request.yml", - name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title} - | if $observation == "duplicate-rows" then . + {event:"branch",status:"queued"}, . + {event:"workflow_run",status:"in_progress"} else . + {event:"workflow_run",status:"in_progress"} end])}]')" \ + [{workflow_runs:( + if $observation == "duplicate-rows" then + {id:5256,run_attempt:1,workflow_id:173511323,event:"repository_dispatch", + path:".github/workflows/preview.yml",name:$title,head_branch:"develop", + head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + display_title:$title} + | [. + {status:"queued"}, . + {status:"in_progress"}] + else + [{id:5256,event:"workflow_run",path:".github/workflows/hosted-identity-request.yml", + name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title,status:"in_progress"}] + end)}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" -grep -Fqx \ - "Skipping proof retry for PR #901: preview source or trusted consumer run 5256 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ - "$reconciler_active_status_advance_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" +if [[ "$observation_case" == duplicate-rows ]]; then + grep -Fqx \ + "Skipping proof retry for PR #901: preview source or trusted consumer run 5256 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ + "$reconciler_active_status_advance_output" + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" +else + grep -Fqx \ + "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ + "$reconciler_active_status_advance_output" + test -s "$FAKE_DISPATCH_LOG" +fi done @@ -3636,7 +3658,12 @@ grep -Fq 'namespace proof-retry evidence is malformed' "$reconciler_workflow" grep -Fq 'proof retry budget exhausted' "$reconciler_workflow" # shellcheck disable=SC2016 # Assert literal resource-version fencing. grep -Fq -- '--resource-version "${namespace_resource_version}"' "$reconciler_workflow" -grep -Fq -- '--arg trusted_workflow_name "Trusted Hosted Identity Request"' "$reconciler_workflow" +# shellcheck disable=SC2016 # Assert canonical workflow lookup and native custody. +grep -Fq -- 'actions/workflows/preview.yml" | jq' "$reconciler_workflow" +# shellcheck disable=SC2016 # Assert the literal jq workflow and repository checks. +grep -Fq -- '.workflow_id == $workflow_id' "$reconciler_workflow" +# shellcheck disable=SC2016 # Assert the literal jq head repository check. +grep -Fq -- '.head_repository.full_name == $repository' "$reconciler_workflow" grep -Fq 'Skipping proof retry for PR #' "$reconciler_workflow" grep -Fq "run-name: \${{ github.event_name == 'workflow_run' && github.event.workflow_run.display_title" "$trusted_workflow" # shellcheck disable=SC2016 # Assert one fail-closed JSON snapshot feeds each namespace decision. From 26fff432941c04cc96563b844b6d2189e9b6a6a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:23:03 +1300 Subject: [PATCH 077/199] Fix ShellCheck diagnostic trap in preview contract test --- dev-tools/tests/preview-priority-contract.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 496caf4e7b..f975aeb185 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail -trap 'rc=$?; printf "Preview priority contract failed at line %s (exit %s)\n" "$LINENO" "$rc" >&2' ERR +report_contract_failure() { + printf 'Preview priority contract failed at line %s (exit %s)\n' "$2" "$1" >&2 +} +trap 'report_contract_failure "$?" "$LINENO"' ERR ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" ALLOCATOR="$ROOT_DIR/dev-tools/hosted/preview/allocate-preview-capacity.sh" From 9cd9b6617f3d84e4400d09223ce131395ba65967 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:39:52 +1300 Subject: [PATCH 078/199] Recover JaCoCo task graph after transient Gradle resolution failures --- .github/workflows/ci.yml | 11 +++ .../gradle-dependency-recovery-contract.sh | 69 +++++++++++++++++++ .../tests/jacoco-combined-report-contract.sh | 26 +++++-- 3 files changed, 100 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59464f8702..22fb2ae1f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -470,6 +470,17 @@ jobs: if: ${{ needs.changes.outputs.lightweight_only != 'true' }} uses: ./.github/actions/setup-helm + - name: Set up Java for Gradle task-graph contracts + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: temurin + java-version: '25' + + - name: Set up Gradle for task-graph contracts + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + - name: 🧪 Validate dev tool contracts if: ${{ needs.changes.outputs.lightweight_only != 'true' }} run: | diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 6311ba52c9..5e34c3c3f8 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1154,6 +1154,75 @@ chmod +x "$CASE_DIR/bin/tee" run_case common-web-support 125 assert_no_retry +prepare_jacoco_case() { + new_case "$1" + mkdir -p "$CASE_DIR/dev-tools/tests" + cp "$ROOT_DIR/dev-tools/tests/jacoco-combined-report-contract.sh" "$CASE_DIR/dev-tools/tests/" +} + +# shellcheck disable=SC2030,SC2031 +run_jacoco_case() ( + cd "$CASE_DIR" + export CASE_DIR + export FAKE_CALL_LOG="$CASE_DIR/calls" + export FAKE_DIAGNOSTIC_CALL_LOG="$CASE_DIR/diagnostic-calls" + export FAKE_LOCK_CALL_LOG="$CASE_DIR/locked-calls" + export FAKE_SLEEP_LOG="$CASE_DIR/sleeps" + export PATH="$CASE_DIR/bin:$PATH" + bash ./dev-tools/tests/jacoco-combined-report-contract.sh > "$CASE_DIR/output" 2>&1 +) + +# An eligible first graph gets one refresh. The real script then checks +# all six graphs, including failures in the graph content itself. +for report_result in valid invalid; do + prepare_jacoco_case "jacoco-task-graph-recovered-$report_result" + write_buildsrc_429_cause + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 ]]; then + cat "$CASE_DIR/buildsrc-cause.log" + exit 1 +fi +if [[ "${1:-}" == --refresh-dependencies ]]; then shift; fi +case "$1" in + :common-saga:test) echo ":common-saga:test SKIPPED" ;; + :common-saga:check|:common-saga:jacocoTestReport) + printf "%s\n" ":common-saga:integrationTest SKIPPED" ":common-saga:jacocoTestReport SKIPPED" ;; + :account-service:jacocoTestReport|:game-session-service:jacocoTestReport) + echo "$1 SKIPPED" ;; + :world-management-service:jacocoTestReport) + if [[ "${FAKE_JACOCO_REPORT_RESULT:?}" == invalid ]]; then + echo ":world-management-service:classes SKIPPED" + fi + echo "$1 SKIPPED" ;; + *) exit 99 ;; +esac' + status=0 + FAKE_JACOCO_REPORT_RESULT="$report_result" run_jacoco_case || status=$? + if [[ "$report_result" == valid ]]; then + [[ "$status" -eq 0 ]] || fail "JaCoCo graph did not recover from eligible bootstrapping failure" + assert_output_contains "JaCoCo combined and slow-service partition report task graph contracts passed" + else + [[ "$status" -eq 1 ]] || fail "JaCoCo accepted a malformed graph after recovery" + assert_output_contains "World coverage aggregation recompiled classes instead of using measured partition classes." + fi + assert_call_count 7 + assert_call 1 ":common-saga:test -PfullCheck --dry-run --no-configuration-cache" + assert_call 2 "--refresh-dependencies :common-saga:test -PfullCheck --dry-run --no-configuration-cache" + [[ "$(grep -c '^--refresh-dependencies ' "$CASE_DIR/calls")" -eq 1 ]] || fail "JaCoCo repeated dependency refresh" + [[ "$(cat "$CASE_DIR/sleeps")" == 2 ]] || fail "JaCoCo did not use exactly one bounded recovery delay" + cmp "$CASE_DIR/calls" "$CASE_DIR/locked-calls" || fail "JaCoCo bypassed the existing locked runner" +done + +# Preserve unrelated Gradle configuration failures without another attempt. +prepare_jacoco_case jacoco-task-graph-semantic-failure +write_wrapper 'printf "%s\n" "FAILURE: Build failed with an exception." "* What went wrong:" "Could not create task :common-saga:test." "* Try:" "BUILD FAILED"; exit 1' +status=0 +run_jacoco_case || status=$? +[[ "$status" -eq 1 ]] || fail "JaCoCo task-graph semantic failure did not retain exit code 1" +assert_no_retry +assert_output_contains "Could not create task :common-saga:test." +cmp "$CASE_DIR/calls" "$CASE_DIR/locked-calls" || fail "JaCoCo bypassed the existing locked runner" + echo "Gradle dependency-recovery contract passed." diff --git a/dev-tools/tests/jacoco-combined-report-contract.sh b/dev-tools/tests/jacoco-combined-report-contract.sh index b27d0d0f06..535afe3d74 100644 --- a/dev-tools/tests/jacoco-combined-report-contract.sh +++ b/dev-tools/tests/jacoco-combined-report-contract.sh @@ -3,6 +3,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" LOCKED_GRADLE="$ROOT_DIR/dev-tools/validation/run-locked-gradle.sh" +RECOVERY_GRADLE="$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" TMP_DIR="$(mktemp -d)" trap 'rm -rf "$TMP_DIR"' EXIT @@ -13,12 +14,25 @@ account_aggregate_graph="$TMP_DIR/account-aggregate-graph" game_session_aggregate_graph="$TMP_DIR/game-session-aggregate-graph" world_aggregate_graph="$TMP_DIR/world-aggregate-graph" -bash "$LOCKED_GRADLE" :common-saga:test -PfullCheck --dry-run --no-configuration-cache >"$unit_graph" -bash "$LOCKED_GRADLE" :common-saga:check -PfullCheck --dry-run --no-configuration-cache >"$check_graph" -bash "$LOCKED_GRADLE" :common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache >"$report_graph" -bash "$LOCKED_GRADLE" :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$account_aggregate_graph" -bash "$LOCKED_GRADLE" :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$game_session_aggregate_graph" -bash "$LOCKED_GRADLE" :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$world_aggregate_graph" +run_task_graph() { + local graph="$1" + local status + shift + if bash "$RECOVERY_GRADLE" --runner "$LOCKED_GRADLE" -- "$@" >"$graph"; then + return 0 + else + status=$? + cat "$graph" >&2 + return "$status" + fi +} + +run_task_graph "$unit_graph" :common-saga:test -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$check_graph" :common-saga:check -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$report_graph" :common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache +run_task_graph "$account_aggregate_graph" :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail +run_task_graph "$game_session_aggregate_graph" :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail +run_task_graph "$world_aggregate_graph" :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail if grep -Eq '^:common-saga:(integrationTest|crossServiceTest|jacocoTestReport)([[:space:]]|$)' "$unit_graph"; then echo "Focused :common-saga:test unexpectedly scheduled categorized tests or the combined report." >&2 From 3bcb3dba9739936bfc108c1e922832aaa3fd483a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 20 Nov 2026 22:02:04 +1300 Subject: [PATCH 079/199] Clarify missing CodeQL results after producer failure --- .github/workflows/static-analysis-summary.yml | 2 ++ dev-tools/tests/static-analysis-summary-contract.sh | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 28a6fdc899..a00663f560 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -239,6 +239,8 @@ jobs: checkName.startsWith("CodeQL Analysis (") && workflowRun?.status === "completed" ) { + // A failed producer without a language job did not establish a skip. + if (terminalFailure.has(workflowRun.conclusion)) return "unavailable"; return "skipped"; } if (workflowRun?.status === "completed") { diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index a1444e5f74..f815ea9652 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -726,6 +726,14 @@ run(github, context, core).then(async () => { writes.some(row => row.body.includes("checks passed"))) { throw new Error(`no-gate candidate ${status}/${conclusion} must display ${shown} and ${headline}`); } + if (status === "completed" && ["startup_failure", "failure"].includes(conclusion)) { + const unavailable = String.fromCharCode(96) + "unavailable" + String.fromCharCode(96); + if (!writes.some(row => + row.body.includes("CodeQL analysis (java): " + unavailable) && + row.body.includes("CodeQL analysis (javascript-typescript): " + unavailable))) { + throw new Error("missing CodeQL language jobs on " + conclusion + " must display unavailable"); + } + } } github.paginate = savedPaginate; const savedActions = github.rest.actions; From 3fab56881c262408e35150e2e6fa1701d33cc6c2 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 20 Nov 2026 22:11:19 +1300 Subject: [PATCH 080/199] Recheck advisory producer attempts and strengthen CI fixtures --- .github/workflows/static-analysis-summary.yml | 17 ++++++++- .../pr-required-gate-context-contract.sh | 9 ++++- .../tests/pr-retarget-workflow-contract.sh | 20 +++++++++++ .../tests/static-analysis-summary-contract.sh | 35 ++++++++++++++++--- 4 files changed, 74 insertions(+), 7 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index a00663f560..4d80666e4e 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -211,7 +211,7 @@ jobs: currentRun.display_title !== expectedTitle) { throw new Error("Static summary cannot confirm the current workflow attempt."); } - return { status: "unavailable", conclusion: null, jobs: [] }; + return { ...candidate, status: "unavailable", conclusion: null, jobs: [] }; } const metadataName = `PR Metadata Edit (${gateName})`; const metadata = data.jobs.some(job => job.status === "completed" && @@ -348,6 +348,21 @@ jobs: return; } + // Reruns can advance a producer without changing the PR tuple. + for (const run of Object.values(workflowRuns)) { + if (!run) continue; + const { data: current } = await github.rest.actions.getWorkflowRun({ + ...context.repo, + run_id: run.id, + }); + if (current?.id !== run.id || current.run_attempt !== run.run_attempt || + current.event !== "pull_request" || current.head_sha !== headSha || + current.display_title !== run.display_title) { + core.info("A selected producer attempt changed while static analysis was being summarized."); + return; + } + } + if (existing && existing.body !== body) { await github.rest.issues.updateComment({ ...context.repo, diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index bd70cd42dc..33f7dd67ef 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -87,6 +87,9 @@ def interpret_selector(node): if (isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], (ast.Eq, ast.NotEq))): values = interpret_selector(node.left), interpret_selector(node.comparators[0]) + # Actions compares strings without regard to case. + if all(type(value) is str for value in values): + values = tuple(value.casefold() for value in values) return (values[0] == values[1]) == isinstance(node.ops[0], ast.Eq) if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "format" and not node.keywords and node.args @@ -95,6 +98,10 @@ def interpret_selector(node): raise ValueError("Unsupported concurrency selector") +for expression, expected in (("'Develop' == 'develop'", True), ("'Develop' != 'develop'", False)): + assert interpret_selector(ast.parse(expression, mode="eval").body) is expected + + assert literal_format("metadata-{0}", 123) == "metadata-123" for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{1}"): try: @@ -499,8 +506,8 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { cancelledReads.add(input.run_id); return {data: cancelledSource(input.run_id)}; }, paginate: async (method, input) => { + assert.equal(input.attempt_number, 1); if (!cancelledReads.has(input.run_id)) { - assert.equal(input.attempt_number, 1); 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" }] }]; } diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 45d8795e9c..f088ccb268 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -646,6 +646,26 @@ smoke, runtime = [yaml.load(Path(path).read_text(), Loader=yaml.BaseLoader) for assert set(smoke["on"]["pull_request"]) == {"types"} assert set(runtime["on"]["pull_request"]) == {"types", "paths"} assert "branches" not in runtime["on"]["workflow_run"] + +# Exercise the actual shell from these two named steps with ordinary outcomes. +import os +import subprocess +import tempfile + +steps = smoke["jobs"]["smoke-gate"]["steps"] +classifier = next(step for step in steps if step.get("id") == "smoke_gate_context") +failure = next(step for step in steps if step.get("name") == "Fail when smoke dependencies did not succeed") +assert failure["if"] == "${{ steps.smoke_gate_context.outputs.execute != 'true' }}" +with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + for result, expected in (("success", "true"), ("failure", "false")): + output.write_text("") + env = {**os.environ, "GITHUB_OUTPUT": str(output), "CHANGES_RESULT": result} + subprocess.run(["bash", "-e", "-c", classifier["run"]], env=env, check=True) + assert output.read_text().strip() == f"execute={expected}" + if result == "failure": + failed = subprocess.run(["bash", "-e", "-c", failure["run"]], env=env, capture_output=True, text=True) + assert failed.returncode != 0, "failed change detection must fail Smoke Gate" PYTHON # Reproduce the metadata-edit sequence structurally: the edit has its own diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index f815ea9652..e416c0c16d 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -193,7 +193,20 @@ const github = { if (changeBaseDuringRun && pullRequestReads === 2) currentBaseSha = "c".repeat(40); return { data: { state: "open", head: { sha: currentHeadSha, repo: { id: 123 }, ref: "feature" }, base: { sha: currentBaseSha, ref: currentBaseRef } } }; } }, - actions: { listWorkflowRuns: codeqlListWorkflowRuns }, + actions: { + listWorkflowRuns: codeqlListWorkflowRuns, + getWorkflowRun: async ({run_id}) => { + const callCount = calls.paginate.length; + try { + for (const workflow_id of ["codeql.yml", "license-scan.yml"]) { + const runs = await github.paginate(codeqlListWorkflowRuns, {workflow_id, head_sha: currentHeadSha, per_page: 100}); + const run = runs.find(row => row.id === run_id); + if (run) return {data: run}; + } + } finally { calls.paginate.splice(callCount); } + throw new Error("unexpected current producer read " + run_id); + }, + }, checks: { listForRef: checksListForRef }, issues: { listComments: commentsList, @@ -737,11 +750,23 @@ run(github, context, core).then(async () => { } github.paginate = savedPaginate; const savedActions = github.rest.actions; + const staleBefore = [calls.updated.length, calls.created.length, calls.deleted.length]; + github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { + const {data} = await savedActions.getWorkflowRun(input); + return {data: {...data, run_attempt: data.run_attempt + 1}}; + }}; + try { await run(github, context, core); } + finally { github.rest.actions = savedActions; } + if (staleBefore.some((length, index) => + length !== [calls.updated.length, calls.created.length, calls.deleted.length][index])) { + throw new Error("a producer rerun after evidence read must not mutate comments"); + } + let currentAttempt = 1; - github.rest.actions = {...savedActions, getWorkflowRun: async ({run_id}) => ({data: { - id: run_id, run_attempt: currentAttempt, event: "pull_request", head_sha: currentHeadSha, - display_title: `CodeQL Analysis pr-42 base-${currentBaseSha} head-${currentHeadSha}`, - }})}; + github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { + const {data} = await savedActions.getWorkflowRun(input); + return {data: input.run_id === 200 ? {...data, run_attempt: currentAttempt} : data}; + }}; for (const duplicate of [false, true]) { github.request = async (route, input) => { const response = await savedRequest(route, input); From 1ace170ef5e572c10996b931785c6b1dfd28f1eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:36:59 +1300 Subject: [PATCH 081/199] Make publisher lookup timing deterministic in the fixture --- .../tests/pr-retarget-workflow-contract.sh | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index f088ccb268..aa3d5897cb 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2206,7 +2206,13 @@ if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then case "$*" in *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source.json"; exit 0 ;; "api repos/example/FireMUD") printf '%s\n' '{"full_name":"example/FireMUD","default_branch":"develop"}'; exit 0 ;; - *actions/runs/202) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-${CONTRACT_DUPLICATE_PATH:-bare}.json"; exit 0 ;; + *actions/runs/202) + if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_MARKER:-}" ]]; then + : >"$CONTRACT_PUBLISHER_LOOKUP_MARKER" + fi + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-${CONTRACT_DUPLICATE_PATH:-bare}.json" + exit 0 + ;; *actions/runs/202/attempts/2/jobs?per_page=100) cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-$CONTRACT_DUPLICATE_JOB.json"; exit 0 ;; esac @@ -2408,13 +2414,29 @@ for variant in terminal multi terminal-no-proof; do require_contains "$contract_fixture_dir/competing-$variant.error" 'completed with failure' fi done +# Freeze the fixture clock until the waiter actually looks up a publisher. Only +# subsequent poll sleeps consume the budget; the outer timeout bounds fixture bugs. +cat >"$contract_fixture_dir/publisher-clock.sh" <<'EOF' +if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then + unset SECONDS + SECONDS=0 + sleep() { + if [[ -f "$CONTRACT_PUBLISHER_LOOKUP_MARKER" ]]; then + SECONDS=$((SECONDS + 1)) + fi + } +fi +EOF for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do - if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success CONTRACT_DUPLICATE_PATH="$variant" \ + lookup_marker="$contract_fixture_dir/publisher-$variant.lookup" + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + CONTRACT_PUBLISHER_LOOKUP_MARKER="$lookup_marker" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success CONTRACT_DUPLICATE_PATH="$variant" \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/publisher-$variant.output" 2>"$contract_fixture_dir/publisher-$variant.error"; then [[ "$variant" == "qualified" ]] || { echo "Untrusted publisher path bypassed: $variant" >&2; exit 1; } @@ -2423,6 +2445,7 @@ for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do [[ "$variant" != "qualified" ]] || { cat "$contract_fixture_dir/publisher-$variant.error" >&2; exit 1; } require_contains "$contract_fixture_dir/publisher-$variant.error" 'Timed out waiting for runtime-images workflow' fi + [[ -f "$lookup_marker" ]] || { echo "Publisher lookup was not reached: $variant" >&2; exit 1; } done for fixture in missing-url empty-url; do if CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$fixture.json" \ From 5d08eaa8915b3b725ce60ecf5dc727173f66dca0 Mon Sep 17 00:00:00 2001 From: Dot Date: Sat, 21 Nov 2026 07:00:18 +1300 Subject: [PATCH 082/199] Qualify summary attempt rows and fence recovery outcomes --- .github/workflows/static-analysis-summary.yml | 4 +- .../tests/static-analysis-summary-contract.sh | 2 +- .../InitialGameplayReleaseJournal.java | 7 +- .../JooqInitialGameplayReleaseJournal.java | 73 ++++------ .../InitialGameplayReleaseController.java | 16 +-- ...ReleaseJournalPostgresIntegrationTest.java | 135 ++++++++++-------- .../InitialGameplayReleaseControllerTest.java | 37 +++-- 7 files changed, 130 insertions(+), 144 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4d80666e4e..7aab1928df 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -195,7 +195,9 @@ jobs: throw new Error("Static summary candidate jobs are incomplete."); } const mismatched = data.jobs.some(job => !Number.isSafeInteger(job?.id) || job.id <= 0 || - job.run_id !== candidate.id || job.run_attempt !== candidate.run_attempt || job.head_sha !== headSha); + job.run_id !== candidate.id || + (job.run_attempt !== undefined && job.run_attempt !== candidate.run_attempt) || + job.head_sha !== headSha); const evidenceNames = [gateName, ...(workflowId === "codeql.yml" ? [ ...detailChecks.map(([, name]) => name), "CodeQL Analysis ($" + "{{ matrix.language }})", ] : [])]; diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index e416c0c16d..7905a6fe61 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -169,7 +169,7 @@ const github = { jobRequests.push(input); if (input.per_page !== 100) throw new Error("candidate must use bounded jobs"); const fromAttempt = (row) => ({ - ...row, run_id: input.run_id, run_attempt: input.attempt_number, head_sha: currentHeadSha, + ...row, run_id: input.run_id, head_sha: currentHeadSha, }); if (input.run_id === 270) { return {data: {total_count: 1, jobs: [fromAttempt({id: 2701, diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java index 8c8de6132b..7432dffebe 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java @@ -32,14 +32,11 @@ Operation bindVerifiedEvidence( OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Instant now); - OutboxEntry recordRetryableEffect( - UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); - /** False only for an exact dispatch superseded after validated durable owner closure. */ boolean recordRetryableEffectForDispatch(OutboxEntry dispatch, String outcomeCode, Instant now); - OutboxEntry recordAmbiguousEffect( - UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now); + /** False only for an exact dispatch superseded after validated durable owner closure. */ + boolean recordAmbiguousEffectForDispatch(OutboxEntry dispatch, String outcomeCode, Instant now); Operation recordEffectReadback( UUID operationId, UUID effectId, UUID attemptId, EffectReadback readback, Instant now); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 6f4c9d0909..2df4e7721c 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -287,67 +287,43 @@ && hasDurableNoEffectClosure(tx, current) } @Override - public OutboxEntry recordRetryableEffect( - UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { - return recordNonterminalEffectOutcome( - operationId, effectId, attemptId, outcomeCode, EffectOutboxState.RETRYABLE, now, null) - .orElseThrow(); + public boolean recordRetryableEffectForDispatch( + OutboxEntry dispatch, String outcomeCode, Instant now) { + return recordNonterminalEffectOutcome(dispatch, outcomeCode, EffectOutboxState.RETRYABLE, now); } @Override - public boolean recordRetryableEffectForDispatch( + public boolean recordAmbiguousEffectForDispatch( OutboxEntry dispatch, String outcomeCode, Instant now) { - Objects.requireNonNull(dispatch, "dispatch must not be null"); - return recordNonterminalEffectOutcome( - dispatch.effect().operationId(), - dispatch.effect().effectId(), - dispatch.lastAttemptId(), - outcomeCode, - EffectOutboxState.RETRYABLE, - now, - dispatch) - .isPresent(); + return recordNonterminalEffectOutcome(dispatch, outcomeCode, EffectOutboxState.AMBIGUOUS, now); } - @Override - public OutboxEntry recordAmbiguousEffect( - UUID operationId, UUID effectId, UUID attemptId, String outcomeCode, Instant now) { - return recordNonterminalEffectOutcome( - operationId, effectId, attemptId, outcomeCode, EffectOutboxState.AMBIGUOUS, now, null) - .orElseThrow(); - } - - private Optional recordNonterminalEffectOutcome( - UUID operationId, - UUID effectId, - UUID attemptId, - String outcomeCode, - EffectOutboxState resultState, - Instant now, - OutboxEntry dispatch) { + private boolean recordNonterminalEffectOutcome( + OutboxEntry dispatch, String outcomeCode, EffectOutboxState resultState, Instant now) { + Objects.requireNonNull(dispatch, "dispatch must not be null"); InitialGameplayReleaseModel.requiredOutcomeCode(outcomeCode); + UUID operationId = dispatch.effect().operationId(); + UUID effectId = dispatch.effect().effectId(); + UUID attemptId = dispatch.lastAttemptId(); return dsl.transactionResult(configuration -> { DSLContext tx = DSL.using(configuration); - Operation operation = dispatch == null ? null : selectOperation(tx, operationId, true); + Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); - if (dispatch != null) { - requireEffectMatchesOperation(current.effect(), operation); - if (dispatch.state() != EffectOutboxState.DISPATCHED - || attemptId == null - || !dispatch.outboxId().equals(current.outboxId()) - || !dispatch.effect().equals(current.effect()) - || !dispatch.payloadDigest().equals(current.payloadDigest())) { - throw conflict("effect dispatch tuple changed"); - } + requireEffectMatchesOperation(current.effect(), operation); + if (dispatch.state() != EffectOutboxState.DISPATCHED + || attemptId == null + || !dispatch.outboxId().equals(current.outboxId()) + || !dispatch.effect().equals(current.effect()) + || !dispatch.payloadDigest().equals(current.payloadDigest())) { + throw conflict("effect dispatch tuple changed"); } if (!Objects.equals(current.lastAttemptId(), attemptId)) { - if (dispatch != null - && hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { - return Optional.empty(); + if (hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { + return false; } throw conflict("effect attempt identity changed"); } - if (dispatch != null && dispatch.attemptCount() != current.attemptCount()) { + if (dispatch.attemptCount() != current.attemptCount()) { throw conflict("effect dispatch generation changed"); } if (current.state() == resultState @@ -355,7 +331,7 @@ && hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { || (current.lastAttemptId() != null && current.state() == EffectOutboxState.RETRYABLE && resultState == EffectOutboxState.AMBIGUOUS)) { - return Optional.of(current); + return true; } if (current.state() != EffectOutboxState.DISPATCHED && !(current.state() == EffectOutboxState.AMBIGUOUS @@ -375,7 +351,8 @@ && hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { operationId, effectId, attemptId); - return Optional.of(selectOutbox(tx, operationId, effectId, false)); + selectOutbox(tx, operationId, effectId, false); + return true; }); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index 98e10c4eae..ccd9334cc0 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -148,12 +148,8 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { applyResult = Objects.requireNonNull(effectPort.apply(dispatched.effect(), attemptId), "applyResult"); } catch (RuntimeException exception) { - journal.recordAmbiguousEffect( - operation.scope().operationId(), - dispatched.effect().effectId(), - attemptId, - "EFFECT_CALL_OUTCOME_UNKNOWN", - clock.instant()); + journal.recordAmbiguousEffectForDispatch( + dispatched, "EFFECT_CALL_OUTCOME_UNKNOWN", clock.instant()); return requireOperation(operation.scope().operationId()); } if (applyResult.status() == ApplyStatus.RETRYABLE_NO_EFFECT @@ -164,12 +160,8 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { return requireOperation(operation.scope().operationId()); } if (applyResult.status() == ApplyStatus.AMBIGUOUS) { - journal.recordAmbiguousEffect( - operation.scope().operationId(), - dispatched.effect().effectId(), - attemptId, - applyResult.outcomeCode(), - clock.instant()); + journal.recordAmbiguousEffectForDispatch( + dispatched, applyResult.outcomeCode(), clock.instant()); return requireOperation(operation.scope().operationId()); } return readBackEffect(operation, dispatched, attemptId); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 8409537636..b9b08b3440 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -139,16 +139,19 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() PublicTransitionTuple resumeTuple = transitionTuple(awaitingResume, TransitionVerb.RESUME); Operation authorized = journal.transition(resumeTuple, base.plusSeconds(4)); assertThat(authorized.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); - OutboxEntry prepare = + OutboxEntry pendingPrepare = journal .findEffect(scope.operationId(), EffectKind.PREPARE_PLAYABLE_STATE_FENCED) .orElseThrow(); - assertThat(prepare.state()).isEqualTo(EffectOutboxState.PENDING); + assertThat(pendingPrepare.state()).isEqualTo(EffectOutboxState.PENDING); UUID prepareAttempt = UUID.randomUUID(); - prepare = + OutboxEntry prepare = journal.claimEffect( - scope.operationId(), prepare.effect().effectId(), prepareAttempt, base.plusSeconds(5)); + scope.operationId(), + pendingPrepare.effect().effectId(), + prepareAttempt, + base.plusSeconds(5)); EffectReadback prepareReadback = new EffectReadback( scope.operationId(), @@ -196,12 +199,10 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() otherAttempt, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); - journal.recordAmbiguousEffect( - scope.operationId(), - prepare.effect().effectId(), - prepareAttempt, - "TRANSPORT_OUTCOME_UNKNOWN", - base.plusSeconds(5)); + assertThat( + journal.recordAmbiguousEffectForDispatch( + prepare, "TRANSPORT_OUTCOME_UNKNOWN", base.plusSeconds(5))) + .isTrue(); Operation releasing = journal.recordEffectReadback( scope.operationId(), @@ -231,15 +232,10 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() .isEqualTo(releasing); assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); assertThat( - journal - .recordAmbiguousEffect( - scope.operationId(), - prepare.effect().effectId(), - prepareAttempt, - "LATE_TRANSPORT_OUTCOME_UNKNOWN", - base.plusSeconds(8)) - .state()) - .isEqualTo(EffectOutboxState.ACKNOWLEDGED); + journal.recordAmbiguousEffectForDispatch( + prepare, "LATE_TRANSPORT_OUTCOME_UNKNOWN", base.plusSeconds(8))) + .isTrue(); + assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); UUID preparedEffectId = prepare.effect().effectId(); String retainedAcknowledgement = storedOutbox(scope.operationId(), preparedEffectId); EffectReadback laterObservation = @@ -285,12 +281,8 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() assertThat(storedOutbox(scope.operationId(), preparedEffectId)) .isEqualTo(retainedAcknowledgement); assertThatThrownBy(() -> - journal.recordAmbiguousEffect( - scope.operationId(), - preparedEffectId, - UUID.randomUUID(), - "WRONG_ATTEMPT", - base.plusSeconds(8))) + journal.recordAmbiguousEffectForDispatch( + withAttempt(prepare, UUID.randomUUID()), "WRONG_ATTEMPT", base.plusSeconds(8))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) .get() @@ -378,12 +370,10 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { journal.claimEffect( scope.operationId(), prepare.effect().effectId(), attemptId, base.plusSeconds(5)); assertThat(dispatched.state()).isEqualTo(EffectOutboxState.DISPATCHED); - journal.recordAmbiguousEffect( - scope.operationId(), - prepare.effect().effectId(), - attemptId, - "TRANSPORT_OUTCOME_UNKNOWN", - base.plusSeconds(6)); + assertThat( + journal.recordAmbiguousEffectForDispatch( + dispatched, "TRANSPORT_OUTCOME_UNKNOWN", base.plusSeconds(6))) + .isTrue(); OutboxEntry retryRead = journal.claimEffect( scope.operationId(), @@ -397,14 +387,14 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { assertThat(journal.find(scope.operationId())).contains(authorized); assertThat(journal.findEffect(scope.operationId(), EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) .isEmpty(); - OutboxEntry definitiveNoEffect = - journal.recordRetryableEffect( - scope.operationId(), - prepare.effect().effectId(), - attemptId, - "OWNER_DECLINED_WITHOUT_EFFECT", - base.plusSeconds(8)); - assertThat(definitiveNoEffect.state()).isEqualTo(EffectOutboxState.RETRYABLE); + assertThat( + journal.recordRetryableEffectForDispatch( + dispatched, "OWNER_DECLINED_WITHOUT_EFFECT", base.plusSeconds(8))) + .isTrue(); + assertThat(journal.findNextEffect(scope.operationId())) + .get() + .extracting(OutboxEntry::state) + .isEqualTo(EffectOutboxState.RETRYABLE); UUID nextAttempt = UUID.randomUUID(); OutboxEntry next = journal.claimEffect( @@ -502,22 +492,13 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(7))) .isEqualTo(authorized); assertThat( - journal - .recordAmbiguousEffect( - scope.operationId(), - effectId, - firstAttempt, - "LATE_TIMEOUT", - base.plusSeconds(7)) - .state()) - .isEqualTo(EffectOutboxState.RETRYABLE); + journal.recordAmbiguousEffectForDispatch( + dispatched, "LATE_TIMEOUT", base.plusSeconds(7))) + .isTrue(); + assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); assertThatThrownBy(() -> - journal.recordAmbiguousEffect( - scope.operationId(), - effectId, - UUID.randomUUID(), - "WRONG_ATTEMPT", - base.plusSeconds(7))) + journal.recordAmbiguousEffectForDispatch( + withAttempt(dispatched, UUID.randomUUID()), "WRONG_ATTEMPT", base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); EffectReadback observedAgain = readbackFor( @@ -590,8 +571,7 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { UUID operationId = dispatched.effect().operationId(); UUID effectId = dispatched.effect().effectId(); UUID attemptId = dispatched.lastAttemptId(); - journal.recordRetryableEffect( - operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(5)); + journal.recordRetryableEffectForDispatch(dispatched, "OWNER_REJECTED", base.plusSeconds(5)); String before = storedOutbox(operationId, effectId); EffectReadback stale = readbackFor( @@ -661,8 +641,7 @@ void unknownReadbackBeforeDefinitiveRejectionAllowsOnlyValidatedSameAttemptClosu "unknown", base.plusSeconds(5)); journal.recordEffectReadback(operationId, effectId, attemptId, unknown, base.plusSeconds(5)); - journal.recordRetryableEffect( - operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(6)); + journal.recordRetryableEffectForDispatch(dispatched, "OWNER_REJECTED", base.plusSeconds(6)); if (variant.equals("missing-digest")) { String retained = storedOutbox(operationId, effectId); assertThatThrownBy(() -> @@ -935,10 +914,12 @@ void retryableEffectWithoutDurableClosurePreservesSameAttemptClaimBehavior() { UUID effectId = dispatched.effect().effectId(); UUID attemptId = dispatched.lastAttemptId(); assertThat( - journal - .recordRetryableEffect( - operationId, effectId, attemptId, "OWNER_REJECTED", base.plusSeconds(5)) - .state()) + journal.recordRetryableEffectForDispatch( + dispatched, "OWNER_REJECTED", base.plusSeconds(5))) + .isTrue(); + assertThat(journal.findNextEffect(operationId)) + .get() + .extracting(OutboxEntry::state) .isEqualTo(EffectOutboxState.RETRYABLE); assertThat(storedOutbox(operationId, effectId)).contains("\"readback_payload\":null"); OutboxEntry retried = @@ -1070,6 +1051,12 @@ void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded OutboxEntry b = journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(6)); String before = storedOutbox(operationId, effectId); + String closedA = storedClosure(a); + assertThat( + journal.recordAmbiguousEffectForDispatch(a, "DELAYED_AMBIGUOUS", base.plusSeconds(7))) + .isFalse(); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat(storedClosure(a)).isEqualTo(closedA); assertThat( journal.recordRetryableEffectForDispatch(a, "DELAYED_NO_EFFECT", base.plusSeconds(7))) .isFalse(); @@ -1205,6 +1192,18 @@ private static OutboxEntry authorizedDispatch(Instant base) { scope.operationId(), pending.effect().effectId(), UUID.randomUUID(), base.plusSeconds(4)); } + private static String storedClosure(OutboxEntry dispatch) { + return java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(c)::text AS row_json" + + " FROM recovery_control.initial_gameplay_release_attempt_closure c" + + " WHERE outbox_id = ? AND attempt_id = ?", + dispatch.outboxId(), + dispatch.lastAttemptId()), + "expected persisted attempt closure") + .get("row_json", String.class); + } + private static String storedOutbox(UUID operationId, UUID effectId) { return java.util.Objects.requireNonNull( dsl.fetchOne( @@ -1334,4 +1333,16 @@ private static InitialGameplayReleaseEvidence evidence(Scope scope) { DIGEST), new RegionLeaseProof("region-a", "lease-identity-51", 10)); } + + private static OutboxEntry withAttempt(OutboxEntry dispatch, UUID attemptId) { + return new OutboxEntry( + dispatch.outboxId(), + dispatch.effect(), + dispatch.payloadDigest(), + dispatch.state(), + dispatch.attemptCount(), + attemptId, + dispatch.lastOutcomeCode(), + dispatch.acknowledgedAt()); + } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index b38c61dc5f..7e17c331fe 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -199,15 +199,20 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { @Test void pendingEffectClaimedByAnotherAttemptDoesNotDispatch() { - assertPendingClaimHandling(false); + assertPendingClaimHandling(false, false); } @Test void pendingEffectApplyExceptionRecordsAmbiguousNotRetryable() { - assertPendingClaimHandling(true); + assertPendingClaimHandling(true, true); } - private void assertPendingClaimHandling(boolean ownsClaim) { + @Test + void pendingEffectAmbiguousResultUsesClaimedDispatch() { + assertPendingClaimHandling(true, false); + } + + private void assertPendingClaimHandling(boolean ownsClaim, boolean transportException) { var journal = mock(InitialGameplayReleaseJournal.class); var port = mock(InitialGameplayReleaseEffectPort.class); var operation = mock(Operation.class); @@ -230,6 +235,8 @@ private void assertPendingClaimHandling(boolean ownsClaim) { .thenReturn(java.util.Optional.of(operation), java.util.Optional.of(after)); when(journal.findNextEffect(operationId)).thenReturn(java.util.Optional.of(pending)); var claimedAttempt = new java.util.concurrent.atomic.AtomicReference(); + var claimed = + mock(net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry.class); when(journal.claimEffect( org.mockito.ArgumentMatchers.eq(operationId), org.mockito.ArgumentMatchers.eq(effectId), @@ -238,10 +245,6 @@ private void assertPendingClaimHandling(boolean ownsClaim) { .thenAnswer(invocation -> { UUID requested = invocation.getArgument(2); claimedAttempt.set(requested); - var claimed = - mock( - net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.OutboxEntry - .class); when(claimed.state()) .thenReturn( net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel @@ -256,9 +259,14 @@ private void assertPendingClaimHandling(boolean ownsClaim) { if (ownsClaim) when(claimed.effect()).thenReturn(effect); return claimed; }); - if (ownsClaim) + if (ownsClaim && transportException) { when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) .thenThrow(new IllegalStateException("response lost after possible owner send")); + } else if (ownsClaim) { + when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) + .thenReturn( + InitialGameplayReleaseEffectPort.EffectApplyResult.ambiguous("OWNER_PENDING")); + } var controller = new InitialGameplayReleaseController( journal, @@ -267,21 +275,20 @@ private void assertPendingClaimHandling(boolean ownsClaim) { port); assertThat(controller.reconcileNextEffect(operationId)).isSameAs(after); assertThat(claimedAttempt.get()).isNotNull(); - verify(journal, never()).recordRetryableEffect(any(), any(), any(), any(), any()); + verify(journal, never()).recordRetryableEffectForDispatch(any(), any(), any()); verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); if (ownsClaim) { verify(port).apply(effect, claimedAttempt.get()); verify(port, never()).readback(any(), any()); verify(journal) - .recordAmbiguousEffect( - org.mockito.ArgumentMatchers.eq(operationId), - org.mockito.ArgumentMatchers.eq(effectId), - org.mockito.ArgumentMatchers.eq(claimedAttempt.get()), - org.mockito.ArgumentMatchers.eq("EFFECT_CALL_OUTCOME_UNKNOWN"), + .recordAmbiguousEffectForDispatch( + org.mockito.ArgumentMatchers.same(claimed), + org.mockito.ArgumentMatchers.eq( + transportException ? "EFFECT_CALL_OUTCOME_UNKNOWN" : "OWNER_PENDING"), any()); } else { verifyNoInteractions(port); - verify(journal, never()).recordAmbiguousEffect(any(), any(), any(), any(), any()); + verify(journal, never()).recordAmbiguousEffectForDispatch(any(), any(), any()); } } From 223e6ba76aaffd181f131556637416ca1b55d1fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:51:07 +1300 Subject: [PATCH 083/199] Recognize exact active trusted preview consumers --- .github/workflows/hosted-identity-request.yml | 4 + .github/workflows/preview-reconciler.yml | 82 +++++++++++++++---- .../architecture/system-architecture-cicd.md | 2 + dev-tools/tests/preview-priority-contract.sh | 39 ++++++++- .../preview-runner-isolation-contract.sh | 3 +- 5 files changed, 111 insertions(+), 19 deletions(-) diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index b022e690c1..9d89a8059e 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -427,6 +427,10 @@ jobs: echo "cleanup_state=${CLEANUP_STATE}" } >> "$GITHUB_OUTPUT" + - name: Trusted preview deploy tuple pr-${{ steps.target.outputs.pr_number }} base-${{ steps.target.outputs.base_sha }} head-${{ steps.target.outputs.head_sha }} merge-${{ steps.target.outputs.merge_sha }} + if: ${{ steps.target.outputs.action == 'deploy' }} + run: echo 'Validated the exact preview deployment target.' + prepare-runtime: name: Prepare Validated Preview Inputs timeout-minutes: 45 diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 0a136385f9..6f6730e57c 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -390,6 +390,39 @@ jobs: ' <<<"$jobs" >/dev/null || return 1 } + trusted_consumer_has_tuple() { + local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest + # A workflow_run display title is inherited from its source. Use the + # trusted validator's completed attempt evidence to bind the tuple. + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 2 + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 + jq -e --argjson id "$run_id" --argjson workflow_id "$consumer_workflow_id" \ + --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" ' + .id == $id and .workflow_id == $workflow_id and .event == "workflow_run" + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) + ' <<<"$latest" >/dev/null || return 2 + if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi + jq -e --argjson attempt "$attempt" --arg head "$run_head" \ + '.run_attempt == $attempt and .head_sha == $head' <<<"$latest" >/dev/null || return 2 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$run_head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) + and ([$jobs[] | select(.name == "Validate Trusted Preview Target")] | length == 1) + and any($jobs[]; .name == "Validate Trusted Preview Target" and .run_id == $id + and .run_attempt == $attempt and .head_sha == $head and .status == "completed") + ' <<<"$jobs" >/dev/null || return 2 + jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Validate Trusted Preview Target" and .conclusion == "success"); + ([.steps[]? | select(.name | startswith("Trusted preview deploy tuple "))] | length) == 1 + and any(.steps[]?; .name == $tuple and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null || return 1 + } + dispatch_candidates() { while IFS=$'\t' read -r _ pr_number head_sha pr_author pr_base_ref pr_state labels_json_base64; do if ! labels_json="$(printf '%s' "$labels_json_base64" | base64 --decode 2>/dev/null)" || @@ -571,6 +604,7 @@ jobs: jq -c \ --arg workflow_name "${preview_workflow_name}" \ --argjson workflow_id "$preview_workflow_id" \ + --argjson consumer_workflow_id "$consumer_workflow_id" \ --arg repository "$GITHUB_REPOSITORY" \ --arg default_branch "${DEFAULT_BRANCH}" \ --arg pr_title "PR preview ${pr_number}" \ @@ -592,11 +626,12 @@ jobs: error("workflow run entry is malformed") else def positive_int: type == "number" and . > 0 and . == floor; - def native_preview: - .workflow_id == $workflow_id - and .repository.full_name == $repository + def native_same_repo: + .repository.full_name == $repository and .head_repository.full_name == $repository - and (.id | positive_int) and (.run_attempt | positive_int) + and (.id | positive_int) and (.run_attempt | positive_int); + def native_preview: + native_same_repo and .workflow_id == $workflow_id and (.name == $workflow_name or .name == .display_title); def trusted_dispatch: native_preview and .event == "repository_dispatch" @@ -612,13 +647,21 @@ jobs: and (.display_title == $pr_title or (.event == "pull_request" and .display_title == $run_name)) and .head_sha == $head_sha and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1; + def trusted_consumer: + native_same_repo and .workflow_id == $consumer_workflow_id and .event == "workflow_run" + and .head_branch == $default_branch + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.display_title == $pr_title or .display_title == $run_name); .[] | select( ( (.firemud_reconciler_branch_filtered == false) or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) ) - and (trusted_dispatch or provisional_pr) + and (trusted_dispatch or provisional_pr or trusted_consumer) and ( .status == "requested" or .status == "queued" @@ -628,7 +671,7 @@ jobs: ) ) | if trusted_dispatch then {id, exact: true} - else {id, run_attempt, event, exact: false} end + else {id, run_attempt, event, head_sha, exact: false} end end end ' <<<"${active_preview_runs_json}" @@ -642,18 +685,22 @@ jobs: if [[ -z "$active_preview_run_id" ]]; then # A same-head title is not proof: the base can move independently. tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" - while IFS=$'\t' read -r run_id run_attempt run_event; do + consumer_tuple="Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + while IFS=$'\t' read -r run_id run_attempt run_event run_head; do [[ -n "$run_id" ]] || continue - if automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event"; then + lookup_status=0 + if [[ "$run_event" == workflow_run ]]; then + trusted_consumer_has_tuple "$run_id" "$run_attempt" "$run_head" "$consumer_tuple" || lookup_status=$? + else + automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + fi + if [[ "$lookup_status" -eq 0 ]]; then active_preview_run_id="$run_id" break - else - lookup_status=$? - if [[ "$lookup_status" -eq 2 ]]; then - active_preview_lookup_unknown=true - fi + elif [[ "$lookup_status" -eq 2 ]]; then + active_preview_lookup_unknown=true fi - done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt, .event] | @tsv' <<<"$preview_candidates") + done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt, .event, .head_sha] | @tsv' <<<"$preview_candidates") fi if [[ -n "${active_preview_run_id}" ]]; then @@ -784,6 +831,13 @@ jobs: echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 exit 1 fi + if ! consumer_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/hosted-identity-request.yml" | jq -er ' + select(.name == "Trusted Hosted Identity Request" and .path == ".github/workflows/hosted-identity-request.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical trusted preview consumer identity; refusing preview reconcile." >&2 + exit 1 + fi dispatch_candidates <<<"$candidate_rows" fi diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 16f12648a5..368779c130 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -238,6 +238,8 @@ Hosted verification waits for the complete readiness tuple defined by the owning Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. +Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. + The initial Telnet-first hosted milestone is complete. Continuing preview acceptance follows [ADR 0178](decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md): one shared semantic authenticated, admitted, `LOOK` assertion set is exercised through both the public Telnet path and the deployed first-party browser path. Telnet proves TCP Proxy and bridge/framing behavior. The bounded browser journey proves frontend delivery, HTTPS bootstrap and discovery, connect-token cookie and `/ws/game/**` admission, one reconnect, logout, and non-reuse. Direct backend WebSocket smoke remains CI or diagnostic evidence rather than a substitute or third required hosted path. Dedicated frontend delivery and the browser journey remain implementation gaps, so current TCP/Telnet preview proof is not yet transport-complete. --- diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index f975aeb185..5f71da8b5d 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -434,6 +434,10 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/pre printf '%s\n' '{"id":173511323,"name":"PR Preview Environment","path":".github/workflows/preview.yml"}' exit 0 fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/hosted-identity-request.yml' ]]; then + printf '%s\n' '{"id":357129350,"name":"Trusted Hosted Identity Request","path":".github/workflows/hosted-identity-request.yml"}' + exit 0 +fi if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request\&status=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then active_query_status="${resource##*&status=}" active_query_status="${active_query_status%%&*}" @@ -481,6 +485,14 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254' ]] printf '%s' "${FAKE_PREVIEW_SOURCE_LATEST_JSON:-null}" exit 0 fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5256/attempts/1/jobs?per_page=100' ]]; then + printf '%s' "${FAKE_TRUSTED_CONSUMER_JOBS_JSON:-null}" + exit 0 +fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5256' ]]; then + printf '%s' "${FAKE_TRUSTED_CONSUMER_LATEST_JSON:-null}" + exit 0 +fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then printf '%s\n' "$*" >> "$FAKE_DISPATCH_LOG" exit 0 @@ -2626,17 +2638,31 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att fi done -for observation_case in duplicate-rows workflow-run-only; do +for observation_case in duplicate-rows workflow-run-only consumer-title-only consumer-stale-attempt; do reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" +consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id:357129350, + path:".github/workflows/hosted-identity-request.yml",name:"Trusted Hosted Identity Request", + head_branch:"develop",head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",display_title:"PR preview 901", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},status:"in_progress"}')" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_TRUSTED_CONSUMER_JOBS_JSON="$(jq -cn \ + --arg observation "$observation_case" \ + --arg tuple "Trusted preview deploy tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" ' + {total_count:1,jobs:[{name:"Validate Trusted Preview Target",run_id:5256,run_attempt:1, + head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",status:"completed",conclusion:"success", + steps:[{name:(if $observation == "consumer-title-only" then "Verify workflow source and immutable PR metadata" else $tuple end), + status:"completed",conclusion:"success"}]}]}')" \ + FAKE_TRUSTED_CONSUMER_LATEST_JSON="$(jq -c --arg observation "$observation_case" \ + 'if $observation == "consumer-stale-attempt" then .run_attempt = 2 else . end' <<<"$consumer_run")" \ FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ --arg observation "$observation_case" \ + --argjson consumer "$consumer_run" \ --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" ' [{workflow_runs:( if $observation == "duplicate-rows" then @@ -2647,18 +2673,23 @@ reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-adva display_title:$title} | [. + {status:"queued"}, . + {status:"in_progress"}] else - [{id:5256,event:"workflow_run",path:".github/workflows/hosted-identity-request.yml", - name:"Trusted Hosted Identity Request",head_branch:"develop",display_title:$title,status:"in_progress"}] + [$consumer] end)}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" -if [[ "$observation_case" == duplicate-rows ]]; then +if [[ "$observation_case" == duplicate-rows || "$observation_case" == workflow-run-only ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5256 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_active_status_advance_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +elif [[ "$observation_case" == consumer-stale-attempt ]]; then + grep -Fqx \ + "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ + "$reconciler_active_status_advance_output" + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" else grep -Fqx \ "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index daf75e104b..8bd60cf4a3 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -106,7 +106,8 @@ active_filter = re.search( def active_ids(row: dict[str, Any]) -> str: return subprocess.check_output([ "jq", "-r", "--arg", "workflow_name", "PR Preview Environment", - "--argjson", "workflow_id", "173511323", "--arg", "repository", "benhook1013/FireMUD", + "--argjson", "workflow_id", "173511323", "--argjson", "consumer_workflow_id", "357129350", + "--arg", "repository", "benhook1013/FireMUD", "--arg", "default_branch", "develop", "--arg", "pr_title", "PR preview 7", "--argjson", "pr_number", "7", "--arg", "head_sha", "a" * 40, "--arg", "run_name", "Preview dispatch pr-7-base-b-head-a-merge-c", From f05dc280cc4db009d09183176bc001365946c69a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:51:07 +1300 Subject: [PATCH 084/199] Qualify fresh Redis sockets in issuer lifecycle fixtures --- ...lGameplayIssuerLifecycleProofFixtures.java | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java index 87619a7e73..c526c1f0cd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -6,11 +6,13 @@ import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisException; import io.lettuce.core.RedisURI; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.codec.RedisCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; import io.lettuce.core.protocol.ProtocolVersion; @@ -104,7 +106,7 @@ protected RedisClient createRedisClient(String username, String password) { if (username != null) builder.withAuthentication(username, password); RedisURI uri = builder.build(); uri.setTimeout(Duration.ofSeconds(5)); - RedisClient client = RedisClient.create(uri); + RedisClient client = username == null ? RedisClient.create(uri) : new IssuerFixtureClient(uri); client.setOptions( ClientOptions.builder() .autoReconnect(false) @@ -113,6 +115,47 @@ protected RedisClient createRedisClient(String username, String password) { return client; } + private static final class IssuerFixtureClient extends RedisClient { + private IssuerFixtureClient(RedisURI uri) { + super(null, uri); + } + + @Override + public StatefulRedisConnection connect(RedisCodec codec) { + try { + return connectAndAuthenticate(codec); + } catch (DisconnectedBeforeUse disconnected) { + // A fresh fixture socket can drop before its first command on a loaded runner. + // Only the read-only role probe ran. The owner still executes its commands once. + return connectAndAuthenticate(codec); + } + } + + private StatefulRedisConnection connectAndAuthenticate(RedisCodec codec) { + var connection = super.connect(codec); + try { + if (!OWNER_PRINCIPAL.equals(connection.sync().aclWhoami())) { + throw new IllegalStateException("Issuer fixture connected as an unexpected Redis user"); + } + return connection; + } catch (RedisException failure) { + boolean disconnected = !connection.isOpen(); + connection.close(); + if (disconnected) throw new DisconnectedBeforeUse(failure); + throw failure; + } catch (RuntimeException failure) { + connection.close(); + throw failure; + } + } + + private static final class DisconnectedBeforeUse extends IllegalStateException { + private DisconnectedBeforeUse(RedisException cause) { + super("Issuer fixture Redis socket disconnected before use", cause); + } + } + } + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture() { return newFixture(controlledCandidate(), 0); } From 8f9a2d48610dae129386115db667d606fd7fc9d0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:51:07 +1300 Subject: [PATCH 085/199] Specify recovery readback clock provenance --- .../recovery/service/InitialGameplayReleaseEffectPort.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 1f429409a6..f464f2334b 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -22,6 +22,12 @@ public interface InitialGameplayReleaseEffectPort { * Returns evidence bound to this exact attempt. PROVEN_NO_EFFECT requires the owner to have * durably closed the attempt so a delayed claimant can no longer apply it; absence alone is not * proof. + * + *

AVAILABLE carries the owner's original observation timestamp. The adapter must establish + * that it is comparable with the recovery controller's UTC clock. The journal checks it against + * the persisted dispatch time and the controller's time after receiving the readback. If that + * clock relationship cannot be established, return UNAVAILABLE. Do not replace the observation + * with an adapter or controller receipt timestamp. */ EffectReadbackResolution readback(TypedEffect effect, UUID attemptId); From 1de9b90ea1876f99be0e682ed954c3607bd51de4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:12:56 +1300 Subject: [PATCH 086/199] Close recovery and CI review findings --- .github/workflows/ci.yml | 4 +- .github/workflows/hosted-identity-request.yml | 2 +- .github/workflows/preview-reconciler.yml | 107 ++--- .github/workflows/preview-runtime-refresh.yml | 48 ++- .../protected-pod-admission-proof.yml | 2 +- .github/workflows/runtime-images.yml | 4 +- .github/workflows/smoke.yml | 66 +-- .github/workflows/static-analysis-summary.yml | 30 +- .../system-architecture-backup-recovery.md | 2 +- .../architecture/system-architecture-cicd.md | 4 +- .../hosted/shared/wait-for-runtime-images.sh | 152 ++++--- .../tests/ci-lightweight-scope-contract.sh | 2 + ...d-identity-controller-workflow-contract.sh | 1 - .../pr-required-gate-context-contract.sh | 76 +++- .../tests/pr-retarget-workflow-contract.sh | 161 ++++++-- .../pr-runtime-image-publication-contract.sh | 10 +- dev-tools/tests/preview-priority-contract.sh | 87 ++-- .../preview-runner-isolation-contract.sh | 37 +- .../tests/preview-runtime-refresh.test.cjs | 57 ++- ...otected-pod-admission-workflow-contract.sh | 8 + .../tests/static-analysis-summary-contract.sh | 28 +- .../InitialGameplayReleaseJournal.java | 15 +- .../JooqInitialGameplayReleaseJournal.java | 97 ++++- .../InitialGameplayReleaseController.java | 31 +- .../InitialGameplayReleaseEffectPort.java | 4 + ...itial_gameplay_release_attempt_closure.sql | 8 + ...ReleaseJournalPostgresIntegrationTest.java | 387 +++++++++--------- .../InitialGameplayReleaseControllerTest.java | 90 ++-- 28 files changed, 982 insertions(+), 538 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22fb2ae1f9..eb43bfb061 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -131,9 +131,9 @@ jobs: const entries = await github.paginate(github.rest.pulls.listFiles, { ...context.repo, pull_number: context.payload.pull_request.number, per_page: 100, }, response => response.data); - const knownDoc = path => typeof path === "string" && + const knownDoc = path => path === "README.md" || (typeof path === "string" && /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && - !path.split("/").includes(".."); + !path.split("/").includes("..")); const after = (await github.rest.pulls.get({ ...context.repo, pull_number: eventPr.number, })).data; diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index 9d89a8059e..71b66c971d 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -16,7 +16,7 @@ permissions: jobs: validate-target: name: Validate Trusted Preview Target - if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.name == 'PR Preview Environment' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository) }} + if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch')) || (github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository) }} timeout-minutes: 10 runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 6f6730e57c..36917c32c0 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -244,13 +244,15 @@ jobs: return "$repair_success" } - record_proof_retry() { + prepare_preview_dispatch() { local namespace="$1" local pr_number="$2" local base_sha="$3" local head_sha="$4" local merge_sha="$5" local image_tag="$6" + local require_deployed_tuple="$7" + local priority="$8" local fresh_namespace_json local fresh_namespace_tuple local current_base_sha @@ -278,12 +280,19 @@ jobs: if ! fresh_namespace_json="$( kubectl get namespace "${namespace}" --ignore-not-found -o json )"; then - echo "Unable to recheck namespace ${namespace} before proof retry dispatch." >&2 + echo "Unable to recheck namespace ${namespace} before preview dispatch." >&2 return 1 fi if [[ -z "${fresh_namespace_json}" ]]; then - echo "Skipping PR #${pr_number}: namespace ${namespace} disappeared before proof retry dispatch." >&2 - return 1 + if [[ "$require_deployed_tuple" == true ]]; then + echo "Skipping PR #${pr_number}: namespace ${namespace} disappeared before proof retry dispatch." >&2 + return 1 + fi + if [[ "$priority" != true && "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is full." + return 1 + fi + return 0 fi if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then echo "Skipping PR #${pr_number}: malformed namespace proof-retry evidence; refusing dispatch." >&2 @@ -298,8 +307,11 @@ jobs: "${current_head_sha}" != "${head_sha}" || "${current_merge_sha}" != "${merge_sha}" || "${current_image_tag}" != "${image_tag}" ]]; then - echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 - return 1 + if [[ "$require_deployed_tuple" == true ]]; then + echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 + return 1 + fi + return 0 fi if [[ "${proof_base_sha}" == "${base_sha}" && "${proof_head_sha}" == "${head_sha}" && @@ -341,22 +353,9 @@ jobs: available_slots=$((max_active - active_count)) dispatch_sent=false automatic_preview_has_tuple() { - local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest + local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 2 - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - .jobs as $jobs - | (($jobs | type) == "array") and (.total_count == ($jobs | length)) - and (.total_count < 100) - and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) - and any($jobs[]; - .name == "Preview Plan" and .run_id == $id and .run_attempt == $attempt - and .head_sha == $head and .status == "completed" and .conclusion == "success" - and ([.steps[]? | select(.name | startswith("Preview resolved tuple "))] | length == 1) - and any(.steps[]?; - (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) - and .status == "completed" and .conclusion == "success")) - ' <<<"$jobs" >/dev/null || return 2 + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 jq -e ' type == "object" @@ -367,38 +366,44 @@ jobs: and (.path | type == "string" and length > 0) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) ' <<<"$latest" >/dev/null || return 2 - if jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' - .id == $id and .run_attempt != $attempt and .head_sha == $head + jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' + .id == $id and .head_sha == $head and .event == $event and .workflow_id == $workflow_id and .repository.full_name == $repository and .head_repository.full_name == $repository and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) - and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) - ' <<<"$latest" >/dev/null; then - return 2 - fi - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' - .id == $id and .run_attempt == $attempt and .head_sha == $head - and .event == $event and .workflow_id == $workflow_id - and .repository.full_name == $repository and .head_repository.full_name == $repository - and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 - and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) - and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) ' <<<"$latest" >/dev/null || return 1 + if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi + [[ "$jobs_available" == true ]] || return 2 + jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) + and (.total_count < 100) + and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) + and any($jobs[]; + .name == "Preview Plan" and .run_id == $id and .run_attempt == $attempt + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and ([.steps[]? | select(.name | startswith("Preview resolved tuple "))] | length == 1) + and any(.steps[]?; + (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null || return 2 jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) ' <<<"$jobs" >/dev/null || return 1 } trusted_consumer_has_tuple() { - local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest + local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest jobs_available=true # A workflow_run display title is inherited from its source. Use the # trusted validator's completed attempt evidence to bind the tuple. - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || return 2 + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 jq -e --argjson id "$run_id" --argjson workflow_id "$consumer_workflow_id" \ - --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" ' - .id == $id and .workflow_id == $workflow_id and .event == "workflow_run" + --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" --arg head "$run_head" ' + .id == $id and .workflow_id == $workflow_id and .event == "workflow_run" and .head_sha == $head + and (.run_attempt | type == "number" and . > 0 and . == floor) and .repository.full_name == $repository and .head_repository.full_name == $repository and .head_branch == $default_branch and (.path | IN(".github/workflows/hosted-identity-request.yml", @@ -407,8 +412,8 @@ jobs: and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) ' <<<"$latest" >/dev/null || return 2 if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi - jq -e --argjson attempt "$attempt" --arg head "$run_head" \ - '.run_attempt == $attempt and .head_sha == $head' <<<"$latest" >/dev/null || return 2 + [[ "$jobs_available" == true ]] || return 2 + jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$run_head" ' .jobs as $jobs | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) @@ -686,8 +691,14 @@ jobs: # A same-head title is not proof: the base can move independently. tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" consumer_tuple="Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + lookup_count=0 while IFS=$'\t' read -r run_id run_attempt run_event run_head; do [[ -n "$run_id" ]] || continue + if (( lookup_count >= 3 )); then + active_preview_lookup_unknown=true + break + fi + lookup_count=$((lookup_count + 1)) lookup_status=0 if [[ "$run_event" == workflow_run ]]; then trusted_consumer_has_tuple "$run_id" "$run_attempt" "$run_head" "$consumer_tuple" || lookup_status=$? @@ -700,7 +711,7 @@ jobs: elif [[ "$lookup_status" -eq 2 ]]; then active_preview_lookup_unknown=true fi - done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[:3][] | [.id, .run_attempt, .event, .head_sha] | @tsv' <<<"$preview_candidates") + done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[] | [.id, .run_attempt, .event, .head_sha] | @tsv' <<<"$preview_candidates") fi if [[ -n "${active_preview_run_id}" ]]; then @@ -712,19 +723,17 @@ jobs: continue fi + require_deployed_tuple=false if [[ "${namespace_exists}" == "true" && "${current_base_sha}" == "${base_sha}" && "${current_head_sha}" == "${head_sha}" && "${current_merge_sha}" == "${merge_sha}" && - "${current_image_tag}" == "${image_tag}" && - ("${proof_base_sha}" != "${base_sha}" || - "${proof_head_sha}" != "${head_sha}" || - "${proof_merge_sha}" != "${merge_sha}" || - "${proof_image_tag}" != "${image_tag}" || - -z "${namespace_uid}" || - "${proof_namespace_uid}" != "${namespace_uid}") ]]; then - record_proof_retry "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" || continue + "${current_image_tag}" == "${image_tag}" ]]; then + require_deployed_tuple=true fi + # A consumer may finish deployment and proof during the active-run lookup. + prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ + "$require_deployed_tuple" "$priority" || continue echo "Dispatching preview render for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag}) from trusted ref ${DEFAULT_BRANCH}" gh api \ diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 3cea49c900..c5aa8c7f3d 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -11,7 +11,7 @@ permissions: {} jobs: refresh: - if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event.workflow_run.event == 'pull_request' && (github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == 'failure') && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -44,7 +44,8 @@ jobs: (typeof run.path === 'string' && run.path.startsWith(previewPath + '@') && run.path.length > previewPath.length + 1); if (!pathMatches || - run.event !== 'pull_request' || run.conclusion !== 'success' || + run.event !== 'pull_request' || run.status !== 'completed' || + !['success', 'failure'].includes(run.conclusion) || run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || run.id !== context.payload.workflow_run.id || !sha.test(run.head_sha)) { @@ -85,20 +86,27 @@ jobs: if (plan.run_id !== run.id || plan.run_attempt !== attempt || plan.head_sha !== run.head_sha || plan.status !== 'completed' || plan.conclusion !== 'success' || !Array.isArray(plan.steps)) { - core.info('Preview Plan does not belong to the successful source attempt; no dispatch.'); + core.info('No successful Preview Plan for the exact source attempt; no dispatch.'); return; } - const tupleSteps = plan.steps.filter(step => String(step.name || '').startsWith('Preview event tuple')); - const step = tupleSteps.length === 1 ? tupleSteps[0] : null; - // Native attempt metadata records the event tuple, not authority by itself. - // Bind it to run/head/association and Git merge parents before use. - const recorded = step?.status === 'completed' && step?.conclusion === 'success' - ? String(step.name).match(/^Preview event tuple pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40})$/) - : null; + const recordedTuple = kind => { + const prefix = `Preview ${kind} tuple `; + const steps = plan.steps.filter(step => typeof step?.name === 'string' && step.name.startsWith(prefix)); + const step = steps.length === 1 ? steps[0] : null; + return step?.status === 'completed' && step.conclusion === 'success' + ? step.name.slice(prefix.length).match(/^pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40})$/) + : null; + }; + const recorded = recordedTuple('event'); + const resolved = recordedTuple('resolved'); const sourceNumber = Number(recorded?.[1]); - if (!recorded || !Number.isSafeInteger(sourceNumber) || - recorded[3] !== run.head_sha || !Array.isArray(run.pull_requests)) { - core.info('Missing or invalid immutable preview tuple metadata; await a fresh preview render.'); + // The event tuple supplies initial comparison identity. The successful + // resolved marker proves the plan selected an eligible deployment. + if (!recorded || !resolved || !Number.isSafeInteger(sourceNumber) || + (run.path !== previewPath && run.path !== `${previewPath}@refs/pull/${sourceNumber}/merge`) || + recorded[3] !== run.head_sha || resolved[3] !== run.head_sha || + resolved[1] !== recorded[1] || !Array.isArray(run.pull_requests)) { + core.info('Missing or invalid immutable eligible preview tuple metadata; await a fresh preview plan.'); return; } const associations = run.pull_requests.filter(item => item?.number === sourceNumber); @@ -159,12 +167,14 @@ jobs: core.info('Current merge is not the exact current base/head tuple; no dispatch.'); return; } - // An event can retain an older base while its merge SHA already - // identifies the current test merge. Admit that mismatch only when - // both independent GitHub reads prove the exact same current merge. - if (recordedMerge.parents[0].sha !== recorded[2] && - (recordedMerge.sha !== merge.sha || recordedMerge.parents[0].sha !== base.object.sha)) { - core.info('Recorded preview merge does not prove its base/head tuple; no dispatch.'); + const resolvedMatchesRecorded = resolved[4] === recordedMerge.sha && + resolved[2] === recordedMerge.parents[0].sha; + const resolvedMatchesCurrent = resolved[4] === merge.sha && resolved[2] === base.object.sha; + // A stale event base can accompany a newer historical merge. Its + // plan must independently resolve that merge and its actual parent. + if ((!resolvedMatchesRecorded && !resolvedMatchesCurrent) || + (recordedMerge.parents[0].sha !== recorded[2] && !resolvedMatchesRecorded)) { + core.info('Resolved preview tuple does not match its verified merge parents; no dispatch.'); return; } // Reuse the canonical default-branch path classifier rather than diff --git a/.github/workflows/protected-pod-admission-proof.yml b/.github/workflows/protected-pod-admission-proof.yml index 9b6d7888d7..1955820a29 100644 --- a/.github/workflows/protected-pod-admission-proof.yml +++ b/.github/workflows/protected-pod-admission-proof.yml @@ -186,7 +186,7 @@ jobs: | jq -er '.serverVersion.gitVersion')" expected_server_version="${KIND_NODE_IMAGE#*:v}" expected_server_version="${expected_server_version%%@*}" - [[ "${server_version#v}" == "$expected_server_version"* ]] || { + [[ "$server_version" == "v${expected_server_version}" ]] || { echo "Kubernetes API version did not match the pinned kind node image" >&2 exit 1 } diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 12813ac28b..7053485ce6 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -57,8 +57,8 @@ permissions: # Cancellation precedes admission: isolate all PR inputs by exact tuple and # let an existing producer finish when duplicate requests arrive. 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' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') && format('branch-{0}', github.event.workflow_run.head_branch)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('ci-push-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} - # Only successful publication callbacks can displace a protected-branch publisher. + 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' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') && format('branch-{0}-sha-{1}-ci-{2}-attempt-{3}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('ci-push-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + # Only duplicate delivery of the same successful push attempt can displace its branch publisher. cancel-in-progress: ${{ 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') }} jobs: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 37f29e56d6..767973543c 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -526,6 +526,16 @@ jobs: class TerminalGitHubRequestError extends Error {} + function isTransientOptionalGitHubError(error) { + const status = error?.status ?? error?.response?.status; + const code = error?.code ?? error?.cause?.code; + return !(error instanceof TerminalGitHubRequestError) && (retryableStatuses.has(status) || + (status == null && [ + "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", + "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", + ].includes(code))); + } + async function withTransientGitHubRetry(label, operation) { const maxAttempts = 4; let retryDelayMs = 1000; @@ -562,7 +572,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "d104522a14446575e61675897a300e387b2f50f3d1c918509751aad3a150b057"; + const canonicalRuntimeWorkflowSha256 = "d237e316d765c6f0c2ec5569af93cbaf218d1f9c65e0877eec1ed2f87c6a0457"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", @@ -1171,6 +1181,18 @@ jobs: retryPrimary: retryPrimary?.identity === identityKey(currentIdentity) ? retryPrimary : null, }; retryPrimary = null; + async function resumePendingPrimary(message) { + const remainingMs = timeoutMs - (Date.now() - started); + if (!selection.pendingPrimary || remainingMs <= 0) return false; + core.warning(message); + retryPrimary = { + id: selection.pendingPrimary.id, + run_attempt: selection.pendingPrimary.run_attempt, + identity: identityKey(currentIdentity), + }; + await new Promise((resolve) => setTimeout(resolve, Math.min(sleepMs, remainingMs))); + return true; + } let matching = await findMatchingRuntimeImagesRun( currentIdentity.sourceEvent, expectedDisplayTitle, @@ -1234,13 +1256,7 @@ jobs: "repository_dispatch", expectedDisplayTitle, currentIdentity ); } catch (error) { - const status = error?.status ?? error?.response?.status; - const code = error?.code ?? error?.cause?.code; - const networkFailure = status == null && [ - "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", - "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", - ].includes(code); - if (!retryableStatuses.has(status) && !networkFailure) throw error; + if (!isTransientOptionalGitHubError(error)) throw error; core.warning("Trusted refresh inventory is unavailable; retain the native wait."); } try { @@ -1356,20 +1372,12 @@ jobs: ) ); } catch (error) { - const status = error?.status ?? error?.response?.status; - if (!selection.pendingPrimary || !retryableStatuses.has(status)) throw error; // Re-read the pending comparison on the next bounded poll. No // partial evidence from this alternative carries into that poll. - core.warning( + if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( `Runtime alternative ${matching.id} jobs are temporarily unavailable; retry exact primary selection.` - ); - retryPrimary = { - id: selection.pendingPrimary.id, - run_attempt: selection.pendingPrimary.run_attempt, - identity: identityKey(currentIdentity), - }; - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; + )) continue smokeGatePolling; + throw error; } if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) { return; @@ -1421,8 +1429,10 @@ jobs: )); continue; } - // A rerun may have superseded the attempt whose snapshot never materialized. - // Only the same run's provably newer attempt warrants reselection. + if (await resumePendingPrimary( + `Runtime alternative ${matching.id} never exposed a complete smoke snapshot; retry exact primary selection.` + )) continue smokeGatePolling; + // With no pending primary, only the same run's provably newer attempt warrants reselection. const { data: latestSnapshotAttempt } = await withTransientGitHubRetry( "runtime attempt lookup after incomplete smoke snapshot", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) @@ -1522,16 +1532,10 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) )); } catch (error) { - const status = error?.status ?? error?.response?.status; - if (!selection.pendingPrimary || !retryableStatuses.has(status)) throw error; - core.warning(`Runtime alternative ${matching.id} final attempt is temporarily unavailable; retry exact primary selection.`); - retryPrimary = { - id: selection.pendingPrimary.id, - run_attempt: selection.pendingPrimary.run_attempt, - identity: identityKey(currentIdentity), - }; - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; + if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( + `Runtime alternative ${matching.id} final attempt is temporarily unavailable; retry exact primary selection.` + )) continue smokeGatePolling; + throw error; } if (!positiveInteger(matching.run_attempt) || currentAttempt.id !== matching.id || currentAttempt.run_attempt !== matching.run_attempt || diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 7aab1928df..fa300ba9e6 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -335,21 +335,6 @@ jobs: return Number(comment.id) < Number(oldest.id) ? comment : oldest; }, null); - const { data: finalPullRequest } = await github.rest.pulls.get({ - ...context.repo, - pull_number: issueNumber, - }); - if ( - finalPullRequest.state !== "open" || - finalPullRequest.head?.repo?.id !== sourceRepositoryId || - finalPullRequest.head?.ref !== sourceBranch || - finalPullRequest.head?.sha !== headSha || - finalPullRequest.base?.sha !== baseSha - ) { - core.info("The pull-request base or head changed while static analysis was being summarized."); - return; - } - // Reruns can advance a producer without changing the PR tuple. for (const run of Object.values(workflowRuns)) { if (!run) continue; @@ -365,6 +350,20 @@ jobs: } } + const comparisonIsCurrent = async () => { + const { data: current } = await github.rest.pulls.get({ + ...context.repo, + pull_number: issueNumber, + }); + const matches = current.state === "open" && + current.head?.repo?.id === sourceRepositoryId && current.head?.ref === sourceBranch && + current.head?.sha === headSha && current.base?.sha === baseSha && + current.base?.ref === currentPullRequest.base?.ref; + if (!matches) core.info("The pull-request base or head changed while static analysis was being summarized."); + return matches; + }; + if (!(await comparisonIsCurrent())) return; + if (existing && existing.body !== body) { await github.rest.issues.updateComment({ ...context.repo, @@ -381,6 +380,7 @@ jobs: for (const comment of summaryComments) { if (comment.id === existing?.id) continue; + if (!(await comparisonIsCurrent())) return; try { await github.rest.issues.deleteComment({ ...context.repo, diff --git a/design/architecture/system-architecture-backup-recovery.md b/design/architecture/system-architecture-backup-recovery.md index 24916008f4..d1a01315d9 100644 --- a/design/architecture/system-architecture-backup-recovery.md +++ b/design/architecture/system-architecture-backup-recovery.md @@ -90,7 +90,7 @@ The typed `initial-gameplay-recover/v1` request binds the control-plane request, Activation still requires real Account authorization/redemption, authenticated owner association/storage verification, an independently proved exclusive maintenance fence and actual acquired lock, genuine current owner evidence/readbacks, and approved isolated deployment/restore topology. A random journal UUID is not a lock or exclusion proof. Later continuation and resume bind the exact retained scope, lock, phase, and evidence; ambiguous effects cannot authorize redispatch or final handoff. Source-level journal tests do not establish these missing end-to-end prerequisites or player-facing recovery readiness. -Owner readback is bound to the exact effect attempt. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. +Outcomes and readbacks are bound to the exact effect attempt and dispatch generation. A definite owner rejection permanently retires that attempt ID, while a locally proved no-send outcome permits another dispatch generation with the same ID. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. A current readback carries an original owner observation time comparable to the controller clock. When newer partial evidence supersedes a definitive observation, progress requires fresh authoritative evidence from the owner. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. The exclusive-fence activation work must also prove the region lease belongs to the requested scope, prevent or reject lease replacement between evidence read and journal authorization/effect application, and define an audited restart or abandonment path after lease replacement that never releases the maintenance fence prematurely. Those owner protocols are not implemented by the source-only journal; a retained evidence snapshot is not a current lease lock. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 368779c130..6d94b497fa 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -228,7 +228,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata, binds the unique tuple step to the native run head and uniquely matching PR association, checks the recorded merge parents, and compares its recorded base with the current branch ref instead of treating mutable API association fields as event history. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata and requires both the immutable event tuple and the eligible deployment plan’s resolved tuple. It binds them to the native run head and unique PR association, independently verifies the recorded and current merge parents, and uses the branch ref for current base authority. A failed render can still trigger repair after a successful eligible plan. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate the additive path-specific policy update: retain `pull_request_target` and `repository_dispatch` and add `pull_request`. Verify fresh natural PR and manual-dispatch events against the merged code; the documentation change itself neither grants authorization nor changes that policy. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. @@ -238,7 +238,7 @@ Hosted verification waits for the complete readiness tuple defined by the owning Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. -Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. +Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. The initial Telnet-first hosted milestone is complete. Continuing preview acceptance follows [ADR 0178](decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md): one shared semantic authenticated, admitted, `LOOK` assertion set is exercised through both the public Telnet path and the deployed first-party browser path. Telnet proves TCP Proxy and bridge/framing behavior. The bounded browser journey proves frontend delivery, HTTPS bootstrap and discovery, connect-token cookie and `/ws/game/**` admission, one reconnect, logout, and non-reuse. Direct backend WebSocket smoke remains CI or diagnostic evidence rather than a substitute or third required hosted path. Dedicated frontend delivery and the browser journey remain implementation gaps, so current TCP/Telnet preview proof is not yet transport-complete. diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index bf9daa6833..34cddf402d 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -166,7 +166,11 @@ for run in ranked[:8] if alternates else ranked[:1]: } fetch_publisher_runs() { - python3 - "${GITHUB_REPOSITORY}" "$1" "$2" "$3" <<'PY_PUBLISHERS' + local -a bound=() + if [[ -n "${4:-}" ]]; then + bound=(timeout --kill-after=1s "$4") + fi + "${bound[@]}" python3 - "${GITHUB_REPOSITORY}" "$1" "$2" "$3" <<'PY_PUBLISHERS' import json import re import subprocess @@ -273,7 +277,9 @@ if wait_mode == "pull-request": else: matching_runs = [] if len(sys.argv) > 7: - matching_runs = [run for run in matching_runs if run.get("event") == "repository_dispatch" + event, title = sys.argv[7:9] + matching_runs = [run for run in matching_runs if run.get("event") == event + and run.get("display_title") == title and run.get("status") == "completed" and run.get("conclusion") == "success"] if not matching_runs: print("missing") @@ -291,47 +297,63 @@ print( ' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" } -# Only a source-ID-bound typed callback with positive native publication proof -# can finish the wait ahead of a competing producer. Skipped publication cannot. +fetch_alternate_run_metadata() { + local lookup_deadline="$1" + local remaining=$((lookup_deadline - SECONDS)) + (( remaining > 0 )) || return 1 + timeout --kill-after=1s "$remaining" gh api "$2" +} + +# A typed publication binds the source run ID. A native callback binds the +# immutable tuple, which the trusted publisher revalidates before writing. +# Both paths need a positive publication step in the exact current attempt. use_completed_duplicate_publication() { - local state older_id older_created inventory upper line publisher_id run attempt jobs latest publisher_path default_branch repository_info - IFS=$'\t' read -r state older_id _ _ _ _ older_created <<<"$1" + local state older_id older_created source_event inventory upper line publisher_id run attempt jobs latest publisher_path default_branch repository_info + local source_state="$1" lookup_deadline="$2" remaining + local source source_attempt source_title source_latest publisher_event expected_title + IFS=$'\t' read -r state older_id _ _ _ source_event older_created <<<"$source_state" [[ "$state" == "found" ]] || return 1 - local source source_attempt source_latest - source="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 - [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source" | read_run_state)" == "$1" ]] || return 1 - source_attempt="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' + source="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source" | read_run_state)" == "$source_state" ]] || return 1 + source_title="$(jq -er '.display_title | select(type == "string")' <<<"$source")" || return 1 + source_attempt="$(jq -er --arg repo "$GITHUB_REPOSITORY" --arg head "$head_sha" ' select(.repository.full_name == $repo and .head_repository.full_name == $repo) + | select(.event != "pull_request" or .head_sha == $head) | .run_attempt | select(type == "number" and . >= 1 and floor == .) ' <<<"$source")" || return 1 + if [[ "$source_event" == "pull_request" ]]; then + publisher_event="workflow_run" + expected_title="Publish PR Runtime Images ${source_title}" + else + publisher_event="repository_dispatch" + expected_title="Publish PR Runtime Images source-run-${older_id}" + fi upper="$(date -u +%Y-%m-%dT%H:%M:%SZ)" || return 1 - inventory="$(fetch_publisher_runs repository_dispatch "$older_created" "$upper")" || return 1 - line="$(read_publisher_state "$older_id" completed-typed <<<"$inventory")" || return 1 + remaining=$((lookup_deadline - SECONDS)) + (( remaining > 0 )) || return 1 + inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || return 1 + line="$(read_publisher_state "$older_id" "$publisher_event" "$expected_title" <<<"$inventory")" || return 1 IFS=$'\t' read -r state publisher_id _ <<<"$line" [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ ]] || return 1 - run="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 + run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || return 1 - default_branch="" - if [[ "$publisher_path" != ".github/workflows/publish-pr-runtime-images.yml" ]]; then - # GitHub may qualify the path by its short ref. A typed dispatch runs - # on the repository default; bind any suffix to that authoritative ref. - [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@"* ]] || return 1 - repository_info="$(gh api "repos/${GITHUB_REPOSITORY}")" || return 1 - default_branch="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' - select(.full_name == $repo) | .default_branch - | select(type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._/-]*$")) - ' <<<"$repository_info")" || return 1 - [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || return 1 - fi + repository_info="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}")" || return 1 + default_branch="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' + select(.full_name == $repo) | .default_branch + | select(type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._/-]*$")) + ' <<<"$repository_info")" || return 1 + # Either event runs on the default branch; a short path suffix must agree. + [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || + "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || return 1 attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ - --arg title "Publish PR Runtime Images source-run-${older_id}" ' - select(.id == $id and .event == "repository_dispatch" and .display_title == $title - and .path == $path and ($branch == "" or .head_branch == $branch) + --arg title "$expected_title" --arg event "$publisher_event" ' + select(.id == $id and .event == $event and .display_title == $title + and .path == $path and .head_branch == $branch and .repository.full_name == $repo and .head_repository.full_name == $repo and .status == "completed" and .conclusion == "success") | .run_attempt | select(type == "number" and . >= 1 and floor == .) ' <<<"$run")" || return 1 - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 + jobs="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' (.jobs | type == "array") and (.total_count == (.jobs | length)) and ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | @@ -341,20 +363,38 @@ use_completed_duplicate_publication() { ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) ' <<<"$jobs" >/dev/null || return 1 - latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 - jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" ' + latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" \ + --arg title "$expected_title" --arg event "$publisher_event" --arg repo "$GITHUB_REPOSITORY" ' .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" - and .path == $path and ($branch == "" or .head_branch == $branch) + and .path == $path and .head_branch == $branch and .event == $event and .display_title == $title + and .repository.full_name == $repo and .head_repository.full_name == $repo ' <<<"$latest" >/dev/null || return 1 - source_latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 - jq -e --argjson attempt "$source_attempt" '.run_attempt == $attempt' <<<"$source_latest" >/dev/null || return 1 - [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$1" ]] || return 1 - printf 'Trusted PR image publisher %s succeeded for %s before a duplicate producer.\n' "$publisher_id" "$image_tag" + source_latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 + jq -e --argjson attempt "$source_attempt" --arg repo "$GITHUB_REPOSITORY" --arg title "$source_title" --arg head "$head_sha" ' + .run_attempt == $attempt and .repository.full_name == $repo and .head_repository.full_name == $repo + and .display_title == $title and (.event != "pull_request" or .head_sha == $head) + ' <<<"$source_latest" >/dev/null || return 1 + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$source_state" ]] || return 1 + (( SECONDS < lookup_deadline )) || return 1 + printf 'Trusted PR image publisher %s succeeded for %s via an alternate producer.\n' "$publisher_id" "$image_tag" +} + +find_completed_alternate_publication() { + local alternate_sources="$1" lookup_deadline="$2" older_state + while IFS= read -r older_state; do + (( SECONDS < lookup_deadline )) || break + if use_completed_duplicate_publication "$older_state" "$lookup_deadline"; then + return 0 + fi + done <<<"$alternate_sources" + return 1 } wait_for_pr_publisher() { local source_run_id="$1" local source_created_at="$2" + local alternate_sources="$3" local coverage_unavailable=false local publisher_start_epoch="${SECONDS}" local publisher_deadline=$((SECONDS + publisher_timeout_seconds)) @@ -374,22 +414,32 @@ wait_for_pr_publisher() { fi publisher_payload+="${publisher_payload:+,}${event_payload}" done + local state run_id run_status run_conclusion run_url + publisher_payload="[${publisher_payload}]" + publisher_state="" + if [[ "${fetch_failed}" == "false" ]] && + publisher_state="$(read_publisher_state "${source_run_id}" <<<"${publisher_payload}")"; then + IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" + if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then + printf 'Trusted PR image publisher %s succeeded for %s.\n' "${run_id}" "${image_tag}" + return 0 + fi + fi + if find_completed_alternate_publication "$alternate_sources" "$publisher_deadline"; then + return 0 + fi if [[ "${fetch_failed}" == "true" ]]; then coverage_unavailable=true sleep "${sleep_seconds}" continue fi coverage_unavailable=false - publisher_payload="[${publisher_payload}]" - if ! publisher_state="$(read_publisher_state "${source_run_id}" <<<"${publisher_payload}")"; then + if [[ -z "${publisher_state}" ]]; 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}" - if [[ "${state}" == "missing" ]]; then local elapsed_seconds=$((SECONDS - publisher_start_epoch)) if (( elapsed_seconds >= missing_workflow_timeout_seconds )); then @@ -403,10 +453,6 @@ wait_for_pr_publisher() { continue fi - if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then - 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 @@ -464,21 +510,19 @@ while (( SECONDS < deadline )); do continue fi - if [[ "$wait_mode" == "pull-request" && "$SECONDS" -lt "$deadline" ]] && - older_states="$(read_run_state "$run_id" alternates <<<"$workflow_payload")"; then - while IFS= read -r older_state; do - [[ "$SECONDS" -lt "$deadline" ]] || break - if use_completed_duplicate_publication "$older_state"; then - exit 0 - fi - done <<<"$older_states" + older_states="" + if [[ "$wait_mode" == "pull-request" && "$SECONDS" -lt "$deadline" ]]; then + if older_states="$(read_run_state "$run_id" alternates <<<"$workflow_payload")" && + find_completed_alternate_publication "$older_states" "$deadline"; then + exit 0 + fi fi if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then 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_created_at}" "$older_states" fi exit 0 fi diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 81fed32238..77766767f8 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -45,6 +45,8 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput } for (const [entries, count, expected, drift] of [ [[{filename: "design/README.md"}], 1, true], + [[{filename: "README.md"}], 1, true], + [[{filename: "README.md", status: "renamed", previous_filename: "services/new-service/Main.java"}], 1, false], [[{filename: "design/README.md"}], 1, false, "head-before"], [[{filename: "design/README.md"}], 1, false, "head-after"], [[{filename: "design/README.md"}], 1, false, "base-after"], diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 14a3a76769..f9136a4b56 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -1034,7 +1034,6 @@ assert validate_job["if"] == ( "${{ (github.event_name == 'workflow_run' && " "github.event.workflow_run.conclusion == 'success' && " "github.event.workflow_run.head_repository.full_name == github.repository && " - "github.event.workflow_run.name == 'PR Preview Environment' && " "(github.event.workflow_run.event == 'pull_request' || " "github.event.workflow_run.event == 'repository_dispatch')) || " "(github.event_name == 'pull_request_target' && " diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 33f7dd67ef..06f151244b 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -9,8 +9,10 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" # green. Base retargets keep the required name and rerun the full gate. python3 - "$ROOT_DIR" <<'PY' import ast +import os from pathlib import Path import re +import subprocess import sys import yaml @@ -112,11 +114,11 @@ for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{ raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") -def effective_group(group, base_ref): +def effective_group(group, action, base_ref): values = { "github.event.changes.base.ref": repr(base_ref), "github.event.pull_request.number": "42", - "github.event.action": "'edited'", + "github.event.action": repr(action), "github.event_name": "'pull_request'", "github.workflow": "'Required Gate'", "github.run_id": "123", @@ -175,10 +177,14 @@ assert not can_reuse_required_name("CodeQL Analysis (${{ matrix.language }})", { def isolates_metadata_group(group, run_scoped): - metadata = effective_group(group, None) - retarget = effective_group(group, "develop") + metadata = effective_group(group, "edited", None) expected_suffix = "-metadata-123" if run_scoped else "-metadata" - return metadata != retarget and metadata.endswith(expected_suffix) and retarget.endswith("-required") + substantive = [effective_group(group, action, base_ref) for action, base_ref in ( + ("edited", "develop"), ("opened", None), ("synchronize", None), ("reopened", None), + )] + return metadata.endswith(expected_suffix) and all( + name != metadata and name.endswith("-required") for name in substantive + ) def excludes_metadata(expression): @@ -282,6 +288,23 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o raise SystemExit(f"{workflow} {gate_name} result step cannot ignore failures") if "if" in result_steps[0]: raise SystemExit(f"{workflow} {gate_name} result step must run unconditionally") + if workflow == "codeql.yml": + step = result_steps[0] + if step["env"].get("SHOULD_RUN") != "${{ needs.changes.outputs.should_run }}" or \ + step["env"].get("ANALYZE_RESULT") != "${{ needs.analyze.result }}": + raise SystemExit("CodeQL enforcement must use actual detector and analyzer results") + for changes, should_run, analyze, success in ( + ("success", "true", "failure", False), + ("success", "true", "success", True), + ("success", "false", "skipped", True), + ("failure", "false", "skipped", False), + ("success", "", "skipped", False), + ): + outcome = subprocess.run(["bash", "-e", "-c", step["run"]], check=False, capture_output=True, + env={**os.environ, "CHANGES_RESULT": changes, + "SHOULD_RUN": should_run, "ANALYZE_RESULT": analyze}) + if (outcome.returncode == 0) != success: + raise SystemExit(f"CodeQL enforcement returned {outcome.returncode} for {changes}/{should_run}/{analyze}") if any("if" in step and "edited" in step["if"] for step in gate.get("steps", [])): raise SystemExit(f"{workflow} {gate_name} steps must not branch on edits; the job condition owns that") @@ -303,13 +326,15 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o if "github.event.pull_request.number" not in group or META.split(" && ", 1)[1] not in group or suffix not in group: raise SystemExit(f"{workflow} concurrency group must keep metadata runs out of the PR's required namespace") if not isolates_metadata_group(group, run_scoped): - raise SystemExit(f"{workflow} effective metadata and retarget groups must differ") + raise SystemExit(f"{workflow} effective metadata and substantive groups must differ") # The old substring guard would accept this expression despite its bypass. bypassed = group.replace(META, "true && 'required' || " + META, 1) assert bypassed != group and META in bypassed and suffix in bypassed - assert effective_group(bypassed, None) == effective_group(bypassed, "develop"), workflow - assert effective_group(bypassed, None).endswith("-required"), workflow + assert effective_group(bypassed, "edited", None) == effective_group(bypassed, "edited", "develop"), workflow + assert effective_group(bypassed, "edited", None).endswith("-required"), workflow assert not isolates_metadata_group(bypassed, run_scoped), workflow + collided = group.replace(META, f"github.event.action == 'synchronize' || {META}", 1) + assert collided != group and not isolates_metadata_group(collided, run_scoped), workflow if concurrency.get("cancel-in-progress") != "true": raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") PY @@ -656,6 +681,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const cancelledWithReplacement = kind === "optional-final-read-cancelled-with-replacement"; const finalAttemptError = kind.startsWith("optional-final-read-attempt-"); const duplicatePrimary = kind === "optional-final-read-duplicate"; + const disappearingSnapshot = kind === "optional-final-read-incomplete-snapshot"; const badStatus = kind.endsWith("-forbidden") ? 403 : kind.endsWith("-missing") ? 404 : 503; const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && badStatus === 503; const primaryReady = () => primaryCanRecover && primaryInventoryReads > 1; @@ -729,7 +755,8 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal if (runId === 44 && cancelledWithReplacement) return {data: dispatchPrimary}; currentRunReads += 1; if (finalAttemptError && currentRunReads >= 2) { - throw Object.assign(new Error(`alternative final workflow-run HTTP ${badStatus}`), {status: badStatus}); + throw Object.assign(new Error("alternative final workflow-run unavailable"), + kind.endsWith("-network") ? {cause: {code: "ECONNRESET"}} : {status: badStatus}); } if (incompleteSnapshot) { snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; @@ -741,9 +768,16 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); - if (input.run_id === 43 && primaryReady()) return {data: exactPrimary}; - if (cancelledWithReplacement && input.run_id === 44) return {data: dispatchPrimary}; + if (input.run_id === 43 && primaryReady()) { + assert.equal(input.attempt_number, exactPrimary.run_attempt); + return {data: exactPrimary}; + } + if (cancelledWithReplacement && input.run_id === 44) { + assert.equal(input.attempt_number, dispatchPrimary.run_attempt); + return {data: dispatchPrimary}; + } if ((cancelledPrimary || cancelledWithReplacement) && input.run_id === 43) { + assert.equal(input.attempt_number, exactPrimary.run_attempt); return {data: {...source, id: 43, event: "pull_request", status: "completed", conclusion: "cancelled"}}; } assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); @@ -752,17 +786,22 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal 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"); if (input.run_id === 43 && primaryReady()) { + assert.equal(input.attempt_number, exactPrimary.run_attempt); return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } if (cancelledWithReplacement && input.run_id === 44) { + assert.equal(input.attempt_number, dispatchPrimary.run_attempt); return [{...job, run_id: 44, steps: [...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } assert.equal(input.run_id, 42); if (h0 && ++alternativeJobsReads > (cancelledPrimary ? 0 : 2) && !finalAttemptError) { + assert.equal(input.attempt_number, source.run_attempt); if (kind.endsWith("-malformed")) return null; - throw Object.assign(new Error(`H0 alternative final attempt jobs HTTP ${badStatus}`), {status: badStatus}); + if (disappearingSnapshot) return []; + throw Object.assign(new Error("alternative final attempt jobs unavailable"), + kind.endsWith("-network") ? {code: "ECONNRESET"} : {status: badStatus}); } if (finalAttemptError && alternativeJobsReads > 2) { return [{...job, steps: [...job.steps, @@ -844,6 +883,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal } for (const [kind, event, selectionMessage] of [ ["optional-final-read-refresh", "repository_dispatch", "supersedes the pending native wait"], + ["optional-final-read-jobs-network", "repository_dispatch", "supersedes the pending native wait"], ["optional-final-read-duplicate", "pull_request", "precedes the pending duplicate"], ]) { const result = await scenario(kind, event); @@ -869,10 +909,14 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert.equal(cancelledReplacement.alternativeJobsReads, 6, "old dispatch proof exhausts final jobs retries"); assert(cancelledReplacement.info.some(line => line.includes("Found runtime-images run 44 with status=completed"))); assert.deepEqual(cancelledReplacement.failures, []); - const finalAttempt = await scenario("optional-final-read-attempt-transient", "repository_dispatch"); - assert.equal(finalAttempt.primaryInventoryReads, 2, "failed final attempt read resumes the native producer"); - assert(finalAttempt.info.some(line => line.includes("Found runtime-images run 43 with status=completed"))); - assert.deepEqual(finalAttempt.failures, []); + for (const kind of ["optional-final-read-attempt-transient", "optional-final-read-attempt-network", + "optional-final-read-incomplete-snapshot"]) { + const result = await scenario(kind, "repository_dispatch"); + assert.equal(result.primaryInventoryReads, 2, `${kind} resumes the native producer`); + assert(result.info.some(line => line.includes("Found runtime-images run 43 with status=completed")), kind); + assert.deepEqual(result.failures, [], kind); + if (kind.endsWith("-snapshot")) assert.equal(result.alternativeJobsReads, 11, kind); + } for (const [kind, code] of [["optional-final-read-attempt-forbidden", 403], ["optional-final-read-attempt-missing", 404]]) { const result = await scenario(kind, "repository_dispatch", true); assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, code, kind); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index aa3d5897cb..01f9377e09 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -656,6 +656,7 @@ steps = smoke["jobs"]["smoke-gate"]["steps"] classifier = next(step for step in steps if step.get("id") == "smoke_gate_context") failure = next(step for step in steps if step.get("name") == "Fail when smoke dependencies did not succeed") assert failure["if"] == "${{ steps.smoke_gate_context.outputs.execute != 'true' }}" +assert failure.get("continue-on-error") in (None, "false"), "dependency failure must fail the Smoke Gate job" with tempfile.TemporaryDirectory() as directory: output = Path(directory) / "output" for result, expected in (("success", "true"), ("failure", "false")): @@ -763,7 +764,13 @@ for branch in ("main", "develop", "feature/parent"): for branch in ("main", "develop"): publisher = callback_group(branch, 7101, 1, "push") - assert publisher == callback_group(branch, 7102, 2, "push", "b" * 40), "protected push publication must retain branch serialization" + assert callback_group(branch, 7101, 1, "push") == publisher, "duplicate delivery retains the exact publisher group" + next_head = callback_group(branch, 7101, 1, "push", "b" * 40) + next_source = callback_group(branch, 7102, 1, "push") + next_attempt = callback_group(branch, 7101, 2, "push") + assert len({publisher, next_head, next_source, next_attempt}) == 4, ( + "a successful callback may cancel only its exact branch, head, source and attempt" + ) assert callback_group(branch, 7101, 1, "push", selector=runtime["concurrency"]["cancel-in-progress"]) == "True" for conclusion in ("failure", "cancelled", "timed_out", "skipped", ""): nonpublisher = callback_group(branch, 7101, 1, "push", conclusion=conclusion) @@ -2204,16 +2211,24 @@ fi if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then case "$*" in - *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source.json"; exit 0 ;; + *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source-${CONTRACT_DUPLICATE_EVENT:-typed}.json"; exit 0 ;; "api repos/example/FireMUD") printf '%s\n' '{"full_name":"example/FireMUD","default_branch":"develop"}'; exit 0 ;; *actions/runs/202) if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_MARKER:-}" ]]; then : >"$CONTRACT_PUBLISHER_LOOKUP_MARKER" fi - cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-${CONTRACT_DUPLICATE_PATH:-bare}.json" + if [[ "${CONTRACT_DUPLICATE_EVENT:-typed}" == "native" ]]; then + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-native.json" + else + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-${CONTRACT_DUPLICATE_PATH:-bare}.json" + fi exit 0 ;; *actions/runs/202/attempts/2/jobs?per_page=100) + if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then + : >"$CONTRACT_STALLED_LOOKUP_MARKER" + sleep 12 + fi cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-$CONTRACT_DUPLICATE_JOB.json"; exit 0 ;; esac fi @@ -2221,6 +2236,23 @@ fi if [[ "$*" == *"publish-pr-runtime-images.yml"* ]]; then [[ "$*" != *"--paginate"* ]] || { echo 'publisher inventory must be bounded' >&2; exit 1; } if [[ -n "${CONTRACT_PUBLISHER_PAYLOAD:-}" ]]; then + if [[ -n "${CONTRACT_LATE_PUBLISHER_MARKER:-}" ]]; then + if [[ "$*" == *created=2026-07-24T00:05:00Z..* ]]; then + : >"$CONTRACT_LATE_PUBLISHER_MARKER" + printf '%s\n' '{"total_count":0,"workflow_runs":[]}' + exit 0 + elif [[ ! -f "$CONTRACT_LATE_PUBLISHER_MARKER" ]]; then + python3 - "$CONTRACT_PUBLISHER_PAYLOAD" <<'PY_QUEUED' +import json +import sys +payload = json.load(open(sys.argv[1])) +print(json.dumps({"total_count": 1, "workflow_runs": [ + {**payload["workflow_runs"][0], "status": "queued", "conclusion": None} +]})) +PY_QUEUED + exit 0 + fi + fi python3 - "$CONTRACT_PUBLISHER_PAYLOAD" "$*" <<'PY_PAGE' import json import re @@ -2330,21 +2362,29 @@ for conclusion in [None, ""]: base = {"id": 202, "event": "repository_dispatch", "status": "completed", "conclusion": "success", "html_url": "https://example.test/publisher/202", "display_title": "Publish PR Runtime Images source-run-101", "created_at": "2026-07-24T00:04:00Z"} repository = {"full_name": "example/FireMUD"} -(root / "duplicate-inventory.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, source]})) +typed_source = {**source, "event": "repository_dispatch", "head_branch": "develop", "head_sha": "d" * 40} +(root / "duplicate-inventory.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, typed_source]})) +(root / "typed-source-inventory.json").write_text(json.dumps({"workflow_runs": [typed_source]})) +(root / "duplicate-native.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, source]})) +(root / "duplicate-late-publisher.json").write_text(json.dumps({"workflow_runs": [ + {**pending_duplicate, "status": "completed", "conclusion": "success"}, typed_source]})) terminal_duplicate = {**pending_duplicate, "status": "completed", "conclusion": "failure"} -intermediate_duplicate = {**source, "id": 103, "created_at": "2026-07-24T00:04:30Z"} +intermediate_duplicate = {**typed_source, "id": 103, "created_at": "2026-07-24T00:04:30Z"} for name, runs in { - "terminal": [terminal_duplicate, source], - "multi": [pending_duplicate, intermediate_duplicate, source], + "terminal": [terminal_duplicate, typed_source], + "multi": [pending_duplicate, intermediate_duplicate, typed_source], "terminal-no-proof": [terminal_duplicate, intermediate_duplicate], }.items(): (root / f"duplicate-{name}.json").write_text(json.dumps({"workflow_runs": runs})) -(root / "duplicate-source.json").write_text(json.dumps({**source, "run_attempt": 1, - "repository": repository, "head_repository": repository})) +for event, run in {"typed": typed_source, "native": source}.items(): + (root / f"duplicate-source-{event}.json").write_text(json.dumps({**run, "run_attempt": 1, + "repository": repository, "head_repository": repository})) publisher_path = ".github/workflows/publish-pr-runtime-images.yml" publisher = {**base, "run_attempt": 2, "path": publisher_path, "head_branch": "develop", "repository": repository, "head_repository": repository} +native_publisher = {**publisher, "event": "workflow_run", "display_title": "Publish PR Runtime Images " + source["display_title"]} +(root / "duplicate-publisher-native.json").write_text(json.dumps(native_publisher)) for variant, change in { "bare": {}, "qualified": {"path": publisher_path + "@develop"}, @@ -2364,6 +2404,7 @@ for conclusion in ["success", "skipped"]: ]})) fixtures = { "dispatch-success": base, + "callback-success": native_publisher, "dispatch-wrong-source": {**base, "display_title": "Publish PR Runtime Images source-run-999"}, "dispatch-wrong-event": {**base, "event": "push"}, "dispatch-malformed-title": {**base, "display_title": "Publish PR Runtime Images source-run-101 extra"}, @@ -2371,7 +2412,7 @@ fixtures = { "callback-wrong-tuple": {**base, "event": "workflow_run", "display_title": "Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-1 base-" + "d" * 40 + " head-" + "a" * 40 + " merge-" + "c" * 40 + " mode-required"}, } for name, run in fixtures.items(): - (root / (name + ".json")).write_text(json.dumps({"total_count": 1, "fixture_event": "workflow_run" if name == "callback-wrong-tuple" else "repository_dispatch", "workflow_runs": [run]})) + (root / (name + ".json")).write_text(json.dumps({"total_count": 1, "fixture_event": "workflow_run" if name.startswith("callback-") else "repository_dispatch", "workflow_runs": [run]})) # Matching publication remains discoverable beyond the first page. many = [{**base, "id": 300 + index, "display_title": f"Publish PR Runtime Images source-run-{500 + index}"} for index in range(100)] + [base] (root / "dispatch-second-page.json").write_text(json.dumps([{"total_count": 101, "workflow_runs": many[:100]}, {"total_count": 101, "workflow_runs": many[100:]}])) @@ -2381,30 +2422,51 @@ many = [{**base, "id": 300 + index, "display_title": f"Publish PR Runtime Images (root / "dispatch-outside-window.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-07-23T00:00:00Z"}]})) (root / "dispatch-invalid-date.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-02-31T00:00:00Z"}]})) PY_FIXTURES -for conclusion in success skipped; do - if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB="$conclusion" \ - CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ - CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ - PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ - HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ - >"$contract_fixture_dir/duplicate-$conclusion.output" 2>"$contract_fixture_dir/duplicate-$conclusion.error"; then - [[ "$conclusion" == "success" ]] || { echo "Skipped publication step bypassed duplicate wait" >&2; exit 1; } - require_contains "$contract_fixture_dir/duplicate-$conclusion.output" 'Trusted PR image publisher 202 succeeded' - else - [[ "$conclusion" == "skipped" ]] || { cat "$contract_fixture_dir/duplicate-$conclusion.error" >&2; exit 1; } - require_contains "$contract_fixture_dir/duplicate-$conclusion.output" 'Waiting for runtime-images workflow 104' - require_contains "$contract_fixture_dir/duplicate-$conclusion.error" 'Timed out waiting for runtime-images workflow' +# Advance the fixture clock at poll sleeps so API fixture speed cannot govern +# success or timeout. The outer timeout still bounds a broken fixture. +cat >"$contract_fixture_dir/publisher-clock.sh" <<'EOF' +if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then + unset SECONDS + SECONDS=0 + sleep() { + SECONDS=$((SECONDS + 1)) + } +fi +EOF +for event in typed native; do + source_inventory="duplicate-inventory" + publisher_inventory="dispatch-success" + if [[ "$event" == "native" ]]; then + source_inventory="duplicate-native" + publisher_inventory="callback-success" fi + for conclusion in success skipped; do + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT="$event" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB="$conclusion" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$source_inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$publisher_inventory.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/duplicate-$event-$conclusion.output" 2>"$contract_fixture_dir/duplicate-$event-$conclusion.error"; then + [[ "$conclusion" == "success" ]] || { echo "Skipped publication step bypassed duplicate wait" >&2; exit 1; } + require_contains "$contract_fixture_dir/duplicate-$event-$conclusion.output" 'Trusted PR image publisher 202 succeeded' + else + [[ "$conclusion" == "skipped" ]] || { cat "$contract_fixture_dir/duplicate-$event-$conclusion.error" >&2; exit 1; } + require_contains "$contract_fixture_dir/duplicate-$event-$conclusion.output" 'Waiting for runtime-images workflow 104' + require_contains "$contract_fixture_dir/duplicate-$event-$conclusion.error" 'Timed out waiting for runtime-images workflow' + fi + done done for variant in terminal multi terminal-no-proof; do - if CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-$variant.json" \ CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=6 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/competing-$variant.output" 2>"$contract_fixture_dir/competing-$variant.error"; then [[ "$variant" != "terminal-no-proof" ]] @@ -2414,19 +2476,32 @@ for variant in terminal multi terminal-no-proof; do require_contains "$contract_fixture_dir/competing-$variant.error" 'completed with failure' fi done -# Freeze the fixture clock until the waiter actually looks up a publisher. Only -# subsequent poll sleeps consume the budget; the outer timeout bounds fixture bugs. -cat >"$contract_fixture_dir/publisher-clock.sh" <<'EOF' -if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then - unset SECONDS - SECONDS=0 - sleep() { - if [[ -f "$CONTRACT_PUBLISHER_LOOKUP_MARKER" ]]; then - SECONDS=$((SECONDS + 1)) - fi - } -fi -EOF +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_LATE_PUBLISHER_MARKER="$contract_fixture_dir/late-publisher.lookup" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-late-publisher.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/late-publisher.output" +require_contains "$contract_fixture_dir/late-publisher.output" 'Matching runtime-images workflow 104 succeeded' +require_contains "$contract_fixture_dir/late-publisher.output" 'Trusted PR image publisher 202 succeeded' + +stalled_status=0 +CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_STALLED_LOOKUP_MARKER="$contract_fixture_dir/stalled-publisher.lookup" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=4 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 9s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/stalled-publisher.output" 2>"$contract_fixture_dir/stalled-publisher.error" || stalled_status=$? +[[ -f "$contract_fixture_dir/stalled-publisher.lookup" && "$stalled_status" == "1" ]] +require_contains "$contract_fixture_dir/stalled-publisher.error" 'Timed out waiting for runtime-images workflow' + for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do lookup_marker="$contract_fixture_dir/publisher-$variant.lookup" if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ @@ -2464,7 +2539,13 @@ for fixture in missing-url empty-url; do fi done for fixture in dispatch-success dispatch-wrong-source dispatch-wrong-event dispatch-malformed-title dispatch-failure callback-wrong-tuple dispatch-second-page dispatch-overflow dispatch-incomplete dispatch-unstable dispatch-outside-window dispatch-invalid-date; do + if [[ "$fixture" == dispatch-* ]]; then + source_inventory="$contract_fixture_dir/typed-source-inventory.json" + else + source_inventory="" + fi if CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$fixture.json" \ + CONTRACT_SOURCE_PAYLOAD="$source_inventory" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 6b21dbc1ab..b18509cba8 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -96,15 +96,17 @@ check(dispatch, "pr-7-base-base1-head-head1-merge-merge1-required") for event in [base, dispatch, {"event_name": "workflow_dispatch"}, {"event_name": "workflow_run", "event": {"workflow_run": {"event": "pull_request", "head_branch": "develop"}}}]: assert evaluate(event, cancel) == "False", event -def push_callback(branch, conclusion, run_id, attempt): +def push_callback(branch, conclusion, run_id, attempt, head_sha="older"): return {**base, "event_name": "workflow_run", "event": {"workflow_run": { - "event": "push", "head_branch": branch, "conclusion": conclusion, + "event": "push", "head_branch": branch, "head_sha": head_sha, "conclusion": conclusion, "id": run_id, "run_attempt": attempt}}} for branch in ("main", "develop"): event = push_callback(branch, "success", 91, 2) assert evaluate(event, cancel) == "True", event - check(event, f"branch-{branch}-required") + check(event, f"branch-{branch}-sha-older-ci-91-attempt-2-required") + check(push_callback(branch, "success", 97, 1, "newer"), + f"branch-{branch}-sha-newer-ci-97-attempt-1-required") for conclusion, run_id, attempt in (("failure", 92, 1), ("cancelled", 93, 2), ("timed_out", 94, 3), (None, 95, 1)): event = push_callback(branch, conclusion, run_id, attempt) @@ -114,6 +116,8 @@ for branch in ("main", "develop"): nonprotected = push_callback("feature/x", "success", 96, 2) assert evaluate(nonprotected, cancel) == "False", nonprotected check(nonprotected, "ci-push-run-96-attempt-2-required") +assert evaluate(push_callback("Develop", "success", 98, 1)).lower() != \ + evaluate(push_callback("develop", "success", 97, 1)).lower() for value in [0, False, "", None]: invalid = copy.deepcopy(dispatch) diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 5f71da8b5d..a01a56ca04 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -5,6 +5,9 @@ report_contract_failure() { } trap 'report_contract_failure "$?" "$LINENO"' ERR +# Python assertions are part of the contract, including the native tuple markers. +python3 -c 'import sys; sys.exit(0 if __debug__ else "Preview priority contract requires Python assertions; unset PYTHONOPTIMIZE.")' + ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" ALLOCATOR="$ROOT_DIR/dev-tools/hosted/preview/allocate-preview-capacity.sh" PRUNER="$ROOT_DIR/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh" @@ -112,6 +115,7 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && exit 1 fi if [[ "${FAKE_PR_901_NAMESPACE_ABSENT:-false}" == true ]] || + [[ "${FAKE_PR_901_NAMESPACE_ABSENT_ON_INITIAL:-false}" == true && "$count" -eq 1 ]] || [[ "${FAKE_PR_901_NAMESPACE_ABSENT_ON_RECHECK:-false}" == true && "$count" -gt 1 ]]; then exit 0 fi @@ -121,13 +125,13 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && exit 0 fi if [[ -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" ]]; then - rm -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" if [[ "${FAKE_ANNOTATE_CONFIRMATION_ERROR:-false}" == true ]]; then exit 1 fi if [[ "${FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE:-false}" == true ]]; then exit 0 fi + rm -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" fi canonical_head() { case "${1:-}" in @@ -485,12 +489,19 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254' ]] printf '%s' "${FAKE_PREVIEW_SOURCE_LATEST_JSON:-null}" exit 0 fi -if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5256/attempts/1/jobs?per_page=100' ]]; then - printf '%s' "${FAKE_TRUSTED_CONSUMER_JOBS_JSON:-null}" +if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9])/attempts/1/jobs\?per_page=100$ ]]; then + [[ "${FAKE_TRUSTED_CONSUMER_JOBS_FAIL:-false}" != true ]] || exit 1 + run_id="${BASH_REMATCH[1]}" + if [[ "$run_id" == 5256 ]]; then + printf '%s' "${FAKE_TRUSTED_CONSUMER_JOBS_JSON:-null}" + else + jq -c --argjson id "$run_id" '.jobs[] |= (.run_id = $id | .steps[].name |= sub("merge-[0-9a-f]{40}$"; "merge-dddddddddddddddddddddddddddddddddddddddd"))' \ + <<<"${FAKE_TRUSTED_CONSUMER_JOBS_JSON:-null}" + fi exit 0 fi -if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5256' ]]; then - printf '%s' "${FAKE_TRUSTED_CONSUMER_LATEST_JSON:-null}" +if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9])$ ]]; then + jq -c --argjson id "${BASH_REMATCH[1]}" '.id = $id' <<<"${FAKE_TRUSTED_CONSUMER_LATEST_JSON:-null}" exit 0 fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then @@ -2581,7 +2592,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple completed_failed_plan; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2589,7 +2600,8 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att plan_jobs="$(jq -cn --arg tuple "$tuple_name" --arg old "$old_tuple_name" \ --arg head "$preview_head_sha" --arg variant "$tuple_case" ' def step($name): {name:$name,status:"completed",conclusion:"success"}; - [{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head,status:"completed",conclusion:"success", + [{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head,status:"completed", + conclusion:(if $variant == "completed_failed_plan" then "failure" else "success" end), steps:(if $variant == "old_merge" or $variant == "stale_attempt_old_tuple" then [step($old)] elif $variant == "ambiguous" then [step($tuple),step($old)] elif $variant == "event_only" then [step($tuple | sub("resolved"; "event"))] @@ -2603,7 +2615,9 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att {id:5254,run_attempt:(if $variant == "stale_attempt" or $variant == "stale_attempt_old_tuple" then 3 else 2 end), head_sha:$head,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:173511323,repository:{full_name:(if $variant == "wrong_latest_repo" then "example/Other" else "example/FireMUD" end)},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} | if $variant == "latest_missing_head" then del(.head_sha) - elif $variant == "latest_missing_path" then del(.path) else . end')" + elif $variant == "latest_missing_path" then del(.path) + elif $variant == "completed_failed_plan" then .status = "completed" + else . end')" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -2638,19 +2652,29 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att fi done -for observation_case in duplicate-rows workflow-run-only consumer-title-only consumer-stale-attempt; do +for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable; do reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id:357129350, path:".github/workflows/hosted-identity-request.yml",name:"Trusted Hosted Identity Request", head_branch:"develop",head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",display_title:"PR preview 901", repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},status:"in_progress"}')" +namespace_absent_on_initial=false +proof_complete=false +if [[ "$observation_case" == consumer-finished || "$observation_case" == consumer-finished-without-proof ]]; then + namespace_absent_on_initial=true +fi +if [[ "$observation_case" == consumer-finished ]]; then + proof_complete=true +fi ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_NAMESPACE_ABSENT_ON_INITIAL="$namespace_absent_on_initial" \ + FAKE_PR_901_PROOF_COMPLETE="$proof_complete" \ + FAKE_TRUSTED_CONSUMER_JOBS_FAIL="$([[ "$observation_case" == consumer-finished-without-proof || "$observation_case" == consumer-active-jobs-unavailable ]] && echo true || echo false)" \ FAKE_TRUSTED_CONSUMER_JOBS_JSON="$(jq -cn \ --arg observation "$observation_case" \ --arg tuple "Trusted preview deploy tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" ' @@ -2659,37 +2683,46 @@ consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id: steps:[{name:(if $observation == "consumer-title-only" then "Verify workflow source and immutable PR metadata" else $tuple end), status:"completed",conclusion:"success"}]}]}')" \ FAKE_TRUSTED_CONSUMER_LATEST_JSON="$(jq -c --arg observation "$observation_case" \ - 'if $observation == "consumer-stale-attempt" then .run_attempt = 2 else . end' <<<"$consumer_run")" \ + 'if $observation == "consumer-stale-attempt" then .run_attempt = 2 + elif $observation | startswith("consumer-finished") then .status = "completed" + else . end' <<<"$consumer_run")" \ FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn \ --arg observation "$observation_case" \ - --argjson consumer "$consumer_run" \ - --arg title "Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" ' + --argjson consumer "$consumer_run" ' [{workflow_runs:( if $observation == "duplicate-rows" then - {id:5256,run_attempt:1,workflow_id:173511323,event:"repository_dispatch", - path:".github/workflows/preview.yml",name:$title,head_branch:"develop", - head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, - display_title:$title} - | [. + {status:"queued"}, . + {status:"in_progress"}] + [$consumer, (5257, 5258 | $consumer + {id:., status:("queued", "in_progress")})] + elif $observation == "lookup-overflow" then + [range(5256; 5260) | $consumer + {id:.}] else [$consumer] end)}]')" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" -) > "$reconciler_active_status_advance_output" +) > "$reconciler_active_status_advance_output" 2>&1 if [[ "$observation_case" == duplicate-rows || "$observation_case" == workflow-run-only ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5256 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_active_status_advance_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" -elif [[ "$observation_case" == consumer-stale-attempt ]]; then +elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == lookup-overflow || "$observation_case" == consumer-active-jobs-unavailable ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_active_status_advance_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +elif [[ "$observation_case" == consumer-finished ]]; then + grep -Fqx 'Skipping PR #901: proof completed before retry dispatch.' "$reconciler_active_status_advance_output" + test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" +elif [[ "$observation_case" == consumer-finished-without-proof ]]; then + grep -Fqx \ + "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ + "$reconciler_active_status_advance_output" + test -s "$FAKE_ANNOTATE_LOG" + test -s "$FAKE_DISPATCH_LOG" else grep -Fqx \ "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ @@ -2898,7 +2931,7 @@ PREVIEW_MAX_ACTIVE=2 \ grep -Fqx "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ "$reconciler_empty_deployed_output" test ! -e "$FAKE_ANNOTATE_LOG" -test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 1 +test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 reset_case reconciler_namespace_absent_output="$TEMP_DIR/reconciler-namespace-absent.out" @@ -2913,7 +2946,7 @@ PREVIEW_MAX_ACTIVE=2 \ grep -Fqx "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ "$reconciler_namespace_absent_output" test ! -e "$FAKE_ANNOTATE_LOG" -test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 1 +test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 grep -Fqx 'get namespace pr-901 --ignore-not-found -o json' "$FAKE_NAMESPACE_SNAPSHOT_LOG" reset_case @@ -2991,8 +3024,8 @@ PREVIEW_MAX_ACTIVE=2 \ grep -Fqx "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ "$reconciler_namespace_absent_on_recheck_output" test ! -e "$FAKE_ANNOTATE_LOG" -test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 -test "$(grep -Fc 'get namespace pr-901 --ignore-not-found -o json' "$FAKE_NAMESPACE_SNAPSHOT_LOG")" -eq 2 +test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 3 +test "$(grep -Fc 'get namespace pr-901 --ignore-not-found -o json' "$FAKE_NAMESPACE_SNAPSHOT_LOG")" -eq 3 reset_case reconciler_namespace_error_output="$TEMP_DIR/reconciler-namespace-error.out" @@ -3103,7 +3136,7 @@ grep -qx 'Namespace pr-901 was deleted during requested-head repair; dispatching grep -Fqx \ "annotate namespace pr-901 firemud.dev/requested-preview-base-sha=${preview_base_sha} firemud.dev/requested-preview-head-sha=${preview_head_sha} firemud.dev/requested-preview-merge-sha=${preview_merge_sha} firemud.dev/requested-preview-image-tag=${preview_image_tag} --overwrite --resource-version rv-901" \ "$FAKE_ANNOTATE_LOG" -test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 3 +test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 4 grep -Fq \ 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' \ "$FAKE_DISPATCH_LOG" @@ -3703,7 +3736,7 @@ grep -Fq "run-name: \${{ github.event_name == 'workflow_run' && github.event.wor # shellcheck disable=SC2016 # Assert one fail-closed JSON snapshot feeds each namespace decision. grep -Fq 'kubectl get namespace "${namespace}" --ignore-not-found -o json' \ "$reconciler_workflow" -# shellcheck disable=SC2016 # Assert the initial, repair, and proof-retry namespace snapshots. +# shellcheck disable=SC2016 # Assert the initial, repair, and pre-dispatch namespace snapshots. test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$reconciler_workflow")" -eq 4 # shellcheck disable=SC2016 # Assert the fresh namespace snapshot fences repair. grep -Fq 'requested preview tuple changed during annotation repair check' "$reconciler_workflow" diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 8bd60cf4a3..f9cc3fd659 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -474,30 +474,33 @@ else: # The plan's local actions and scripts must come from the default branch; the # render's PR checkout is exact, unprivileged, and bound to the planned merge. plan_checkouts = checkouts(preview_jobs["preview-plan"]) -if len(plan_checkouts) != 1 or plan_checkouts[0].get("with", {}).get("ref") != "${{ github.event.repository.default_branch }}": - raise AssertionError("preview plan must check out the trusted default branch") +if len(plan_checkouts) != 1: + raise AssertionError("preview plan must have one trusted tools checkout") render_checkouts = checkouts(preview_jobs["preview-render"]) if len(render_checkouts) != 2: raise AssertionError("preview render must isolate trusted tools and candidate chart checkouts") -def check_render_tools_checkout(checkout: dict[str, Any]) -> None: + +def check_trusted_tools_checkout(checkout: dict[str, Any]) -> None: options = checkout.get("with", {}) if options.get("ref") != "${{ github.event.repository.default_branch }}" or options.get("path") is not None: - raise AssertionError("preview render tools must remain rooted at the trusted default branch") + raise AssertionError("preview tools must remain rooted at the trusted default branch") if "repository" in options and options["repository"] != "${{ github.repository }}": - raise AssertionError("preview render tools must check out the current repository") + raise AssertionError("preview tools must check out the current repository") + +for tools_checkout in (plan_checkouts[0], render_checkouts[0]): + check_trusted_tools_checkout(tools_checkout) + for override, reason in ( + ({"repository": "other-owner/other-repo"}, "preview tools must check out the current repository"), + ({"path": "candidate"}, "preview tools must remain rooted at the trusted default branch"), + ): + try: + check_trusted_tools_checkout({**tools_checkout, "with": {**tools_checkout["with"], **override}}) + except AssertionError as error: + if str(error) != reason: + raise + else: + raise AssertionError(f"untrusted tools checkout escaped checking: {override}") -check_render_tools_checkout(render_checkouts[0]) -foreign_tools_checkout = { - **render_checkouts[0], - "with": {**render_checkouts[0]["with"], "repository": "other-owner/other-repo"}, -} -try: - check_render_tools_checkout(foreign_tools_checkout) -except AssertionError as error: - if str(error) != "preview render tools must check out the current repository": - raise -else: - raise AssertionError("foreign render tools checkout escaped repository checking") def check_candidate_checkout(step: dict[str, Any]) -> None: options = step.get("with", {}) if options.get("repository", "$"+"{{ github.repository }}") != "$"+"{{ github.repository }}": diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 255cc9052b..c66cf38e60 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -10,15 +10,20 @@ const script = workflow.jobs.refresh.steps[1].with.script; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const E = 'e'.repeat(40); const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40), D = 'd'.repeat(40); +const tupleStep = (kind, base, merge) => ({ + name: `Preview ${kind} tuple pr-7 base-${base} head-${C} merge-${merge}`, + status: 'completed', conclusion: 'success', +}); function fixture() { return { - run: {id: 99, run_attempt: 2, display_title: `PR preview 7 base-${D} head-${C} merge-${E}`, path: '.github/workflows/preview.yml', event: 'pull_request', conclusion: 'success', + run: {id: 99, run_attempt: 2, display_title: `PR preview 7 base-${D} head-${C} merge-${E}`, path: '.github/workflows/preview.yml', event: 'pull_request', status: 'completed', conclusion: 'success', repository: {full_name: 'example/FireMUD'}, head_repository: {full_name: 'example/FireMUD'}, head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: D}}]}, pr: {number: 7, state: 'open', head: {sha: C, repo: {full_name: 'example/FireMUD'}}, base: {ref: 'develop', repo: {full_name: 'example/FireMUD'}}, merge_commit_sha: A, labels: [], user: {login: 'developer'}}, - jobs: [{name: 'Preview Plan', run_id: 99, run_attempt: 2, head_sha: C, workflow_name: 'PR Preview Environment', status: 'completed', conclusion: 'success', steps: [{name: `Preview event tuple pr-7 base-${D} head-${C} merge-${E}`, status: 'completed', conclusion: 'success'}]}], + jobs: [{name: 'Preview Plan', run_id: 99, run_attempt: 2, head_sha: C, workflow_name: 'PR Preview Environment', status: 'completed', conclusion: 'success', + steps: [tupleStep('event', D, E), tupleStep('resolved', D, E)]}], recordedMerge: {sha: E, parents: [{sha: D}, {sha: C}]}, base: {object: {sha: B}}, merge: {sha: A, parents: [{sha: B}, {sha: C}]}, }; @@ -50,7 +55,13 @@ async function execute(f, sent = []) { assert.equal(ref, 'heads/' + f.pr.base.ref); return {data: f.base}; }}, - repos: {getCommit: async ({ref}) => ({data: ref === E ? f.recordedMerge : f.merge}), createDispatchEvent: async p => sent.push(p)}, + repos: { + getCommit: async ({ref}) => { + (f.mergeReads ??= []).push(ref); + return {data: f.mergeReads.length === 1 ? f.recordedMerge : f.merge}; + }, + createDispatchEvent: async p => sent.push(p), + }, }}; await new AsyncFunction('github', 'context', 'core', 'require', script)(github, {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99, run_attempt: 2}, repository: {default_branch: 'develop'}}}, {info(message) {(f.messages ??= []).push(message);}}, name => { @@ -71,14 +82,23 @@ async function execute(f, sent = []) { return sent; } test('exact stale-base current tuple produces only the typed refresh', async () => { - assert.deepEqual(await execute(fixture()), [{owner: 'example', repo: 'FireMUD', + const f = fixture(); + assert.deepEqual(await execute(f), [{owner: 'example', repo: 'FireMUD', event_type: 'pr-runtime-base-refresh', client_payload: {pr_number: '7', base_ref: 'develop', base_sha: B, head_sha: C, merge_sha: A, image_tag: `pr-merge-${A}`}}]); + assert.deepEqual(f.mergeReads, [E, A]); +}); +test('a completed render failure permits repair when the plan was eligible', async () => { + const f = fixture(); f.run.conclusion = 'failure'; + assert.equal((await execute(f)).length, 1); }); for (const [name, mutate] of Object.entries({ wrongPath: f => f.run.path = '.github/workflows/attacker.yml', + wrongQualifiedPath: f => f.run.path += '@refs/pull/8/merge', wrongEvent: f => f.run.event = 'repository_dispatch', - failedSource: f => f.run.conclusion = 'failure', + unfinishedSource: f => f.run.status = 'in_progress', + cancelledSource: f => f.run.conclusion = 'cancelled', + failedPlan: f => { f.run.conclusion = 'failure'; f.jobs[0].conclusion = 'failure'; }, wrongRepository: f => f.run.repository.full_name = 'fork/FireMUD', forkSource: f => f.run.head_repository.full_name = 'fork/FireMUD', absentAssociation: f => f.run.pull_requests = [], @@ -105,6 +125,10 @@ for (const [name, mutate] of Object.entries({ duplicatePlan: f => f.jobs.push(f.jobs[0]), duplicateTuple: f => f.jobs[0].steps.push(f.jobs[0].steps[0]), failedTuple: f => f.jobs[0].steps[0].conclusion = "failure", + skippedResolvedTuple: f => f.jobs[0].steps[1].conclusion = 'skipped', + missingResolvedTuple: f => f.jobs[0].steps.pop(), + badResolvedParent: f => f.jobs[0].steps[1] = tupleStep('resolved', B, E), + ambiguousResolvedTuple: f => f.jobs[0].steps.push(f.jobs[0].steps[1]), malformedTuple: f => f.jobs[0].steps[0].name = "Preview event tuple invalid", invalidBase: f => f.base.object.sha = 'invalid', invalidMerge: f => f.pr.merge_commit_sha = 'invalid', @@ -279,8 +303,29 @@ test('priority removed during active lookup refuses dispatch', async () => { test('event base drift can repair the independently revalidated current merge', async () => { const f = fixture(); - f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${D} head-${C} merge-${A}`; + f.jobs[0].steps = [tupleStep('event', D, A), tupleStep('resolved', B, A)]; + f.recordedMerge = structuredClone(f.merge); assert.equal((await execute(f)).length, 1); + assert.deepEqual(f.mergeReads, [A, A]); + + const moved = fixture(); + moved.jobs[0].steps = [tupleStep('event', D, A), tupleStep('resolved', B, A)]; + moved.recordedMerge = structuredClone(moved.merge); + moved.merge.parents[0].sha = D; + assert.deepEqual(await execute(moved), []); + assert.deepEqual(moved.mergeReads, [A, A]); +}); + +test('a resolved historical merge can precede a second base advance', async () => { + const intermediateBase = 'f'.repeat(40); + const f = fixture(); + f.recordedMerge.parents[0].sha = intermediateBase; + f.jobs[0].steps[1] = tupleStep('resolved', intermediateBase, E); + const dispatches = await execute(f); + assert.equal(dispatches.length, 1); + assert.equal(dispatches[0].client_payload.base_sha, B); + assert.equal(dispatches[0].client_payload.merge_sha, A); + assert.deepEqual(f.mergeReads, [E, A]); }); test('truncated or oversized attempt inventory is refused', async () => { diff --git a/dev-tools/tests/protected-pod-admission-workflow-contract.sh b/dev-tools/tests/protected-pod-admission-workflow-contract.sh index a9c8911d1b..d9f0bbef90 100644 --- a/dev-tools/tests/protected-pod-admission-workflow-contract.sh +++ b/dev-tools/tests/protected-pod-admission-workflow-contract.sh @@ -4,6 +4,8 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" python3 - "$ROOT_DIR" <<'PY' import json, os, pathlib, subprocess, sys, tempfile import yaml +if not __debug__: + raise SystemExit("Protected Pod admission proof requires Python assertions") root = pathlib.Path(sys.argv[1]) workflow = yaml.safe_load((root / ".github/workflows/protected-pod-admission-proof.yml").read_text()) steps = workflow["jobs"]["admission-only"]["steps"] @@ -15,6 +17,12 @@ inspects = [line for script in runs for line in script.splitlines() if 'owner_la assert len(inspects) == 2 assert all('15s docker inspect' in line and '|| owner_label=""' in line for line in inspects) proof = next(script for script in runs if "policy_deadline=" in script) +version_guard = proof[proof.index('expected_server_version='):proof.index("printf 'kubernetes_context=")] +for actual, expected in [("v1.34.1", 0), ("v1.34.10", 1), ("v1.34.1-unexpected", 1)]: + result = subprocess.run(["bash", "-c", version_guard], capture_output=True, env={ + **os.environ, "KIND_NODE_IMAGE": "kindest/node:v1.34.1@sha256:pin", "server_version": actual, + }) + assert result.returncode == expected, (actual, result.returncode, result.stderr) wait = proof[proof.index('policy_deadline='):proof.index('elapsed fixture_rollout')] wait = wait[:wait.index('phase_started=')] # Execute the real wait body against bounded fake API/time, never a cluster. diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 7905a6fe61..5b672e58fc 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -33,7 +33,7 @@ grep -Fq 'cancel-in-progress: false' "$workflow" grep -Fq 'group: static-analysis-summary-pr-${{ needs.resolve-summary-target.outputs.pull-number }}' "$workflow" grep -Fq 'const headSha = currentPullRequest.head?.sha;' "$workflow" grep -Fq 'context.payload.workflow_run.display_title !== expectedSourceTitle' "$workflow" -grep -Fq 'finalPullRequest.base?.sha !== baseSha' "$workflow" +grep -Fq 'current.base?.sha === baseSha' "$workflow" grep -Fq 'run?.display_title === expectedTitle' "$workflow" grep -Fq 'comment.user?.login === "github-actions[bot]"' "$workflow" grep -Fq 'if (comment.id === existing?.id) continue;' "$workflow" @@ -159,6 +159,8 @@ let changeHeadDuringComments = false; let deleteStatus = null; let existingBody = "### Static Analysis Summary\nold"; const calls = { paginate: [], deleted: [], updated: [], created: [] }; +const mutationCounts = () => [calls.updated.length, calls.created.length, calls.deleted.length]; +const mutationsChanged = before => mutationCounts().some((count, index) => count !== before[index]); const codeqlListWorkflowRuns = async () => undefined; const checksListForRef = async () => undefined; const commentsList = async () => undefined; @@ -750,17 +752,27 @@ run(github, context, core).then(async () => { } github.paginate = savedPaginate; const savedActions = github.rest.actions; - const staleBefore = [calls.updated.length, calls.created.length, calls.deleted.length]; + const staleBefore = mutationCounts(); github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { const {data} = await savedActions.getWorkflowRun(input); return {data: {...data, run_attempt: data.run_attempt + 1}}; }}; try { await run(github, context, core); } finally { github.rest.actions = savedActions; } - if (staleBefore.some((length, index) => - length !== [calls.updated.length, calls.created.length, calls.deleted.length][index])) { + if (mutationsChanged(staleBefore)) { throw new Error("a producer rerun after evidence read must not mutate comments"); } + const beforeHeadMovement = mutationCounts(); + github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { + const response = await savedActions.getWorkflowRun(input); + currentHeadSha = "e".repeat(40); + return response; + }}; + try { await run(github, context, core); } + finally { github.rest.actions = savedActions; currentHeadSha = headSha; } + if (mutationsChanged(beforeHeadMovement)) { + throw new Error("head movement during producer recheck must not mutate comments"); + } let currentAttempt = 1; github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { @@ -786,21 +798,21 @@ run(github, context, core).then(async () => { } } currentAttempt = 2; - const staleAttemptWrites = calls.updated.length + calls.created.length; + const staleAttemptWrites = mutationCounts(); let staleAttemptRefused = false; try { await run(github, context, core); } catch (error) { staleAttemptRefused = error.message.includes("cannot confirm the current workflow attempt"); } finally { github.rest.actions = savedActions; } - if (!staleAttemptRefused || calls.updated.length + calls.created.length !== staleAttemptWrites) { + if (!staleAttemptRefused || mutationsChanged(staleAttemptWrites)) { throw new Error("an older ambiguous snapshot must not overwrite a newer summary"); } - const writesBefore = calls.updated.length + calls.created.length; + const writesBefore = mutationCounts(); github.request = async () => ({ data: { total_count: 101, jobs: [] } }); let refused = false; try { await run(github, context, core); } catch (error) { refused = error.message.includes("jobs are incomplete"); } finally { github.request = savedRequest; } - if (!refused || calls.updated.length + calls.created.length !== writesBefore) throw new Error("incomplete candidate jobs must not publish success"); + if (!refused || mutationsChanged(writesBefore)) throw new Error("incomplete candidate jobs must not mutate comments"); console.log("static analysis summary behavioral contract passed"); }, ); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java index 7432dffebe..1d0fb4d2c2 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java @@ -32,14 +32,19 @@ Operation bindVerifiedEvidence( OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Instant now); - /** False only for an exact dispatch superseded after validated durable owner closure. */ - boolean recordRetryableEffectForDispatch(OutboxEntry dispatch, String outcomeCode, Instant now); + /** False only for an exact dispatch superseded after definitive owner rejection or closure. */ + boolean recordRetryableEffectForDispatch( + OutboxEntry dispatch, RetrySource source, String outcomeCode, Instant now); - /** False only for an exact dispatch superseded after validated durable owner closure. */ + /** False only for an exact dispatch superseded after definitive owner rejection or closure. */ boolean recordAmbiguousEffectForDispatch(OutboxEntry dispatch, String outcomeCode, Instant now); - Operation recordEffectReadback( - UUID operationId, UUID effectId, UUID attemptId, EffectReadback readback, Instant now); + enum RetrySource { + NOT_DISPATCHED, + OWNER_REJECTED + } + + Operation recordEffectReadback(OutboxEntry dispatch, EffectReadback readback, Instant now); Optional findEffect(UUID operationId, EffectKind effectKind); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 2df4e7721c..324e415778 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -248,7 +248,8 @@ public OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); requireEffectMatchesOperation(current.effect(), operation); - if (hasRetainedClosure(tx, current, attemptId, null)) { + if (hasRetainedClosure(tx, current, attemptId, null) + || hasRetainedOwnerRejection(tx, current, attemptId, null)) { throw conflict("a retry must use a new effect attempt identity"); } if (current.state() == EffectOutboxState.DISPATCHED @@ -288,18 +289,29 @@ && hasDurableNoEffectClosure(tx, current) @Override public boolean recordRetryableEffectForDispatch( - OutboxEntry dispatch, String outcomeCode, Instant now) { - return recordNonterminalEffectOutcome(dispatch, outcomeCode, EffectOutboxState.RETRYABLE, now); + OutboxEntry dispatch, RetrySource source, String outcomeCode, Instant now) { + Objects.requireNonNull(source, "retry source must not be null"); + return recordNonterminalEffectOutcome( + dispatch, + outcomeCode, + EffectOutboxState.RETRYABLE, + source == RetrySource.OWNER_REJECTED, + now); } @Override public boolean recordAmbiguousEffectForDispatch( OutboxEntry dispatch, String outcomeCode, Instant now) { - return recordNonterminalEffectOutcome(dispatch, outcomeCode, EffectOutboxState.AMBIGUOUS, now); + return recordNonterminalEffectOutcome( + dispatch, outcomeCode, EffectOutboxState.AMBIGUOUS, false, now); } private boolean recordNonterminalEffectOutcome( - OutboxEntry dispatch, String outcomeCode, EffectOutboxState resultState, Instant now) { + OutboxEntry dispatch, + String outcomeCode, + EffectOutboxState resultState, + boolean ownerRejected, + Instant now) { Objects.requireNonNull(dispatch, "dispatch must not be null"); InitialGameplayReleaseModel.requiredOutcomeCode(outcomeCode); UUID operationId = dispatch.effect().operationId(); @@ -312,13 +324,12 @@ private boolean recordNonterminalEffectOutcome( requireEffectMatchesOperation(current.effect(), operation); if (dispatch.state() != EffectOutboxState.DISPATCHED || attemptId == null - || !dispatch.outboxId().equals(current.outboxId()) - || !dispatch.effect().equals(current.effect()) - || !dispatch.payloadDigest().equals(current.payloadDigest())) { + || !sameEffect(dispatch, current)) { throw conflict("effect dispatch tuple changed"); } if (!Objects.equals(current.lastAttemptId(), attemptId)) { - if (hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount())) { + if (hasRetainedClosure(tx, current, attemptId, dispatch.attemptCount()) + || hasRetainedOwnerRejection(tx, current, attemptId, dispatch.attemptCount())) { return false; } throw conflict("effect attempt identity changed"); @@ -326,18 +337,33 @@ private boolean recordNonterminalEffectOutcome( if (dispatch.attemptCount() != current.attemptCount()) { throw conflict("effect dispatch generation changed"); } - if (current.state() == resultState - || current.state() == EffectOutboxState.ACKNOWLEDGED + if (current.state() == EffectOutboxState.ACKNOWLEDGED || (current.lastAttemptId() != null && current.state() == EffectOutboxState.RETRYABLE && resultState == EffectOutboxState.AMBIGUOUS)) { return true; } - if (current.state() != EffectOutboxState.DISPATCHED + if (current.state() != resultState + && current.state() != EffectOutboxState.DISPATCHED && !(current.state() == EffectOutboxState.AMBIGUOUS && resultState == EffectOutboxState.RETRYABLE)) { throw conflict("effect is not in a dispatchable attempt"); } + if (ownerRejected) { + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_attempt_rejection + (outbox_id, attempt_id, attempt_ordinal) + VALUES (?, ?, ?) + ON CONFLICT (outbox_id, attempt_id) DO NOTHING + """, + current.outboxId(), + attemptId, + dispatch.attemptCount()); + } + if (current.state() == resultState) { + return true; + } tx.execute( """ UPDATE recovery_control.initial_gameplay_release_outbox @@ -358,18 +384,30 @@ private boolean recordNonterminalEffectOutcome( @Override public Operation recordEffectReadback( - UUID operationId, UUID effectId, UUID attemptId, EffectReadback readback, Instant now) { + OutboxEntry dispatch, EffectReadback readback, Instant now) { + Objects.requireNonNull(dispatch, "dispatch must not be null"); Objects.requireNonNull(readback, "readback must not be null"); Objects.requireNonNull(now, "now must not be null"); + UUID operationId = dispatch.effect().operationId(); + UUID effectId = dispatch.effect().effectId(); return dsl.transactionResult(configuration -> { DSLContext tx = DSL.using(configuration); Operation operation = selectOperation(tx, operationId, true); OutboxEntry current = selectOutbox(tx, operationId, effectId, true); requireEffectMatchesOperation(current.effect(), operation); - requireReadbackMatches(readback, current, operationId, effectId); - if (current.lastAttemptId() == null || !current.lastAttemptId().equals(attemptId)) { + if (!sameEffect(dispatch, current) + || (dispatch.state() != EffectOutboxState.DISPATCHED + && dispatch.state() != EffectOutboxState.AMBIGUOUS)) { + throw conflict("effect readback dispatch tuple changed"); + } + if (dispatch.lastAttemptId() == null + || !dispatch.lastAttemptId().equals(current.lastAttemptId())) { throw conflict("effect readback belongs to another attempt"); } + if (dispatch.attemptCount() != current.attemptCount()) { + throw conflict("effect readback dispatch generation changed"); + } + requireReadbackMatches(readback, current, operationId, effectId); String readbackDigest = tupleCodec.digest(readback); if (current.state() == EffectOutboxState.ACKNOWLEDGED || current.state() == EffectOutboxState.RETRYABLE) { @@ -483,6 +521,12 @@ && sameRetainedOutcome(readback, stored, storedDigest)) { }); } + private static boolean sameEffect(OutboxEntry dispatch, OutboxEntry current) { + return dispatch.outboxId().equals(current.outboxId()) + && dispatch.effect().equals(current.effect()) + && dispatch.payloadDigest().equals(current.payloadDigest()); + } + @Override public Optional findEffect(UUID operationId, EffectKind effectKind) { Record record = @@ -788,6 +832,29 @@ private boolean hasRetainedClosure( return true; } + private static boolean hasRetainedOwnerRejection( + DSLContext tx, OutboxEntry current, UUID attemptId, Integer expectedOrdinal) { + Record row = + tx.fetchOne( + """ + SELECT attempt_ordinal FROM recovery_control.initial_gameplay_release_attempt_rejection + WHERE outbox_id = ? AND attempt_id = ? + """, + current.outboxId(), + attemptId); + if (row == null) { + return false; + } + Integer ordinal = row.get("attempt_ordinal", Integer.class); + if (ordinal == null + || ordinal < 1 + || ordinal > current.attemptCount() + || (expectedOrdinal != null && !expectedOrdinal.equals(ordinal))) { + throw conflict("retained owner rejection dispatch generation changed"); + } + return true; + } + private boolean hasDurableNoEffectClosure(DSLContext tx, OutboxEntry current) { Record stored = tx.fetchOne( diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index ccd9334cc0..3af726d0d9 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal.RetrySource; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.ContinueRecovery; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.Resume; @@ -128,7 +129,7 @@ public Operation reconcileNextEffect(UUID operationId) { || outbox.state() == EffectOutboxState.RETRYABLE) { return applyEffect(operation, outbox); } - return readBackEffect(operation, outbox, outbox.lastAttemptId()); + return readBackEffect(operation, outbox); } private Operation applyEffect(Operation operation, OutboxEntry outbox) { @@ -156,7 +157,12 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { || applyResult.status() == ApplyStatus.NOT_DISPATCHED) { // An exact, durably closed prior dispatch can be superseded while the apply call was pending. journal.recordRetryableEffectForDispatch( - dispatched, applyResult.outcomeCode(), clock.instant()); + dispatched, + applyResult.status() == ApplyStatus.NOT_DISPATCHED + ? RetrySource.NOT_DISPATCHED + : RetrySource.OWNER_REJECTED, + applyResult.outcomeCode(), + clock.instant()); return requireOperation(operation.scope().operationId()); } if (applyResult.status() == ApplyStatus.AMBIGUOUS) { @@ -164,10 +170,11 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { dispatched, applyResult.outcomeCode(), clock.instant()); return requireOperation(operation.scope().operationId()); } - return readBackEffect(operation, dispatched, attemptId); + return readBackEffect(operation, dispatched); } - private Operation readBackEffect(Operation operation, OutboxEntry outbox, UUID attemptId) { + private Operation readBackEffect(Operation operation, OutboxEntry outbox) { + UUID attemptId = outbox.lastAttemptId(); if (attemptId == null) { throw new InitialGameplayReleaseConflictException( "IDEMPOTENCY_CONFLICT: dispatched effect has no attempt identity"); @@ -189,8 +196,7 @@ private Operation readBackEffect(Operation operation, OutboxEntry outbox, UUID a throw new InitialGameplayReleaseConflictException( "IDEMPOTENCY_CONFLICT: effect readback observation time changed"); } - return journal.recordEffectReadback( - operation.scope().operationId(), outbox.effect().effectId(), attemptId, readback, now); + return journal.recordEffectReadback(outbox, readback, now); } private Operation transition( @@ -222,14 +228,13 @@ private Operation transition( if (prior.isPresent()) { return prior.orElseThrow(); } - EvidenceResolution resolution = evidenceProvider.read(operation.scope()); - if (resolution.status() == ResolutionStatus.UNAVAILABLE) { - Optional committedWhileReading = journal.findTransition(tuple); - if (committedWhileReading.isPresent()) { - return committedWhileReading.orElseThrow(); - } + try { + verifyFreshEvidence(operation, evidenceProvider.read(operation.scope())); + } catch (OwnerBoundaryUnavailableException + | IllegalArgumentException + | InitialGameplayReleaseConflictException evidenceFailure) { + return journal.findTransition(tuple).orElseThrow(() -> evidenceFailure); } - verifyFreshEvidence(operation, resolution); return journal.transition(tuple, clock.instant()); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index f464f2334b..892b7e773e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -28,6 +28,10 @@ public interface InitialGameplayReleaseEffectPort { * the persisted dispatch time and the controller's time after receiving the readback. If that * clock relationship cannot be established, return UNAVAILABLE. Do not replace the observation * with an adapter or controller receipt timestamp. + * + *

If a newer partial observation supersedes an older definitive receipt, advancing the + * transition requires a fresh exact observation from the owner. Returning the older receipt with + * a new timestamp is insufficient. */ EffectReadbackResolution readback(TypedEffect effect, UUID attemptId); diff --git a/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql index d63df340f2..472833ec1d 100644 --- a/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql +++ b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql @@ -27,3 +27,11 @@ CREATE TABLE recovery_control.initial_gameplay_release_attempt_closure ( CHECK (recorded_at >= dispatched_at), PRIMARY KEY (outbox_id, attempt_id) ); + +CREATE TABLE recovery_control.initial_gameplay_release_attempt_rejection ( + outbox_id UUID NOT NULL + REFERENCES recovery_control.initial_gameplay_release_outbox(outbox_id) ON DELETE RESTRICT, + attempt_id UUID NOT NULL, + attempt_ordinal INTEGER NOT NULL CHECK (attempt_ordinal > 0), + PRIMARY KEY (outbox_id, attempt_id) +); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index b9b08b3440..50eccb0e40 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.UUID; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal.RetrySource; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; import net.firedevops.firemud.recovery.journal.JooqInitialGameplayReleaseJournal; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectKind; @@ -48,6 +49,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -104,6 +107,7 @@ static void tearDown() throws Exception { void clearJournal() { dsl.execute( "TRUNCATE TABLE recovery_control.initial_gameplay_release_attempt_closure, " + + "recovery_control.initial_gameplay_release_attempt_rejection, " + "recovery_control.initial_gameplay_release_outbox, " + "recovery_control.initial_gameplay_release_transition, " + "recovery_control.initial_gameplay_release_operation"); @@ -165,13 +169,8 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() "gamesession-preparation-readback-1", base.plusSeconds(6)); UUID prepareEffectId = prepare.effect().effectId(); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - prepareEffectId, - prepareAttempt, - prepareReadback, - base.plusSeconds(5))) + assertThatThrownBy( + () -> journal.recordEffectReadback(prepare, prepareReadback, base.plusSeconds(5))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("observation is in the future"); assertThat(journal.find(scope.operationId())).contains(authorized); @@ -191,44 +190,25 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, "wrong-attempt", base.plusSeconds(6)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - prepareEffectId, - prepareAttempt, - otherAttempt, - base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(prepare, otherAttempt, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat( journal.recordAmbiguousEffectForDispatch( prepare, "TRANSPORT_OUTCOME_UNKNOWN", base.plusSeconds(5))) .isTrue(); + OutboxEntry ambiguous = journal.findNextEffect(scope.operationId()).orElseThrow(); + assertThat(ambiguous.state()).isEqualTo(EffectOutboxState.AMBIGUOUS); Operation releasing = - journal.recordEffectReadback( - scope.operationId(), - prepare.effect().effectId(), - prepareAttempt, - prepareReadback, - prepareReadback.observedAt()); + journal.recordEffectReadback(ambiguous, prepareReadback, prepareReadback.observedAt()); assertThat(releasing.phase()).isEqualTo(Phase.RELEASING); String retainedPrepare = storedOutbox(scope.operationId(), prepareEffectId); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - prepareEffectId, - prepareAttempt, - prepareReadback, - base.plusSeconds(5))) + assertThatThrownBy( + () -> journal.recordEffectReadback(prepare, prepareReadback, base.plusSeconds(5))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect readback observation is in the future"); assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); - assertThat( - journal.recordEffectReadback( - scope.operationId(), - prepareEffectId, - prepareAttempt, - prepareReadback, - prepareReadback.observedAt())) + assertThat(journal.recordEffectReadback(prepare, prepareReadback, prepareReadback.observedAt())) .isEqualTo(releasing); assertThat(storedOutbox(scope.operationId(), prepareEffectId)).isEqualTo(retainedPrepare); assertThat( @@ -245,23 +225,12 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() EffectReadbackState.PREPARED_FENCED, prepareReadback.readbackIdentity(), base.plusSeconds(8)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - preparedEffectId, - prepareAttempt, - laterObservation, - base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(prepare, laterObservation, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), preparedEffectId)) .isEqualTo(retainedAcknowledgement); - assertThat( - journal.recordEffectReadback( - scope.operationId(), - preparedEffectId, - prepareAttempt, - laterObservation, - base.plusSeconds(9))) + assertThat(journal.recordEffectReadback(prepare, laterObservation, base.plusSeconds(9))) .isEqualTo(releasing); EffectReadback changedReceipt = readbackFor( @@ -270,13 +239,8 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() EffectReadbackState.PREPARED_FENCED, "different-durable-receipt", base.plusSeconds(8)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - preparedEffectId, - prepareAttempt, - changedReceipt, - base.plusSeconds(9))) + assertThatThrownBy( + () -> journal.recordEffectReadback(prepare, changedReceipt, base.plusSeconds(9))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), preparedEffectId)) .isEqualTo(retainedAcknowledgement); @@ -310,12 +274,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() "gamesession-owner-handoff-readback-1", base.plusSeconds(9)); Operation finalized = - journal.recordEffectReadback( - scope.operationId(), - handoff.effect().effectId(), - handoffAttempt, - handoffReadback, - base.plusSeconds(10)); + journal.recordEffectReadback(handoff, handoffReadback, base.plusSeconds(10)); assertThat(finalized.phase()).isEqualTo(Phase.FINALIZED); assertThat(finalized.finalizedAt()).isEqualTo(base.plusSeconds(10)); @@ -389,7 +348,10 @@ void tupleConflictAndAmbiguousEffectNeverAdvanceOrRedispatch() { .isEmpty(); assertThat( journal.recordRetryableEffectForDispatch( - dispatched, "OWNER_DECLINED_WITHOUT_EFFECT", base.plusSeconds(8))) + dispatched, + RetrySource.OWNER_REJECTED, + "OWNER_DECLINED_WITHOUT_EFFECT", + base.plusSeconds(8))) .isTrue(); assertThat(journal.findNextEffect(scope.operationId())) .get() @@ -418,16 +380,15 @@ void delayedSameAttemptPreparationCannotOverrideNewerAmbiguity() { EffectReadbackState.UNKNOWN_OR_PARTIAL, "latest-unknown", base.plusSeconds(6)); - journal.recordEffectReadback(operationId, effectId, attemptId, unknown, base.plusSeconds(6)); + journal.recordEffectReadback(dispatched, unknown, base.plusSeconds(6)); String retained = storedOutbox(operationId, effectId); for (EffectReadbackState delayedState : List.of(EffectReadbackState.UNKNOWN_OR_PARTIAL, EffectReadbackState.PREPARED_FENCED)) { EffectReadback delayed = readbackFor(dispatched, attemptId, delayedState, "delayed", base.plusSeconds(5)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, delayed, base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, delayed, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("predates the retained same-attempt observation"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); @@ -443,8 +404,7 @@ void delayedSameAttemptPreparationCannotOverrideNewerAmbiguity() { EffectReadbackState.PREPARED_FENCED, "fresh-owner-proof", base.plusSeconds(8)); - Operation advanced = - journal.recordEffectReadback(operationId, effectId, attemptId, fresh, base.plusSeconds(8)); + Operation advanced = journal.recordEffectReadback(dispatched, fresh, base.plusSeconds(8)); assertThat(advanced.phase()).isEqualTo(Phase.RELEASING); assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) .isPresent(); @@ -481,15 +441,11 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { EffectReadbackState.PROVEN_NO_EFFECT, "durable-closure", base.plusSeconds(5)); - assertThat( - journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(6))) + assertThat(journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(6))) .isEqualTo(authorized); String retained = storedOutbox(scope.operationId(), effectId); - assertThat( - journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(7))) + assertThat(journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(7))) .isEqualTo(authorized); assertThat( journal.recordAmbiguousEffectForDispatch( @@ -507,9 +463,7 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { EffectReadbackState.PROVEN_NO_EFFECT, "durable-closure", base.plusSeconds(6)); - assertThat( - journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, observedAgain, base.plusSeconds(7))) + assertThat(journal.recordEffectReadback(dispatched, observedAgain, base.plusSeconds(7))) .isEqualTo(authorized); for (Instant invalid : List.of(base.plusSeconds(3), base.plusSeconds(8))) { EffectReadback invalidObservation = @@ -520,12 +474,7 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { "durable-closure", invalid); assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), - effectId, - firstAttempt, - invalidObservation, - base.plusSeconds(7))) + journal.recordEffectReadback(dispatched, invalidObservation, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); } EffectReadback differentClosure = @@ -535,9 +484,8 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { EffectReadbackState.PROVEN_NO_EFFECT, "different-closure", base.plusSeconds(6)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, differentClosure, base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, differentClosure, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); @@ -557,9 +505,8 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { assertThat(replacement) .contains( "\"readback_identity\":null", "\"readback_payload\":null", "\"readback_digest\":null"); - assertThatThrownBy(() -> - journal.recordEffectReadback( - scope.operationId(), effectId, firstAttempt, terminal, base.plusSeconds(9))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(9))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(replacement); } @@ -571,7 +518,8 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { UUID operationId = dispatched.effect().operationId(); UUID effectId = dispatched.effect().effectId(); UUID attemptId = dispatched.lastAttemptId(); - journal.recordRetryableEffectForDispatch(dispatched, "OWNER_REJECTED", base.plusSeconds(5)); + journal.recordRetryableEffectForDispatch( + dispatched, RetrySource.OWNER_REJECTED, "OWNER_REJECTED", base.plusSeconds(5)); String before = storedOutbox(operationId, effectId); EffectReadback stale = readbackFor( @@ -580,9 +528,7 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { EffectReadbackState.PROVEN_NO_EFFECT, "closure", base.plusSeconds(3)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, stale, base.plusSeconds(6))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, stale, base.plusSeconds(6))) .isInstanceOf(InitialGameplayReleaseConflictException.class); EffectReadback future = readbackFor( @@ -591,9 +537,7 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { EffectReadbackState.PROVEN_NO_EFFECT, "closure", base.plusSeconds(7)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, future, base.plusSeconds(6))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, future, base.plusSeconds(6))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); EffectReadback closure = @@ -603,23 +547,19 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { EffectReadbackState.PROVEN_NO_EFFECT, "closure", base.plusSeconds(6)); - journal.recordEffectReadback(operationId, effectId, attemptId, closure, base.plusSeconds(6)); + journal.recordEffectReadback(dispatched, closure, base.plusSeconds(6)); String retained = storedOutbox(operationId, effectId); assertThat(retained).contains(tupleCodec.digest(closure)); - journal.recordEffectReadback(operationId, effectId, attemptId, closure, base.plusSeconds(7)); + journal.recordEffectReadback(dispatched, closure, base.plusSeconds(7)); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); Operation beforeReplay = journal.find(operationId).orElseThrow(); - assertThat( - journal.recordEffectReadback( - operationId, effectId, attemptId, future, base.plusSeconds(8))) + assertThat(journal.recordEffectReadback(dispatched, future, base.plusSeconds(8))) .isEqualTo(beforeReplay); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); UUID nextAttempt = UUID.randomUUID(); journal.claimEffect(operationId, effectId, nextAttempt, base.plusSeconds(8)); String replaced = storedOutbox(operationId, effectId); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, closure, base.plusSeconds(9))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, closure, base.plusSeconds(9))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(replaced); } @@ -640,8 +580,9 @@ void unknownReadbackBeforeDefinitiveRejectionAllowsOnlyValidatedSameAttemptClosu EffectReadbackState.UNKNOWN_OR_PARTIAL, "unknown", base.plusSeconds(5)); - journal.recordEffectReadback(operationId, effectId, attemptId, unknown, base.plusSeconds(5)); - journal.recordRetryableEffectForDispatch(dispatched, "OWNER_REJECTED", base.plusSeconds(6)); + journal.recordEffectReadback(dispatched, unknown, base.plusSeconds(5)); + journal.recordRetryableEffectForDispatch( + dispatched, RetrySource.OWNER_REJECTED, "OWNER_REJECTED", base.plusSeconds(6)); if (variant.equals("missing-digest")) { String retained = storedOutbox(operationId, effectId); assertThatThrownBy(() -> @@ -678,9 +619,7 @@ void unknownReadbackBeforeDefinitiveRejectionAllowsOnlyValidatedSameAttemptClosu EffectReadbackState.PROVEN_NO_EFFECT, "closure", base.plusSeconds(3)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, stale, base.plusSeconds(7))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, stale, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); EffectReadback closure = @@ -691,19 +630,16 @@ void unknownReadbackBeforeDefinitiveRejectionAllowsOnlyValidatedSameAttemptClosu "closure", base.plusSeconds(7)); if (variant.equals("valid")) { - journal.recordEffectReadback( - operationId, effectId, attemptId, closure, base.plusSeconds(7)); + journal.recordEffectReadback(dispatched, closure, base.plusSeconds(7)); String retained = storedOutbox(operationId, effectId); assertThat(retained).contains(tupleCodec.digest(closure)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, unknown, base.plusSeconds(8))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, unknown, base.plusSeconds(8))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); } else { - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, closure, base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, closure, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); } @@ -736,9 +672,7 @@ void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrec EffectReadbackState.PROVEN_NO_EFFECT, "before-dispatch-floor", floor.minusNanos(1)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, dispatched.lastAttemptId(), stale, base.plusSeconds(5))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, stale, base.plusSeconds(5))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); EffectReadback closure = @@ -748,14 +682,10 @@ void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrec EffectReadbackState.PROVEN_NO_EFFECT, "same-instant", dispatchInstant); - Operation recorded = - journal.recordEffectReadback( - operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(5)); + Operation recorded = journal.recordEffectReadback(dispatched, closure, base.plusSeconds(5)); String retained = storedOutbox(operationId, effectId); assertThat(retained).contains(tupleCodec.digest(closure)); - assertThat( - journal.recordEffectReadback( - operationId, effectId, dispatched.lastAttemptId(), closure, base.plusSeconds(6))) + assertThat(journal.recordEffectReadback(dispatched, closure, base.plusSeconds(6))) .isEqualTo(recorded); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); } @@ -850,38 +780,27 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { UUID attemptId = dispatched.lastAttemptId(); EffectReadback valid = readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(5)); - Operation settled = - journal.recordEffectReadback( - operationId, effectId, attemptId, valid, base.plusSeconds(6)); + Operation settled = journal.recordEffectReadback(dispatched, valid, base.plusSeconds(6)); String before = storedOutbox(operationId, effectId); - assertThat( - journal.recordEffectReadback( - operationId, effectId, attemptId, valid, base.plusSeconds(7))) + assertThat(journal.recordEffectReadback(dispatched, valid, base.plusSeconds(7))) .isEqualTo(settled); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); EffectReadback observedAgain = readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(6)); - assertThat( - journal.recordEffectReadback( - operationId, effectId, attemptId, observedAgain, base.plusSeconds(7))) + assertThat(journal.recordEffectReadback(dispatched, observedAgain, base.plusSeconds(7))) .isEqualTo(settled); EffectReadback stale = readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(3)); EffectReadback future = readbackFor(dispatched, attemptId, state, "terminal", base.plusSeconds(8)); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, stale, base.plusSeconds(7))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, stale, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect readback is stale"); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, future, base.plusSeconds(7))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, future, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect readback observation is in the future"); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, valid, base.plusSeconds(4))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, valid, base.plusSeconds(4))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect readback observation is in the future"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); @@ -896,9 +815,7 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { effectId)) .isEqualTo(1); String corrupt = storedOutbox(operationId, effectId); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, valid, base.plusSeconds(8))) + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, valid, base.plusSeconds(8))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("retained effect readback does not match exact replay"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(corrupt); @@ -907,26 +824,47 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { } @Test - void retryableEffectWithoutDurableClosurePreservesSameAttemptClaimBehavior() { + void definitiveOwnerRejectionRequiresFreshAttemptEvenAfterReplacement() { Instant base = Instant.parse("2026-09-01T00:00:00Z"); OutboxEntry dispatched = authorizedDispatch(base); UUID operationId = dispatched.effect().operationId(); UUID effectId = dispatched.effect().effectId(); - UUID attemptId = dispatched.lastAttemptId(); + UUID rejectedAttempt = dispatched.lastAttemptId(); assertThat( journal.recordRetryableEffectForDispatch( - dispatched, "OWNER_REJECTED", base.plusSeconds(5))) + dispatched, RetrySource.OWNER_REJECTED, "OWNER_REJECTED", base.plusSeconds(5))) .isTrue(); assertThat(journal.findNextEffect(operationId)) .get() .extracting(OutboxEntry::state) .isEqualTo(EffectOutboxState.RETRYABLE); assertThat(storedOutbox(operationId, effectId)).contains("\"readback_payload\":null"); + assertThatThrownBy( + () -> journal.claimEffect(operationId, effectId, rejectedAttempt, base.plusSeconds(6))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("a retry must use a new effect attempt identity"); + UUID freshAttempt = UUID.randomUUID(); OutboxEntry retried = - journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(6)); + journal.claimEffect(operationId, effectId, freshAttempt, base.plusSeconds(6)); assertThat(retried.state()).isEqualTo(EffectOutboxState.DISPATCHED); - assertThat(retried.lastAttemptId()).isEqualTo(attemptId); + assertThat(retried.lastAttemptId()).isEqualTo(freshAttempt); assertThat(retried.attemptCount()).isEqualTo(dispatched.attemptCount() + 1); + assertThat( + journal.recordAmbiguousEffectForDispatch( + dispatched, "LATE_TRANSPORT_ERROR", base.plusSeconds(7))) + .isFalse(); + assertThat(journal.findNextEffect(operationId)).contains(retried); + assertThat( + journal.recordRetryableEffectForDispatch( + retried, RetrySource.NOT_DISPATCHED, "TRANSPORT_REFUSED", base.plusSeconds(8))) + .isTrue(); + var reopened = new JooqInitialGameplayReleaseJournal(dsl, tupleCodec); + String before = storedOutbox(operationId, effectId); + assertThatThrownBy( + () -> reopened.claimEffect(operationId, effectId, rejectedAttempt, base.plusSeconds(9))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("a retry must use a new effect attempt identity"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); } @Test @@ -1020,9 +958,8 @@ void claimAndReadbackRejectEffectFromAnotherMaintenanceLockWithoutWrites() { () -> journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(5))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("retained effect does not match the operation-owned tuple"); - assertThatThrownBy(() -> - journal.recordEffectReadback( - operationId, effectId, attemptId, readback, base.plusSeconds(6))) + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, readback, base.plusSeconds(6))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("retained effect does not match the operation-owned tuple"); assertThat(journal.find(operationId)).contains(corrupted); @@ -1038,9 +975,7 @@ void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded UUID operationId = a.effect().operationId(); UUID effectId = a.effect().effectId(); journal.recordEffectReadback( - operationId, - effectId, - a.lastAttemptId(), + a, readbackFor( a, a.lastAttemptId(), @@ -1058,16 +993,15 @@ void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); assertThat(storedClosure(a)).isEqualTo(closedA); assertThat( - journal.recordRetryableEffectForDispatch(a, "DELAYED_NO_EFFECT", base.plusSeconds(7))) + journal.recordRetryableEffectForDispatch( + a, RetrySource.OWNER_REJECTED, "DELAYED_NO_EFFECT", base.plusSeconds(7))) .isFalse(); assertThatThrownBy(() -> journal.claimEffect(operationId, effectId, a.lastAttemptId(), base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); journal.recordEffectReadback( - operationId, - effectId, - b.lastAttemptId(), + b, readbackFor( b, b.lastAttemptId(), @@ -1095,25 +1029,92 @@ void delayedTransportOnlyGenerationCannotMutateSameIdRetry() { UUID attemptId = original.lastAttemptId(); assertThat( journal.recordRetryableEffectForDispatch( - original, "TRANSPORT_REFUSED", base.plusSeconds(5))) + original, RetrySource.NOT_DISPATCHED, "TRANSPORT_REFUSED", base.plusSeconds(5))) .isTrue(); OutboxEntry retry = journal.claimEffect(operationId, effectId, attemptId, base.plusSeconds(6)); assertThat(retry.attemptCount()).isEqualTo(original.attemptCount() + 1); String before = storedOutbox(operationId, effectId); assertThatThrownBy(() -> journal.recordRetryableEffectForDispatch( - original, "STALE_TRANSPORT_REFUSED", base.plusSeconds(7))) + original, + RetrySource.NOT_DISPATCHED, + "STALE_TRANSPORT_REFUSED", + base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect dispatch generation changed"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); assertThat( journal.recordRetryableEffectForDispatch( - retry, "CURRENT_TRANSPORT_REFUSED", base.plusSeconds(8))) + retry, + RetrySource.NOT_DISPATCHED, + "CURRENT_TRANSPORT_REFUSED", + base.plusSeconds(8))) .isTrue(); } @Test - void migrationRefusesClaimedLegacyOutboxAndRollsBack() throws Exception { + void delayedReadbackCannotMutateSameIdRetryWithinTheSameStoredMicrosecond() { + Instant base = Instant.parse("2026-09-01T00:00:00.000000100Z"); + OutboxEntry original = authorizedDispatch(base); + UUID operationId = original.effect().operationId(); + UUID effectId = original.effect().effectId(); + UUID attemptId = original.lastAttemptId(); + Instant firstDispatch = base.plusSeconds(4); + String dispatchTimeQuery = + "SELECT last_dispatched_at FROM recovery_control.initial_gameplay_release_outbox" + + " WHERE outbox_id = ?"; + var firstStoredDispatch = dsl.fetchSingle(dispatchTimeQuery, original.outboxId()).get(0); + var oldReadback = + readbackFor( + original, + attemptId, + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "original-observation", + firstDispatch.plusNanos(100)); + assertThat( + journal.recordRetryableEffectForDispatch( + original, + RetrySource.NOT_DISPATCHED, + "TRANSPORT_REFUSED", + firstDispatch.plusNanos(200))) + .isTrue(); + OutboxEntry replacement = + journal.claimEffect(operationId, effectId, attemptId, firstDispatch.plusNanos(300)); + assertThat(replacement.lastAttemptId()).isEqualTo(attemptId); + assertThat(replacement.attemptCount()).isEqualTo(original.attemptCount() + 1); + assertThat(dsl.fetchSingle(dispatchTimeQuery, replacement.outboxId()).get(0)) + .isEqualTo(firstStoredDispatch); + + Instant receivedAt = firstDispatch.plusNanos(600); + String before = storedOutbox(operationId, effectId); + Operation operation = journal.find(operationId).orElseThrow(); + assertThatThrownBy(() -> journal.recordEffectReadback(original, oldReadback, receivedAt)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback dispatch generation changed"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat(journal.find(operationId)).contains(operation); + assertThat(journal.findNextEffect(operationId)).contains(replacement); + + var currentReadback = + readbackFor( + replacement, + attemptId, + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "replacement-observation", + firstDispatch.plusNanos(500)); + assertThat(journal.recordEffectReadback(replacement, currentReadback, receivedAt)) + .isEqualTo(operation); + assertThat(storedOutbox(operationId, effectId)).contains(tupleCodec.digest(currentReadback)); + assertThat(journal.findNextEffect(operationId)) + .get() + .extracting(OutboxEntry::state) + .isEqualTo(EffectOutboxState.AMBIGUOUS); + } + + @ParameterizedTest(name = "prior claim: {0}") + @ValueSource(booleans = {false, true}) + void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) + throws Exception { String database = "legacy_closure_" + UUID.randomUUID().toString().replace("-", ""); dsl.execute("CREATE DATABASE " + database); String canonicalUrl = POSTGRES.getJdbcUrl(); @@ -1143,15 +1144,16 @@ void migrationRefusesClaimedLegacyOutboxAndRollsBack() throws Exception { legacy.transition(transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base); legacy.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base); OutboxEntry pending = legacy.findNextEffect(scope.operationId()).orElseThrow(); - UUID legacyAttempt = UUID.randomUUID(); - assertThat( - legacyDsl.execute( - "UPDATE recovery_control.initial_gameplay_release_outbox " - + "SET state='dispatched', attempt_count=1, last_attempt_id=?, " - + "last_dispatched_at=now() WHERE outbox_id=?", - legacyAttempt, - pending.outboxId())) - .isEqualTo(1); + if (claimed) { + assertThat( + legacyDsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox " + + "SET state='dispatched', attempt_count=1, last_attempt_id=?, " + + "last_dispatched_at=now() WHERE outbox_id=?", + UUID.randomUUID(), + pending.outboxId())) + .isEqualTo(1); + } OutboxEntry before = legacy.findNextEffect(scope.operationId()).orElseThrow(); Flyway upgrade = Flyway.configure() @@ -1160,16 +1162,31 @@ void migrationRefusesClaimedLegacyOutboxAndRollsBack() throws Exception { .defaultSchema(SCHEMA) .locations("classpath:db/recovery-control-migration") .load(); - assertThatThrownBy(() -> upgrade.migrate()) - .hasStackTraceContaining("requires no prior claims"); - assertThat(legacy.findNextEffect(scope.operationId())).contains(before); - assertThat( - legacyDsl - .fetchSingle( - "SELECT to_regclass('recovery_control.initial_gameplay_release_attempt_closure')") - .get(0)) - .isNull(); - assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("1"); + if (claimed) { + assertThatThrownBy(() -> upgrade.migrate()) + .hasStackTraceContaining("requires no prior claims"); + assertThat(legacy.findNextEffect(scope.operationId())).contains(before); + assertThat( + legacyDsl + .fetchSingle( + "SELECT to_regclass('recovery_control.initial_gameplay_release_attempt_closure')") + .get(0)) + .isNull(); + assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("1"); + } else { + upgrade.migrate(); + assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("2"); + assertThat(legacy.findNextEffect(scope.operationId())).contains(pending); + UUID freshAttempt = UUID.randomUUID(); + OutboxEntry dispatched = + legacy.claimEffect( + scope.operationId(), pending.effect().effectId(), freshAttempt, base); + assertThat(dispatched.outboxId()).isEqualTo(pending.outboxId()); + assertThat(dispatched.effect()).isEqualTo(pending.effect()); + assertThat(dispatched.state()).isEqualTo(EffectOutboxState.DISPATCHED); + assertThat(dispatched.lastAttemptId()).isEqualTo(freshAttempt); + assertThat(dispatched.attemptCount()).isEqualTo(1); + } } } finally { dsl.execute("DROP DATABASE " + database); diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 7e17c331fe..67f8c89576 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java @@ -20,7 +20,9 @@ import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.MaintenanceLockPresence; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Mutation; import net.firedevops.firemud.common.recovery.InitialGameplayRecoverRequest.Target; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; +import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal.RetrySource; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseTupleCodec; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseCommands.Resume; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.InitialGameplayReleaseEvidence; @@ -32,8 +34,12 @@ import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.Scope; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.TransitionVerb; import net.firedevops.firemud.recovery.model.MaintenanceLockCredential; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort.EffectApplyResult; +import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.EvidenceResolution; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider.ResolutionStatus; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; @@ -199,20 +205,33 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { @Test void pendingEffectClaimedByAnotherAttemptDoesNotDispatch() { - assertPendingClaimHandling(false, false); + assertPendingClaimHandling(false, null, null); } @Test void pendingEffectApplyExceptionRecordsAmbiguousNotRetryable() { - assertPendingClaimHandling(true, true); + assertPendingClaimHandling(true, null, null); } @Test void pendingEffectAmbiguousResultUsesClaimedDispatch() { - assertPendingClaimHandling(true, false); + assertPendingClaimHandling(true, EffectApplyResult.ambiguous("OWNER_PENDING"), null); } - private void assertPendingClaimHandling(boolean ownsClaim, boolean transportException) { + @Test + void pendingEffectNotDispatchedRecordsLocalRetryProvenance() { + assertPendingClaimHandling( + true, EffectApplyResult.notDispatched("TRANSPORT_REFUSED"), RetrySource.NOT_DISPATCHED); + } + + @Test + void pendingEffectDefinitiveOwnerRejectionRecordsOwnerRetryProvenance() { + assertPendingClaimHandling( + true, EffectApplyResult.retryableNoEffect("OWNER_REJECTED"), RetrySource.OWNER_REJECTED); + } + + private void assertPendingClaimHandling( + boolean ownsClaim, EffectApplyResult applyResult, RetrySource expectedRetrySource) { var journal = mock(InitialGameplayReleaseJournal.class); var port = mock(InitialGameplayReleaseEffectPort.class); var operation = mock(Operation.class); @@ -259,13 +278,11 @@ private void assertPendingClaimHandling(boolean ownsClaim, boolean transportExce if (ownsClaim) when(claimed.effect()).thenReturn(effect); return claimed; }); - if (ownsClaim && transportException) { + if (ownsClaim && applyResult == null) { when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) .thenThrow(new IllegalStateException("response lost after possible owner send")); } else if (ownsClaim) { - when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) - .thenReturn( - InitialGameplayReleaseEffectPort.EffectApplyResult.ambiguous("OWNER_PENDING")); + when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())).thenReturn(applyResult); } var controller = new InitialGameplayReleaseController( @@ -275,19 +292,31 @@ private void assertPendingClaimHandling(boolean ownsClaim, boolean transportExce port); assertThat(controller.reconcileNextEffect(operationId)).isSameAs(after); assertThat(claimedAttempt.get()).isNotNull(); - verify(journal, never()).recordRetryableEffectForDispatch(any(), any(), any()); - verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); - if (ownsClaim) { + if (expectedRetrySource == null) { + verify(journal, never()).recordRetryableEffectForDispatch(any(), any(), any(), any()); + } else { + verify(journal) + .recordRetryableEffectForDispatch( + org.mockito.ArgumentMatchers.same(claimed), + org.mockito.ArgumentMatchers.eq(expectedRetrySource), + org.mockito.ArgumentMatchers.eq(applyResult.outcomeCode()), + any()); + } + verify(journal, never()).recordEffectReadback(any(), any(), any()); + if (!ownsClaim) { + verifyNoInteractions(port); + } else { verify(port).apply(effect, claimedAttempt.get()); verify(port, never()).readback(any(), any()); + } + if (ownsClaim && expectedRetrySource == null) { verify(journal) .recordAmbiguousEffectForDispatch( org.mockito.ArgumentMatchers.same(claimed), org.mockito.ArgumentMatchers.eq( - transportException ? "EFFECT_CALL_OUTCOME_UNKNOWN" : "OWNER_PENDING"), + applyResult == null ? "EFFECT_CALL_OUTCOME_UNKNOWN" : applyResult.outcomeCode()), any()); } else { - verifyNoInteractions(port); verify(journal, never()).recordAmbiguousEffectForDispatch(any(), any(), any()); } } @@ -312,17 +341,19 @@ void applyOutcomeCodesUseJournalContract() { .isEqualTo("OWNER_BUSY"); } - @Test - void unavailableOwnerEvidenceReturnsConcurrentExactCommittedTransition() { - assertUnavailableTransition(true); + @ParameterizedTest + @EnumSource(ResolutionStatus.class) + void ownerEvidenceFailureReturnsConcurrentExactCommittedTransition(ResolutionStatus status) { + assertEvidenceFailureTransition(status, true); } - @Test - void unavailableOwnerEvidenceWithoutCommittedTransitionStillFailsClosed() { - assertUnavailableTransition(false); + @ParameterizedTest + @EnumSource(ResolutionStatus.class) + void ownerEvidenceFailureWithoutCommittedTransitionStillFailsClosed(ResolutionStatus status) { + assertEvidenceFailureTransition(status, false); } - private void assertUnavailableTransition(boolean committed) { + private void assertEvidenceFailureTransition(ResolutionStatus status, boolean committed) { var journal = mock(InitialGameplayReleaseJournal.class); var codec = mock(InitialGameplayReleaseTupleCodec.class); var provider = mock(InitialGameplayReleaseEvidenceProvider.class); @@ -360,8 +391,13 @@ private void assertUnavailableTransition(boolean committed) { .thenReturn( java.util.Optional.empty(), committed ? java.util.Optional.of(after) : java.util.Optional.empty()); - when(provider.read(scope)) - .thenReturn(InitialGameplayReleaseEvidenceProvider.EvidenceResolution.unavailable()); + InitialGameplayReleaseEvidence changedEvidence = null; + if (status == ResolutionStatus.AVAILABLE) { + changedEvidence = mock(InitialGameplayReleaseEvidence.class); + when(changedEvidence.evidenceIdentity()).thenReturn("proof"); + when(codec.digest(changedEvidence)).thenReturn("d".repeat(64)); + } + when(provider.read(scope)).thenReturn(new EvidenceResolution(status, changedEvidence)); var controller = new InitialGameplayReleaseController( journal, codec, provider, mock(InitialGameplayReleaseEffectPort.class)); @@ -369,10 +405,14 @@ private void assertUnavailableTransition(boolean committed) { if (committed) { assertThat(controller.resume(command)).isSameAs(after); + } else if (status == ResolutionStatus.AVAILABLE) { + assertThatThrownBy(() -> controller.resume(command)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("owner evidence changed after readiness was recorded"); } else { assertThatThrownBy(() -> controller.resume(command)) .isInstanceOf(OwnerBoundaryUnavailableException.class) - .hasMessage("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_UNAVAILABLE"); + .hasMessage("INITIAL_GAMEPLAY_RELEASE_EVIDENCE_" + status.name()); } verify(journal, org.mockito.Mockito.times(2)).findTransition(tuple); verify(journal, never()).transition(any(), any()); @@ -459,7 +499,7 @@ private void assertReadbackFailureReloadsLatestOperation(boolean throwsException assertThat(controller.reconcileNextEffect(scope.operationId())).isSameAs(after); verify(effectPort).readback(effect, attempt); - verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); + verify(journal, never()).recordEffectReadback(any(), any(), any()); } @Test @@ -541,6 +581,6 @@ void futureDatedOwnerReadbackCannotAdvanceJournal() { assertThatThrownBy(() -> controller.reconcileNextEffect(scope.operationId())) .isInstanceOf( net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException.class); - verify(journal, never()).recordEffectReadback(any(), any(), any(), any(), any()); + verify(journal, never()).recordEffectReadback(any(), any(), any()); } } From cc17d852ae9039e58425145b7f2f29c15f5b64af Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:48:25 +1300 Subject: [PATCH 087/199] Fence runtime publication and recovery readback races --- .github/actionlint.yaml | 3 + .../scripts/classify-change-scope.test.cjs | 1 + .github/workflows/ci.yml | 35 ++-- .github/workflows/preview-reconciler.yml | 165 +++++++++++++++- .github/workflows/preview-runtime-refresh.yml | 25 ++- .github/workflows/runtime-images.yml | 4 + .github/workflows/smoke.yml | 18 +- .github/workflows/static-analysis-summary.yml | 6 +- .../system-architecture-backup-recovery.md | 4 +- .../architecture/system-architecture-cicd.md | 4 +- .../hosted/shared/wait-for-runtime-images.sh | 141 ++++++++------ .../tests/ci-lightweight-scope-contract.sh | 7 +- ...d-identity-controller-workflow-contract.sh | 4 +- .../pr-required-gate-context-contract.sh | 89 ++++++++- .../tests/pr-retarget-workflow-contract.sh | 143 ++++++++++++++ .../pr-runtime-image-publication-contract.sh | 10 + dev-tools/tests/preview-priority-contract.sh | 180 ++++++++++++++++-- .../preview-runner-isolation-contract.sh | 1 + .../tests/preview-runtime-refresh.test.cjs | 43 ++++- ...otected-pod-admission-workflow-contract.sh | 14 +- .../tests/static-analysis-summary-contract.sh | 37 +++- dev-tools/validation/check-flyway-versions.py | 25 ++- .../JooqInitialGameplayReleaseJournal.java | 10 + .../model/InitialGameplayReleaseModel.java | 4 + ...eniedInitialGameplayReleaseEffectPort.java | 4 +- .../InitialGameplayReleaseController.java | 6 +- .../InitialGameplayReleaseEffectPort.java | 20 +- ...ReleaseJournalPostgresIntegrationTest.java | 45 ++++- .../InitialGameplayReleaseModelTest.java | 19 ++ .../InitialGameplayReleaseControllerTest.java | 28 +-- 30 files changed, 936 insertions(+), 159 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 1783aa6378..38448fa6ca 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -18,6 +18,9 @@ paths: .github/workflows/hosted-identity-request.yml: ignore: - 'unexpected key "queue" for "concurrency" section' + .github/workflows/runtime-images.yml: + ignore: + - 'unexpected key "queue" for "concurrency" section' .github/workflows/preview-cleanup-proof.yml: ignore: - 'unexpected key "queue" for "concurrency" section' diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 47cb2fd2fe..e5a45574bc 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -542,6 +542,7 @@ test("shared modules force every Gradle module, including common-redis-contracts ]); assert.equal(result.runAll, true); + assert.ok(result.affectedModules.includes("common-redis-contracts")); assert.deepEqual(result.affectedModules, ALL_MODULES); assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("recovery-controller-service", "hosted-environment-identity-controller")); }); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb43bfb061..412037d94e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,10 +112,10 @@ jobs: const moduleScopeAvailable = Array.isArray(scope.affectedModules) && Array.isArray(scope.bootableModules) && Array.isArray(ALL_MODULES) && completeModules.every(module => ALL_MODULES.includes(module)); - // An old module inventory must not turn proven documentation-only PRs - // into full builds. Re-read complete native paths rather than trusting - // an old classifier's module knowledge for new service directories. - let documentationOnly = false; + // Re-read complete native paths before preserving an older classifier's + // lightweight lane. Unrecognized service and runtime inputs keep full proof. + let lightweightFallback = false; + let fallbackPython = false; if (!moduleScopeAvailable && scope.lightweightOnly === true && context.eventName === "pull_request") { try { @@ -134,33 +134,40 @@ jobs: const knownDoc = path => path === "README.md" || (typeof path === "string" && /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && !path.split("/").includes("..")); + const knownValidationPython = path => typeof path === "string" && + /^dev-tools\/validation\/[A-Za-z0-9_./-]+\.py$/.test(path) && + !path.split("/").includes("..") && + path !== "dev-tools/validation/gradle-run-supervisor.py"; + const knownLightweightPath = path => knownDoc(path) || knownValidationPython(path); const after = (await github.rest.pulls.get({ ...context.repo, pull_number: eventPr.number, })).data; - documentationOnly = exactEvent(before) && exactEvent(after) && + lightweightFallback = exactEvent(before) && exactEvent(after) && Number.isInteger(context.payload.pull_request.changed_files) && entries.length > 0 && entries.length === context.payload.pull_request.changed_files && - entries.every(entry => entry && knownDoc(entry.filename) && + entries.every(entry => entry && knownLightweightPath(entry.filename) && ["added", "removed", "modified", "renamed"].includes(entry.status) && - (entry.status !== "renamed" || knownDoc(entry.previous_filename)) && - (entry.previous_filename === undefined || knownDoc(entry.previous_filename))); + (entry.status !== "renamed" || knownLightweightPath(entry.previous_filename)) && + (entry.previous_filename === undefined || knownLightweightPath(entry.previous_filename))); + fallbackPython = lightweightFallback && entries.some(entry => + knownValidationPython(entry.filename) || knownValidationPython(entry.previous_filename)); } catch { // Missing or incomplete native evidence keeps the full fallback. } } outputs = { - run_all: scope.runAll || (!moduleScopeAvailable && !documentationOnly), + run_all: scope.runAll || (!moduleScopeAvailable && !lightweightFallback), affected_services: scope.affectedServices, - affected_modules: documentationOnly ? [] : (moduleScopeAvailable ? scope.affectedModules : completeModules), - bootable_modules: documentationOnly ? [] : (moduleScopeAvailable ? scope.bootableModules : completeBootableModules), + affected_modules: lightweightFallback ? [] : (moduleScopeAvailable ? scope.affectedModules : completeModules), + bootable_modules: lightweightFallback ? [] : (moduleScopeAvailable ? scope.bootableModules : completeBootableModules), docs_changed: scope.docsChanged, frontend_changed: scope.frontendChanged, - python_changed: scope.pythonChanged, + python_changed: scope.pythonChanged || fallbackPython, design_docs_changed: scope.designDocsChanged, - validation_python_changed: scope.validationPythonChanged, + validation_python_changed: scope.validationPythonChanged || fallbackPython, postgres_runtime_proof_changed: scope.postgresRuntimeProofChanged === undefined ? true : scope.postgresRuntimeProofChanged, - lightweight_only: (moduleScopeAvailable || documentationOnly) && scope.lightweightOnly, + lightweight_only: (moduleScopeAvailable || lightweightFallback) && scope.lightweightOnly, }; } else { core.warning("Base revision predates the change classifier; using complete validation scope."); diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 36917c32c0..e9c6f1731c 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -276,6 +276,20 @@ jobs: local namespace_uid local namespace_resource_version local next_retry_count + local reservation_namespace_json + + proof_retry_reservation_count="" + proof_retry_previous_count="" + proof_retry_previous_base_sha="" + proof_retry_previous_head_sha="" + proof_retry_previous_merge_sha="" + proof_retry_previous_image_tag="" + proof_retry_reservation_namespace_uid="" + proof_retry_reservation_resource_version="" + proof_retry_reservation_base_sha="" + proof_retry_reservation_head_sha="" + proof_retry_reservation_merge_sha="" + proof_retry_reservation_image_tag="" if ! fresh_namespace_json="$( kubectl get namespace "${namespace}" --ignore-not-found -o json @@ -334,21 +348,110 @@ jobs: echo "Skipping PR #${pr_number}: proof retry budget exhausted for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}." >&2 return 3 fi - if ! kubectl annotate namespace "${namespace}" \ + if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ "firemud.dev/proof-retry-count=${next_retry_count}" \ "firemud.dev/proof-retry-base-sha=${base_sha}" \ "firemud.dev/proof-retry-head-sha=${head_sha}" \ "firemud.dev/proof-retry-merge-sha=${merge_sha}" \ "firemud.dev/proof-retry-image-tag=${image_tag}" \ --overwrite \ - --resource-version "${namespace_resource_version}" >/dev/null; then + --resource-version "${namespace_resource_version}" -o json)"; then echo "Skipping PR #${pr_number}: Namespace ${namespace} changed before proof retry evidence could be recorded." >&2 return 1 fi + proof_retry_reservation_count="${next_retry_count}" + proof_retry_previous_count="${retry_count}" + proof_retry_previous_base_sha="${retry_base_sha}" + proof_retry_previous_head_sha="${retry_head_sha}" + proof_retry_previous_merge_sha="${retry_merge_sha}" + proof_retry_previous_image_tag="${retry_image_tag}" + proof_retry_reservation_namespace_uid="${namespace_uid}" + proof_retry_reservation_resource_version="$(jq -er --arg uid "${namespace_uid}" \ + '.metadata | select(.uid == $uid) | .resourceVersion | select(type == "string" and length > 0)' \ + <<<"${reservation_namespace_json}" 2>/dev/null || true)" + proof_retry_reservation_base_sha="${base_sha}" + proof_retry_reservation_head_sha="${head_sha}" + proof_retry_reservation_merge_sha="${merge_sha}" + proof_retry_reservation_image_tag="${image_tag}" echo "Recorded proof retry ${next_retry_count}/3 for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag})." return 0 } + compensate_rejected_proof_retry() { + local namespace="$1" + local pr_number="$2" + local fresh_namespace_json + local fresh_namespace_tuple + local current_base_sha + local current_head_sha + local current_merge_sha + local current_image_tag + local retry_count + local retry_base_sha + local retry_head_sha + local retry_merge_sha + local retry_image_tag + local namespace_uid + local namespace_resource_version + local -a annotations=() + + if [[ -z "${proof_retry_reservation_count}" ]]; then + return 0 + fi + if ! fresh_namespace_json="$(kubectl get namespace "${namespace}" --ignore-not-found -o json)"; then + echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + if [[ -z "${fresh_namespace_json}" ]] || + ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then + echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ + _ _ _ _ _ _ _ _ _ retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ + namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "${namespace_uid}" != "${proof_retry_reservation_namespace_uid}" || + -z "${proof_retry_reservation_resource_version}" || + "${namespace_resource_version}" != "${proof_retry_reservation_resource_version}" || + "${current_base_sha}" != "${proof_retry_reservation_base_sha}" || + "${current_head_sha}" != "${proof_retry_reservation_head_sha}" || + "${current_merge_sha}" != "${proof_retry_reservation_merge_sha}" || + "${current_image_tag}" != "${proof_retry_reservation_image_tag}" || + "${retry_count}" != "${proof_retry_reservation_count}" || + "${retry_base_sha}" != "${proof_retry_reservation_base_sha}" || + "${retry_head_sha}" != "${proof_retry_reservation_head_sha}" || + "${retry_merge_sha}" != "${proof_retry_reservation_merge_sha}" || + "${retry_image_tag}" != "${proof_retry_reservation_image_tag}" || + -z "${namespace_resource_version}" ]]; then + echo "Proof-retry reservation for PR #${pr_number} changed before confirmed-rejection compensation; leaving its budget charged." >&2 + return 1 + fi + + if [[ -n "${proof_retry_previous_count}" ]]; then + annotations+=( + "firemud.dev/proof-retry-count=${proof_retry_previous_count}" + "firemud.dev/proof-retry-base-sha=${proof_retry_previous_base_sha}" + "firemud.dev/proof-retry-head-sha=${proof_retry_previous_head_sha}" + "firemud.dev/proof-retry-merge-sha=${proof_retry_previous_merge_sha}" + "firemud.dev/proof-retry-image-tag=${proof_retry_previous_image_tag}" + ) + else + annotations+=( + firemud.dev/proof-retry-count- + firemud.dev/proof-retry-base-sha- + firemud.dev/proof-retry-head-sha- + firemud.dev/proof-retry-merge-sha- + firemud.dev/proof-retry-image-tag- + ) + fi + if ! kubectl annotate namespace "${namespace}" "${annotations[@]}" \ + --overwrite --resource-version "${namespace_resource_version}" >/dev/null; then + echo "Unable to release rejected proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + echo "Released proof-retry reservation for PR #${pr_number} after GitHub confirmed dispatch rejection." + } + active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" available_slots=$((max_active - active_count)) dispatch_sent=false @@ -365,6 +468,7 @@ jobs: and (.event | type == "string" and length > 0) and (.path | type == "string" and length > 0) and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) + and (if .status == "completed" then (.conclusion | type == "string" and length > 0) else true end) ' <<<"$latest" >/dev/null || return 2 jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' .id == $id and .head_sha == $head @@ -373,7 +477,7 @@ jobs: and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) ' <<<"$latest" >/dev/null || return 1 - if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi + if jq -e '.status == "completed" and .conclusion != "success"' <<<"$latest" >/dev/null; then return 1; fi [[ "$jobs_available" == true ]] || return 2 jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' @@ -382,7 +486,8 @@ jobs: and (.total_count < 100) and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) and any($jobs[]; - .name == "Preview Plan" and .run_id == $id and .run_attempt == $attempt + .name == "Preview Plan" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) and .head_sha == $head and .status == "completed" and .conclusion == "success" and ([.steps[]? | select(.name | startswith("Preview resolved tuple "))] | length == 1) and any(.steps[]?; @@ -392,6 +497,11 @@ jobs: jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) ' <<<"$jobs" >/dev/null || return 1 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + # The trusted consumer may be queued after the active-run inventory. + # Defer one cycle after an exact successful source completion. + return 3 + fi } trusted_consumer_has_tuple() { @@ -419,7 +529,8 @@ jobs: | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) and ([$jobs[] | select(.name == "Validate Trusted Preview Target")] | length == 1) and any($jobs[]; .name == "Validate Trusted Preview Target" and .run_id == $id - and .run_attempt == $attempt and .head_sha == $head and .status == "completed") + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed") ' <<<"$jobs" >/dev/null || return 2 jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Validate Trusted Preview Target" and .conclusion == "success"); @@ -687,6 +798,7 @@ jobs: active_preview_run_id="$(jq -rs '[.[] | select(.exact)][0].id // empty' <<<"$preview_candidates")" active_preview_lookup_unknown=false + completed_preview_handoff_run_id="" if [[ -z "$active_preview_run_id" ]]; then # A same-head title is not proof: the base can move independently. tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" @@ -708,6 +820,9 @@ jobs: if [[ "$lookup_status" -eq 0 ]]; then active_preview_run_id="$run_id" break + elif [[ "$lookup_status" -eq 3 ]]; then + completed_preview_handoff_run_id="$run_id" + break elif [[ "$lookup_status" -eq 2 ]]; then active_preview_lookup_unknown=true fi @@ -718,6 +833,10 @@ jobs: echo "Skipping proof retry for PR #${pr_number}: preview source or trusted consumer run ${active_preview_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." continue fi + if [[ -n "${completed_preview_handoff_run_id}" ]]; then + echo "Deferring proof retry for PR #${pr_number}: successful exact preview source run ${completed_preview_handoff_run_id} may still be handing off to the trusted consumer." + continue + fi if [[ "$active_preview_lookup_unknown" == true ]]; then echo "Skipping proof retry for PR #${pr_number}: active preview tuple lookup unavailable; retry budget unchanged." continue @@ -732,11 +851,24 @@ jobs: require_deployed_tuple=true fi # A consumer may finish deployment and proof during the active-run lookup. + local proof_retry_reservation_count="" + local proof_retry_previous_count="" + local proof_retry_previous_base_sha="" + local proof_retry_previous_head_sha="" + local proof_retry_previous_merge_sha="" + local proof_retry_previous_image_tag="" + local proof_retry_reservation_namespace_uid="" + local proof_retry_reservation_resource_version="" + local proof_retry_reservation_base_sha="" + local proof_retry_reservation_head_sha="" + local proof_retry_reservation_merge_sha="" + local proof_retry_reservation_image_tag="" prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ "$require_deployed_tuple" "$priority" || continue echo "Dispatching preview render for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag}) from trusted ref ${DEFAULT_BRANCH}" - gh api \ + dispatch_exit=0 + if dispatch_response="$(gh api --include \ --method POST \ "repos/${GITHUB_REPOSITORY}/dispatches" \ -f event_type=preview-deploy \ @@ -747,8 +879,25 @@ jobs: -f "client_payload[base_sha]=${base_sha}" \ -f "client_payload[merge_sha]=${merge_sha}" \ -f "client_payload[image_tag]=${image_tag}" \ - -f 'client_payload[preview_domain]=preview.firedevops.net' - dispatch_sent=true + -f 'client_payload[preview_domain]=preview.firedevops.net')"; then + dispatch_exit=0 + else + dispatch_exit=$? + fi + dispatch_status_line_count="$(grep -cE '^HTTP/[0-9.]+ [0-9]{3} ' <<<"${dispatch_response}" || true)" + dispatch_http_status="$(awk '/^HTTP\/[0-9.]+ [0-9][0-9][0-9] / { print $2; exit }' <<<"${dispatch_response}")" + if [[ "${dispatch_exit}" -eq 0 && "${dispatch_status_line_count}" -eq 1 && + "${dispatch_http_status}" == 204 ]]; then + dispatch_sent=true + elif [[ "${dispatch_status_line_count}" -eq 1 && "${dispatch_http_status}" =~ ^4[0-9][0-9]$ ]]; then + echo "GitHub confirmed preview dispatch rejection for PR #${pr_number} (HTTP ${dispatch_http_status})." + if ! compensate_rejected_proof_retry "$namespace" "$pr_number"; then + echo "The rejected dispatch could not be safely compensated; its proof-retry budget remains charged." >&2 + fi + else + echo "Preview dispatch outcome for PR #${pr_number} is ambiguous (gh=${dispatch_exit}, HTTP=${dispatch_http_status:-unknown}); proof-retry budget remains charged." >&2 + dispatch_sent=true + fi done } diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index c5aa8c7f3d..150b7ed403 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -83,7 +83,7 @@ jobs: return; } const plan = plans[0]; - if (plan.run_id !== run.id || plan.run_attempt !== attempt || + if (plan.run_id !== run.id || (plan.run_attempt !== undefined && plan.run_attempt !== attempt) || plan.head_sha !== run.head_sha || plan.status !== 'completed' || plan.conclusion !== 'success' || !Array.isArray(plan.steps)) { core.info('No successful Preview Plan for the exact source attempt; no dispatch.'); @@ -169,11 +169,18 @@ jobs: } const resolvedMatchesRecorded = resolved[4] === recordedMerge.sha && resolved[2] === recordedMerge.parents[0].sha; - const resolvedMatchesCurrent = resolved[4] === merge.sha && resolved[2] === base.object.sha; // A stale event base can accompany a newer historical merge. Its // plan must independently resolve that merge and its actual parent. - if ((!resolvedMatchesRecorded && !resolvedMatchesCurrent) || - (recordedMerge.parents[0].sha !== recorded[2] && !resolvedMatchesRecorded)) { + if (recordedMerge.parents[0].sha !== recorded[2] && !resolvedMatchesRecorded) { + core.info('Recorded merge and event base disagree without exact resolved evidence; no dispatch.'); + return; + } + let resolvedMerge = resolved[4] === recordedMerge.sha ? recordedMerge : merge; + if (resolved[4] !== resolvedMerge.sha) { + ({data: resolvedMerge} = await github.rest.repos.getCommit({...context.repo, ref: resolved[4]})); + } + if (resolvedMerge?.sha !== resolved[4] || resolvedMerge.parents?.length !== 2 || + resolvedMerge.parents[0].sha !== resolved[2] || resolvedMerge.parents[1].sha !== resolved[3]) { core.info('Resolved preview tuple does not match its verified merge parents; no dispatch.'); return; } @@ -236,6 +243,16 @@ jobs: if (page === 3) throw new Error('Active runtime inventory exceeds bounded lookup'); } } + const {data: latestRun} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: run.id, + }); + if (latestRun?.id !== run.id || latestRun.run_attempt !== attempt || + latestRun.head_sha !== run.head_sha || latestRun.event !== run.event || + latestRun.path !== run.path || latestRun.status !== 'completed' || + latestRun.conclusion !== run.conclusion) { + core.info('Source attempt changed during runtime lookup; no dispatch.'); + return; + } const {data: latestPr} = await github.rest.pulls.get({ ...context.repo, pull_number: source.number, }); diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 7053485ce6..62615d551f 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1974,6 +1974,10 @@ jobs: 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 + concurrency: + group: runtime-image-promotion-${{ needs.image-meta.outputs.head_branch }} + cancel-in-progress: false + queue: max permissions: contents: read packages: write diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 767973543c..472f6777c0 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -572,7 +572,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "d237e316d765c6f0c2ec5569af93cbaf218d1f9c65e0877eec1ed2f87c6a0457"; + const canonicalRuntimeWorkflowSha256 = "777b2527be618a77674d20338ca30bca771f81afd010165bb33b2b72465779df"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", @@ -1555,10 +1555,18 @@ jobs: core.info("Current-base identity changed after the final runtime attempt lookup; resume exact selection."); continue smokeGatePolling; } - const { data: acceptanceAttempt } = await withTransientGitHubRetry( - "current-base runtime attempt lookup after live identity validation", - () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) - ); + let acceptanceAttempt; + try { + ({ data: acceptanceAttempt } = await withTransientGitHubRetry( + "current-base runtime attempt lookup after live identity validation", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + )); + } catch (error) { + if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( + `Runtime alternative ${matching.id} final current-base attempt is temporarily unavailable; retry exact primary selection.` + )) continue smokeGatePolling; + throw error; + } if (acceptanceAttempt.id !== matching.id || acceptanceAttempt.run_attempt !== matching.run_attempt || acceptanceAttempt.status !== "completed" || acceptanceAttempt.conclusion !== "success") { diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index fa300ba9e6..92f34646f8 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -220,7 +220,7 @@ jobs: job.conclusion === "skipped" && (job.name === metadataName || String(job.name || "").includes("'" + metadataName + "'"))); const substantive = data.jobs.some(job => job.name === gateName); - if (metadata && !substantive) continue; + if (metadata && !substantive && candidate.conclusion === "skipped") continue; if (!substantive) { if (candidate.status === "completed" && terminalFailure.has(candidate.conclusion)) { return { ...candidate, jobs: data.jobs }; @@ -241,8 +241,8 @@ jobs: checkName.startsWith("CodeQL Analysis (") && workflowRun?.status === "completed" ) { - // A failed producer without a language job did not establish a skip. - if (terminalFailure.has(workflowRun.conclusion)) return "unavailable"; + // A failed run or partial rerun without a language job did not prove a skip. + if (terminalFailure.has(workflowRun.conclusion) || workflowRun.run_attempt > 1) return "unavailable"; return "skipped"; } if (workflowRun?.status === "completed") { diff --git a/design/architecture/system-architecture-backup-recovery.md b/design/architecture/system-architecture-backup-recovery.md index d1a01315d9..f662cceef2 100644 --- a/design/architecture/system-architecture-backup-recovery.md +++ b/design/architecture/system-architecture-backup-recovery.md @@ -84,13 +84,13 @@ For the pre-release `secretComplianceRefresh` handoff, the recovery controller i ### Source-Only Initial Gameplay Release Foundation -`recovery-controller-service` retains an isolated `initial_gameplay_release` journal, immutable scope/evidence tuples, guarded continuation/resume transitions, and a transactional effect outbox. Its PostgreSQL endpoint must be a dedicated recovery-control instance and volume outside business restore targets; configuration deliberately has no shared-business-database fallback. This foundation is not deployed or registered as a runtime service. +`recovery-controller-service` retains an isolated `initial_gameplay_release` journal, immutable scope/evidence tuples, guarded continuation/resume transitions, and a transactional effect outbox. Its PostgreSQL endpoint must be a dedicated recovery-control instance and volume outside business restore targets; configuration deliberately has no shared-business-database fallback. This foundation is not deployed or registered as a runtime service. A source-only upgrade of an existing fixture or development database requires stopping and draining all V1 writers before applying V2, and keeping them stopped through validation. The migration refuses prior claims, and its table lock protects the inspection and migration transaction. Mixed-version writing is unsupported. The typed `initial-gameplay-recover/v1` request binds the control-plane request, recovery operation, canonical tenant, Kubernetes target namespace, separate playable-state namespace, Game Session instance/launch association, peer/storage binding, and evidence/audit selectors. These selectors are not authority. The public owner entry point remains unconditionally fail-closed before journal, evidence, or effect interactions. No public ingress, scheduler, or effect dispatcher is registered; default evidence and effect ports deny. Activation still requires real Account authorization/redemption, authenticated owner association/storage verification, an independently proved exclusive maintenance fence and actual acquired lock, genuine current owner evidence/readbacks, and approved isolated deployment/restore topology. A random journal UUID is not a lock or exclusion proof. Later continuation and resume bind the exact retained scope, lock, phase, and evidence; ambiguous effects cannot authorize redispatch or final handoff. Source-level journal tests do not establish these missing end-to-end prerequisites or player-facing recovery readiness. -Outcomes and readbacks are bound to the exact effect attempt and dispatch generation. A definite owner rejection permanently retires that attempt ID, while a locally proved no-send outcome permits another dispatch generation with the same ID. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. A current readback carries an original owner observation time comparable to the controller clock. When newer partial evidence supersedes a definitive observation, progress requires fresh authoritative evidence from the owner. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. +Outcomes and readbacks are bound to the exact effect attempt and dispatch generation. A definite owner rejection permanently retires that attempt ID, while a locally proved no-send outcome permits another dispatch generation with the same ID. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. A current readback carries the requested dispatch generation and an original owner observation time comparable to the controller clock. When newer partial evidence supersedes a definitive observation, progress requires fresh authoritative evidence from the owner. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. The exclusive-fence activation work must also prove the region lease belongs to the requested scope, prevent or reject lease replacement between evidence read and journal authorization/effect application, and define an audited restart or abandonment path after lease replacement that never releases the maintenance fence prematurely. Those owner protocols are not implemented by the source-only journal; a retained evidence snapshot is not a current lease lock. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6d94b497fa..5622c01ede 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -217,6 +217,8 @@ Release dependency-notice automation is a separate concern from repository scrip --- +Runtime image builds and smoke proof retain their source commit and attempt identity. The branch promotion job serializes mutable-tag updates for each branch and verifies its live head inside the promotion queue. + ## PR Preview Environments FireMUD's preview workflow is reserved for real reviewer-accessible PR environments, not CI-only stack boot validation. The [`.github/workflows/preview.yml`](../../.github/workflows/preview.yml) workflow targets a hosted single-node k3s cluster and follows this contract: @@ -238,7 +240,7 @@ Hosted verification waits for the complete readiness tuple defined by the owning Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. -Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. +Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. A successful exact source completion during lookup defers one retry cycle while its trusted consumer may enter the queue. A confirmed GitHub dispatch rejection releases only the matching Namespace retry reservation, fenced by the returned resource version. An uncertain dispatch outcome leaves the reservation charged. The initial Telnet-first hosted milestone is complete. Continuing preview acceptance follows [ADR 0178](decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md): one shared semantic authenticated, admitted, `LOOK` assertion set is exercised through both the public Telnet path and the deployed first-party browser path. Telnet proves TCP Proxy and bridge/framing behavior. The bounded browser journey proves frontend delivery, HTTPS bootstrap and discovery, connect-token cookie and `/ws/game/**` admission, one reconnect, logout, and non-reuse. Direct backend WebSocket smoke remains CI or diagnostic evidence rather than a substitute or third required hosted path. Dedicated frontend delivery and the browser journey remain implementation gaps, so current TCP/Telnet preview proof is not yet transport-complete. diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 34cddf402d..6372f1e045 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -276,6 +276,7 @@ if wait_mode == "pull-request": ] else: matching_runs = [] +all_candidates = len(sys.argv) > 9 and sys.argv[9] == "all" if len(sys.argv) > 7: event, title = sys.argv[7:9] matching_runs = [run for run in matching_runs if run.get("event") == event @@ -285,15 +286,16 @@ if not matching_runs: print("missing") raise SystemExit(0) -run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True)[0] -print( - "found\t{}\t{}\t{}\t{}".format( - run.get("id", ""), - run.get("status", ""), - run.get("conclusion", ""), - run.get("html_url", ""), +ranked = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True) +for run in ranked if all_candidates else ranked[:1]: + print( + "found\t{}\t{}\t{}\t{}".format( + run.get("id", ""), + run.get("status", ""), + run.get("conclusion", ""), + run.get("html_url", ""), + ) ) -) ' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" } @@ -308,9 +310,10 @@ fetch_alternate_run_metadata() { # immutable tuple, which the trusted publisher revalidates before writing. # Both paths need a positive publication step in the exact current attempt. use_completed_duplicate_publication() { - local state older_id older_created source_event inventory upper line publisher_id run attempt jobs latest publisher_path default_branch repository_info + local state older_id older_created source_event inventory upper publisher_lines publisher_id publisher_status publisher_conclusion local source_state="$1" lookup_deadline="$2" remaining local source source_attempt source_title source_latest publisher_event expected_title + local run attempt jobs latest publisher_path default_branch repository_info IFS=$'\t' read -r state older_id _ _ _ source_event older_created <<<"$source_state" [[ "$state" == "found" ]] || return 1 source="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 @@ -332,52 +335,58 @@ use_completed_duplicate_publication() { remaining=$((lookup_deadline - SECONDS)) (( remaining > 0 )) || return 1 inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || return 1 - line="$(read_publisher_state "$older_id" "$publisher_event" "$expected_title" <<<"$inventory")" || return 1 - IFS=$'\t' read -r state publisher_id _ <<<"$line" - [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ ]] || return 1 - run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 - publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || return 1 + publisher_lines="$(read_publisher_state "$older_id" "$publisher_event" "$expected_title" all <<<"$inventory")" || return 1 + [[ "$publisher_lines" != "missing" ]] || return 1 repository_info="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}")" || return 1 default_branch="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' select(.full_name == $repo) | .default_branch | select(type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._/-]*$")) ' <<<"$repository_info")" || return 1 - # Either event runs on the default branch; a short path suffix must agree. - [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || - "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || return 1 - attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ - --arg title "$expected_title" --arg event "$publisher_event" ' - select(.id == $id and .event == $event and .display_title == $title - and .path == $path and .head_branch == $branch - and .repository.full_name == $repo and .head_repository.full_name == $repo - and .status == "completed" and .conclusion == "success") - | .run_attempt | select(type == "number" and . >= 1 and floor == .) - ' <<<"$run")" || return 1 - jobs="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || return 1 - jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' - (.jobs | type == "array") and (.total_count == (.jobs | length)) and - ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | - ($jobs | length) == 1 and ($jobs[0] | - .run_id == $id and .run_attempt == $attempt and - .status == "completed" and .conclusion == "success" and - ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | - ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) - ' <<<"$jobs" >/dev/null || return 1 - latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || return 1 - jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" \ - --arg title "$expected_title" --arg event "$publisher_event" --arg repo "$GITHUB_REPOSITORY" ' - .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" - and .path == $path and .head_branch == $branch and .event == $event and .display_title == $title - and .repository.full_name == $repo and .head_repository.full_name == $repo - ' <<<"$latest" >/dev/null || return 1 - source_latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 - jq -e --argjson attempt "$source_attempt" --arg repo "$GITHUB_REPOSITORY" --arg title "$source_title" --arg head "$head_sha" ' - .run_attempt == $attempt and .repository.full_name == $repo and .head_repository.full_name == $repo - and .display_title == $title and (.event != "pull_request" or .head_sha == $head) - ' <<<"$source_latest" >/dev/null || return 1 - [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$source_state" ]] || return 1 - (( SECONDS < lookup_deadline )) || return 1 - printf 'Trusted PR image publisher %s succeeded for %s via an alternate producer.\n' "$publisher_id" "$image_tag" + while IFS=$'\t' read -r state publisher_id publisher_status publisher_conclusion _; do + [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ && + "$publisher_status" == "completed" && "$publisher_conclusion" == "success" ]] || continue + (( SECONDS < lookup_deadline )) || break + run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue + publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || continue + # Either event runs on the default branch; a short path suffix must agree. + [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || + "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || continue + attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ + --arg title "$expected_title" --arg event "$publisher_event" ' + select(.id == $id and .event == $event and .display_title == $title + and .path == $path and .head_branch == $branch + and .repository.full_name == $repo and .head_repository.full_name == $repo + and .status == "completed" and .conclusion == "success") + | .run_attempt | select(type == "number" and . >= 1 and floor == .) + ' <<<"$run")" || continue + jobs="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || continue + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' + (.jobs | type == "array") and (.total_count == (.jobs | length)) and + ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | + ($jobs | length) == 1 and ($jobs[0] | + .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and + .status == "completed" and .conclusion == "success" and + ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | + ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) + ' <<<"$jobs" >/dev/null || continue + latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" \ + --arg title "$expected_title" --arg event "$publisher_event" --arg repo "$GITHUB_REPOSITORY" ' + .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" + and .path == $path and .head_branch == $branch and .event == $event and .display_title == $title + and .repository.full_name == $repo and .head_repository.full_name == $repo + ' <<<"$latest" >/dev/null || continue + source_latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || continue + jq -e --argjson attempt "$source_attempt" --arg repo "$GITHUB_REPOSITORY" --arg title "$source_title" --arg head "$head_sha" ' + .run_attempt == $attempt and .repository.full_name == $repo and .head_repository.full_name == $repo + and .display_title == $title and (.event != "pull_request" or .head_sha == $head) + ' <<<"$source_latest" >/dev/null || continue + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$source_state" ]] || continue + (( SECONDS < lookup_deadline )) || break + printf 'Trusted PR image publisher %s succeeded for %s via an alternate producer.\n' "$publisher_id" "$image_tag" + return 0 + done <<<"$publisher_lines" + return 1 } find_completed_alternate_publication() { @@ -425,6 +434,18 @@ wait_for_pr_publisher() { return 0 fi fi + local refreshed_source_payload refreshed_alternates + if refreshed_source_payload="$(fetch_workflow_runs \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/runtime-images.yml/runs?per_page=100" \ + "refreshing alternate runtime-image sources while waiting for publication")"; then + if refreshed_alternates="$(read_run_state "${source_run_id}" alternates <<<"${refreshed_source_payload}")"; then + if [[ "${refreshed_alternates}" == "missing" ]]; then + alternate_sources="" + else + alternate_sources="${refreshed_alternates}" + fi + fi + fi if find_completed_alternate_publication "$alternate_sources" "$publisher_deadline"; then return 0 fi @@ -510,23 +531,27 @@ while (( SECONDS < deadline )); do continue fi - older_states="" - if [[ "$wait_mode" == "pull-request" && "$SECONDS" -lt "$deadline" ]]; then - if older_states="$(read_run_state "$run_id" alternates <<<"$workflow_payload")" && - find_completed_alternate_publication "$older_states" "$deadline"; then - exit 0 - fi - fi - if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then 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 + older_states="" + if [[ "$SECONDS" -lt "$deadline" ]]; then + older_states="$(read_run_state "$run_id" alternates <<<"${workflow_payload}")" || older_states="" + fi wait_for_pr_publisher "${run_id}" "${run_created_at}" "$older_states" fi exit 0 fi + older_states="" + if [[ "$wait_mode" == "pull-request" && "$SECONDS" -lt "$deadline" ]]; then + if older_states="$(read_run_state "$run_id" alternates <<<"$workflow_payload")" && + find_completed_alternate_publication "$older_states" "$deadline"; then + exit 0 + fi + fi + if [[ "${run_status}" == "completed" ]]; then printf 'Matching runtime-images workflow %s completed with %s for %s.\n' \ "${run_id}" "${run_conclusion}" "${image_tag}" >&2 diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 77766767f8..c083534b57 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -43,9 +43,12 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput assert.deepEqual(JSON.parse(outputs.bootable_modules), compatible ? ["account-service"] : [...BOOTABLE_MODULES]); } - for (const [entries, count, expected, drift] of [ + for (const [entries, count, expected, drift, expectsPython = false] of [ [[{filename: "design/README.md"}], 1, true], [[{filename: "README.md"}], 1, true], + [[{filename: "dev-tools/validation/check-flyway-versions.py"}], 1, true, undefined, true], + [[{filename: "dev-tools/validation/gradle-run-supervisor.py"}], 1, false], + [[{filename: "services/recovery-controller-service/src/main/java/Example.java"}], 1, false], [[{filename: "README.md", status: "renamed", previous_filename: "services/new-service/Main.java"}], 1, false], [[{filename: "design/README.md"}], 1, false, "head-before"], [[{filename: "design/README.md"}], 1, false, "head-after"], @@ -74,6 +77,8 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput head: {sha: "a".repeat(40)}, base: {sha: "b".repeat(40)}}}}, {setOutput: (name, value) => outputs[name] = value, warning() {}}); assert.equal(outputs.lightweight_only, String(expected)); + assert.equal(outputs.validation_python_changed, String(expectsPython)); + assert.equal(outputs.python_changed, String(expectsPython)); assert.equal(outputs.run_all, String(!expected)); assert.deepEqual(JSON.parse(outputs.affected_modules), expected ? [] : ALL_MODULES); assert.deepEqual(JSON.parse(outputs.bootable_modules), expected ? [] : [...BOOTABLE_MODULES]); diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index f9136a4b56..7ad7f995e8 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -4064,7 +4064,7 @@ run_preview_derive_target() { env \ PATH="$preview_derive_stub_dir:$PATH" \ EVENT_NAME=pull_request \ - GITHUB_REF=refs/heads/develop \ + GITHUB_REF=refs/pull/901/merge \ DEFAULT_BRANCH=develop \ EVENT_ACTION=synchronize \ EVENT_PR_NUMBER=901 \ @@ -4076,7 +4076,7 @@ run_preview_derive_target() { CLIENT_ACTION='' \ GITHUB_REPOSITORY=example/FireMUD \ GH_TOKEN=fake \ - GITHUB_SHA="$preview_derive_head_lower" \ + GITHUB_SHA="$preview_derive_merge_lower" \ PREVIEW_DERIVE_PR_JSON="$preview_derive_pr_json" \ PREVIEW_DERIVE_PR_JSON_1='' \ PREVIEW_DERIVE_PR_JSON_2='' \ diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 06f151244b..2fe62be1c7 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -114,13 +114,13 @@ for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{ raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") -def effective_group(group, action, base_ref): +def effective_group(group, action, base_ref, workflow_name="Required Gate"): values = { "github.event.changes.base.ref": repr(base_ref), "github.event.pull_request.number": "42", "github.event.action": repr(action), "github.event_name": "'pull_request'", - "github.workflow": "'Required Gate'", + "github.workflow": repr(workflow_name), "github.run_id": "123", "github.ref": "'refs/pull/42/merge'", } @@ -138,6 +138,19 @@ def effective_group(group, action, base_ref): return re.sub(r"\$\{\{(.*?)\}\}", render, group) +def cross_workflow_group_collisions(rendered_groups): + owners = {} + collisions = [] + for workflow, action, group in rendered_groups: + key = group.casefold() + prior = owners.get(key) + if prior is not None and prior[0] != workflow: + collisions.append((prior, (workflow, action, group))) + else: + owners[key] = (workflow, action, group) + return collisions + + def can_reuse_required_name(name, required_names): if not name: return False @@ -337,6 +350,31 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o assert collided != group and not isolates_metadata_group(collided, run_scoped), workflow if concurrency.get("cancel-in-progress") != "true": raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") + +rendered_substantive_groups = [] +for workflow, (workflow_name, *_rest) in gates.items(): + data = yaml.load((root / ".github/workflows" / workflow).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + group = data["concurrency"]["group"] + if data.get("name") != workflow_name: + raise SystemExit(f"{workflow} actual name must match its required-gate contract") + for action, base_ref in (("opened", None), ("synchronize", None), ("reopened", None), ("edited", "develop")): + rendered_substantive_groups.append(( + workflow, + action, + effective_group(group, action, base_ref, workflow_name), + )) + +collisions = cross_workflow_group_collisions(rendered_substantive_groups) +if collisions: + first, second = collisions[0] + raise SystemExit( + f"required workflows {first[0]} and {second[0]} share a substantive concurrency group " + f"for the same PR (case-insensitive): {first[2]!r} / {second[2]!r}" + ) +assert cross_workflow_group_collisions([ + ("validation.yml", "opened", "required-pr-42"), + ("smoke.yml", "edited", "REQUIRED-PR-42"), +]), "the collision detector must model GitHub's case-insensitive group comparison" PY # shellcheck disable=SC2016 # Match the checked-in arithmetic assignment literally. @@ -675,7 +713,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", captureLookupFailure = false) { let now = 1000, snapshots = 0, reads = 0, currentRunReads = 0, refreshInventoryReads = 0; - const liveFallback = kind.startsWith("trusted-current-base"); + const liveFallback = kind.startsWith("trusted-current-base") || kind === "optional-final-acceptance-transient"; const h0 = kind.startsWith("optional-final-read-"); const cancelledPrimary = kind === "optional-final-read-cancelled-primary"; const cancelledWithReplacement = kind === "optional-final-read-cancelled-with-replacement"; @@ -686,6 +724,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && badStatus === 503; const primaryReady = () => primaryCanRecover && primaryInventoryReads > 1; let alternativeJobsReads = 0, primaryInventoryReads = 0, lookupFailure; + let pullRequestLookups = 0, acceptanceLookupArmed = false, acceptanceLookupAttempts = 0; const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); const tupleAdvanced = () => kind === "trusted-current-base-advances" && currentRunReads >= 2; let rerunStartedDuringLatestIdentityRead = false; @@ -731,6 +770,10 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const github = {rest: { pulls: {get: async () => { reads += 1; + pullRequestLookups += 1; + if (kind === "optional-final-acceptance-transient" && pullRequestLookups === 4) { + acceptanceLookupArmed = true; + } if (kind === "trusted-current-base-attempt-advances" && currentRunReads >= 2) { rerunStartedDuringLatestIdentityRead = true; } @@ -753,6 +796,15 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal getWorkflowRun: async ({run_id: runId}) => { if (runId === 43 && primaryReady()) return {data: exactPrimary}; if (runId === 44 && cancelledWithReplacement) return {data: dispatchPrimary}; + if (kind === "optional-final-acceptance-transient" && runId === 44) { + return {data: {...source, id: 44, event: "repository_dispatch", head_sha: defaultSha, + head_branch: "develop", status: "completed", conclusion: "success"}}; + } + if (kind === "optional-final-acceptance-transient" && acceptanceLookupArmed) { + acceptanceLookupAttempts += 1; + if (acceptanceLookupAttempts === 4) acceptanceLookupArmed = false; + throw Object.assign(new Error("final current-base workflow-run lookup unavailable"), {status: 503}); + } currentRunReads += 1; if (finalAttemptError && currentRunReads >= 2) { throw Object.assign(new Error("alternative final workflow-run unavailable"), @@ -772,6 +824,10 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert.equal(input.attempt_number, exactPrimary.run_attempt); return {data: exactPrimary}; } + if (kind === "optional-final-acceptance-transient" && input.run_id === 44) { + return {data: {...source, id: 44, event: "repository_dispatch", head_sha: defaultSha, + head_branch: "develop", status: "completed", conclusion: "success"}}; + } if (cancelledWithReplacement && input.run_id === 44) { assert.equal(input.attempt_number, dispatchPrimary.run_attempt); return {data: dispatchPrimary}; @@ -790,6 +846,10 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } + if (kind === "optional-final-acceptance-transient" && input.run_id === 44) { + return [{...job, run_id: 44, head_sha: defaultSha, steps: [...job.steps, + {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + } if (cancelledWithReplacement && input.run_id === 44) { assert.equal(input.attempt_number, dispatchPrimary.run_attempt); return [{...job, run_id: 44, steps: [...job.steps, @@ -826,6 +886,18 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal }}; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); + if (kind === "optional-final-acceptance-transient" && input.event === "repository_dispatch") { + primaryInventoryReads += 1; + const pending = {...source, id: 44, event: "repository_dispatch", head_sha: defaultSha, + head_branch: "develop", created_at: "2026-09-01T00:00:01Z", + status: primaryInventoryReads === 1 ? "in_progress" : "completed", + conclusion: primaryInventoryReads === 1 ? null : "success"}; + const completed = {...source, id: 42, event: "repository_dispatch", head_sha: defaultSha, + head_branch: "develop", created_at: "2026-09-01T00:00:00Z", + status: "completed", conclusion: "success"}; + yield {data: primaryInventoryReads === 1 ? [pending, completed] : [pending]}; + return; + } if (h0 && input.event === "pull_request") { primaryInventoryReads += 1; const primary = {...exactPrimary, status: cancelledPrimary || cancelledWithReplacement || primaryReady() ? "completed" : "queued", @@ -863,7 +935,8 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal if (!captureLookupFailure) throw error; lookupFailure = error; } - return {failures, refs, snapshots, info, refreshInventoryReads, alternativeJobsReads, primaryInventoryReads, lookupFailure}; + return {failures, refs, snapshots, info, refreshInventoryReads, alternativeJobsReads, primaryInventoryReads, + acceptanceLookupAttempts, lookupFailure}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -917,6 +990,14 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert.deepEqual(result.failures, [], kind); if (kind.endsWith("-snapshot")) assert.equal(result.alternativeJobsReads, 11, kind); } + const finalCurrentBaseRetry = await scenario("optional-final-acceptance-transient", "repository_dispatch"); + assert.equal(finalCurrentBaseRetry.acceptanceLookupAttempts, 4, + "the final optional current-base attempt read must exhaust only its bounded transient retries"); + assert.equal(finalCurrentBaseRetry.primaryInventoryReads, 2, + "a transient final current-base attempt read must restore and reselect the pending exact producer"); + assert(finalCurrentBaseRetry.info.some(line => line.includes("Found runtime-images run 44 with status=completed"))); + assert.deepEqual(finalCurrentBaseRetry.failures, [], + "the pending exact producer may pass after the final transient read recovers"); for (const [kind, code] of [["optional-final-read-attempt-forbidden", 403], ["optional-final-read-attempt-missing", 404]]) { const result = await scenario(kind, "repository_dispatch", true); assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, code, kind); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 01f9377e09..229475e90b 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2211,6 +2211,21 @@ fi if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then case "$*" in + *actions/runs/201/attempts/2/jobs?per_page=100) + if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then + : >"$CONTRACT_STALLED_LOOKUP_MARKER" + sleep 12 + fi + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-success.json"; exit 0 ;; + *actions/runs/201) + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201.json"; exit 0 ;; + *actions/runs/203/attempts/3/jobs?per_page=100) + if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_LOG:-}" ]]; then + printf '%s\n' 203 >>"$CONTRACT_PUBLISHER_LOOKUP_LOG" + fi + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-203.json"; exit 0 ;; + *actions/runs/203) + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-203.json"; exit 0 ;; *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source-${CONTRACT_DUPLICATE_EVENT:-typed}.json"; exit 0 ;; "api repos/example/FireMUD") printf '%s\n' '{"full_name":"example/FireMUD","default_branch":"develop"}'; exit 0 ;; *actions/runs/202) @@ -2225,6 +2240,9 @@ if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then exit 0 ;; *actions/runs/202/attempts/2/jobs?per_page=100) + if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_LOG:-}" ]]; then + printf '%s\n' 202 >>"$CONTRACT_PUBLISHER_LOOKUP_LOG" + fi if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then : >"$CONTRACT_STALLED_LOOKUP_MARKER" sleep 12 @@ -2233,6 +2251,18 @@ if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then esac fi +if [[ -n "${CONTRACT_REFRESH_SOURCE_PAYLOAD:-}" && "$*" == *"actions/workflows/runtime-images.yml/runs"* ]]; then + invocation=0 + [[ ! -f "$CONTRACT_REFRESH_SOURCE_STATE" ]] || invocation="$(cat "$CONTRACT_REFRESH_SOURCE_STATE")" + printf '%s\n' "$((invocation + 1))" >"$CONTRACT_REFRESH_SOURCE_STATE" + if (( invocation == 0 )); then + cat "$CONTRACT_SOURCE_PAYLOAD" + else + cat "$CONTRACT_REFRESH_SOURCE_PAYLOAD" + fi + exit 0 +fi + if [[ "$*" == *"publish-pr-runtime-images.yml"* ]]; then [[ "$*" != *"--paginate"* ]] || { echo 'publisher inventory must be bounded' >&2; exit 1; } if [[ -n "${CONTRACT_PUBLISHER_PAYLOAD:-}" ]]; then @@ -2368,6 +2398,12 @@ typed_source = {**source, "event": "repository_dispatch", "head_branch": "develo (root / "duplicate-native.json").write_text(json.dumps({"workflow_runs": [pending_duplicate, source]})) (root / "duplicate-late-publisher.json").write_text(json.dumps({"workflow_runs": [ {**pending_duplicate, "status": "completed", "conclusion": "success"}, typed_source]})) +initial_alternate_wait = {**pending_duplicate, "event": "repository_dispatch", "head_branch": "develop", + "head_sha": "d" * 40, "status": "completed", "conclusion": "success"} +pending_alternate = {**typed_source, "status": "in_progress", "conclusion": None} +completed_alternate = {**typed_source, "status": "completed", "conclusion": "success"} +(root / "refresh-alternates-initial.json").write_text(json.dumps({"workflow_runs": [initial_alternate_wait, pending_alternate]})) +(root / "refresh-alternates-completed.json").write_text(json.dumps({"workflow_runs": [initial_alternate_wait, completed_alternate]})) terminal_duplicate = {**pending_duplicate, "status": "completed", "conclusion": "failure"} intermediate_duplicate = {**typed_source, "id": 103, "created_at": "2026-07-24T00:04:30Z"} for name, runs in { @@ -2385,6 +2421,13 @@ publisher = {**base, "run_attempt": 2, "path": publisher_path, "head_branch": "d "head_repository": repository} native_publisher = {**publisher, "event": "workflow_run", "display_title": "Publish PR Runtime Images " + source["display_title"]} (root / "duplicate-publisher-native.json").write_text(json.dumps(native_publisher)) +direct_source = {**pending_duplicate, "status": "completed", "conclusion": "success"} +direct_publisher = {**native_publisher, "id": 201, "run_attempt": 2, + "created_at": "2026-07-24T00:07:00Z"} +alternate_publisher = {**native_publisher, "id": 202, "run_attempt": 2, + "created_at": "2026-07-24T00:06:00Z"} +(root / "direct-success-sources.json").write_text(json.dumps({"workflow_runs": [direct_source, source]})) +(root / "duplicate-publisher-201.json").write_text(json.dumps(direct_publisher)) for variant, change in { "bare": {}, "qualified": {"path": publisher_path + "@develop"}, @@ -2402,6 +2445,26 @@ for conclusion in ["success", "skipped"]: {"name": "Publish fixed PR image tags", "status": "completed", "conclusion": conclusion} ]} ]})) +(root / "duplicate-publisher-203.json").write_text(json.dumps({**publisher, "id": 203, "run_attempt": 3, + "created_at": "2026-07-24T00:04:30Z"})) +(root / "duplicate-jobs-203.json").write_text(json.dumps({"total_count": 1, "jobs": [ + {"name": "Publish Fixed PR Merge Image Tags", "run_id": 203, "run_attempt": 3, + "status": "completed", "conclusion": "success", "steps": [ + {"name": "Publish fixed PR image tags", "status": "completed", "conclusion": "skipped"} + ]} +]})) +(root / "duplicate-jobs-success-absent.json").write_text(json.dumps({"total_count": 1, "jobs": [ + {"name": "Publish Fixed PR Merge Image Tags", "run_id": 202, + "status": "completed", "conclusion": "success", "steps": [ + {"name": "Publish fixed PR image tags", "status": "completed", "conclusion": "success"} + ]} +]})) +(root / "duplicate-jobs-success-null.json").write_text(json.dumps({"total_count": 1, "jobs": [ + {"name": "Publish Fixed PR Merge Image Tags", "run_id": 202, "run_attempt": None, + "status": "completed", "conclusion": "success", "steps": [ + {"name": "Publish fixed PR image tags", "status": "completed", "conclusion": "success"} + ]} +]})) fixtures = { "dispatch-success": base, "callback-success": native_publisher, @@ -2413,6 +2476,15 @@ fixtures = { } for name, run in fixtures.items(): (root / (name + ".json")).write_text(json.dumps({"total_count": 1, "fixture_event": "workflow_run" if name.startswith("callback-") else "repository_dispatch", "workflow_runs": [run]})) +multiple_publishers = [ + {**base, "id": 202, "created_at": "2026-07-24T00:04:00Z"}, + {**base, "id": 203, "created_at": "2026-07-24T00:04:30Z"}, +] +(root / "dispatch-multiple-publishers.json").write_text(json.dumps({"total_count": 2, + "fixture_event": "repository_dispatch", "workflow_runs": multiple_publishers})) +direct_and_alternate = [alternate_publisher, direct_publisher] +(root / "direct-and-alt-publishers.json").write_text(json.dumps({"total_count": 2, + "fixture_event": "workflow_run", "workflow_runs": direct_and_alternate})) # Matching publication remains discoverable beyond the first page. many = [{**base, "id": 300 + index, "display_title": f"Publish PR Runtime Images source-run-{500 + index}"} for index in range(100)] + [base] (root / "dispatch-second-page.json").write_text(json.dumps([{"total_count": 101, "workflow_runs": many[:100]}, {"total_count": 101, "workflow_runs": many[100:]}])) @@ -2459,6 +2531,44 @@ for event in typed native; do fi done done +for job_fixture in success-absent success-null; do + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB="$job_fixture" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/job-run-attempt-$job_fixture.output" 2>"$contract_fixture_dir/job-run-attempt-$job_fixture.error"; then + [[ "$job_fixture" == "success-absent" ]] || { echo "Present null run_attempt must be rejected" >&2; exit 1; } + require_contains "$contract_fixture_dir/job-run-attempt-$job_fixture.output" 'Trusted PR image publisher 202 succeeded' + else + [[ "$job_fixture" == "success-null" ]] || { cat "$contract_fixture_dir/job-run-attempt-$job_fixture.error" >&2; exit 1; } + require_contains "$contract_fixture_dir/job-run-attempt-$job_fixture.error" 'Timed out waiting for runtime-images workflow' + fi +done + +if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_PUBLISHER_LOOKUP_LOG="$contract_fixture_dir/publisher-candidate-lookups" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-multiple-publishers.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/multiple-publishers.output" 2>"$contract_fixture_dir/multiple-publishers.error"; then + require_contains "$contract_fixture_dir/multiple-publishers.output" 'Trusted PR image publisher 202 succeeded' +else + cat "$contract_fixture_dir/multiple-publishers.error" >&2 + exit 1 +fi +[[ "$(cat "$contract_fixture_dir/publisher-candidate-lookups")" == $'203\n202' ]] || { + echo "Publisher verification must try the newer incumbent and then its older matching candidate" >&2 + exit 1 +} + for variant in terminal multi terminal-no-proof; do if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ @@ -2489,6 +2599,39 @@ BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ require_contains "$contract_fixture_dir/late-publisher.output" 'Matching runtime-images workflow 104 succeeded' require_contains "$contract_fixture_dir/late-publisher.output" 'Trusted PR image publisher 202 succeeded' +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + CONTRACT_DUPLICATE_EVENT=native CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_STALLED_LOOKUP_MARKER="$contract_fixture_dir/direct-before-alternate.lookup" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-success-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-and-alt-publishers.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=5 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/direct-before-alternate.output" +require_contains "$contract_fixture_dir/direct-before-alternate.output" 'Trusted PR image publisher 201 succeeded' +[[ ! -e "$contract_fixture_dir/direct-before-alternate.lookup" ]] || { + echo "A positive direct publisher must be checked before querying alternate publisher jobs" >&2 + exit 1 +} + +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ + CONTRACT_REFRESH_SOURCE_STATE="$contract_fixture_dir/refresh-source-state" \ + CONTRACT_REFRESH_SOURCE_PAYLOAD="$contract_fixture_dir/refresh-alternates-completed.json" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/refresh-alternates-initial.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=5 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/refreshed-alternate.output" 2>"$contract_fixture_dir/refreshed-alternate.error" || { + cat "$contract_fixture_dir/refreshed-alternate.output" "$contract_fixture_dir/refreshed-alternate.error" >&2 + exit 1 + } +require_contains "$contract_fixture_dir/refreshed-alternate.output" 'Matching runtime-images workflow 104 succeeded' +require_contains "$contract_fixture_dir/refreshed-alternate.output" 'Trusted PR image publisher 202 succeeded' + stalled_status=0 CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ CONTRACT_STALLED_LOOKUP_MARKER="$contract_fixture_dir/stalled-publisher.lookup" \ diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index b18509cba8..5ff5bc80dd 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -20,6 +20,14 @@ from pathlib import Path source = Path(sys.argv[1]).read_text() group = re.search(r"^ group: (runtime-images-.*)$", source, re.MULTILINE).group(1) cancel = re.search(r"^ cancel-in-progress: (.*)$", source, re.MULTILINE).group(1) +promotion = re.search(r"^ publish-runtime-images:\n((?:^ .*\n|^\n)+)", source, re.MULTILINE).group(1) +assert re.search( + r"^ concurrency:\n" + r" group: runtime-image-promotion-\$\{\{ needs\.image-meta\.outputs\.head_branch \}\}\n" + r" cancel-in-progress: false\n" + r" queue: max$", promotion, re.MULTILINE +) +assert re.search(r'assert_current_branch_head\n\s+promote_alias "\$candidate" "\$branch_tag"', promotion) class Context: def __init__(self, value=None): @@ -118,6 +126,8 @@ assert evaluate(nonprotected, cancel) == "False", nonprotected check(nonprotected, "ci-push-run-96-attempt-2-required") assert evaluate(push_callback("Develop", "success", 98, 1)).lower() != \ evaluate(push_callback("develop", "success", 97, 1)).lower() +assert evaluate(push_callback("develop", "success", 91, 2)).lower() != \ + evaluate(push_callback("main", "success", 91, 2)).lower() for value in [0, False, "", None]: invalid = copy.deepcopy(dispatch) diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index a01a56ca04..6302737c2b 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -58,7 +58,13 @@ assert marker["if"] == "${{ github.event_name == 'pull_request' && steps.derive. assert marker["name"] == "Preview resolved tuple pr-${{ steps.derive.outputs.pr_number }} base-${{ steps.derive.outputs.base_sha }} head-${{ steps.derive.outputs.head_sha }} merge-${{ steps.derive.outputs.merge_sha }}" assert index > next(i for i,s in enumerate(steps) if s.get("id") == "derive") assert index > next(i for i,s in enumerate(steps) if s.get("id") == "eligibility") -assert sum(s.get("name", "").startswith("Preview event tuple ") for s in steps) == 1 +event_markers = [(i, s) for i, s in enumerate(steps) if s.get("name", "").startswith("Preview event tuple ")] +assert len(event_markers) == 1 +event_index, event_marker = event_markers[0] +assert event_marker["run"] == ":" +assert event_marker["if"] == "${{ github.event_name == 'pull_request' }}" +assert event_marker["name"] == "Preview event tuple pr-${{ github.event.pull_request.number }} base-${{ github.event.pull_request.base.sha }} head-${{ github.event.pull_request.head.sha }} merge-${{ github.sha }}" +assert event_index < next(i for i,s in enumerate(steps) if s.get("id") == "derive") PY cardinality_workflow="$TEMP_DIR/step-cardinality.yml" @@ -167,7 +173,22 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_retry_head="${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" snapshot_retry_merge="${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" snapshot_retry_image="${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" - if [[ "${FAKE_PR_901_PROOF_COMPLETE:-true}" == true ]]; then + snapshot_resource_version=rv-901 + if [[ -f "${FAKE_PROOF_RETRY_RESERVATION_MARKER:-}" && + ! -f "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:-}" ]]; then + snapshot_retry_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" + snapshot_retry_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" + snapshot_retry_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" + snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" + snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" + snapshot_resource_version=rv-902 + fi + proof_complete="${FAKE_PR_901_PROOF_COMPLETE:-true}" + if [[ "${FAKE_PR_901_PROOF_COMPLETE_AFTER_CONSUMER_COMPLETION:-false}" == true && + -f "${FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER:-}" ]]; then + proof_complete=true + fi + if [[ "$proof_complete" == true ]]; then snapshot_proof_base="$snapshot_base" snapshot_proof_head="$snapshot_head" snapshot_proof_merge="$snapshot_merge" @@ -200,7 +221,8 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && --arg retry_merge "$snapshot_retry_merge" \ --arg retry_image "$snapshot_retry_image" \ --arg uid "$snapshot_uid" \ - '{metadata:{name:"pr-901",uid:$uid,resourceVersion:"rv-901",annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head,"firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image,"firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head,"firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image,"firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head,"firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image,"firemud.dev/proof-preview-namespace-uid":$proof_uid,"firemud.dev/proof-retry-count":$retry_count,"firemud.dev/proof-retry-base-sha":$retry_base,"firemud.dev/proof-retry-head-sha":$retry_head,"firemud.dev/proof-retry-merge-sha":$retry_merge,"firemud.dev/proof-retry-image-tag":$retry_image}}}' + --arg resource_version "$snapshot_resource_version" \ + '{metadata:{name:"pr-901",uid:$uid,resourceVersion:$resource_version,annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head,"firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image,"firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head,"firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image,"firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head,"firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image,"firemud.dev/proof-preview-namespace-uid":$proof_uid,"firemud.dev/proof-retry-count":$retry_count,"firemud.dev/proof-retry-base-sha":$retry_base,"firemud.dev/proof-retry-head-sha":$retry_head,"firemud.dev/proof-retry-merge-sha":$retry_merge,"firemud.dev/proof-retry-image-tag":$retry_image}}}' exit 0 fi if [[ "$1" == get && "$2" == namespace && @@ -306,6 +328,33 @@ if [[ "$1" == wait && "$2" == --for=delete ]]; then fi if [[ "$1" == annotate && "$2" == namespace ]]; then printf '%s\n' "$*" >> "$FAKE_ANNOTATE_LOG" + if [[ "${3:-}" == pr-901 && -n "${FAKE_DISPATCH_HTTP_STATUS:-}" ]]; then + if [[ "$*" == *"--resource-version rv-902"* ]]; then + : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" + elif [[ "$*" == *"firemud.dev/proof-retry-count="* ]]; then + local_count="" + local_base="" + local_head="" + local_merge="" + local_image="" + for annotation in "$@"; do + case "$annotation" in + firemud.dev/proof-retry-count=*) local_count="${annotation#*=}" ;; + firemud.dev/proof-retry-base-sha=*) local_base="${annotation#*=}" ;; + firemud.dev/proof-retry-head-sha=*) local_head="${annotation#*=}" ;; + firemud.dev/proof-retry-merge-sha=*) local_merge="${annotation#*=}" ;; + firemud.dev/proof-retry-image-tag=*) local_image="${annotation#*=}" ;; + esac + done + jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ + --arg merge "$local_merge" --arg image "$local_image" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image}' \ + > "${FAKE_PROOF_RETRY_RESERVATION_MARKER:?}" + if [[ "$*" == *"-o json"* ]]; then + printf '%s' '{"metadata":{"uid":"uid-pr-901","resourceVersion":"rv-902"}}' + fi + fi + fi if [[ "${FAKE_ANNOTATE_ERROR:-false}" == true ]]; then : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" exit 1 @@ -501,12 +550,33 @@ if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9 exit 0 fi if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9])$ ]]; then - jq -c --argjson id "${BASH_REMATCH[1]}" '.id = $id' <<<"${FAKE_TRUSTED_CONSUMER_LATEST_JSON:-null}" + run_id="${BASH_REMATCH[1]}" + latest_json="$(jq -c --argjson id "$run_id" '.id = $id' <<<"${FAKE_TRUSTED_CONSUMER_LATEST_JSON:-null}")" + if [[ "$run_id" == 5256 ]] && jq -e '.status == "completed"' <<<"$latest_json" >/dev/null; then + : > "${FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER:?}" + fi + printf '%s' "$latest_json" exit 0 fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then printf '%s\n' "$*" >> "$FAKE_DISPATCH_LOG" - exit 0 + if [[ "${FAKE_DISPATCH_MISSING_STATUS:-false}" == true ]]; then + exit "${FAKE_DISPATCH_GH_EXIT_CODE:-1}" + fi + dispatch_status="${FAKE_DISPATCH_HTTP_STATUS:-204}" + case "$dispatch_status" in + 204) dispatch_reason='No Content' ;; + 422) dispatch_reason='Unprocessable Content' ;; + 500) dispatch_reason='Internal Server Error' ;; + 403) dispatch_reason='Forbidden' ;; + 404) dispatch_reason='Not Found' ;; + *) dispatch_reason='Test Status' ;; + esac + printf 'HTTP/2.0 %s %s\n' "$dispatch_status" "$dispatch_reason" + if [[ "$dispatch_status" == 204 ]]; then + exit 0 + fi + exit "${FAKE_DISPATCH_GH_EXIT_CODE:-1}" fi case "$resource" in */git/ref/heads/*) @@ -950,6 +1020,9 @@ export FAKE_COMMENT_METHOD_LOG="$TEMP_DIR/comment-method.log" export FAKE_ANNOTATE_LOG="$TEMP_DIR/annotate.log" export FAKE_ANNOTATE_FAILURE_MARKER="$TEMP_DIR/annotate-failure.marker" export FAKE_DISPATCH_LOG="$TEMP_DIR/dispatch.log" +export FAKE_PROOF_RETRY_RESERVATION_MARKER="$TEMP_DIR/proof-retry-reservation.json" +export FAKE_PROOF_RETRY_COMPENSATED_MARKER="$TEMP_DIR/proof-retry-compensated.marker" +export FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER="$TEMP_DIR/trusted-consumer-completed.marker" export FAKE_COMMENT_TARGET_LOG="$TEMP_DIR/comment-target.log" export FAKE_PREVIOUS_COMMENT_ID_LOG="$TEMP_DIR/previous-comment-id.log" export FAKE_TARGET_CALLS="$TEMP_DIR/target-calls" @@ -986,7 +1059,7 @@ adversarial_labels_base64="$(printf '%s' '[{"name":"custom:label"},{"name":"quot invalid_json_labels_base64="$(printf '%s' '{invalid-json' | base64 | tr -d '\n')" reset_case() { - rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" + rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" export GITHUB_OUTPUT="$TEMP_DIR/output" export FAKE_TARGET_PRIORITY=true export FAKE_TARGET_LABELS_VALID=valid @@ -2592,7 +2665,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple completed_failed_plan; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2600,13 +2673,17 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att plan_jobs="$(jq -cn --arg tuple "$tuple_name" --arg old "$old_tuple_name" \ --arg head "$preview_head_sha" --arg variant "$tuple_case" ' def step($name): {name:$name,status:"completed",conclusion:"success"}; - [{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head,status:"completed", + [{name:"Preview Plan",run_id:5254, + run_attempt:(if $variant == "job_attempt_mismatch" then 1 elif $variant == "job_attempt_null" then null else 2 end), + head_sha:$head,status:"completed", conclusion:(if $variant == "completed_failed_plan" then "failure" else "success" end), steps:(if $variant == "old_merge" or $variant == "stale_attempt_old_tuple" then [step($old)] + elif $variant == "completed_success_old_tuple" then [step($old)] elif $variant == "ambiguous" then [step($tuple),step($old)] elif $variant == "event_only" then [step($tuple | sub("resolved"; "event"))] elif $variant == "old_event_current_plan" then [step($old | sub("resolved"; "event")),step($tuple)] else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] | + if $variant == "job_attempt_missing" then map(del(.run_attempt)) else . end | if $variant == "missing" then {jobs:[],total_count:0} elif $variant == "jobs_incomplete" then {jobs:.,total_count:2} elif $variant == "jobs_malformed" then {jobs:null,total_count:1} @@ -2616,7 +2693,8 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att head_sha:$head,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:173511323,repository:{full_name:(if $variant == "wrong_latest_repo" then "example/Other" else "example/FireMUD" end)},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) - elif $variant == "completed_failed_plan" then .status = "completed" + elif $variant == "completed_failed_plan" then .status = "completed" | .conclusion = "failure" + elif $variant == "completed_success" or $variant == "completed_success_old_tuple" then .status = "completed" | .conclusion = "success" else . end')" ( cd "$ROOT_DIR" @@ -2632,18 +2710,24 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_output" - if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == target || "$tuple_case" == old_event_current_plan ]]; then + if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == target || "$tuple_case" == old_event_current_plan || "$tuple_case" == job_attempt_missing ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" - elif [[ "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple ]]; then + elif [[ "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" + elif [[ "$tuple_case" == completed_success ]]; then + grep -Fqx \ + "Deferring proof retry for PR #901: successful exact preview source run 5254 may still be handing off to the trusted consumer." \ + "$reconciler_pull_request_output" + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" else grep -Fqx \ "Dispatching preview render for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag}) from trusted ref develop" \ @@ -2652,7 +2736,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att fi done -for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable; do +for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable consumer-job-attempt-missing consumer-job-attempt-mismatch consumer-job-attempt-null; do reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id:357129350, @@ -2661,11 +2745,12 @@ consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id: repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"},status:"in_progress"}')" namespace_absent_on_initial=false proof_complete=false +proof_after_consumer_completion=false if [[ "$observation_case" == consumer-finished || "$observation_case" == consumer-finished-without-proof ]]; then namespace_absent_on_initial=true fi if [[ "$observation_case" == consumer-finished ]]; then - proof_complete=true + proof_after_consumer_completion=true fi ( cd "$ROOT_DIR" @@ -2674,14 +2759,16 @@ fi FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_NAMESPACE_ABSENT_ON_INITIAL="$namespace_absent_on_initial" \ FAKE_PR_901_PROOF_COMPLETE="$proof_complete" \ + FAKE_PR_901_PROOF_COMPLETE_AFTER_CONSUMER_COMPLETION="$proof_after_consumer_completion" \ FAKE_TRUSTED_CONSUMER_JOBS_FAIL="$([[ "$observation_case" == consumer-finished-without-proof || "$observation_case" == consumer-active-jobs-unavailable ]] && echo true || echo false)" \ FAKE_TRUSTED_CONSUMER_JOBS_JSON="$(jq -cn \ --arg observation "$observation_case" \ --arg tuple "Trusted preview deploy tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" ' - {total_count:1,jobs:[{name:"Validate Trusted Preview Target",run_id:5256,run_attempt:1, + {total_count:1,jobs:[{name:"Validate Trusted Preview Target",run_id:5256, + run_attempt:(if $observation == "consumer-job-attempt-mismatch" then 2 elif $observation == "consumer-job-attempt-null" then null else 1 end), head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",status:"completed",conclusion:"success", steps:[{name:(if $observation == "consumer-title-only" then "Verify workflow source and immutable PR metadata" else $tuple end), - status:"completed",conclusion:"success"}]}]}')" \ + status:"completed",conclusion:"success"}]}]} | if $observation == "consumer-job-attempt-missing" then .jobs[0] |= del(.run_attempt) else . end')" \ FAKE_TRUSTED_CONSUMER_LATEST_JSON="$(jq -c --arg observation "$observation_case" \ 'if $observation == "consumer-stale-attempt" then .run_attempt = 2 elif $observation | startswith("consumer-finished") then .status = "completed" @@ -2700,13 +2787,13 @@ fi PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_active_status_advance_output" 2>&1 -if [[ "$observation_case" == duplicate-rows || "$observation_case" == workflow-run-only ]]; then +if [[ "$observation_case" == duplicate-rows || "$observation_case" == workflow-run-only || "$observation_case" == consumer-job-attempt-missing ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5256 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_active_status_advance_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" -elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == lookup-overflow || "$observation_case" == consumer-active-jobs-unavailable ]]; then +elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == lookup-overflow || "$observation_case" == consumer-active-jobs-unavailable || "$observation_case" == consumer-job-attempt-mismatch || "$observation_case" == consumer-job-attempt-null ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_active_status_advance_output" @@ -2715,6 +2802,7 @@ elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == elif [[ "$observation_case" == consumer-finished ]]; then grep -Fqx 'Skipping PR #901: proof completed before retry dispatch.' "$reconciler_active_status_advance_output" test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 + test -e "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" elif [[ "$observation_case" == consumer-finished-without-proof ]]; then @@ -2763,6 +2851,7 @@ reconciler_preserved_proof_retry_output="$TEMP_DIR/reconciler-preserved-proof-re FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_DISPATCH_HTTP_STATUS=204 \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_preserved_proof_retry_output" @@ -2771,6 +2860,59 @@ grep -Fqx \ "$reconciler_preserved_proof_retry_output" grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" +test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 + +reset_case +reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=2 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_DISPATCH_HTTP_STATUS=422 \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_rejected_proof_retry_output" 2>&1 +grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 422).' \ + "$reconciler_rejected_proof_retry_output" +grep -Fq 'Released proof-retry reservation for PR #901 after GitHub confirmed dispatch rejection.' \ + "$reconciler_rejected_proof_retry_output" +grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" +grep -Fq -- 'firemud.dev/proof-retry-count=2' "$FAKE_ANNOTATE_LOG" +grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG" +test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" + +reset_case +reconciler_ambiguous_proof_retry_output="$TEMP_DIR/reconciler-ambiguous-proof-retry.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=2 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_DISPATCH_HTTP_STATUS=500 \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_ambiguous_proof_retry_output" 2>&1 +grep -Fq 'outcome for PR #901 is ambiguous (gh=1, HTTP=500); proof-retry budget remains charged.' \ + "$reconciler_ambiguous_proof_retry_output" +test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 +test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" +if grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG"; then + echo "ambiguous dispatch outcome released a proof-retry reservation" >&2 + exit 1 +fi reset_case reconciler_exhausted_proof_retry_output="$TEMP_DIR/reconciler-exhausted-proof-retry.out" @@ -3736,8 +3878,8 @@ grep -Fq "run-name: \${{ github.event_name == 'workflow_run' && github.event.wor # shellcheck disable=SC2016 # Assert one fail-closed JSON snapshot feeds each namespace decision. grep -Fq 'kubectl get namespace "${namespace}" --ignore-not-found -o json' \ "$reconciler_workflow" -# shellcheck disable=SC2016 # Assert the initial, repair, and pre-dispatch namespace snapshots. -test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$reconciler_workflow")" -eq 4 +# shellcheck disable=SC2016 # Assert the initial, repair, pre-dispatch, and compensation snapshots. +test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$reconciler_workflow")" -eq 5 # shellcheck disable=SC2016 # Assert the fresh namespace snapshot fences repair. grep -Fq 'requested preview tuple changed during annotation repair check' "$reconciler_workflow" # The janitor keeps explicit kubeconfig selection on the consuming kubectl steps; diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index f9cc3fd659..2f0c8b822f 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -11,6 +11,7 @@ python3 -c 'import yaml' >/dev/null 2>&1 || { echo "python3 with PyYAML is required for the preview runner isolation contract." >&2 exit 1 } +python3 -c 'import sys; sys.exit(0 if __debug__ else "Preview runner isolation contract requires Python assertions; unset PYTHONOPTIMIZE.")' python3 - "$ROOT_DIR" <<'PY' from __future__ import annotations diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index c66cf38e60..94b62d1234 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -36,7 +36,11 @@ async function execute(f, sent = []) { return {data: f.inventory ?? {total_count: f.jobs.length, jobs: f.jobs}}; }, rest: { actions: { - getWorkflowRun: async () => ({data: f.run}), + getWorkflowRun: async ({run_id}) => { + assert.equal(run_id, 99); + f.runReads = (f.runReads ?? 0) + 1; + return {data: f.runReads === 1 ? f.run : f.latestRun ?? f.run}; + }, getWorkflow: async () => ({data: {id: 42, path: '.github/workflows/runtime-images.yml'}}), listWorkflowRuns: async args => { assert.equal(args.workflow_id, 42); @@ -53,12 +57,13 @@ async function execute(f, sent = []) { }}, git: {getRef: async ({ref}) => { assert.equal(ref, 'heads/' + f.pr.base.ref); - return {data: f.base}; + f.baseReads = (f.baseReads ?? 0) + 1; + return {data: f.baseReads === 1 ? f.base : f.latestBase ?? f.base}; }}, repos: { getCommit: async ({ref}) => { (f.mergeReads ??= []).push(ref); - return {data: f.mergeReads.length === 1 ? f.recordedMerge : f.merge}; + return {data: [f.recordedMerge, f.merge, f.resolvedMerge][f.mergeReads.length - 1]}; }, createDispatchEvent: async p => sent.push(p), }, @@ -92,6 +97,10 @@ test('a completed render failure permits repair when the plan was eligible', asy const f = fixture(); f.run.conclusion = 'failure'; assert.equal((await execute(f)).length, 1); }); +test('the pinned Jobs endpoint identifies a plan without a row-level attempt number', async () => { + const f = fixture(); delete f.jobs[0].run_attempt; + assert.equal((await execute(f)).length, 1); +}); for (const [name, mutate] of Object.entries({ wrongPath: f => f.run.path = '.github/workflows/attacker.yml', wrongQualifiedPath: f => f.run.path += '@refs/pull/8/merge', @@ -122,6 +131,7 @@ for (const [name, mutate] of Object.entries({ wrongRun: f => f.run.id = 100, wrongAttempt: f => f.run.run_attempt = 3, wrongJobAttempt: f => f.jobs[0].run_attempt = 3, + nullJobAttempt: f => f.jobs[0].run_attempt = null, duplicatePlan: f => f.jobs.push(f.jobs[0]), duplicateTuple: f => f.jobs[0].steps.push(f.jobs[0].steps[0]), failedTuple: f => f.jobs[0].steps[0].conclusion = "failure", @@ -328,6 +338,33 @@ test('a resolved historical merge can precede a second base advance', async () = assert.deepEqual(f.mergeReads, [E, A]); }); +test('a third independently verified merge can be the resolved plan', async () => { + const plannedMerge = 'f'.repeat(40); + const plannedBase = '0'.repeat(40); + for (const exact of [true, false]) { + const f = fixture(); + f.jobs[0].steps[1] = tupleStep('resolved', plannedBase, plannedMerge); + f.resolvedMerge = {sha: plannedMerge, parents: [{sha: exact ? plannedBase : D}, {sha: C}]}; + const dispatches = await execute(f); + assert.equal(dispatches.length, exact ? 1 : 0); + if (exact) assert.equal(dispatches[0].client_payload.merge_sha, A); + assert.deepEqual(f.mergeReads, [E, A, plannedMerge]); + } +}); + +test('a branch ref advance during lookup invalidates the live merge', async () => { + const f = fixture(); + f.latestBase = {object: {sha: 'f'.repeat(40)}}; + assert.deepEqual(await execute(f), []); + assert.equal(f.baseReads, 2); +}); + +test('a newer source attempt during lookup invalidates the plan observation', async () => { + const f = fixture(); f.latestRun = {...f.run, run_attempt: 3}; + assert.deepEqual(await execute(f), []); + assert.equal(f.runReads, 2); +}); + test('truncated or oversized attempt inventory is refused', async () => { for (const inventory of [{total_count: 301, jobs: []}, {total_count: 2, jobs: []}]) { const f = fixture(); f.inventory = inventory; diff --git a/dev-tools/tests/protected-pod-admission-workflow-contract.sh b/dev-tools/tests/protected-pod-admission-workflow-contract.sh index d9f0bbef90..91610ba41e 100644 --- a/dev-tools/tests/protected-pod-admission-workflow-contract.sh +++ b/dev-tools/tests/protected-pod-admission-workflow-contract.sh @@ -35,7 +35,12 @@ with tempfile.TemporaryDirectory(prefix="firemud-policy-wait-") as directory: command("date", 'import os,pathlib\np=pathlib.Path(os.environ["CLOCK"]);n=int(p.read_text()) if p.exists() else 0;p.write_text(str(n+30));print(n)\n') command("sleep", 'pass\n') command("kubectl", '''import os,pathlib,json,sys -p=pathlib.Path(os.environ["CALLS"]);n=int(p.read_text()) if p.exists() else 0;p.write_text(str(n+1)) +assert "--request-timeout=5s" in sys.argv +policy = sys.argv[sys.argv.index("validatingadmissionpolicy") + 1] +p=pathlib.Path(os.environ["CALLS"]) +calls=p.read_text().splitlines() if p.exists() else [] +n=len(calls) +p.write_text("\\n".join([*calls, policy]) + "\\n") if os.environ["CASE"]=="api-error":sys.exit(1) ready=os.environ["CASE"] in ("ready", "warnings", "ignore") or (os.environ["CASE"]=="late" and n>0) print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Ignore" if os.environ["CASE"]=="ignore" else "Fail"},"status":{"observedGeneration":2 if ready else 1,"typeChecking":{"expressionWarnings":["bad"] if os.environ["CASE"]=="warnings" else []}}})) @@ -49,7 +54,12 @@ print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Ignore" i result = subprocess.run(["bash", "-c", "set -euo pipefail\nrun_wait() {\n"+wait+"\n}\nrun_wait"], env=env, capture_output=True, text=True, timeout=10) assert (result.returncode == 0) == success, (case, result.stderr) if success: - assert int((tmp/"calls").read_text()) >= 4 + calls = (tmp/"calls").read_text().splitlines() + assert set(calls) == { + "firemud-trust-runtime-namespace-boundary", "firemud-trust-runtime-binding-boundary", + "firemud-trust-runtime-pod-boundary", "firemud-trust-runtime-pod-identity", + } + assert len(calls) == (5 if case == "late" else 4) else: assert "policy_readiness=timeout" in result.stderr print("Protected Pod workflow bounded cleanup/readiness contract passed") diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 5b672e58fc..af1e483d29 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -85,6 +85,8 @@ python3 - "$workflow" "$test_root/summary-target.js" <<'PY_TARGET' import sys from pathlib import Path import yaml +if not __debug__: + raise SystemExit("Static analysis summary resolver proof requires Python assertions") workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) assert "concurrency" not in workflow, "unvalidated callbacks must not share a workflow queue" resolver = workflow["jobs"]["resolve-summary-target"] @@ -255,7 +257,7 @@ const github = { created_at: "2026-09-20T12:00:00Z", run_attempt: 1, status: "completed", - conclusion: "success", + conclusion: "skipped", }, { id: 250, @@ -712,6 +714,37 @@ run(github, context, core).then(async () => { rerunWrites.some(row => row.body.includes("checks passed"))) { throw new Error("a prior attempt's status cannot replace the selected running rerun"); } + github.paginate = async (method, input) => { + const rows = await savedPaginate(method, input); + return method === codeqlListWorkflowRuns && input.workflow_id === "codeql.yml" + ? rows.map(row => row.id === 270 ? {...row, conclusion: "startup_failure"} : row) + : rows; + }; + const rawNameStart = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(rawNameStart).some(row => row.body.includes("CodeQL gate: \`startup_failure\`"))) { + throw new Error("a terminal workflow failure with a raw skipped gate name must remain visible"); + } + github.paginate = savedPaginate; + github.request = async (route, input) => { + if (input.run_id !== 200) return savedRequest(route, input); + const job = (id, name) => ({id, name, run_id: 200, run_attempt: 2, head_sha: currentHeadSha, + status: "completed", conclusion: "success"}); + return {data: {total_count: 2, jobs: [job(20021, "CodeQL Gate"), job(20022, "CodeQL Analysis (javascript-typescript)")]}}; + }; + github.paginate = async (method, input) => { + const rows = await savedPaginate(method, input); + return method === codeqlListWorkflowRuns && input.workflow_id === "codeql.yml" + ? rows.map(row => row.id === 200 ? {...row, run_attempt: 2, conclusion: "success"} : row) + : rows; + }; + const partialStart = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(partialStart).some(row => row.body.includes("CodeQL analysis (java): \`unavailable\`") && + row.body.includes("CodeQL analysis (javascript-typescript): \`success\`"))) { + throw new Error("a partial rerun cannot report an unobserved language as skipped"); + } + github.paginate = savedPaginate; github.request = async (route, input) => { if (input.run_id !== 270) return savedRequest(route, input); return {data: {total_count: 1, jobs: [{ @@ -786,7 +819,7 @@ run(github, context, core).then(async () => { const jobs = response.data.jobs; const gate = jobs.find(job => job.name === "CodeQL Gate"); if (duplicate) jobs.push({...gate, id: gate.id + 50000}); - else gate.run_attempt += 1; + else gate.run_attempt = input.attempt_number + 1; return {data: {jobs, total_count: jobs.length}}; }; const unavailableStart = calls.updated.length; diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index aa60119f6b..0f19b471d4 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -13,6 +13,7 @@ VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/(?:migration|recovery-control-migration)/") +RECOVERY_MIGRATION_DIR = "/db/recovery-control-migration/" RUNTIME_DEPENDENCY_RE = re.compile( r'(?:implementation|api|runtimeOnly)\s*\(\s*project\(\s*":([^\"]+)"' r'|dependencies\.add\(\s*"(?:implementation|api|runtimeOnly)"\s*,\s*project\.project\(\s*":([^\"]+)"' @@ -141,6 +142,8 @@ def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], migrations = discover_migration_files(snapshot) grouped: dict[str, list[MigrationFile]] = {} for item in migrations: + if RECOVERY_MIGRATION_DIR in item.path and not recovery_location_configured(snapshot, item.project): + continue grouped.setdefault(item.project, []).append(item) shared = grouped.get("common-saga", []) for adopter in saga_adopters(snapshot): @@ -148,10 +151,24 @@ def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], return grouped, migrations +def recovery_location_configured(snapshot: Snapshot, project: str) -> bool: + # The isolated owner uses the packaged Spring Flyway settings in application.yml. + settings = snapshot.get(f"services/{project}/src/main/resources/application.yml", b"").decode() + spring = re.search(r"(?m)^spring:[ \t]*\n((?:[ \t]+[^\n]*\n|\n)+)", settings + "\n") + flyway = re.search(r"(?m)^ flyway:[ \t]*\n((?: [^\n]*\n|\n)+)", spring[1]) if spring else None + locations = re.search(r"(?m)^ locations:[ \t]*(.+)$", flyway[1]) if flyway else None + return bool(locations and "classpath:db/recovery-control-migration" in { + path.strip().strip("\"'") for path in locations[1].split(",") + }) + + def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str], int, int]: grouped, migrations = effective_sets(current) parent_grouped, parent_migrations = effective_sets(parent) if parent is not None else ({}, []) issues = [] + for project in sorted({item.project for item in migrations if RECOVERY_MIGRATION_DIR in item.path}): + if not recovery_location_configured(current, project): + issues.append(f"services/{project}: packaged Spring Flyway configuration does not select the recovery-control location") for project, items in sorted(grouped.items()): seen: dict[tuple[int, ...], MigrationFile] = {} for item in items: @@ -265,8 +282,13 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str check("java/sql duplicate", {**history, "services/example-service/src/main/java/db/migration/V1__dup.java": b"// dup"}, history, "duplicate version V1") recovery = "services/recovery-controller-service/src/main/resources/db/recovery-control-migration/" - recovery_history = {recovery + "V1__journal.sql": b"-- journal"} + recovery_config = "services/recovery-controller-service/src/main/resources/application.yml" + recovery_settings = b"spring:\n flyway:\n locations: classpath:db/recovery-control-migration\n" + recovery_history = {recovery + "V1__journal.sql": b"-- journal", recovery_config: recovery_settings} check("unchanged isolated recovery history", recovery_history, recovery_history, None) + check("disconnected isolated recovery history", { + **recovery_history, recovery_config: recovery_settings.replace(b"recovery-control-migration", b"migration"), + }, recovery_history, "historical effective migration no longer applied") check("duplicate recovery version", {**recovery_history, recovery + "V1__duplicate.sql": b"-- duplicate"}, recovery_history, "duplicate version V1") check("changed recovery history", {recovery + "V1__journal.sql": b"-- rewritten"}, @@ -275,6 +297,7 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str root = Path(tmp) (root / recovery).mkdir(parents=True) (root / recovery / "V1__journal.sql").write_bytes(b"-- journal") + (root / recovery_config).write_bytes(recovery_settings) if current_snapshot(root) != recovery_history or not all(map(relevant_path, recovery_history)): raise AssertionError("isolated recovery history is not selected for both snapshots") diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 324e415778..5bacf79d01 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -816,6 +816,7 @@ private boolean hasRetainedClosure( || !current.effect().operationId().equals(retained.operationId()) || !current.effect().effectId().equals(retained.effectId()) || !attemptId.equals(retained.attemptId()) + || retained.attemptOrdinal() != ordinal || current.effect().kind() != retained.effectKind() || !current.effect().operationTupleDigest().equals(retained.operationTupleDigest()) || !current.payloadDigest().equals(retained.payloadDigest()) @@ -916,6 +917,11 @@ private void requireNonRegressingReadback( if (readback.observedAt().isBefore(previous.observedAt())) { throw conflict("effect readback predates the retained same-attempt observation"); } + if (previous.state() == EffectReadbackState.UNKNOWN_OR_PARTIAL + && readback.state() != EffectReadbackState.UNKNOWN_OR_PARTIAL + && !readback.observedAt().isAfter(previous.observedAt())) { + throw conflict("definitive effect readback must be newer than retained partial evidence"); + } } private boolean hasValidatedUnknownReadback( @@ -964,6 +970,7 @@ private boolean sameRetainedOutcome(EffectReadback readback, Record stored, Stri readback.operationId(), readback.effectId(), readback.attemptId(), + readback.attemptOrdinal(), readback.effectKind(), readback.operationTupleDigest(), readback.payloadDigest(), @@ -975,6 +982,9 @@ private boolean sameRetainedOutcome(EffectReadback readback, Record stored, Stri private void requireReadbackMatches( EffectReadback readback, OutboxEntry outbox, UUID operationId, UUID effectId) { + if (readback.attemptOrdinal() != outbox.attemptCount()) { + throw conflict("effect readback dispatch generation changed"); + } if (!readback.operationId().equals(operationId) || !readback.operationId().equals(outbox.effect().operationId()) || !readback.effectId().equals(effectId) diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java index ad12657fb1..dc470d481c 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModel.java @@ -691,6 +691,7 @@ public record EffectReadback( UUID operationId, UUID effectId, UUID attemptId, + int attemptOrdinal, EffectKind effectKind, String operationTupleDigest, String payloadDigest, @@ -702,6 +703,9 @@ public record EffectReadback( attemptId = requiredUuid(attemptId, "attemptId"); operationId = requiredUuid(operationId, "operationId"); effectId = requiredUuid(effectId, "effectId"); + if (attemptOrdinal < 1) { + throw new IllegalArgumentException("attemptOrdinal must be positive"); + } Objects.requireNonNull(effectKind, "effectKind must not be null"); operationTupleDigest = requiredDigest(operationTupleDigest, "operationTupleDigest"); payloadDigest = requiredDigest(payloadDigest, "payloadDigest"); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java index 03fe0a9094..46d58960b2 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/DeniedInitialGameplayReleaseEffectPort.java @@ -8,12 +8,12 @@ */ public class DeniedInitialGameplayReleaseEffectPort implements InitialGameplayReleaseEffectPort { @Override - public EffectApplyResult apply(TypedEffect effect, UUID attemptId) { + public EffectApplyResult apply(TypedEffect effect, UUID attemptId, int attemptOrdinal) { return EffectApplyResult.notDispatched("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); } @Override - public EffectReadbackResolution readback(TypedEffect effect, UUID attemptId) { + public EffectReadbackResolution readback(TypedEffect effect, UUID attemptId, int attemptOrdinal) { return EffectReadbackResolution.unavailable(); } } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java index 3af726d0d9..84fbbe0498 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseController.java @@ -147,7 +147,9 @@ private Operation applyEffect(Operation operation, OutboxEntry outbox) { final EffectApplyResult applyResult; try { applyResult = - Objects.requireNonNull(effectPort.apply(dispatched.effect(), attemptId), "applyResult"); + Objects.requireNonNull( + effectPort.apply(dispatched.effect(), attemptId, dispatched.attemptCount()), + "applyResult"); } catch (RuntimeException exception) { journal.recordAmbiguousEffectForDispatch( dispatched, "EFFECT_CALL_OUTCOME_UNKNOWN", clock.instant()); @@ -181,7 +183,7 @@ private Operation readBackEffect(Operation operation, OutboxEntry outbox) { } EffectReadbackResolution resolution; try { - resolution = effectPort.readback(outbox.effect(), attemptId); + resolution = effectPort.readback(outbox.effect(), attemptId, outbox.attemptCount()); } catch (RuntimeException exception) { return requireOperation(operation.scope().operationId()); } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java index 892b7e773e..5a1e980878 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/service/InitialGameplayReleaseEffectPort.java @@ -11,17 +11,19 @@ */ public interface InitialGameplayReleaseEffectPort { /** - * RETRYABLE_NO_EFFECT is a definitive owner rejection for this exact attempt, never a timeout or - * absence observation. The owner must not apply the rejected attempt later. NOT_DISPATCHED means - * the local adapter can prove it never sent this attempt; it is retryable without owner evidence. - * A possibly transmitted request must not be classified as NOT_DISPATCHED. + * Applies the effect for its exact attempt and dispatch ordinal. RETRYABLE_NO_EFFECT is a + * definitive owner rejection for this exact attempt, never a timeout or absence observation. The + * owner must not apply the rejected attempt later. NOT_DISPATCHED means the local adapter can + * prove it never sent this attempt; it is retryable without owner evidence. A possibly + * transmitted request must not be classified as NOT_DISPATCHED. */ - EffectApplyResult apply(TypedEffect effect, UUID attemptId); + EffectApplyResult apply(TypedEffect effect, UUID attemptId, int attemptOrdinal); /** - * Returns evidence bound to this exact attempt. PROVEN_NO_EFFECT requires the owner to have - * durably closed the attempt so a delayed claimant can no longer apply it; absence alone is not - * proof. + * Returns evidence bound to this exact attempt and dispatch ordinal. The owner must return the + * requested ordinal in the typed receipt so an earlier observation for a reused attempt ID cannot + * satisfy a later dispatch. PROVEN_NO_EFFECT requires the owner to have durably closed the + * attempt so a delayed claimant can no longer apply it; absence alone is not proof. * *

AVAILABLE carries the owner's original observation timestamp. The adapter must establish * that it is comparable with the recovery controller's UTC clock. The journal checks it against @@ -33,7 +35,7 @@ public interface InitialGameplayReleaseEffectPort { * transition requires a fresh exact observation from the owner. Returning the older receipt with * a new timestamp is insufficient. */ - EffectReadbackResolution readback(TypedEffect effect, UUID attemptId); + EffectReadbackResolution readback(TypedEffect effect, UUID attemptId, int attemptOrdinal); record EffectApplyResult(ApplyStatus status, String outcomeCode) { public EffectApplyResult { diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 50eccb0e40..97a8c0dc8f 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -78,6 +78,7 @@ static void setUp() throws Exception { .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) .schemas(SCHEMA) .defaultSchema(SCHEMA) + .table("flyway_schema_history_recovery_control") .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/recovery-control-migration") .load(); @@ -161,6 +162,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() scope.operationId(), prepare.effect().effectId(), prepareAttempt, + prepare.attemptCount(), prepare.effect().kind(), prepare.effect().operationTupleDigest(), prepare.payloadDigest(), @@ -183,6 +185,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() scope.operationId(), prepareEffectId, UUID.randomUUID(), + prepare.attemptCount(), prepare.effect().kind(), prepare.effect().operationTupleDigest(), prepare.payloadDigest(), @@ -266,6 +269,7 @@ void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() scope.operationId(), handoff.effect().effectId(), handoffAttempt, + handoff.attemptCount(), handoff.effect().kind(), handoff.effect().operationTupleDigest(), handoff.payloadDigest(), @@ -383,14 +387,34 @@ void delayedSameAttemptPreparationCannotOverrideNewerAmbiguity() { journal.recordEffectReadback(dispatched, unknown, base.plusSeconds(6)); String retained = storedOutbox(operationId, effectId); - for (EffectReadbackState delayedState : - List.of(EffectReadbackState.UNKNOWN_OR_PARTIAL, EffectReadbackState.PREPARED_FENCED)) { - EffectReadback delayed = - readbackFor(dispatched, attemptId, delayedState, "delayed", base.plusSeconds(5)); + for (EffectReadback delayed : + List.of( + readbackFor( + dispatched, + attemptId, + EffectReadbackState.UNKNOWN_OR_PARTIAL, + "delayed-unknown", + base.plusSeconds(5)), + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PREPARED_FENCED, + "delayed-older-definitive", + base.plusSeconds(5)), + readbackFor( + dispatched, + attemptId, + EffectReadbackState.PREPARED_FENCED, + "delayed-equal-time-definitive", + base.plusSeconds(6)))) { assertThatThrownBy( () -> journal.recordEffectReadback(dispatched, delayed, base.plusSeconds(7))) .isInstanceOf(InitialGameplayReleaseConflictException.class) - .hasMessageContaining("predates the retained same-attempt observation"); + .hasMessageContaining( + delayed.observedAt().equals(unknown.observedAt()) + && delayed.state() != EffectReadbackState.UNKNOWN_OR_PARTIAL + ? "definitive effect readback must be newer than retained partial evidence" + : "predates the retained same-attempt observation"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); assertThat(journal.find(operationId)).contains(before); assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) @@ -983,10 +1007,11 @@ void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded "closed-a", base.plusSeconds(5)), base.plusSeconds(5)); + String closedA = storedClosure(a); OutboxEntry b = journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(6)); + assertThat(storedClosure(a)).isEqualTo(closedA); String before = storedOutbox(operationId, effectId); - String closedA = storedClosure(a); assertThat( journal.recordAmbiguousEffectForDispatch(a, "DELAYED_AMBIGUOUS", base.plusSeconds(7))) .isFalse(); @@ -1091,6 +1116,9 @@ void delayedReadbackCannotMutateSameIdRetryWithinTheSameStoredMicrosecond() { assertThatThrownBy(() -> journal.recordEffectReadback(original, oldReadback, receivedAt)) .isInstanceOf(InitialGameplayReleaseConflictException.class) .hasMessageContaining("effect readback dispatch generation changed"); + assertThatThrownBy(() -> journal.recordEffectReadback(replacement, oldReadback, receivedAt)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback dispatch generation changed"); assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); assertThat(journal.find(operationId)).contains(operation); assertThat(journal.findNextEffect(operationId)).contains(replacement); @@ -1124,6 +1152,8 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) .schemas(SCHEMA) .defaultSchema(SCHEMA) + .table("flyway_schema_history_recovery_control") + .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/recovery-control-migration") .target("1") .load() @@ -1160,6 +1190,8 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) .schemas(SCHEMA) .defaultSchema(SCHEMA) + .table("flyway_schema_history_recovery_control") + .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/recovery-control-migration") .load(); if (claimed) { @@ -1242,6 +1274,7 @@ private static EffectReadback readbackFor( entry.effect().operationId(), entry.effect().effectId(), attempt, + entry.attemptCount(), entry.effect().kind(), entry.effect().operationTupleDigest(), entry.payloadDigest(), diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index e3d1703ecd..5e4564eb12 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -437,6 +437,7 @@ void noEffectReadbackRequiresClosedAttemptRatherThanObservedAbsence() { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + 1, InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, DIGEST, DIGEST, @@ -446,11 +447,28 @@ void noEffectReadbackRequiresClosedAttemptRatherThanObservedAbsence() { "absence-only", java.time.Instant.EPOCH)) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + new InitialGameplayReleaseModel.EffectReadback( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 0, + InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, + DIGEST, + DIGEST, + InitialGameplayReleaseModel.EffectReadbackState.PREPARED_FENCED, + InitialGameplayReleaseModel.EffectReadbackAuthority + .GAME_SESSION_DURABLE_CURRENT_STATE, + "invalid-generation", + java.time.Instant.EPOCH)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("attemptOrdinal must be positive"); var closed = new InitialGameplayReleaseModel.EffectReadback( UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + 1, InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, DIGEST, DIGEST, @@ -504,6 +522,7 @@ void journalReadbackRejectsNulInIdentityBeforePersistence() { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + 1, InitialGameplayReleaseModel.EffectKind.PREPARE_PLAYABLE_STATE_FENCED, DIGEST, DIGEST, diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java index 67f8c89576..e2c44d4991 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/service/InitialGameplayReleaseControllerTest.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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -195,11 +196,11 @@ void unconfiguredGameSessionEffectPortDoesNotDispatch() { DIGEST, "proof-identity-1"); - var result = port.apply(effect, UUID.randomUUID()); + var result = port.apply(effect, UUID.randomUUID(), 1); assertThat(result.status()) .isEqualTo(InitialGameplayReleaseEffectPort.ApplyStatus.NOT_DISPATCHED); assertThat(result.outcomeCode()).isEqualTo("GAME_SESSION_EFFECT_OWNER_UNAVAILABLE"); - assertThat(port.readback(effect, UUID.randomUUID()).status()) + assertThat(port.readback(effect, UUID.randomUUID(), 1).status()) .isEqualTo(InitialGameplayReleaseEffectPort.ReadbackStatus.UNAVAILABLE); } @@ -275,14 +276,18 @@ private void assertPendingClaimHandling( : new UUID( ~requested.getMostSignificantBits(), requested.getLeastSignificantBits())); - if (ownsClaim) when(claimed.effect()).thenReturn(effect); + if (ownsClaim) { + when(claimed.effect()).thenReturn(effect); + when(claimed.attemptCount()).thenReturn(2); + } return claimed; }); if (ownsClaim && applyResult == null) { - when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())) + when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any(), anyInt())) .thenThrow(new IllegalStateException("response lost after possible owner send")); } else if (ownsClaim) { - when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any())).thenReturn(applyResult); + when(port.apply(org.mockito.ArgumentMatchers.eq(effect), any(), anyInt())) + .thenReturn(applyResult); } var controller = new InitialGameplayReleaseController( @@ -306,8 +311,8 @@ private void assertPendingClaimHandling( if (!ownsClaim) { verifyNoInteractions(port); } else { - verify(port).apply(effect, claimedAttempt.get()); - verify(port, never()).readback(any(), any()); + verify(port).apply(effect, claimedAttempt.get(), 2); + verify(port, never()).readback(any(), any(), anyInt()); } if (ownsClaim && expectedRetrySource == null) { verify(journal) @@ -484,10 +489,10 @@ private void assertReadbackFailureReloadsLatestOperation(boolean throwsException .thenReturn(java.util.Optional.of(before), java.util.Optional.of(after)); when(journal.findNextEffect(scope.operationId())).thenReturn(java.util.Optional.of(outbox)); if (throwsException) { - when(effectPort.readback(effect, attempt)) + when(effectPort.readback(effect, attempt, outbox.attemptCount())) .thenThrow(new IllegalStateException("owner readback failed")); } else { - when(effectPort.readback(effect, attempt)) + when(effectPort.readback(effect, attempt, outbox.attemptCount())) .thenReturn(InitialGameplayReleaseEffectPort.EffectReadbackResolution.unavailable()); } var controller = @@ -498,7 +503,7 @@ private void assertReadbackFailureReloadsLatestOperation(boolean throwsException effectPort); assertThat(controller.reconcileNextEffect(scope.operationId())).isSameAs(after); - verify(effectPort).readback(effect, attempt); + verify(effectPort).readback(effect, attempt, outbox.attemptCount()); verify(journal, never()).recordEffectReadback(any(), any(), any()); } @@ -558,6 +563,7 @@ void futureDatedOwnerReadbackCannotAdvanceJournal() { scope.operationId(), effect.effectId(), attempt, + outbox.attemptCount(), effect.kind(), DIGEST, DIGEST, @@ -569,7 +575,7 @@ void futureDatedOwnerReadbackCannotAdvanceJournal() { now.plusSeconds(1)); when(journal.find(scope.operationId())).thenReturn(java.util.Optional.of(operation)); when(journal.findNextEffect(scope.operationId())).thenReturn(java.util.Optional.of(outbox)); - when(effectPort.readback(effect, attempt)) + when(effectPort.readback(effect, attempt, outbox.attemptCount())) .thenReturn(InitialGameplayReleaseEffectPort.EffectReadbackResolution.available(readback)); var controller = new InitialGameplayReleaseController( From c07995cbf23a99e54858322bbd8887352c6a6ad2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:50:02 +1300 Subject: [PATCH 088/199] Harden preview and runtime publication and recovery replay --- .github/workflows/ci.yml | 4 +- .github/workflows/codeql.yml | 2 +- .github/workflows/license-scan.yml | 2 +- .github/workflows/preview-reconciler.yml | 303 ++++++++++++- .github/workflows/preview-runtime-refresh.yml | 14 +- .../workflows/publish-pr-runtime-images.yml | 3 +- .github/workflows/runtime-images.yml | 11 +- .github/workflows/smoke.yml | 2 +- .github/workflows/static-analysis-summary.yml | 15 +- .../system-architecture-backup-recovery.md | 2 +- dev-tools/README.md | 2 + .../hosted/shared/wait-for-runtime-images.sh | 247 ++++++---- .../tests/ci-validation-summary-contract.sh | 14 +- ...d-identity-controller-workflow-contract.sh | 5 +- .../pr-required-gate-context-contract.sh | 19 +- .../tests/pr-retarget-workflow-contract.sh | 304 ++++++++++++- .../pr-runtime-image-publication-contract.sh | 44 +- dev-tools/tests/preview-priority-contract.sh | 421 ++++++++++++++++-- .../tests/preview-runtime-refresh.test.cjs | 10 +- .../tests/static-analysis-summary-contract.sh | 55 ++- dev-tools/validation/check-flyway-versions.py | 54 ++- ...lDatabaseHostEnvironmentPostProcessor.java | 26 ++ .../InitialGameplayReleaseTupleCodec.java | 44 +- .../JooqInitialGameplayReleaseJournal.java | 43 +- .../main/resources/META-INF/spring.factories | 1 + ...ReleaseJournalPostgresIntegrationTest.java | 406 +++++++++++++++-- ...abaseHostEnvironmentPostProcessorTest.java | 42 ++ ...overyControllerOwnerConfigurationTest.java | 56 ++- .../InitialGameplayReleaseModelTest.java | 25 ++ 29 files changed, 1930 insertions(+), 246 deletions(-) create mode 100644 services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java create mode 100644 services/recovery-controller-service/src/main/resources/META-INF/spring.factories create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 412037d94e..1ce00f1e44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -788,10 +788,10 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false - - name: Set up Python for Gradle recovery + - name: Set up Python for Flyway validation and Gradle recovery uses: ./.github/actions/setup-python with: - requirements: none + requirements: yaml - name: 🧪 Check Flyway Migration Versions env: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 6a7bf93c13..b47a03b168 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -9,7 +9,7 @@ on: - cron: '0 0 * * 0' workflow_dispatch: -run-name: CodeQL Analysis ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }} +run-name: CodeQL Analysis ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && ' mode-metadata' || '' }} permissions: contents: read diff --git a/.github/workflows/license-scan.yml b/.github/workflows/license-scan.yml index e7d2445ef8..64e7cf1402 100644 --- a/.github/workflows/license-scan.yml +++ b/.github/workflows/license-scan.yml @@ -7,7 +7,7 @@ on: types: [opened, synchronize, reopened, edited] workflow_dispatch: -run-name: License Gate ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }} +run-name: License Gate ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && ' mode-metadata' || '' }} permissions: contents: read diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index e9c6f1731c..ff2804f8a5 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -13,7 +13,8 @@ permissions: concurrency: group: preview-reconciler-${{ github.workflow }} - cancel-in-progress: true + # A scheduled run must not cancel an in-flight wait for GitHub's rate-limit reset. + cancel-in-progress: false jobs: reconcile-previews: @@ -68,6 +69,7 @@ jobs: preview_workflow_name="PR Preview Environment" eligibility_script="./dev-tools/hosted/preview/preview-eligibility.py" max_active="${PREVIEW_MAX_ACTIVE:-2}" + preview_handoff_window_seconds=600 parse_namespace_tuple() { jq -er ' @@ -454,9 +456,20 @@ jobs: active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" available_slots=$((max_active - active_count)) + dispatch_outcome_failed=false + refresh_available_slots() { + local live_namespaces live_count + if ! live_namespaces="$(kubectl get namespaces -l firemud.dev/preview=true -o name)"; then + return 1 + fi + live_count="$(printf '%s\n' "$live_namespaces" | sed '/^$/d' | wc -l)" + available_slots=$((max_active - live_count)) + } dispatch_sent=false + completed_preview_source_updated_at="" automatic_preview_has_tuple() { local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true + local event_tuple="${tuple/Preview resolved tuple /Preview event tuple }" # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 @@ -478,6 +491,7 @@ jobs: and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) ' <<<"$latest" >/dev/null || return 1 if jq -e '.status == "completed" and .conclusion != "success"' <<<"$latest" >/dev/null; then return 1; fi + if [[ "$event" == pull_request_target ]]; then return 2; fi [[ "$jobs_available" == true ]] || return 2 jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' @@ -489,21 +503,222 @@ jobs: .name == "Preview Plan" and .run_id == $id and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) and .head_sha == $head and .status == "completed" and .conclusion == "success" - and ([.steps[]? | select(.name | startswith("Preview resolved tuple "))] | length == 1) - and any(.steps[]?; - (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) - and .status == "completed" and .conclusion == "success")) + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length <= 1) + and ([.steps[] | select(.name | startswith("Preview event tuple "))] | length <= 1) + and ([.steps[] | select(.name == "Explain preview skip")] | length <= 1) + and (if ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length) == 1 then + any(.steps[]; (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + else + any(.steps[]; (.name | test("^Preview event tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + end)) ' <<<"$jobs" >/dev/null || return 2 + if jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) + ' <<<"$jobs" >/dev/null; then + : + elif jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + return 1 + elif jq -e --arg tuple "$event_tuple" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == $tuple + and .status == "completed" and .conclusion == "success") + and any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null && + jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + # A completed successful plan with its successful skip explanation proves no deployable plan ran. + return 1 + elif jq -e --arg prefix "Preview event tuple pr-${pr} base-" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + (.name | startswith($prefix)) and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + # An event marker alone cannot establish either a deployable plan or a completed no-op. + return 2 + else + return 2 + fi jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) ' <<<"$jobs" >/dev/null || return 1 if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" # The trusted consumer may be queued after the active-run inventory. # Defer one cycle after an exact successful source completion. return 3 fi } + recent_successful_source_handoff() { + local pr_number="$1" head_sha="$2" tuple_step="$3" + local source_runs source_candidates source_candidate_count source_inventory_now + local run_id run_attempt run_event run_head run_updated_at lookup_status source_updated_epoch now_epoch source_age + local consumer_runs consumer_candidates consumer_candidate_count + local consumer_run_id consumer_attempt consumer_head consumer_status consumer_created_after + local run_name="Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" + local pr_title="PR preview ${pr_number}" + + if ! source_runs="$(gh api --method GET \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ + -f event=pull_request -f status=completed -f per_page=100 -f "head_sha=${head_sha}")"; then + echo "Unable to inspect recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 + return 2 + fi + if ! jq -e --argjson workflow_id "$preview_workflow_id" 'type == "object" + and (.total_count | type == "number" and . >= 0 and . == floor) + and (.workflow_runs | type == "array" and length <= 100) + and (.total_count == (.workflow_runs | length)) + and all(.workflow_runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) + and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) + and (.event | type == "string") and (.status | type == "string") + and (.conclusion | type == "string") and (.name | type == "string") + and (.display_title | type == "string") and (.head_branch | type == "string") + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | type == "string") + and (.updated_at | type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")) + and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") + and (.pull_requests | type == "array"))' <<<"$source_runs" >/dev/null; then + echo "Recent completed preview-source inventory is malformed or truncated; retry budget unchanged." >&2 + return 2 + fi + source_inventory_now="$(date -u +%s)" + if ! source_candidates="$(jq -r \ + --arg repository "$GITHUB_REPOSITORY" --arg head "$head_sha" \ + --arg workflow_name "$preview_workflow_name" --arg pr_title "$pr_title" \ + --arg run_name "$run_name" --argjson workflow_id "$preview_workflow_id" \ + --argjson now "$source_inventory_now" --argjson window "$preview_handoff_window_seconds" \ + --argjson pr_number "$pr_number" ' + def positive_int: type == "number" and . > 0 and . == floor; + [ .workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "pull_request" + and .status == "completed" and .conclusion == "success" + and (.name == $workflow_name or .name == .display_title) + and (.display_title == $pr_title or .display_title == $run_name) + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_sha == $head + and (.path == ".github/workflows/preview.yml" + or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) + and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) + | (.updated_at | fromdateiso8601) as $updated + | select($updated <= $now and ($now - $updated) < $window) + | [.id, .run_attempt, .event, .head_sha, .updated_at] + ] | sort_by(.[0]) | reverse | .[] | @tsv + ' <<<"$source_runs")"; then + echo "Unable to parse recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 + return 2 + fi + source_candidate_count="$(printf '%s\n' "$source_candidates" | sed '/^$/d' | wc -l)" + if (( source_candidate_count > 3 )); then + echo "Recent completed preview-source lookup exceeded its three-run bound; retry budget unchanged." >&2 + return 2 + fi + + while IFS=$'\t' read -r run_id run_attempt run_event run_head run_updated_at; do + [[ -n "$run_id" ]] || continue + completed_preview_source_updated_at="" + lookup_status=0 + automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + if [[ "$lookup_status" -eq 2 ]]; then + echo "Recent preview-source attempt ${run_id} could not be verified; retry budget unchanged." >&2 + return 2 + fi + [[ "$lookup_status" -eq 3 ]] || continue + if [[ "$completed_preview_source_updated_at" != "$run_updated_at" ]]; then + echo "Recent preview-source inventory changed during exact-attempt lookup; retry budget unchanged." >&2 + return 2 + fi + if [[ ! "$completed_preview_source_updated_at" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] || + ! source_updated_epoch="$(date -u -d "$completed_preview_source_updated_at" +%s 2>/dev/null)" || + ! now_epoch="$(date -u +%s)"; then + echo "Recent preview-source completion time is unavailable; retry budget unchanged." >&2 + return 2 + fi + source_age=$((now_epoch - source_updated_epoch)) + if (( source_age < 0 )); then + echo "Recent preview-source completion time is in the future; retry budget unchanged." >&2 + return 2 + fi + if (( source_age >= preview_handoff_window_seconds )); then + continue + fi + + consumer_created_after="$(date -u -d "@$((now_epoch - preview_handoff_window_seconds))" +%Y-%m-%dT%H:%M:%SZ)" + if ! consumer_runs="$(gh api --method GET \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/${consumer_workflow_id}/runs" \ + -f event=workflow_run -f per_page=100 -f "branch=${DEFAULT_BRANCH}" \ + -f "created=>=${consumer_created_after}")"; then + echo "Unable to recheck trusted consumers after recent source completion; retry budget unchanged." >&2 + return 2 + fi + if ! jq -e --argjson workflow_id "$consumer_workflow_id" 'type == "object" + and (.total_count | type == "number" and . >= 0 and . == floor) + and (.workflow_runs | type == "array" and length <= 100) + and (.total_count == (.workflow_runs | length)) + and all(.workflow_runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) + and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) + and (.event | type == "string") and (.status | type == "string") + and (.name | type == "string") and (.display_title | type == "string") + and (.head_branch | type == "string") + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | type == "string") + and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string"))' <<<"$consumer_runs" >/dev/null; then + echo "Fresh trusted-consumer inventory is malformed or truncated; retry budget unchanged." >&2 + return 2 + fi + if ! consumer_candidates="$(jq -r \ + --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" \ + --arg pr_title "$pr_title" --arg run_name "$run_name" \ + --argjson workflow_id "$consumer_workflow_id" ' + def positive_int: type == "number" and . > 0 and . == floor; + [ .workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "workflow_run" + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) + and .head_branch == $default_branch + and .repository.full_name == $repository and .head_repository.full_name == $repository + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.display_title == $pr_title or .display_title == $run_name)) + | [.id, .run_attempt, .head_sha] + ] | sort_by(.[0]) | reverse | .[] | @tsv + ' <<<"$consumer_runs")"; then + echo "Unable to parse fresh trusted-consumer inventory; retry budget unchanged." >&2 + return 2 + fi + consumer_candidate_count="$(printf '%s\n' "$consumer_candidates" | sed '/^$/d' | wc -l)" + if (( consumer_candidate_count > 3 )); then + echo "Fresh trusted-consumer lookup exceeded its three-run bound; retry budget unchanged." >&2 + return 2 + fi + while IFS=$'\t' read -r consumer_run_id consumer_attempt consumer_head; do + [[ -n "$consumer_run_id" ]] || continue + consumer_status=0 + trusted_consumer_has_tuple "$consumer_run_id" "$consumer_attempt" "$consumer_head" \ + "Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" || consumer_status=$? + if [[ "$consumer_status" -eq 0 ]]; then + echo "Skipping proof retry for PR #${pr_number}: trusted consumer run ${consumer_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." + return 0 + elif [[ "$consumer_status" -eq 2 ]]; then + echo "Fresh trusted-consumer run ${consumer_run_id} could not be verified; retry budget unchanged." >&2 + return 2 + fi + done <<<"$consumer_candidates" + echo "Deferring proof retry for PR #${pr_number}: exact successful preview source run ${run_id} is within the ${preview_handoff_window_seconds}-second trusted-consumer handoff window." + return 3 + done <<<"$source_candidates" + return 1 + } + trusted_consumer_has_tuple() { local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest jobs_available=true # A workflow_run display title is inherited from its source. Use the @@ -585,7 +800,7 @@ jobs: fi if [[ "$dispatch_sent" == "true" ]]; then - echo "Skipping PR #${pr_number}: another preview repair was already dispatched this cycle." + echo "Skipping PR #${pr_number}: the preview dispatch cycle already stopped after a request attempt." continue fi @@ -623,8 +838,15 @@ jobs: _ _ _ _ _ \ namespace_uid _ <<<"${namespace_tuple}" elif [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is full." - continue + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + continue + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + continue + fi fi mergeable="$(jq -r 'if (.mergeable | type) == "boolean" then (.mergeable | tostring) else "invalid" end' <<<"${live_pr_json}")" @@ -711,8 +933,15 @@ jobs: if [[ "$namespace_exists" != "true" ]]; then if [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is full." - continue + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + continue + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + continue + fi fi fi @@ -842,6 +1071,24 @@ jobs: continue fi + recent_handoff_status=0 + recent_successful_source_handoff "$pr_number" "$head_sha" "$tuple_step" || recent_handoff_status=$? + case "$recent_handoff_status" in + 0 | 3) + continue + ;; + 2) + echo "Skipping proof retry for PR #${pr_number}: recent preview handoff lookup unavailable; retry budget unchanged." >&2 + continue + ;; + 1) + ;; + *) + echo "Unexpected recent preview handoff status: ${recent_handoff_status}" >&2 + exit 1 + ;; + esac + require_deployed_tuple=false if [[ "${namespace_exists}" == "true" && "${current_base_sha}" == "${base_sha}" && @@ -886,15 +1133,47 @@ jobs: fi dispatch_status_line_count="$(grep -cE '^HTTP/[0-9.]+ [0-9]{3} ' <<<"${dispatch_response}" || true)" dispatch_http_status="$(awk '/^HTTP\/[0-9.]+ [0-9][0-9][0-9] / { print $2; exit }' <<<"${dispatch_response}")" + dispatch_retry_after="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^retry-after:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_rate_remaining="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-remaining:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_rate_reset="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-reset:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_error_body="$(awk 'BEGIN { body=0 } { sub(/\r$/, ""); if (!body && $0 == "") { body=1; next } if (body) print }' <<<"${dispatch_response}")" + dispatch_rate_limit_body=false + if jq -e 'type == "object" and ((.message // "") | type == "string" and test("rate limit"; "i"))' \ + <<<"${dispatch_error_body}" >/dev/null 2>&1; then + dispatch_rate_limit_body=true + fi + rate_limited_dispatch=false + if [[ "${dispatch_http_status}" == 429 ]] || + [[ "${dispatch_http_status}" == 403 && + ( "${dispatch_retry_after}" =~ ^[0-9]+$ || + "${dispatch_rate_remaining}" == 0 || + "${dispatch_rate_limit_body}" == true ) ]]; then + rate_limited_dispatch=true + fi if [[ "${dispatch_exit}" -eq 0 && "${dispatch_status_line_count}" -eq 1 && "${dispatch_http_status}" == 204 ]]; then dispatch_sent=true elif [[ "${dispatch_status_line_count}" -eq 1 && "${dispatch_http_status}" =~ ^4[0-9][0-9]$ ]]; then + dispatch_outcome_failed=true echo "GitHub confirmed preview dispatch rejection for PR #${pr_number} (HTTP ${dispatch_http_status})." if ! compensate_rejected_proof_retry "$namespace" "$pr_number"; then echo "The rejected dispatch could not be safely compensated; its proof-retry budget remains charged." >&2 fi + if [[ "${rate_limited_dispatch}" == true ]]; then + rate_limit_wait_seconds=60 + if [[ "${dispatch_retry_after}" =~ ^[0-9]+$ ]]; then + rate_limit_wait_seconds=$((10#${dispatch_retry_after})) + elif [[ "${dispatch_rate_remaining}" == 0 && "${dispatch_rate_reset}" =~ ^[0-9]+$ ]]; then + current_epoch="$(date -u +%s)" + rate_limit_wait_seconds=$((10#${dispatch_rate_reset} - current_epoch)) + (( rate_limit_wait_seconds > 0 )) || rate_limit_wait_seconds=60 + fi + echo "GitHub rate-limited preview dispatch; stopping this cycle and waiting ${rate_limit_wait_seconds} seconds before another attempt." + dispatch_sent=true + sleep "${rate_limit_wait_seconds}" + fi else + dispatch_outcome_failed=true echo "Preview dispatch outcome for PR #${pr_number} is ambiguous (gh=${dispatch_exit}, HTTP=${dispatch_http_status:-unknown}); proof-retry budget remains charged." >&2 dispatch_sent=true fi @@ -998,6 +1277,10 @@ jobs: fi dispatch_candidates <<<"$candidate_rows" fi + if [[ "$dispatch_outcome_failed" == true ]]; then + echo "One or more preview dispatch outcomes or capacity checks failed; review this job before another repair cycle." >&2 + exit 1 + fi - name: Remove preview kubeconfig if: ${{ always() }} diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 150b7ed403..517ece850e 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -154,7 +154,9 @@ jobs: const {data: base} = await github.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}`, }); - if (!sha.test(base.object?.sha) || (isIntegrationBase && recorded[2] === base.object.sha)) { + const eventBaseMatchesMerge = recorded[2] === recordedMerge.parents[0].sha; + if (!sha.test(base.object?.sha) || + (isIntegrationBase && eventBaseMatchesMerge && recorded[2] === base.object.sha)) { core.info('No stale source base to repair; no dispatch.'); return; } @@ -167,14 +169,8 @@ jobs: core.info('Current merge is not the exact current base/head tuple; no dispatch.'); return; } - const resolvedMatchesRecorded = resolved[4] === recordedMerge.sha && - resolved[2] === recordedMerge.parents[0].sha; - // A stale event base can accompany a newer historical merge. Its - // plan must independently resolve that merge and its actual parent. - if (recordedMerge.parents[0].sha !== recorded[2] && !resolvedMatchesRecorded) { - core.info('Recorded merge and event base disagree without exact resolved evidence; no dispatch.'); - return; - } + // The event and the plan can observe different base advances. The + // resolved plan must independently prove its ordered parents. let resolvedMerge = resolved[4] === recordedMerge.sha ? recordedMerge : merge; if (resolved[4] !== resolvedMerge.sha) { ({data: resolvedMerge} = await github.rest.repos.getCommit({...context.repo, ref: resolved[4]})); diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 1054d88508..51d04e46aa 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -7,7 +7,8 @@ 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) }} +# Typed refresh callbacks include the exact source run ID because their tuple can be reused. +run-name: Publish PR Runtime Images ${{ github.event.workflow_run.event == 'repository_dispatch' && format('{0} source-run-{1}', github.event.workflow_run.display_title, github.event.workflow_run.id) || github.event.workflow_run.display_title || format('source-run-{0}', github.event.client_payload.source_run_id) }} permissions: {} diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 62615d551f..0d75e7abfe 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -256,6 +256,15 @@ jobs: echo "Runtime branch publication is restricted to main or develop." >&2 exit 1 } + current_head="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" --jq '.object.sha')" + [[ "$current_head" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication could not prove the live ${HEAD_BRANCH} head." >&2 + exit 1 + } + if [[ "$current_head" != "$HEAD_SHA" ]]; then + echo "Skipping runtime builds for obsolete ${HEAD_BRANCH}@${HEAD_SHA}; current head is ${current_head}." + exit 0 + fi fi if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then @@ -285,7 +294,7 @@ jobs: } >> "$GITHUB_OUTPUT" - name: Verify successful CI push for manual publication - if: ${{ github.event_name == 'workflow_dispatch' }} + if: ${{ github.event_name == 'workflow_dispatch' && steps.meta.outputs.head_sha != '' }} env: GH_TOKEN: ${{ github.token }} EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 472f6777c0..b6ffda1965 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -572,7 +572,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "777b2527be618a77674d20338ca30bca771f81afd010165bb33b2b72465779df"; + const canonicalRuntimeWorkflowSha256 = "1e069f10479faeca137c56b731ecf4a7357d47b8f2dd536f6483a80c1c5fa9c5"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 92f34646f8..003f5cb0e6 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -269,10 +269,11 @@ jobs: return [label, normalizeStatus(candidates[0], checkName, workflowRun)]; }); - const workflowRuns = { + const selectWorkflowRuns = async () => ({ codeql: await workflowRunFor("codeql.yml", "CodeQL Gate"), license: await workflowRunFor("license-scan.yml", "License Gate"), - }; + }); + const workflowRuns = await selectWorkflowRuns(); // Each serialized producer completion publishes one bounded snapshot. // A running counterpart stays pending until its completion callback refreshes this comment. const checks = resolveStatuses(workflowRuns); @@ -350,6 +351,16 @@ jobs: } } + if (!failedChecks.length && !unavailableChecks.length && !pendingChecks.length) { + const latest = await selectWorkflowRuns(); + if (Object.entries(workflowRuns).some(([name, selected]) => + ["id", "run_attempt", "status", "conclusion"].some(field => + selected?.[field] !== latest[name]?.[field]))) { + core.info("A producer selection changed before the passing summary could be published."); + return; + } + } + const comparisonIsCurrent = async () => { const { data: current } = await github.rest.pulls.get({ ...context.repo, diff --git a/design/architecture/system-architecture-backup-recovery.md b/design/architecture/system-architecture-backup-recovery.md index f662cceef2..0ddf0aa9dc 100644 --- a/design/architecture/system-architecture-backup-recovery.md +++ b/design/architecture/system-architecture-backup-recovery.md @@ -90,7 +90,7 @@ The typed `initial-gameplay-recover/v1` request binds the control-plane request, Activation still requires real Account authorization/redemption, authenticated owner association/storage verification, an independently proved exclusive maintenance fence and actual acquired lock, genuine current owner evidence/readbacks, and approved isolated deployment/restore topology. A random journal UUID is not a lock or exclusion proof. Later continuation and resume bind the exact retained scope, lock, phase, and evidence; ambiguous effects cannot authorize redispatch or final handoff. Source-level journal tests do not establish these missing end-to-end prerequisites or player-facing recovery readiness. -Outcomes and readbacks are bound to the exact effect attempt and dispatch generation. A definite owner rejection permanently retires that attempt ID, while a locally proved no-send outcome permits another dispatch generation with the same ID. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. A current readback carries the requested dispatch generation and an original owner observation time comparable to the controller clock. When newer partial evidence supersedes a definitive observation, progress requires fresh authoritative evidence from the owner. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. +Outcomes and readbacks are bound to the exact effect attempt and dispatch generation. A definite owner rejection permanently retires that attempt ID, while a locally proved no-send outcome permits another dispatch generation with the same ID. `PROVEN_NO_EFFECT` requires durable closure of that attempt: the owner must reject every delayed apply for the closed attempt before another attempt becomes retryable. Merely observing no current effect is insufficient. An exact replay of a retained closure receipt may return the current operation after a replacement attempt starts. It leaves the replacement attempt and its evidence intact. A current readback carries the requested dispatch generation and an original owner observation time comparable to the controller clock. When newer partial evidence supersedes a definitive observation, progress requires fresh authoritative evidence from the owner. The source model distinguishes this terminal authority from current-state readback, but no real owner adapter is qualified yet. Activation proof must exercise a claimant delayed after journal dispatch against owner closure and subsequent retry. The exclusive-fence activation work must also prove the region lease belongs to the requested scope, prevent or reject lease replacement between evidence read and journal authorization/effect application, and define an audited restart or abandonment path after lease replacement that never releases the maintenance fence prematurely. Those owner protocols are not implemented by the source-only journal; a retained evidence snapshot is not a current lease lock. diff --git a/dev-tools/README.md b/dev-tools/README.md index 8ee605d09e..303abfba78 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -53,6 +53,8 @@ FireController is maintained outside this repository. Use the `firecontroller-us - `tests/dev-certs-retention-contract.sh` – validates retained development certificate bundles and proves refusal/preservation for incomplete material and linked paths. - `validation/` – repo policy and static validation scripts used by Gradle and CI. +Local `checkFlywayVersions` uses the repository's [pinned YAML requirements](../config/python/yaml-requirements.txt) to read the packaged Spring migration configuration. Install them in the Python environment used by Gradle with `python3 -m pip install --require-hashes -r config/python/yaml-requirements.txt`. + The documentation lock is sourced from the unpinned direct roots in `config/docs/requirements.in` and generated into `config/docs/requirements.txt` with the repository Python version and `pip-compile --allow-unsafe --generate-hashes --index-url=https://pypi.org/simple --output-file=config/docs/requirements.txt config/docs/requirements.in`. The existing lock seeds compilation and preserves satisfying package pins unless you explicitly request an upgrade. When the installed pip-tools version mis-serializes its default index options into an unsupported header, set `CUSTOM_COMPILE_COMMAND` to that exact command so the generated header remains parseable. Keep the source roots and lock hashes in sync; do not edit lock hashes manually. ## Placement guidance diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 6372f1e045..93e3890cb3 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -44,9 +44,14 @@ deadline=$((SECONDS + timeout_seconds)) fetch_workflow_runs() { local endpoint="$1" local wait_context="$2" + local remaining_seconds="${3:-}" local payload + local -a bound=() + if [[ -n "$remaining_seconds" ]]; then + bound=(timeout --signal=KILL "$remaining_seconds") + fi - if ! payload="$(gh api --paginate --slurp "${endpoint}")"; then + if ! payload="$("${bound[@]}" gh api --paginate --slurp "${endpoint}")"; then printf 'GitHub API poll failed while %s; retrying within the existing wait deadline.\n' \ "${wait_context}" >&2 return 1 @@ -168,7 +173,7 @@ for run in ranked[:8] if alternates else ranked[:1]: fetch_publisher_runs() { local -a bound=() if [[ -n "${4:-}" ]]; then - bound=(timeout --kill-after=1s "$4") + bound=(timeout --signal=KILL "$4") fi "${bound[@]}" python3 - "${GITHUB_REPOSITORY}" "$1" "$2" "$3" <<'PY_PUBLISHERS' import json @@ -237,9 +242,11 @@ import json import re import sys -wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id = sys.argv[1:7] +wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id, source_event = sys.argv[1:8] if not re.fullmatch(r"[1-9][0-9]*", source_run_id): raise SystemExit(1) +if source_event not in {"pull_request", "repository_dispatch"}: + raise SystemExit(1) try: payload = json.load(sys.stdin) except json.JSONDecodeError: @@ -258,27 +265,37 @@ workflow_runs = [ if any(not isinstance(run, dict) for run in workflow_runs): raise SystemExit(1) if wait_mode == "pull-request": - 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}") - 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 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") - ] + matching_runs = [] + for run in workflow_runs: + tokens = run.get("display_title", "").split() + tuple_matches = ( + tokens[:8] == [ + "Publish", "PR", "Runtime", "Images", "Build", "Runtime", "Images", + "secure-pr-artifact", + ] + and re.fullmatch(r"pr-[1-9][0-9]{0,50}", tokens[8] if len(tokens) > 8 else "") + and len(tokens) >= 13 + 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" + ) + if source_event == "pull_request": + if run.get("event") == "workflow_run" and len(tokens) == 13 and tuple_matches: + matching_runs.append(run) + elif ( + run.get("event") == "workflow_run" and len(tokens) == 14 and tuple_matches + and tokens[13] == f"source-run-{source_run_id}" + ) or ( + run.get("event") == "repository_dispatch" + and run.get("display_title") == f"Publish PR Runtime Images source-run-{source_run_id}" + ): + matching_runs.append(run) else: matching_runs = [] -all_candidates = len(sys.argv) > 9 and sys.argv[9] == "all" -if len(sys.argv) > 7: - event, title = sys.argv[7:9] +all_candidates = len(sys.argv) > 10 and sys.argv[10] == "all" +if len(sys.argv) > 8: + event, title = sys.argv[8:10] matching_runs = [run for run in matching_runs if run.get("event") == event and run.get("display_title") == title and run.get("status") == "completed" and run.get("conclusion") == "success"] @@ -303,17 +320,19 @@ fetch_alternate_run_metadata() { local lookup_deadline="$1" local remaining=$((lookup_deadline - SECONDS)) (( remaining > 0 )) || return 1 - timeout --kill-after=1s "$remaining" gh api "$2" + timeout --signal=KILL "$remaining" gh api "$2" } -# A typed publication binds the source run ID. A native callback binds the -# immutable tuple, which the trusted publisher revalidates before writing. -# Both paths need a positive publication step in the exact current attempt. +# PR callbacks bind the immutable source tuple. Typed native and explicit +# publishers bind the exact source run ID as well as the tuple. Every path +# needs a positive publication step in the exact current attempt. use_completed_duplicate_publication() { local state older_id older_created source_event inventory upper publisher_lines publisher_id publisher_status publisher_conclusion local source_state="$1" lookup_deadline="$2" remaining + local proof_origin="${3:-alternate}" local source source_attempt source_title source_latest publisher_event expected_title local run attempt jobs latest publisher_path default_branch repository_info + local -a publisher_events=() IFS=$'\t' read -r state older_id _ _ _ source_event older_created <<<"$source_state" [[ "$state" == "found" ]] || return 1 source="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || return 1 @@ -325,67 +344,82 @@ use_completed_duplicate_publication() { | .run_attempt | select(type == "number" and . >= 1 and floor == .) ' <<<"$source")" || return 1 if [[ "$source_event" == "pull_request" ]]; then - publisher_event="workflow_run" - expected_title="Publish PR Runtime Images ${source_title}" + publisher_events=(workflow_run) else - publisher_event="repository_dispatch" - expected_title="Publish PR Runtime Images source-run-${older_id}" + # Typed refresh producers have two trusted publication paths. The native + # callback title includes the exact source ID; explicit dispatch carries it + # in the closed source-run title. + publisher_events=(workflow_run repository_dispatch) fi upper="$(date -u +%Y-%m-%dT%H:%M:%SZ)" || return 1 - remaining=$((lookup_deadline - SECONDS)) - (( remaining > 0 )) || return 1 - inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || return 1 - publisher_lines="$(read_publisher_state "$older_id" "$publisher_event" "$expected_title" all <<<"$inventory")" || return 1 - [[ "$publisher_lines" != "missing" ]] || return 1 repository_info="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}")" || return 1 default_branch="$(jq -er --arg repo "$GITHUB_REPOSITORY" ' select(.full_name == $repo) | .default_branch | select(type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._/-]*$")) ' <<<"$repository_info")" || return 1 - while IFS=$'\t' read -r state publisher_id publisher_status publisher_conclusion _; do - [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ && - "$publisher_status" == "completed" && "$publisher_conclusion" == "success" ]] || continue - (( SECONDS < lookup_deadline )) || break - run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue - publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || continue - # Either event runs on the default branch; a short path suffix must agree. - [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || - "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || continue - attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ - --arg title "$expected_title" --arg event "$publisher_event" ' - select(.id == $id and .event == $event and .display_title == $title - and .path == $path and .head_branch == $branch - and .repository.full_name == $repo and .head_repository.full_name == $repo - and .status == "completed" and .conclusion == "success") - | .run_attempt | select(type == "number" and . >= 1 and floor == .) - ' <<<"$run")" || continue - jobs="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || continue - jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' - (.jobs | type == "array") and (.total_count == (.jobs | length)) and - ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | - ($jobs | length) == 1 and ($jobs[0] | - .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and - .status == "completed" and .conclusion == "success" and - ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | - ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) - ' <<<"$jobs" >/dev/null || continue - latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue - jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" \ - --arg title "$expected_title" --arg event "$publisher_event" --arg repo "$GITHUB_REPOSITORY" ' - .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" - and .path == $path and .head_branch == $branch and .event == $event and .display_title == $title - and .repository.full_name == $repo and .head_repository.full_name == $repo - ' <<<"$latest" >/dev/null || continue - source_latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || continue - jq -e --argjson attempt "$source_attempt" --arg repo "$GITHUB_REPOSITORY" --arg title "$source_title" --arg head "$head_sha" ' - .run_attempt == $attempt and .repository.full_name == $repo and .head_repository.full_name == $repo - and .display_title == $title and (.event != "pull_request" or .head_sha == $head) - ' <<<"$source_latest" >/dev/null || continue - [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$source_state" ]] || continue - (( SECONDS < lookup_deadline )) || break - printf 'Trusted PR image publisher %s succeeded for %s via an alternate producer.\n' "$publisher_id" "$image_tag" - return 0 - done <<<"$publisher_lines" + for publisher_event in "${publisher_events[@]}"; do + if [[ "$publisher_event" == "workflow_run" ]]; then + expected_title="Publish PR Runtime Images ${source_title}" + [[ "$source_event" != "repository_dispatch" ]] || expected_title+=" source-run-${older_id}" + else + expected_title="Publish PR Runtime Images source-run-${older_id}" + fi + remaining=$((lookup_deadline - SECONDS)) + (( remaining > 0 )) || break + inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || continue + publisher_lines="$(read_publisher_state "$older_id" "$source_event" "$publisher_event" "$expected_title" all <<<"$inventory")" || continue + [[ "$publisher_lines" != "missing" ]] || continue + while IFS=$'\t' read -r state publisher_id publisher_status publisher_conclusion _; do + [[ "$state" == "found" && "$publisher_id" =~ ^[1-9][0-9]*$ && + "$publisher_status" == "completed" && "$publisher_conclusion" == "success" ]] || continue + (( SECONDS < lookup_deadline )) || break + run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue + publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || continue + # Either event runs on the default branch; a short path suffix must agree. + [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || + "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || continue + attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ + --arg title "$expected_title" --arg event "$publisher_event" ' + select(.id == $id and .event == $event and .display_title == $title + and .path == $path and .head_branch == $branch + and .repository.full_name == $repo and .head_repository.full_name == $repo + and .status == "completed" and .conclusion == "success") + | .run_attempt | select(type == "number" and . >= 1 and floor == .) + ' <<<"$run")" || continue + jobs="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}/attempts/${attempt}/jobs?per_page=100")" || continue + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" ' + (.jobs | type == "array") and (.total_count == (.jobs | length)) and + ([.jobs[] | select(.name == "Publish Fixed PR Merge Image Tags")] as $jobs | + ($jobs | length) == 1 and ($jobs[0] | + .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and + .status == "completed" and .conclusion == "success" and + ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | + ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) + ' <<<"$jobs" >/dev/null || continue + source_latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${older_id}")" || continue + jq -e --argjson attempt "$source_attempt" --arg repo "$GITHUB_REPOSITORY" --arg title "$source_title" --arg head "$head_sha" ' + .run_attempt == $attempt and .repository.full_name == $repo and .head_repository.full_name == $repo + and .display_title == $title and (.event != "pull_request" or .head_sha == $head) + ' <<<"$source_latest" >/dev/null || continue + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$source_latest" | read_run_state)" == "$source_state" ]] || continue + # Re-read the mutable publisher attempt after source validation so this is + # the last API proof read before accepting its immutable publication step. + latest="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue + jq -e --argjson id "$publisher_id" --argjson attempt "$attempt" --arg path "$publisher_path" --arg branch "$default_branch" \ + --arg title "$expected_title" --arg event "$publisher_event" --arg repo "$GITHUB_REPOSITORY" ' + .id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success" + and .path == $path and .head_branch == $branch and .event == $event and .display_title == $title + and .repository.full_name == $repo and .head_repository.full_name == $repo + ' <<<"$latest" >/dev/null || continue + (( SECONDS < lookup_deadline )) || break + if [[ "$proof_origin" == "direct" ]]; then + printf 'Trusted PR image publisher %s succeeded for %s as the direct source.\n' "$publisher_id" "$image_tag" + else + printf 'Trusted PR image publisher %s succeeded for %s via an alternate producer.\n' "$publisher_id" "$image_tag" + fi + return 0 + done <<<"$publisher_lines" + done return 1 } @@ -401,22 +435,41 @@ find_completed_alternate_publication() { } wait_for_pr_publisher() { - local source_run_id="$1" - local source_created_at="$2" - local alternate_sources="$3" + local source_state="$1" + local alternate_sources="$2" + local source_state_name source_run_id source_status source_conclusion source_state_event source_created_at local coverage_unavailable=false local publisher_start_epoch="${SECONDS}" local publisher_deadline=$((SECONDS + publisher_timeout_seconds)) + local -a direct_publisher_events=() + IFS=$'\t' read -r source_state_name source_run_id source_status source_conclusion _ source_state_event source_created_at <<<"$source_state" + if [[ "$source_state_name" != "found" || "$source_status" != "completed" || "$source_conclusion" != "success" ]]; then + printf 'Refusing publisher wait without the selected successful runtime source state.\n' >&2 + exit 1 + fi + if [[ "$source_state_event" == "pull_request" ]]; then + direct_publisher_events=(workflow_run) + else + direct_publisher_events=(workflow_run repository_dispatch) + fi while (( SECONDS < publisher_deadline )); do - local publisher_payload publisher_state event_payload publisher_event fetch_failed + local publisher_payload publisher_state event_payload publisher_event fetch_failed direct_success_unproven + local publisher_inventory_remaining publisher_payload="" fetch_failed=false + direct_success_unproven=false local poll_upper_bound poll_upper_bound="$(date -u +%Y-%m-%dT%H:%M:%SZ)" # Preserve complete discovery within the verified source creation window. - for publisher_event in workflow_run repository_dispatch; do + for publisher_event in "${direct_publisher_events[@]}"; do + publisher_inventory_remaining=$((publisher_deadline - SECONDS)) + if (( publisher_inventory_remaining <= 0 )); then + fetch_failed=true + break + fi if ! event_payload="$( - fetch_publisher_runs "${publisher_event}" "${source_created_at}" "${poll_upper_bound}" + fetch_publisher_runs "${publisher_event}" "${source_created_at}" "${poll_upper_bound}" \ + "${publisher_inventory_remaining}" )"; then fetch_failed=true break @@ -427,17 +480,20 @@ wait_for_pr_publisher() { publisher_payload="[${publisher_payload}]" publisher_state="" if [[ "${fetch_failed}" == "false" ]] && - publisher_state="$(read_publisher_state "${source_run_id}" <<<"${publisher_payload}")"; then + publisher_state="$(read_publisher_state "${source_run_id}" "${source_state_event}" <<<"${publisher_payload}")"; then IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then - printf 'Trusted PR image publisher %s succeeded for %s.\n' "${run_id}" "${image_tag}" - return 0 + if use_completed_duplicate_publication "$source_state" "$publisher_deadline" direct; then + return 0 + fi + direct_success_unproven=true fi fi local refreshed_source_payload refreshed_alternates - if refreshed_source_payload="$(fetch_workflow_runs \ + local source_refresh_remaining=$((publisher_deadline - SECONDS)) + if (( source_refresh_remaining > 0 )) && refreshed_source_payload="$(fetch_workflow_runs \ "repos/${GITHUB_REPOSITORY}/actions/workflows/runtime-images.yml/runs?per_page=100" \ - "refreshing alternate runtime-image sources while waiting for publication")"; then + "refreshing alternate runtime-image sources while waiting for publication" "$source_refresh_remaining")"; then if refreshed_alternates="$(read_run_state "${source_run_id}" alternates <<<"${refreshed_source_payload}")"; then if [[ "${refreshed_alternates}" == "missing" ]]; then alternate_sources="" @@ -461,6 +517,13 @@ wait_for_pr_publisher() { continue fi + if [[ "$direct_success_unproven" == "true" ]]; then + printf 'Trusted PR image publisher %s completed successfully, but its exact current-attempt fixed-tag publication proof is unavailable; retrying.\n' \ + "$run_id" >&2 + sleep "${sleep_seconds}" + continue + fi + if [[ "${state}" == "missing" ]]; then local elapsed_seconds=$((SECONDS - publisher_start_epoch)) if (( elapsed_seconds >= missing_workflow_timeout_seconds )); then @@ -509,7 +572,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_state}" if [[ "${state}" == "missing" ]]; then elapsed_seconds=$((SECONDS - start_epoch)) @@ -539,7 +602,7 @@ while (( SECONDS < deadline )); do if [[ "$SECONDS" -lt "$deadline" ]]; then older_states="$(read_run_state "$run_id" alternates <<<"${workflow_payload}")" || older_states="" fi - wait_for_pr_publisher "${run_id}" "${run_created_at}" "$older_states" + wait_for_pr_publisher "${run_state}" "$older_states" fi exit 0 fi diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 68dfe1ac3e..19e10cc62b 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -200,11 +200,21 @@ async function noWrites(config, reject = false) { + ': `' + conclusion + '`')); } } - const newModules = harness({jobs: [...clone(jobs), + const moduleJobs = [ row('Build and Test (recovery-controller-service / full)', 995), - row('Build and Test (common-redis-contracts / full)', 996)]}); + row('Build and Test (common-redis-contracts / full)', 996), + ]; + const newModules = harness({jobs: [...clone(jobs), ...moduleJobs]}); await newModules.run(); assert.match(newModules.calls.creates[0].body, /All validation checks passed/); + for (const failedModule of moduleJobs) { + const moduleFailure = harness({jobs: [...clone(jobs), ...moduleJobs.map(job => + job.id === failedModule.id ? {...job, conclusion: 'failure'} : job)]}); + await moduleFailure.run(); + assert.match(moduleFailure.calls.creates[0].body, /One or more validation checks failed/); + assert.match(moduleFailure.calls.creates[0].body, /Service build\/test matrix: `failure`/); + assert.doesNotMatch(moduleFailure.calls.creates[0].body, /All validation checks passed/); + } const metadataSplit = clone(jobs); for (const job of metadataSplit) { job.conclusion = 'skipped'; job.steps = []; } assert.equal((await noWrites({ jobs: metadataSplit })).comments.length, 0); diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 7ad7f995e8..596e5eb0b2 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6623,12 +6623,13 @@ case "$resource" in --arg head "${TEST_PR_HEAD_SHA:-cccccccccccccccccccccccccccccccccccccccc}" \ --arg repository "${TEST_PR_HEAD_REPOSITORY:-example/FireMUD}" \ --arg base_ref "${TEST_PR_BASE_REF:-develop}" \ + --arg base_sha "${TEST_PR_BASE_SHA:-dddddddddddddddddddddddddddddddddddddddd}" \ --arg merge "${TEST_PR_MERGE_SHA:-cccccccccccccccccccccccccccccccccccccccc}" \ --argjson mergeable "${TEST_PR_MERGEABLE:-true}" \ --argjson mergeable_state "$mergeable_state_json" \ --argjson labels "${TEST_PR_LABELS_JSON:-[]}" \ --argjson changed_files "$changed_file_count" \ - '{state:$state,changed_files:$changed_files,head:{sha:$head,repo:{full_name:$repository}},base:{ref:$base_ref,sha:"dddddddddddddddddddddddddddddddddddddddd",repo:{full_name:"example/FireMUD"}},merge_commit_sha:$merge,mergeable:$mergeable,mergeable_state:$mergeable_state,labels:$labels}' + '{state:$state,changed_files:$changed_files,head:{sha:$head,repo:{full_name:$repository}},base:{ref:$base_ref,sha:$base_sha,repo:{full_name:"example/FireMUD"}},merge_commit_sha:$merge,mergeable:$mergeable,mergeable_state:$mergeable_state,labels:$labels}' ;; repos/example/FireMUD/git/ref/heads/*) printf '%s' '{"ref":"refs/heads/develop","object":{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}' @@ -6852,12 +6853,14 @@ FAKE_FIXTURE_CERTIFICATE_MODE=standalone FAKE_FIXTURE_EXPOSURE_MODE=public \ # association; the sanitized artifact also records the different execution merge M. native_merge_sha=dddddddddddddddddddddddddddddddddddddddd native_source_run_json="$(jq -c '.pull_requests[0].base.sha = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"' <<<"$valid_workflow_run_json")" +TEST_PR_BASE_SHA="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" \ TEST_PR_MERGE_SHA="$native_merge_sha" \ FAKE_FIXTURE_METADATA_MERGE_SHA="$native_merge_sha" \ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$native_source_run_json" \ run_deploy_target_fixture native-distinct-merge 0 'action=deploy' grep -Fxq 'head_sha=cccccccccccccccccccccccccccccccccccccccc' "$TEMP_DIR/deploy-target-native-distinct-merge.output" grep -Fxq "merge_sha=$native_merge_sha" "$TEMP_DIR/deploy-target-native-distinct-merge.output" +TEST_PR_BASE_SHA="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" \ TEST_PR_MERGE_SHA="$native_merge_sha" \ FAKE_FIXTURE_METADATA_MERGE_SHA="$native_merge_sha" \ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$native_source_run_json" \ diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 2fe62be1c7..9fa238504b 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -114,15 +114,15 @@ for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{ raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") -def effective_group(group, action, base_ref, workflow_name="Required Gate"): +def effective_group(group, action, base_ref, workflow_name="Required Gate", *, push_branch=None): values = { "github.event.changes.base.ref": repr(base_ref), "github.event.pull_request.number": "42", "github.event.action": repr(action), - "github.event_name": "'pull_request'", + "github.event_name": repr("push" if push_branch else "pull_request"), "github.workflow": repr(workflow_name), "github.run_id": "123", - "github.ref": "'refs/pull/42/merge'", + "github.ref": repr(f"refs/heads/{push_branch}" if push_branch else "refs/pull/42/merge"), } def render(match): @@ -265,6 +265,8 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o f"{workflow_name} ${{{{ github.event_name == 'pull_request' && format('pr-{{0}} base-{{1}} head-{{2}}', " "github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }}" ) + if workflow in {"codeql.yml", "license-scan.yml"}: + expected_title += f"${{{{ {META} && ' mode-metadata' || '' }}}}" if data.get("run-name") != expected_title: raise SystemExit(f"{workflow} must publish its canonical pull-request run title") if data["jobs"]["changes"].get("name") != change_job: @@ -371,6 +373,17 @@ if collisions: f"required workflows {first[0]} and {second[0]} share a substantive concurrency group " f"for the same PR (case-insensitive): {first[2]!r} / {second[2]!r}" ) +for branch in ("main", "develop"): + push_groups = [] + for workflow in ("ci.yml", "security.yml"): + data = yaml.load((root / ".github/workflows" / workflow).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + push_groups.append(( + workflow, + "push", + effective_group(data["concurrency"]["group"], None, None, data["name"], push_branch=branch), + )) + if cross_workflow_group_collisions(push_groups): + raise SystemExit(f"Security and Validation share a push concurrency group on {branch}") assert cross_workflow_group_collisions([ ("validation.yml", "opened", "required-pr-42"), ("smoke.yml", "edited", "REQUIRED-PR-42"), diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 229475e90b..c51454e3d9 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1986,8 +1986,9 @@ 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) }}" +# shellcheck disable=SC2016 # This assertion intentionally matches the typed callback source ID binding. +require_contains "$pr_image_publisher_path" "run-name: Publish PR Runtime Images \${{ github.event.workflow_run.event == 'repository_dispatch' && format('{0} source-run-{1}'," +require_contains "$pr_image_publisher_path" "github.event.workflow_run.id) || github.event.workflow_run.display_title || format('source-run-{0}', github.event.client_payload.source_run_id) }}" 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' @@ -2063,11 +2064,12 @@ PY require_contains "$image_wait_path" 'publish-pr-runtime-images.yml/runs?event={event}&created={lower_text}..{upper_text}&per_page=100' require_contains "$image_wait_path" '"Publish", "PR", "Runtime", "Images", "Build", "Runtime", "Images"' -require_contains "$image_wait_path" 're.fullmatch(r"pr-[1-9][0-9]{0,50}", tokens[8])' +require_contains "$image_wait_path" 're.fullmatch(r"pr-[1-9][0-9]{0,50}", tokens[8] if len(tokens) > 8 else "")' require_contains "$image_wait_path" 'tokens[9] == f"base-{base_sha}"' require_contains "$image_wait_path" 'tokens[10] == f"head-{head_sha}"' require_contains "$image_wait_path" 'tokens[11] == f"merge-{merge_sha}"' require_contains "$image_wait_path" 'tokens[12] == "mode-required"' +require_contains "$image_wait_path" 'tokens[13] == f"source-run-{source_run_id}"' require_contains "$image_wait_path" 'wait_for_pr_publisher' # shellcheck disable=SC2016 # This assertion intentionally matches a literal shell default expression. require_contains "$image_wait_path" 'publisher_timeout_seconds="${HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS:-${timeout_seconds}}"' @@ -2198,6 +2200,7 @@ fi cat >"$contract_fixture_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail +fixture_dir="${PATH%%:*}" if [[ -n "${CONTRACT_GH_STATE_FILE:-}" ]]; then invocation=0 @@ -2212,13 +2215,21 @@ fi if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then case "$*" in *actions/runs/201/attempts/2/jobs?per_page=100) + if [[ "${CONTRACT_DUPLICATE_DIRECT_JOB:-success}" == "skipped" ]]; then + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-201-skipped.json" + else + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-201.json" + fi + exit 0 ;; + *actions/runs/202/attempts/2/jobs?per_page=100) + if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_LOG:-}" ]]; then + printf '%s\n' 202 >>"$CONTRACT_PUBLISHER_LOOKUP_LOG" + fi if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then : >"$CONTRACT_STALLED_LOOKUP_MARKER" - sleep 12 + command sleep 12 fi - cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-success.json"; exit 0 ;; - *actions/runs/201) - cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201.json"; exit 0 ;; + cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-${CONTRACT_DUPLICATE_JOB:-success}.json"; exit 0 ;; *actions/runs/203/attempts/3/jobs?per_page=100) if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_LOG:-}" ]]; then printf '%s\n' 203 >>"$CONTRACT_PUBLISHER_LOOKUP_LOG" @@ -2226,28 +2237,106 @@ if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-203.json"; exit 0 ;; *actions/runs/203) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-203.json"; exit 0 ;; - *actions/runs/101) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source-${CONTRACT_DUPLICATE_EVENT:-typed}.json"; exit 0 ;; + *actions/runs/104) cat "$CONTRACT_DUPLICATE_DIR/duplicate-source-104-${CONTRACT_DUPLICATE_DIRECT_EVENT:-native}.json"; exit 0 ;; + *actions/runs/101) + if [[ -n "${CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK:-}" ]]; then + invocation=0 + [[ ! -f "$CONTRACT_SOURCE_READ_STATE" ]] || invocation="$(cat "$CONTRACT_SOURCE_READ_STATE")" + printf '%s\n' "$((invocation + 1))" >"$CONTRACT_SOURCE_READ_STATE" + if (( invocation >= 1 )); then + : >"$CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK" + fi + fi + cat "$CONTRACT_DUPLICATE_DIR/duplicate-source-${CONTRACT_DUPLICATE_EVENT:-typed}.json" + exit 0 ;; "api repos/example/FireMUD") printf '%s\n' '{"full_name":"example/FireMUD","default_branch":"develop"}'; exit 0 ;; *actions/runs/202) if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_MARKER:-}" ]]; then : >"$CONTRACT_PUBLISHER_LOOKUP_MARKER" fi + if [[ -n "${CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK:-}" && -f "$CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK" ]]; then + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-rerun.json" + exit 0 + fi if [[ "${CONTRACT_DUPLICATE_EVENT:-typed}" == "native" ]]; then cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-native.json" + elif [[ "${CONTRACT_DUPLICATE_TYPED_NATIVE:-false}" == "true" ]]; then + cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-typed-native.json" else cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-${CONTRACT_DUPLICATE_PATH:-bare}.json" fi exit 0 ;; + *actions/runs/201) + case "${CONTRACT_DUPLICATE_DIRECT_PUBLISHER:-native}" in + typed) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201-typed.json" ;; + typed-native) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201-typed-native.json" ;; + typed-native-old) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201-typed-native-old.json" ;; + *) cat "$CONTRACT_DUPLICATE_DIR/duplicate-publisher-201.json" ;; + esac + exit 0 ;; + esac +fi + +if [[ -z "${CONTRACT_DUPLICATE_DIR:-}" ]]; then + case "$*" in *actions/runs/202/attempts/2/jobs?per_page=100) - if [[ -n "${CONTRACT_PUBLISHER_LOOKUP_LOG:-}" ]]; then - printf '%s\n' 202 >>"$CONTRACT_PUBLISHER_LOOKUP_LOG" + cat <<'JSON' +{"total_count":1,"jobs":[{"name":"Publish Fixed PR Merge Image Tags","run_id":202,"run_attempt":2,"status":"completed","conclusion":"success","steps":[{"name":"Publish fixed PR image tags","status":"completed","conclusion":"success"}]}]} +JSON + exit 0 ;; + *actions/runs/202) + if [[ -n "${CONTRACT_PUBLISHER_PAYLOAD:-}" ]]; then + python3 - "$CONTRACT_PUBLISHER_PAYLOAD" <<'PY_PUBLISHER_DETAIL' +import json +import sys +payload = json.load(open(sys.argv[1])) +pages = payload if isinstance(payload, list) else [payload] +runs = [run for page in pages for run in page.get("workflow_runs", [])] +run = next((run for run in runs if run.get("id") == 202), None) +if run is None: + raise SystemExit(1) +run.update({"run_attempt": 2, "path": ".github/workflows/publish-pr-runtime-images.yml", + "head_branch": "develop", "repository": {"full_name": "example/FireMUD"}, + "head_repository": {"full_name": "example/FireMUD"}}) +print(json.dumps(run)) +PY_PUBLISHER_DETAIL + else + exit 1 fi - if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then - : >"$CONTRACT_STALLED_LOOKUP_MARKER" - sleep 12 + exit 0 ;; + *actions/runs/201/attempts/2/jobs?per_page=100) + cat <<'JSON' +{"total_count":1,"jobs":[{"name":"Publish Fixed PR Merge Image Tags","run_id":201,"run_attempt":2,"status":"completed","conclusion":"success","steps":[{"name":"Publish fixed PR image tags","status":"completed","conclusion":"success"}]}]} +JSON + exit 0 ;; + *actions/runs/101) + if [[ -n "${CONTRACT_SOURCE_PAYLOAD:-}" ]]; then + python3 - "$CONTRACT_SOURCE_PAYLOAD" <<'PY_SOURCE_DETAIL' +import json +import sys +payload = json.load(open(sys.argv[1])) +pages = payload if isinstance(payload, list) else [payload] +runs = [run for page in pages for run in page.get("workflow_runs", [])] +run = next((run for run in runs if run.get("id") == 101), None) +if run is None: + raise SystemExit(1) +run.update({"run_attempt": 1, "repository": {"full_name": "example/FireMUD"}, + "head_repository": {"full_name": "example/FireMUD"}}) +print(json.dumps(run)) +PY_SOURCE_DETAIL + else + cat <<'JSON' +{"id":101,"event":"pull_request","status":"completed","conclusion":"success","head_sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","html_url":"https://example.test/runtime/101","display_title":"Build Runtime Images secure-pr-artifact pr-1 base-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb head-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa merge-cccccccccccccccccccccccccccccccccccccccc mode-required","created_at":"2026-07-24T00:01:00Z","run_attempt":1,"repository":{"full_name":"example/FireMUD"},"head_repository":{"full_name":"example/FireMUD"}} +JSON fi - cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-$CONTRACT_DUPLICATE_JOB.json"; exit 0 ;; + exit 0 ;; + *actions/runs/201) + cat <<'JSON' +{"id":201,"run_attempt":2,"event":"workflow_run","status":"completed","conclusion":"success","display_title":"Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-1 base-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb head-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa merge-cccccccccccccccccccccccccccccccccccccccc mode-required","path":".github/workflows/publish-pr-runtime-images.yml","head_branch":"develop","repository":{"full_name":"example/FireMUD"},"head_repository":{"full_name":"example/FireMUD"}} +JSON + exit 0 ;; + "api repos/example/FireMUD") printf '%s\n' '{"full_name":"example/FireMUD","default_branch":"develop"}'; exit 0 ;; esac fi @@ -2255,6 +2344,11 @@ if [[ -n "${CONTRACT_REFRESH_SOURCE_PAYLOAD:-}" && "$*" == *"actions/workflows/r invocation=0 [[ ! -f "$CONTRACT_REFRESH_SOURCE_STATE" ]] || invocation="$(cat "$CONTRACT_REFRESH_SOURCE_STATE")" printf '%s\n' "$((invocation + 1))" >"$CONTRACT_REFRESH_SOURCE_STATE" + if (( invocation > 0 )) && [[ -n "${CONTRACT_REFRESH_SOURCE_STALL_SECONDS:-}" ]]; then + python3 -c 'import sys, time; time.sleep(float(sys.argv[1]))' "$CONTRACT_REFRESH_SOURCE_STALL_SECONDS" + echo 'controlled runtime-image source refresh outage' >&2 + exit 1 + fi if (( invocation == 0 )); then cat "$CONTRACT_SOURCE_PAYLOAD" else @@ -2428,10 +2522,61 @@ alternate_publisher = {**native_publisher, "id": 202, "run_attempt": 2, "created_at": "2026-07-24T00:06:00Z"} (root / "direct-success-sources.json").write_text(json.dumps({"workflow_runs": [direct_source, source]})) (root / "duplicate-publisher-201.json").write_text(json.dumps(direct_publisher)) +for event, source_run in { + "native": {**direct_source, "run_attempt": 1}, + "typed": {**typed_source, "id": 104, "status": "completed", "conclusion": "success", + "created_at": "2026-07-24T00:05:00Z", "run_attempt": 1}, +}.items(): + (root / f"duplicate-source-104-{event}.json").write_text(json.dumps({ + **source_run, "repository": repository, "head_repository": repository, + })) +direct_typed_source = {**typed_source, "id": 104, "status": "completed", "conclusion": "success", + "created_at": "2026-07-24T00:05:00Z"} +(root / "direct-typed-success-sources.json").write_text(json.dumps({ + "workflow_runs": [direct_typed_source, typed_source], +})) +direct_typed_publisher = {**alternate_publisher, "event": "repository_dispatch", + "display_title": "Publish PR Runtime Images source-run-104"} +(root / "duplicate-publisher-201-typed.json").write_text(json.dumps(direct_typed_publisher)) +native_typed_direct_publisher = {**direct_publisher, "event": "workflow_run", + "display_title": "Publish PR Runtime Images " + typed_source["display_title"] + " source-run-104"} +native_typed_alternate_publisher = {**alternate_publisher, "event": "workflow_run", + "display_title": "Publish PR Runtime Images " + typed_source["display_title"] + " source-run-101"} +old_native_typed_publisher = {**native_typed_direct_publisher, + "display_title": "Publish PR Runtime Images " + typed_source["display_title"]} +(root / "duplicate-publisher-201-typed-native.json").write_text(json.dumps(native_typed_direct_publisher)) +(root / "duplicate-publisher-201-typed-native-old.json").write_text(json.dumps(old_native_typed_publisher)) +(root / "duplicate-publisher-typed-native.json").write_text(json.dumps(native_typed_alternate_publisher)) +for event, publisher_run, fixture_event in [ + ("native", direct_publisher, "workflow_run"), + ("typed", direct_typed_publisher, "repository_dispatch"), + ("typed-native", native_typed_direct_publisher, "workflow_run"), + ("typed-native-old", old_native_typed_publisher, "workflow_run"), +]: + (root / f"direct-publisher-only-{event}.json").write_text(json.dumps({ + "total_count": 1, "fixture_event": fixture_event, "workflow_runs": [publisher_run], + })) +for conclusion in ["success", "skipped"]: + (root / f"duplicate-jobs-201{'-skipped' if conclusion == 'skipped' else ''}.json").write_text(json.dumps({ + "total_count": 1, "jobs": [{ + "name": "Publish Fixed PR Merge Image Tags", "run_id": 201, "run_attempt": 2, + "status": "completed", "conclusion": "success", "steps": [{ + "name": "Publish fixed PR image tags", "status": "completed", "conclusion": conclusion, + }], + }], + })) +direct_only_native = {**direct_source, "created_at": "2026-07-24T00:05:00Z"} +cached_typed_alternate = {**typed_source, "status": "completed", "conclusion": "success"} +(root / "cached-alternate-sources.json").write_text(json.dumps({ + "workflow_runs": [direct_only_native, cached_typed_alternate], +})) +(root / "duplicate-publisher-rerun.json").write_text(json.dumps({ + **alternate_publisher, "run_attempt": 3, "status": "in_progress", "conclusion": None, +})) for variant, change in { "bare": {}, "qualified": {"path": publisher_path + "@develop"}, - "wrong-ref": {"path": publisher_path + "@other", "head_branch": "other"}, + "wrong-ref": {"path": publisher_path + "@other", "head_branch": "develop"}, "wrong-head": {"path": publisher_path + "@develop", "head_branch": "other"}, "full-ref": {"path": publisher_path + "@refs/heads/develop"}, "wrong-workflow": {"path": ".github/workflows/other.yml@develop"}, @@ -2503,6 +2648,20 @@ if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then sleep() { SECONDS=$((SECONDS + 1)) } + if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then + timeout() { + local timeout_budget="${2:-0}" timeout_status + if command timeout "$@"; then + timeout_status=0 + else + timeout_status=$? + fi + if [[ -f "$CONTRACT_STALLED_LOOKUP_MARKER" && "$timeout_status" -ne 0 ]]; then + SECONDS=$((SECONDS + timeout_budget)) + fi + return "$timeout_status" + } + fi fi EOF for event in typed native; do @@ -2615,6 +2774,118 @@ require_contains "$contract_fixture_dir/direct-before-alternate.output" 'Trusted exit 1 } +for direct_variant in native typed typed-native; do + direct_event="$direct_variant" + source_inventory="direct-success-sources" + direct_publisher_variant="$direct_variant" + if [[ "$direct_variant" != "native" ]]; then + direct_event=typed + source_inventory="direct-typed-success-sources" + fi + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT="$direct_event" \ + CONTRACT_DUPLICATE_DIRECT_EVENT="$direct_event" CONTRACT_DUPLICATE_DIRECT_JOB=skipped \ + CONTRACT_DUPLICATE_DIRECT_PUBLISHER="$direct_publisher_variant" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$source_inventory.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-publisher-only-$direct_variant.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/direct-skipped-$direct_variant.output" \ + 2>"$contract_fixture_dir/direct-skipped-$direct_variant.error"; then + echo "A successful direct $direct_variant publisher workflow with a skipped image step must not be accepted" >&2 + exit 1 + fi + if ! grep -Fq 'Timed out waiting for trusted PR image publisher' \ + "$contract_fixture_dir/direct-skipped-$direct_variant.error"; then + cat "$contract_fixture_dir/direct-skipped-$direct_variant.output" \ + "$contract_fixture_dir/direct-skipped-$direct_variant.error" >&2 + exit 1 + fi + if rg -q 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/direct-skipped-$direct_variant.output"; then + echo "A direct publisher with a skipped image step was accepted for $direct_variant" >&2 + exit 1 + fi +done + +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_DIRECT_JOB=success \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-publisher-only-typed-native.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/typed-native-direct.output" 2>"$contract_fixture_dir/typed-native-direct.error" || { + cat "$contract_fixture_dir/typed-native-direct.output" "$contract_fixture_dir/typed-native-direct.error" >&2 + exit 1 + } +require_contains "$contract_fixture_dir/typed-native-direct.output" \ + 'Trusted PR image publisher 201 succeeded for pr-merge-' +require_contains "$contract_fixture_dir/typed-native-direct.output" 'as the direct source' + +if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native-old \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-publisher-only-typed-native-old.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/typed-native-old.output" 2>"$contract_fixture_dir/typed-native-old.error"; then + echo "A typed native publisher title without its source run ID must not be accepted" >&2 + exit 1 +fi +require_contains "$contract_fixture_dir/typed-native-old.error" \ + 'Timed out waiting for trusted PR image publisher' + +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ + CONTRACT_REFRESH_SOURCE_STATE="$contract_fixture_dir/cached-refresh-state" \ + CONTRACT_REFRESH_SOURCE_PAYLOAD="$contract_fixture_dir/refresh-alternates-completed.json" \ + CONTRACT_REFRESH_SOURCE_STALL_SECONDS=1 \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/cached-alternate-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=5 HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS=5 \ + HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 10s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/cached-refresh.output" 2>"$contract_fixture_dir/cached-refresh.error" || { + cat "$contract_fixture_dir/cached-refresh.output" "$contract_fixture_dir/cached-refresh.error" >&2 + exit 1 + } +require_contains "$contract_fixture_dir/cached-refresh.error" \ + 'GitHub API poll failed while refreshing alternate runtime-image sources' +require_contains "$contract_fixture_dir/cached-refresh.output" \ + 'Trusted PR image publisher 202 succeeded for pr-merge-' +require_contains "$contract_fixture_dir/cached-refresh.output" 'via an alternate producer' + +CONTRACT_DUPLICATE_EVENT=typed CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ + CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK="$contract_fixture_dir/publisher-rerun-marker" \ + CONTRACT_SOURCE_READ_STATE="$contract_fixture_dir/source-read-state" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/cached-alternate-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/publisher-rerun.output" 2>"$contract_fixture_dir/publisher-rerun.error" || : +[[ -f "$contract_fixture_dir/publisher-rerun-marker" ]] || { + echo "The fixture did not rerun the publisher during source revalidation" >&2 + exit 1 +} +if rg -q 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/publisher-rerun.output"; then + echo "A rerun publisher attempt was accepted using the predecessor attempt's job proof" >&2 + exit 1 +fi +require_contains "$contract_fixture_dir/publisher-rerun.error" \ + 'Timed out waiting for trusted PR image publisher' + BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ CONTRACT_REFRESH_SOURCE_STATE="$contract_fixture_dir/refresh-source-state" \ @@ -2633,7 +2904,8 @@ require_contains "$contract_fixture_dir/refreshed-alternate.output" 'Matching ru require_contains "$contract_fixture_dir/refreshed-alternate.output" 'Trusted PR image publisher 202 succeeded' stalled_status=0 -CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_JOB=success \ CONTRACT_STALLED_LOOKUP_MARKER="$contract_fixture_dir/stalled-publisher.lookup" \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/duplicate-inventory.json" \ CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/dispatch-success.json" \ diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 5ff5bc80dd..1202ef6402 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -13,8 +13,11 @@ python3 -c 'import sys; sys.exit(0 if __debug__ else "Runtime image publication # This bounded expression uses only property reads, equality, boolean operators and format. python3 - "$RUNTIME_WORKFLOW" <<'PY_CONCURRENCY' import copy +import os import re +import subprocess import sys +import tempfile from pathlib import Path source = Path(sys.argv[1]).read_text() @@ -29,6 +32,43 @@ assert re.search( ) assert re.search(r'assert_current_branch_head\n\s+promote_alias "\$candidate" "\$branch_tag"', promotion) +# Run the actual branch metadata step with current, obsolete and unverifiable branch heads. +meta = re.search(r"^ - name: Derive image tags\n.*?^ run: \|\n((?:^ [^\n]*\n|^\n)+)", + source, re.MULTILINE | re.DOTALL).group(1) +meta = re.sub(r"(?m)^ ", "", meta) +branch_head = "a" * 40 +with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "output" + stub = Path(temporary) / "gh" + stub.write_text('#!/usr/bin/env bash\n' + '[[ "$*" == "api repos/owner/repo/git/ref/heads/develop --jq .object.sha" ]] || exit 2\n' + 'printf "%s\\n" "$FIXTURE_LIVE_HEAD"\n') + stub.chmod(0o755) + for event in ("workflow_run", "workflow_dispatch"): + script = meta + for expression, value in { + "github.event_name": event, "github.event.workflow_run.event": "push", + "github.event.workflow_run.conclusion": "success", "github.event.workflow_run.head_sha": branch_head, + }.items(): + script = script.replace("${{ " + expression + " }}", value) + for live_head, admitted, status in [(branch_head, True, 0), ("b" * 40, False, 0), ("unknown", False, 1)]: + output.write_text("") + environment = { + **os.environ, "PATH": temporary + ":" + os.environ["PATH"], + "GITHUB_REPOSITORY": "owner/repo", "GITHUB_SHA": branch_head, + "GITHUB_REF_NAME": "develop", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_OUTPUT": str(output), "FIXTURE_LIVE_HEAD": live_head, + "EVENT_HEAD_BRANCH": "develop", "EVENT_HEAD_SHA": "", + } + result = subprocess.run(["bash", "-c", script], env=environment, capture_output=True, text=True) + assert result.returncode == status, result.stderr + if admitted: + assert f"head_sha={branch_head}\n" in output.read_text() + assert "head_branch=develop\n" in output.read_text() + else: + assert not output.read_text(), output.read_text() +assert "github.event_name == 'workflow_dispatch' && steps.meta.outputs.head_sha != ''" in source + class Context: def __init__(self, value=None): self.value = value @@ -158,7 +198,9 @@ require_contains() { } } -require_contains 'run-name: Publish PR Runtime Images ${{ github.event.workflow_run.display_title ||' +require_contains "run-name: Publish PR Runtime Images \${{ github.event.workflow_run.event == 'repository_dispatch' && format('{0} source-run-{1}'," +require_contains 'github.event.workflow_run.display_title || format' +require_contains 'github.event.client_payload.source_run_id' require_contains 'pr-merge-' require_contains 'pr-runtime-provenance.json' require_contains 'source run title does not contain exact PR/base/head/merge/mode metadata' diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 6302737c2b..fbe2a43245 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -104,6 +104,23 @@ if [[ "$*" == *"get namespaces"* ]]; then if [[ "${FAKE_NAMESPACE_LIST_ERROR:-false}" == true ]]; then exit 1 fi + if [[ "$*" == *"-o name"* && -n "${FAKE_NAMESPACE_COUNT_SEQUENCE:-}" ]]; then + call_count=0 + if [[ -f "$FAKE_NAMESPACE_LIST_CALLS" ]]; then + call_count="$(<"$FAKE_NAMESPACE_LIST_CALLS")" + fi + call_count=$((call_count + 1)) + printf '%s' "$call_count" > "$FAKE_NAMESPACE_LIST_CALLS" + IFS=',' read -r -a namespace_counts <<<"$FAKE_NAMESPACE_COUNT_SEQUENCE" + sequence_index=$((call_count - 1)) + if (( sequence_index >= ${#namespace_counts[@]} )); then + sequence_index=$((${#namespace_counts[@]} - 1)) + fi + for ((namespace_index = 1; namespace_index <= namespace_counts[sequence_index]; namespace_index++)); do + printf 'namespace/fake-%s\n' "$namespace_index" + done + exit 0 + fi printf '%b' "${FAKE_NAMESPACE_ROWS:-}" exit 0 fi @@ -174,15 +191,20 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_retry_merge="${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" snapshot_retry_image="${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" snapshot_resource_version=rv-901 - if [[ -f "${FAKE_PROOF_RETRY_RESERVATION_MARKER:-}" && - ! -f "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:-}" ]]; then - snapshot_retry_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" - snapshot_retry_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" - snapshot_retry_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" - snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" - snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" - snapshot_resource_version=rv-902 + if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then + jq -cn \ + --arg count "$snapshot_retry_count" --arg base "$snapshot_retry_base" \ + --arg head "$snapshot_retry_head" --arg merge "$snapshot_retry_merge" \ + --arg image "$snapshot_retry_image" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"}' \ + > "$FAKE_PROOF_RETRY_STATE_MARKER" fi + snapshot_retry_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_retry_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_retry_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_resource_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" proof_complete="${FAKE_PR_901_PROOF_COMPLETE:-true}" if [[ "${FAKE_PR_901_PROOF_COMPLETE_AFTER_CONSUMER_COMPLETION:-false}" == true && -f "${FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER:-}" ]]; then @@ -328,24 +350,58 @@ if [[ "$1" == wait && "$2" == --for=delete ]]; then fi if [[ "$1" == annotate && "$2" == namespace ]]; then printf '%s\n' "$*" >> "$FAKE_ANNOTATE_LOG" - if [[ "${3:-}" == pr-901 && -n "${FAKE_DISPATCH_HTTP_STATUS:-}" ]]; then + if [[ "${FAKE_ANNOTATE_ERROR:-false}" == true ]]; then + : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" + exit 1 + fi + if [[ "${3:-}" == pr-901 && ( "$*" == *"firemud.dev/proof-retry-count="* || "$*" == *"--resource-version rv-902"* ) ]]; then + if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then + jq -cn \ + --arg count "${FAKE_PR_901_PROOF_RETRY_COUNT:-}" \ + --arg base "${FAKE_PR_901_PROOF_RETRY_BASE_SHA:-}" \ + --arg head "${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" \ + --arg merge "${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" \ + --arg image "${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"}' \ + > "$FAKE_PROOF_RETRY_STATE_MARKER" + fi + state_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" + expected_version=rv-901 if [[ "$*" == *"--resource-version rv-902"* ]]; then + expected_version=rv-902 + fi + if [[ "$state_version" != "$expected_version" ]]; then + exit 1 + fi + local_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" + local_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_STATE_MARKER")" + local_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" + local_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" + local_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" + for annotation in "$@"; do + case "$annotation" in + firemud.dev/proof-retry-count=*) local_count="${annotation#*=}" ;; + firemud.dev/proof-retry-count-) local_count="" ;; + firemud.dev/proof-retry-base-sha=*) local_base="${annotation#*=}" ;; + firemud.dev/proof-retry-base-sha-) local_base="" ;; + firemud.dev/proof-retry-head-sha=*) local_head="${annotation#*=}" ;; + firemud.dev/proof-retry-head-sha-) local_head="" ;; + firemud.dev/proof-retry-merge-sha=*) local_merge="${annotation#*=}" ;; + firemud.dev/proof-retry-merge-sha-) local_merge="" ;; + firemud.dev/proof-retry-image-tag=*) local_image="${annotation#*=}" ;; + firemud.dev/proof-retry-image-tag-) local_image="" ;; + esac + done + state_resource_version=rv-902 + if [[ "$expected_version" == rv-902 ]]; then + state_resource_version=rv-903 : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" - elif [[ "$*" == *"firemud.dev/proof-retry-count="* ]]; then - local_count="" - local_base="" - local_head="" - local_merge="" - local_image="" - for annotation in "$@"; do - case "$annotation" in - firemud.dev/proof-retry-count=*) local_count="${annotation#*=}" ;; - firemud.dev/proof-retry-base-sha=*) local_base="${annotation#*=}" ;; - firemud.dev/proof-retry-head-sha=*) local_head="${annotation#*=}" ;; - firemud.dev/proof-retry-merge-sha=*) local_merge="${annotation#*=}" ;; - firemud.dev/proof-retry-image-tag=*) local_image="${annotation#*=}" ;; - esac - done + fi + jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ + --arg merge "$local_merge" --arg image "$local_image" --arg rv "$state_resource_version" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:$rv}' \ + > "$FAKE_PROOF_RETRY_STATE_MARKER" + if [[ "$expected_version" == rv-901 ]]; then jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ --arg merge "$local_merge" --arg image "$local_image" \ '{count:$count,base:$base,head:$head,merge:$merge,image:$image}' \ @@ -355,10 +411,6 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then fi fi fi - if [[ "${FAKE_ANNOTATE_ERROR:-false}" == true ]]; then - : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" - exit 1 - fi exit 0 fi if [[ "$*" == "-n firemud-system get hostedenvironmentidentities.platform.firemud.dev -o json" ]]; then @@ -460,6 +512,12 @@ set -euo pipefail printf '%s\n' "$*" >> "$FAKE_HELM_LOG" EOF +cat > "$TEMP_DIR/bin/sleep" <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >> "$FAKE_SLEEP_LOG" +EOF + cat > "$TEMP_DIR/bin/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail @@ -472,6 +530,7 @@ for arg in "$@"; do has_jq=true fi done + fake_labels_json() { local priority="$1" local labels_valid="$2" @@ -491,6 +550,42 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/hos printf '%s\n' '{"id":357129350,"name":"Trusted Hosted Identity Request","path":".github/workflows/hosted-identity-request.yml"}' exit 0 fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/173511323/runs' ]]; then + if [[ "$*" != *"--method GET"* || "$*" != *"event=pull_request"* || + "$*" != *"status=completed"* || "$*" != *"head_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* || + "$*" == *"head="* ]]; then + echo "recent source inventory did not use bounded GET/head_sha query parameters: $*" >&2 + exit 1 + fi + if [[ "$*" == *"event=pull_request"* ]]; then + if [[ -v FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON ]]; then + printf '%s' "$FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON" + else + printf '%s' '{"total_count":0,"workflow_runs":[]}' + fi + else + if [[ -v FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON ]]; then + printf '%s' "$FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON" + else + printf '%s' '{"total_count":0,"workflow_runs":[]}' + fi + fi + exit 0 +fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/357129350/runs' ]]; then + if [[ "$*" != *"--method GET"* || "$*" != *"event=workflow_run"* || + "$*" != *"branch=develop"* || "$*" == *"head="* ]]; then + echo "fresh consumer inventory did not use bounded GET/branch query parameters: $*" >&2 + exit 1 + fi + printf '%s\n' "$*" >> "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" + if [[ -v FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON ]]; then + printf '%s' "$FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON" + else + printf '%s' '{"total_count":0,"workflow_runs":[]}' + fi + exit 0 +fi if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request\&status=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then active_query_status="${resource##*&status=}" active_query_status="${active_query_status%%&*}" @@ -569,10 +664,24 @@ if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then 422) dispatch_reason='Unprocessable Content' ;; 500) dispatch_reason='Internal Server Error' ;; 403) dispatch_reason='Forbidden' ;; + 429) dispatch_reason='Too Many Requests' ;; 404) dispatch_reason='Not Found' ;; *) dispatch_reason='Test Status' ;; esac printf 'HTTP/2.0 %s %s\n' "$dispatch_status" "$dispatch_reason" + if [[ -n "${FAKE_DISPATCH_RETRY_AFTER:-}" ]]; then + printf 'Retry-After: %s\n' "$FAKE_DISPATCH_RETRY_AFTER" + fi + if [[ -n "${FAKE_DISPATCH_RATE_REMAINING:-}" ]]; then + printf 'X-RateLimit-Remaining: %s\n' "$FAKE_DISPATCH_RATE_REMAINING" + fi + if [[ -n "${FAKE_DISPATCH_RATE_RESET:-}" ]]; then + printf 'X-RateLimit-Reset: %s\n' "$FAKE_DISPATCH_RATE_RESET" + fi + printf '\n' + if [[ "$dispatch_status" != 204 ]]; then + jq -cn --arg message "${FAKE_DISPATCH_ERROR_MESSAGE:-Forbidden}" '{message:$message}' + fi if [[ "$dispatch_status" == 204 ]]; then exit 0 fi @@ -604,6 +713,9 @@ case "$resource" in fi printf '%s' '[[{"filename":"README.md"}]]' ;; + */pulls/902/files\?per_page=100) + printf '%s' '[[{"filename":"README.md"}]]' + ;; */pulls/101/files\?per_page=100|*/pulls/102/files\?per_page=100) printf '%s' '[[{"filename":"README.md"}]]' ;; @@ -730,11 +842,23 @@ case "$resource" in --arg head "$live_head" \ --arg base_ref "${FAKE_PR_901_BASE_REF:-develop}" \ --arg head_repository "${FAKE_PR_901_HEAD_REPOSITORY:-example/FireMUD}" \ + --arg head_ref "${FAKE_PR_901_HEAD_REF:-feature-preview}" \ --arg base_repository "${FAKE_PR_901_BASE_REPOSITORY:-example/FireMUD}" \ --arg mergeable "${FAKE_PR_901_MERGEABLE:-true}" \ --argjson mergeable_state "$mergeable_state_json" \ --arg priority "${FAKE_PR_901_PRIORITY:-true}" \ - '{state:$state,head:{sha:$head,repo:{full_name:$head_repository}},base:{ref:$base_ref,repo:{full_name:$base_repository}},merge_commit_sha:"cccccccccccccccccccccccccccccccccccccccc",changed_files:1,mergeable:($mergeable == "true"),mergeable_state:$mergeable_state,user:{login:"human"},labels:(if $priority == "true" then [{name:"preview:priority"}] else [] end)}' + '{state:$state,head:{sha:$head,ref:$head_ref,repo:{full_name:$head_repository}},base:{ref:$base_ref,repo:{full_name:$base_repository}},merge_commit_sha:"cccccccccccccccccccccccccccccccccccccccc",changed_files:1,mergeable:($mergeable == "true"),mergeable_state:$mergeable_state,user:{login:"human"},labels:(if $priority == "true" then [{name:"preview:priority"}] else [] end)}' + ;; + */pulls/902) + if [[ "$has_jq" == true ]]; then + printf 'open\t%s\t%s\n' "${FAKE_PR_902_HEAD:-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}" \ + "$(fake_labels_json false valid | base64 | tr -d '\n')" + exit 0 + fi + jq -cn \ + --arg head "${FAKE_PR_902_HEAD:-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}" \ + --arg head_ref "${FAKE_PR_902_HEAD_REF:-feature-preview}" \ + '{state:"open",head:{sha:$head,ref:$head_ref,repo:{full_name:"example/FireMUD"}},base:{ref:"develop",repo:{full_name:"example/FireMUD"}},merge_commit_sha:"cccccccccccccccccccccccccccccccccccccccc",changed_files:1,mergeable:true,mergeable_state:"clean",user:{login:"human"},labels:[]}' ;; */pulls/101) if [[ -n "${FAKE_PRUNE_QUERY_LOG:-}" ]]; then @@ -998,6 +1122,7 @@ chmod +x \ "$TEMP_DIR/bin/kubectl" \ "$TEMP_DIR/bin/gh" \ "$TEMP_DIR/bin/helm" \ + "$TEMP_DIR/bin/sleep" \ "$TEMP_DIR/delete" \ "$TEMP_DIR/identity-request" \ "$TEMP_DIR/identity-wait" \ @@ -1022,6 +1147,10 @@ export FAKE_ANNOTATE_FAILURE_MARKER="$TEMP_DIR/annotate-failure.marker" export FAKE_DISPATCH_LOG="$TEMP_DIR/dispatch.log" export FAKE_PROOF_RETRY_RESERVATION_MARKER="$TEMP_DIR/proof-retry-reservation.json" export FAKE_PROOF_RETRY_COMPENSATED_MARKER="$TEMP_DIR/proof-retry-compensated.marker" +export FAKE_PROOF_RETRY_STATE_MARKER="$TEMP_DIR/proof-retry-state.json" +export FAKE_SLEEP_LOG="$TEMP_DIR/sleep.log" +export FAKE_NAMESPACE_LIST_CALLS="$TEMP_DIR/namespace-list-calls" +export FAKE_RECENT_HANDOFF_LOOKUP_LOG="$TEMP_DIR/recent-handoff-lookup.log" export FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER="$TEMP_DIR/trusted-consumer-completed.marker" export FAKE_COMMENT_TARGET_LOG="$TEMP_DIR/comment-target.log" export FAKE_PREVIOUS_COMMENT_ID_LOG="$TEMP_DIR/previous-comment-id.log" @@ -1054,12 +1183,13 @@ export FAKE_TARGET_MERGE_SHA="cccccccccccccccccccccccccccccccccccccccc" priority_candidate_head="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" export FAKE_NAMESPACE_ROWS='2026-01-01T00:00:00Z|pr-101|101|2026-01-02T00:00:00Z|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb|head-101|cccccccccccccccccccccccccccccccccccccccc|image-101\n2026-01-03T00:00:00Z|pr-102|102|2026-01-04T00:00:00Z|base-102|head-102|merge-102|image-102\n' priority_labels_base64="$(printf '%s' '[{"name":"preview:priority"}]' | base64 | tr -d '\n')" +ordinary_labels_base64="$(printf '%s' '[]' | base64 | tr -d '\n')" adversarial_priority_labels_base64="$(printf '%s' '[{"name":"preview:priority"},{"name":"quote\"slash\\label"}]' | base64 | tr -d '\n')" adversarial_labels_base64="$(printf '%s' '[{"name":"custom:label"},{"name":"quote\"slash\\label"}]' | base64 | tr -d '\n')" invalid_json_labels_base64="$(printf '%s' '{invalid-json' | base64 | tr -d '\n')" reset_case() { - rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" + rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" "$FAKE_PROOF_RETRY_STATE_MARKER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_SLEEP_LOG" "$FAKE_NAMESPACE_LIST_CALLS" "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" export GITHUB_OUTPUT="$TEMP_DIR/output" export FAKE_TARGET_PRIORITY=true export FAKE_TARGET_LABELS_VALID=valid @@ -1088,6 +1218,8 @@ reset_case() { export FAKE_PRIORITY_CANDIDATE_NAMESPACE_LOOKUP_ERROR=false export FAKE_PRIORITY_CANDIDATE_NAMESPACE_ABSENT=false export FAKE_ACTIVE_PREVIEW_RUNS_JSON='[]' + export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON='{"total_count":0,"workflow_runs":[]}' + export FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON='{"total_count":0,"workflow_runs":[]}' export FAKE_PR_901_OWNER='' export FAKE_PR_901_HEAD="$priority_candidate_head" export FAKE_PR_901_BASE_REF=develop @@ -1135,6 +1267,7 @@ reset_case() { export FAKE_IDENTITY_LIST_FAIL=false export FAKE_IDENTITY_LIST_JSON='{"apiVersion":"platform.firemud.dev/v1alpha1","kind":"HostedEnvironmentIdentityList","items":[]}' export FAKE_NAMESPACE_LIST_ERROR=false + export FAKE_NAMESPACE_COUNT_SEQUENCE='' export FAKE_RUNTIME_LOOKUP_ERROR=false export FAKE_RUNTIME_LOOKUP_IDENTITY='' export FAKE_RUNTIME_NAMESPACE_PRESENT=true @@ -2665,7 +2798,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple completed_noop; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2681,6 +2814,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att elif $variant == "completed_success_old_tuple" then [step($old)] elif $variant == "ambiguous" then [step($tuple),step($old)] elif $variant == "event_only" then [step($tuple | sub("resolved"; "event"))] + elif $variant == "completed_noop" then [step($tuple | sub("resolved"; "event")),step("Explain preview skip")] elif $variant == "old_event_current_plan" then [step($old | sub("resolved"; "event")),step($tuple)] else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] | if $variant == "job_attempt_missing" then map(del(.run_attempt)) else . end | @@ -2694,7 +2828,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) elif $variant == "completed_failed_plan" then .status = "completed" | .conclusion = "failure" - elif $variant == "completed_success" or $variant == "completed_success_old_tuple" then .status = "completed" | .conclusion = "success" + elif $variant == "completed_success" or $variant == "completed_success_old_tuple" or $variant == "completed_noop" then .status = "completed" | .conclusion = "success" else . end')" ( cd "$ROOT_DIR" @@ -2710,13 +2844,13 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_pull_request_output" - if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == target || "$tuple_case" == old_event_current_plan || "$tuple_case" == job_attempt_missing ]]; then + if [[ "$tuple_case" == current || "$tuple_case" == qualified || "$tuple_case" == old_event_current_plan || "$tuple_case" == job_attempt_missing ]]; then grep -Fqx \ "Skipping proof retry for PR #901: preview source or trusted consumer run 5254 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" - elif [[ "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null ]]; then + elif [[ "$tuple_case" == target || "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_pull_request_output" @@ -2736,6 +2870,102 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att fi done +make_recent_source_evidence() { + local updated_at="$1" + local tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" + FAKE_PREVIEW_PLAN_JOBS_JSON="$(jq -cn --arg tuple "$tuple_name" --arg head "$preview_head_sha" ' + {total_count:1,jobs:[{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head, + status:"completed",conclusion:"success",steps:[{name:$tuple,status:"completed",conclusion:"success"}]}]}')" + export FAKE_PREVIEW_PLAN_JOBS_JSON + FAKE_PREVIEW_SOURCE_LATEST_JSON="$(jq -cn --arg head "$preview_head_sha" --arg updated_at "$updated_at" ' + {id:5254,run_attempt:2,head_sha:$head,event:"pull_request",workflow_id:173511323, + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + pull_requests:[{number:901}],path:".github/workflows/preview.yml",status:"completed", + conclusion:"success",updated_at:$updated_at}')" + export FAKE_PREVIEW_SOURCE_LATEST_JSON + FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON="$(jq -cn --arg head "$preview_head_sha" \ + --arg updated_at "$updated_at" ' + {total_count:1,workflow_runs:[{id:5254,run_attempt:2,workflow_id:173511323,event:"pull_request", + status:"completed",conclusion:"success",name:"PR preview 901",display_title:"PR preview 901", + head_branch:"feature-preview",head_sha:$head,path:".github/workflows/preview.yml", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + pull_requests:[{number:901}],updated_at:$updated_at}]}')" + export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON +} + +reset_case +recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +make_recent_source_evidence "$recent_source_updated_at" +reconciler_recent_source_handoff_output="$TEMP_DIR/reconciler-recent-source-handoff.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_recent_source_handoff_output" +grep -Fqx \ + "Deferring proof retry for PR #901: exact successful preview source run 5254 is within the 600-second trusted-consumer handoff window." \ + "$reconciler_recent_source_handoff_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" +test -s "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" + +reset_case +recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +make_recent_source_evidence "$recent_source_updated_at" +recent_consumer_tuple="Trusted preview deploy tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" +FAKE_TRUSTED_CONSUMER_JOBS_JSON="$(jq -cn --arg tuple "$recent_consumer_tuple" ' + {total_count:1,jobs:[{name:"Validate Trusted Preview Target",run_id:5256,run_attempt:1, + head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",status:"completed",conclusion:"success", + steps:[{name:$tuple,status:"completed",conclusion:"success"}]}]}')" +export FAKE_TRUSTED_CONSUMER_JOBS_JSON +export FAKE_TRUSTED_CONSUMER_LATEST_JSON='{"id":5256,"run_attempt":1,"event":"workflow_run","workflow_id":357129350,"path":".github/workflows/hosted-identity-request.yml","name":"Trusted Hosted Identity Request","head_branch":"develop","head_sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","display_title":"PR preview 901","repository":{"full_name":"example/FireMUD"},"head_repository":{"full_name":"example/FireMUD"},"status":"queued"}' +export FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON='{"total_count":1,"workflow_runs":[{"id":5256,"run_attempt":1,"event":"workflow_run","workflow_id":357129350,"path":".github/workflows/hosted-identity-request.yml","name":"Trusted Hosted Identity Request","head_branch":"develop","head_sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","display_title":"PR preview 901","repository":{"full_name":"example/FireMUD"},"head_repository":{"full_name":"example/FireMUD"},"status":"queued"}]}' +reconciler_handoff_race_output="$TEMP_DIR/reconciler-handoff-race.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_handoff_race_output" +grep -Fq 'trusted consumer run 5256' "$reconciler_handoff_race_output" +test -s "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + +reset_case +recent_source_updated_at="$(date -u -d '20 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" +make_recent_source_evidence "$recent_source_updated_at" +FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON="$(jq -cn --arg head "$preview_head_sha" \ + --arg updated_at "$recent_source_updated_at" '[range(5250;5254) as $id | { + id:$id,run_attempt:1,workflow_id:173511323,event:"pull_request",status:"completed", + conclusion:"success",name:"PR preview 901",display_title:"PR preview 901", + head_branch:"feature-preview",head_sha:$head,path:".github/workflows/preview.yml", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + pull_requests:[{number:901}],updated_at:$updated_at}] | {total_count:length,workflow_runs:.}')" +export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON +reconciler_expired_source_output="$TEMP_DIR/reconciler-expired-source.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_expired_source_output" +grep -Fq 'Dispatching preview render for PR #901' "$reconciler_expired_source_output" +test -s "$FAKE_DISPATCH_LOG" + for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable consumer-job-attempt-missing consumer-job-attempt-mismatch consumer-job-attempt-null; do reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" @@ -2838,6 +3068,30 @@ grep -Fq -- 'firemud.dev/proof-retry-count=1' "$FAKE_ANNOTATE_LOG" grep -Fq -- '--resource-version rv-901' "$FAKE_ANNOTATE_LOG" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" +for namespace_count_sequence in 2,1 2,2; do + reset_case + reconciler_capacity_refresh_output="$TEMP_DIR/reconciler-capacity-refresh-${namespace_count_sequence//,/-}.out" + export FAKE_NAMESPACE_COUNT_SEQUENCE="$namespace_count_sequence" + ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_PRIORITY=false \ + FAKE_PR_901_NAMESPACE_ABSENT=true \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$reconciler_capacity_refresh_output" + test "$(<"$FAKE_NAMESPACE_LIST_CALLS")" -eq 2 + if [[ "$namespace_count_sequence" == 2,1 ]]; then + grep -Fq 'Dispatching preview render for PR #901' "$reconciler_capacity_refresh_output" + test -s "$FAKE_DISPATCH_LOG" + else + grep -Fq 'Skipping ordinary PR #901: preview capacity is still full after refresh.' \ + "$reconciler_capacity_refresh_output" + test ! -e "$FAKE_DISPATCH_LOG" + fi +done + reset_case reconciler_preserved_proof_retry_output="$TEMP_DIR/reconciler-preserved-proof-retry.out" ( @@ -2864,7 +3118,7 @@ test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 reset_case reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry.out" -( +if ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ @@ -2878,7 +3132,10 @@ reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retr FAKE_DISPATCH_HTTP_STATUS=422 \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" -) > "$reconciler_rejected_proof_retry_output" 2>&1 +) > "$reconciler_rejected_proof_retry_output" 2>&1; then + echo "confirmed dispatch rejection left the reconcile job successful" >&2 + exit 1 +fi grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 422).' \ "$reconciler_rejected_proof_retry_output" grep -Fq 'Released proof-retry reservation for PR #901 after GitHub confirmed dispatch rejection.' \ @@ -2887,12 +3144,17 @@ grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" grep -Fq -- 'firemud.dev/proof-retry-count=2' "$FAKE_ANNOTATE_LOG" grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG" test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" +jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == "2" and .base == $base and .head == $head and .merge == $merge + and .image == $image and .resourceVersion == "rv-903"' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null reset_case reconciler_ambiguous_proof_retry_output="$TEMP_DIR/reconciler-ambiguous-proof-retry.out" -( +if ( cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ @@ -2904,16 +3166,93 @@ reconciler_ambiguous_proof_retry_output="$TEMP_DIR/reconciler-ambiguous-proof-re FAKE_DISPATCH_HTTP_STATUS=500 \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" -) > "$reconciler_ambiguous_proof_retry_output" 2>&1 +) > "$reconciler_ambiguous_proof_retry_output" 2>&1; then + echo "ambiguous dispatch outcome left the reconcile job successful" >&2 + exit 1 +fi grep -Fq 'outcome for PR #901 is ambiguous (gh=1, HTTP=500); proof-retry budget remains charged.' \ "$reconciler_ambiguous_proof_retry_output" test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 +test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 +jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == "3" and .base == $base and .head == $head and .merge == $merge + and .image == $image and .resourceVersion == "rv-902"' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" if grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG"; then echo "ambiguous dispatch outcome released a proof-retry reservation" >&2 exit 1 fi +for rate_case in http-429 http-403-evidence; do + reset_case + rate_limit_output="$TEMP_DIR/reconciler-rate-limit-${rate_case}.out" + rate_status=429 + rate_after=90 + if [[ "$rate_case" == http-403-evidence ]]; then + rate_status=403 + rate_after=30 + fi + if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=2 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_DISPATCH_HTTP_STATUS="$rate_status" \ + FAKE_DISPATCH_RETRY_AFTER="$rate_after" \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$rate_limit_output" 2>&1; then + echo "rate-limited dispatch left the reconcile job successful" >&2 + exit 1 + fi + grep -Fq "GitHub rate-limited preview dispatch; stopping this cycle and waiting" "$rate_limit_output" + grep -Fq 'the preview dispatch cycle already stopped after a request attempt' "$rate_limit_output" + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + test "$(<"$FAKE_SLEEP_LOG")" = "$rate_after" + test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" + jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == "2" and .base == $base and .head == $head and .merge == $merge + and .image == $image and .resourceVersion == "rv-903"' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null +done + +reset_case +reconciler_candidate_rejection_output="$TEMP_DIR/reconciler-candidate-rejection.out" +if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=2 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_DISPATCH_HTTP_STATUS=403 \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_candidate_rejection_output" 2>&1; then + echo "definitive dispatch rejections left the reconcile job successful" >&2 + exit 1 +fi +grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 403).' "$reconciler_candidate_rejection_output" +if ! grep -Fq 'Dispatching preview render for PR #902' "$reconciler_candidate_rejection_output"; then + cat "$reconciler_candidate_rejection_output" >&2 + exit 1 +fi +test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 2 +test ! -e "$FAKE_SLEEP_LOG" + reset_case reconciler_exhausted_proof_retry_output="$TEMP_DIR/reconciler-exhausted-proof-retry.out" ( @@ -3101,7 +3440,7 @@ reconciler_unvalidated_priority_output="$TEMP_DIR/reconciler-unvalidated-priorit PREVIEW_MAX_ACTIVE=1 \ bash "$RECONCILER_RUN" ) > "$reconciler_unvalidated_priority_output" -grep -qx 'Skipping ordinary PR #901: preview capacity is full.' \ +grep -qx 'Skipping ordinary PR #901: preview capacity is still full after refresh.' \ "$reconciler_unvalidated_priority_output" test ! -e "$FAKE_DISPATCH_LOG" test ! -e "$FAKE_RECONCILER_RESOLUTION_LOG" @@ -3855,7 +4194,7 @@ assert not any( PY grep -q -- '--retire-terminal-identities' "$ROOT_DIR/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh" grep -q 'Skipping ordinary PR #' "$reconciler_workflow" -grep -q 'another preview repair was already dispatched this cycle' "$reconciler_workflow" +grep -q 'preview dispatch cycle already stopped after a request attempt' "$reconciler_workflow" # Proof repair is bounded by the exact deployed tuple and must not duplicate an # active source or trusted consumer run. grep -Fq 'firemud.dev/proof-retry-count' "$reconciler_workflow" diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 94b62d1234..9751b96d5f 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -122,7 +122,6 @@ for (const [name, mutate] of Object.entries({ malformedLabels: f => f.pr.labels = [{name: 3}], appBot: f => f.pr.user.login = 'app/renovate', bot: f => f.pr.user.login = 'renovate[bot]', - currentBase: f => { f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${B} head-${C} merge-${E}`; f.recordedMerge.parents[0].sha = B; }, legacyTitle: f => f.jobs[0].steps = [], missingTitle: f => f.jobs = [], spoofTitleHead: f => f.jobs[0].steps[0].name = `Preview event tuple pr-7 base-${D} head-${B} merge-${E}`, @@ -149,6 +148,14 @@ for (const [name, mutate] of Object.entries({ })) test(`fails closed: ${name}`, async () => { const f = fixture(); mutate(f); assert.deepEqual(await execute(f), []); }); +test('a current integration event merge needs no lookup of the live merge', async () => { + const f = fixture(); + f.jobs[0].steps = [tupleStep('event', B, E), tupleStep('resolved', B, E)]; + f.recordedMerge.parents[0].sha = B; + assert.deepEqual(await execute(f), []); + assert.deepEqual(f.mergeReads, [E]); +}); + test('observer checks out only trusted policy and has no artifact or candidate execution', () => { assert.deepEqual(workflow.permissions, {}); assert.deepEqual(workflow.jobs.refresh.permissions, @@ -343,6 +350,7 @@ test('a third independently verified merge can be the resolved plan', async () = const plannedBase = '0'.repeat(40); for (const exact of [true, false]) { const f = fixture(); + f.recordedMerge.parents[0].sha = '1'.repeat(40); f.jobs[0].steps[1] = tupleStep('resolved', plannedBase, plannedMerge); f.resolvedMerge = {sha: plannedMerge, parents: [{sha: exact ? plannedBase : D}, {sha: C}]}; const dispatches = await execute(f); diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index af1e483d29..295890337b 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -121,7 +121,10 @@ function group(run) { return outputs["pull-number"] ? `static-analysis-summary-pr-${outputs["pull-number"]}` : null; } const a = group(source()), b = group(source(99)); -assert.notEqual(a, b, "same source branch must not couple different PR queues"); +assert.equal(a, "static-analysis-summary-pr-42"); +assert.equal(b, "static-analysis-summary-pr-99"); +assert.equal(group({...source(), display_title: source().display_title + " mode-metadata"}), null); + assert.equal(a, group(source(42, "License Gate")), "producer channels must serialize per PR"); assert.equal(a, group(source(42, "CodeQL Analysis", "c".repeat(40))), "head advance must keep the PR queue"); for (const pull_requests of [[{number: 99}, {number: 42}], [{number: 42}, {number: 99}]]) { @@ -259,6 +262,16 @@ const github = { status: "completed", conclusion: "skipped", }, + { + id: 280, + event: "pull_request", + head_sha: headSha, + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha} mode-metadata`, + created_at: "2026-09-20T18:00:00Z", + run_attempt: 1, + status: "completed", + conclusion: "cancelled", + }, { id: 250, event: "pull_request", @@ -479,7 +492,8 @@ async function assertCompletionOrders() { }); calls.paginate.length = 0; await run(github, context, core); - if (calls.paginate.length !== 3) throw new Error("each callback must take exactly one snapshot of both producers and comments"); + const reads = comments[0]?.body.includes("checks passed") ? 5 : 3; + if (calls.paginate.length !== reads) throw new Error("producer selection should repeat only before publishing a pass"); }; await callback(first); if (creates !== 1 || updates !== 0 || comments.length !== 1 || !comments[0].body.includes("still running")) { @@ -577,6 +591,41 @@ async function assertAssociationSelection() { } source.head_repository = {id: 123}; source.head_branch = "feature"; } +async function assertProducerSelectionRace() { + const originalPaginate = github.paginate; + const comments = [{id: 42, user: {login: "github-actions[bot]"}, + body: "### Static Analysis Summary\nchecks are still running"}]; + for (const movedWorkflow of ["codeql.yml", "license-scan.yml"]) { + let readComments = false; + currentHeadSha = headSha; currentBaseSha = baseSha; + currentBaseRef = "develop"; pullRequestReads = 0; + Object.assign(context.payload.workflow_run, { + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, + display_title: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + head_repository: {id: 123}, head_branch: "feature", pull_requests: [{number: 42}], + }); + github.paginate = async (method, input) => { + const rows = await originalPaginate(method, input); + if (method === commentsList) { + readComments = true; + return comments; + } + if (method === checksListForRef) { + return rows.map(row => ({...row, status: "completed", conclusion: "success"})); + } + if (method !== codeqlListWorkflowRuns) return rows; + const selected = rows.filter(row => row.id === (input.workflow_id === "codeql.yml" ? 200 : 300)); + if (!readComments || input.workflow_id !== movedWorkflow) return selected; + return [...selected, {...selected[0], id: 999, created_at: "2026-09-24T00:00:00Z", + status: "in_progress", conclusion: null}]; + }; + const before = mutationCounts(); + try { await run(github, context, core); } finally { github.paginate = originalPaginate; } + if (!readComments || mutationsChanged(before)) throw new Error("a new selected producer must preserve the pending comment"); + if (!jobRequests.some(({run_id}) => run_id === 999)) throw new Error("the newer producer was not checked"); + jobRequests.length = 0; + } +} async function assertInterruptedRecovery() { const originalPaginate = github.paginate; const reset = () => { @@ -620,6 +669,7 @@ async function assertInterruptedRecovery() { } run(github, context, core).then(async () => { if (calls.paginate.length !== 3) throw new Error(`expected three paginated calls, got ${calls.paginate.length}`); + if (jobRequests.some(({run_id}) => run_id === 280)) throw new Error("cancelled metadata with no job evidence must not enter selection"); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) throw new Error("only the later duplicate should be deleted"); @@ -694,6 +744,7 @@ run(github, context, core).then(async () => { if (error?.status !== 500) throw error; deleteStatus = null; await assertCompletionOrders(); + await assertProducerSelectionRace(); await assertInterruptedRecovery(); await assertAssociationSelection(); if (!jobRequests.some(input => input.run_id === 270)) throw new Error("metadata race was not classified from candidate jobs"); diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 0f19b471d4..23e9013293 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -11,6 +11,8 @@ import tempfile from pathlib import Path +import yaml + VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/(?:migration|recovery-control-migration)/") RECOVERY_MIGRATION_DIR = "/db/recovery-control-migration/" @@ -152,14 +154,30 @@ def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], def recovery_location_configured(snapshot: Snapshot, project: str) -> bool: - # The isolated owner uses the packaged Spring Flyway settings in application.yml. - settings = snapshot.get(f"services/{project}/src/main/resources/application.yml", b"").decode() - spring = re.search(r"(?m)^spring:[ \t]*\n((?:[ \t]+[^\n]*\n|\n)+)", settings + "\n") - flyway = re.search(r"(?m)^ flyway:[ \t]*\n((?: [^\n]*\n|\n)+)", spring[1]) if spring else None - locations = re.search(r"(?m)^ locations:[ \t]*(.+)$", flyway[1]) if flyway else None - return bool(locations and "classpath:db/recovery-control-migration" in { - path.strip().strip("\"'") for path in locations[1].split(",") - }) + flyway = {} + # Spring Boot gives .yml properties precedence over same-location .yaml. + for extension in ("yaml", "yml"): + config_path = f"services/{project}/src/main/resources/application.{extension}" + try: + settings = yaml.safe_load(snapshot.get(config_path, b"")) or {} + except yaml.YAMLError as error: + raise ValueError(f"{config_path}: invalid packaged Spring configuration: {error}") from error + for section in ("spring", "flyway"): + if not isinstance(settings, dict): + return False + settings = settings.get(section) or {} + if not isinstance(settings, dict): + return False + flyway.update(settings) + if str(flyway.get("enabled", True)).strip().lower() not in {"true", "on", "yes", "1"}: + return False + locations = flyway.get("locations", []) + if isinstance(locations, str): + locations = locations.split(",") + return isinstance(locations, list) and any( + isinstance(location, str) and location.strip() == "classpath:db/recovery-control-migration" + for location in locations + ) def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str], int, int]: @@ -168,7 +186,7 @@ def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str issues = [] for project in sorted({item.project for item in migrations if RECOVERY_MIGRATION_DIR in item.path}): if not recovery_location_configured(current, project): - issues.append(f"services/{project}: packaged Spring Flyway configuration does not select the recovery-control location") + issues.append(f"services/{project}: packaged Spring configuration must enable Flyway and select the recovery-control location") for project, items in sorted(grouped.items()): seen: dict[tuple[int, ...], MigrationFile] = {} for item in items: @@ -286,6 +304,24 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str recovery_settings = b"spring:\n flyway:\n locations: classpath:db/recovery-control-migration\n" recovery_history = {recovery + "V1__journal.sql": b"-- journal", recovery_config: recovery_settings} check("unchanged isolated recovery history", recovery_history, recovery_history, None) + yaml_config = recovery_config.removesuffix(".yml") + ".yaml" + renamed_recovery_config = {recovery + "V1__journal.sql": b"-- journal", yaml_config: recovery_settings} + check("equivalent application.yaml recovery history", renamed_recovery_config, recovery_history, None) + check("application.yml override disables recovery history", { + **renamed_recovery_config, recovery_config: b"spring:\n flyway:\n enabled: false\n", + }, recovery_history, "historical effective migration no longer applied") + recovery_list_settings = ( + b"spring:\n flyway:\n enabled: true\n locations:\n" + b" - classpath:db/recovery-control-migration\n" + ) + check("equivalent enabled list recovery history", + {**recovery_history, recovery_config: recovery_list_settings}, recovery_history, None) + for disabled in ( + recovery_settings.replace(b" locations:", b" enabled: false\n locations:"), + recovery_list_settings.replace(b"enabled: true", b'enabled: "false"'), + ): + check("disabled recovery history", {**recovery_history, recovery_config: disabled}, + recovery_history, "historical effective migration no longer applied") check("disconnected isolated recovery history", { **recovery_history, recovery_config: recovery_settings.replace(b"recovery-control-migration", b"migration"), }, recovery_history, "historical effective migration no longer applied") diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java new file mode 100644 index 0000000000..2a6f0995b3 --- /dev/null +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.recovery.config; + +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +/** Rejects an implicit or empty recovery-control database endpoint before datasource setup. */ +public final class RecoveryControlDatabaseHostEnvironmentPostProcessor + implements EnvironmentPostProcessor, Ordered { + public static final String HOST_PROPERTY = "FIREMUD_RECOVERY_CONTROL_DB_HOST"; + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + String host = environment.getProperty(HOST_PROPERTY); + if (host == null || host.isBlank()) { + throw new IllegalStateException(HOST_PROPERTY + " must name the isolated recovery database"); + } + } + + @Override + public int getOrder() { + return Ordered.LOWEST_PRECEDENCE; + } +} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index c526b91b06..57e07c53c5 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Component; import tools.jackson.core.JacksonException; import tools.jackson.core.json.JsonWriteFeature; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; /** Stable JSON and digest encoding for the operation-owned immutable tuples. */ @@ -89,20 +90,49 @@ public InitialGameplayReleaseModel.PeerStorageBinding readPeerStorageBinding(Str public InitialGameplayReleaseModel.InitialGameplayReleaseEvidence readEvidence(String json) { try { - return objectMapper.readValue( - json, InitialGameplayReleaseModel.InitialGameplayReleaseEvidence.class); + JsonNode persisted = objectMapper.readTree(json); + JsonNode persistedCapacity = persisted.path("issuerLayout").path("capacityVector"); + requireCanonicalCapacityVectorKeys(persistedCapacity); + var evidence = + objectMapper.treeToValue( + persisted, InitialGameplayReleaseModel.InitialGameplayReleaseEvidence.class); + if (evidence != null + && !hasCanonicalJsonShape(persistedCapacity, evidence.issuerLayout().capacityVector())) { + throw new IllegalStateException( + "Persisted initial gameplay release evidence has a noncanonical shape"); + } + return evidence; } catch (JacksonException exception) { throw new IllegalStateException( "Unable to read persisted initial gameplay release evidence", exception); } } + private static void requireCanonicalCapacityVectorKeys(JsonNode capacityVector) { + if (!capacityVector.isObject()) return; + for (String key : capacityVector.propertyNames()) { + if (!(key.equals("0") || key.matches("[1-9][0-9]*"))) { + throw new IllegalStateException( + "Persisted initial gameplay release evidence has a noncanonical shape: " + + "capacity vector key is not a canonical decimal integer"); + } + try { + Integer.parseInt(key); + } catch (NumberFormatException exception) { + throw new IllegalStateException( + "Persisted initial gameplay release evidence has a noncanonical shape: " + + "capacity vector key is outside the integer range", + exception); + } + } + } + InitialGameplayReleaseModel.PublicTransitionTuple readPublicTransition(String json) { try { var tuple = objectMapper.readValue(json, InitialGameplayReleaseModel.PublicTransitionTuple.class); // JSONB may reorder object properties, but stored fields and JSON value types must be exact. - if (tuple == null || !objectMapper.readTree(json).equals(objectMapper.valueToTree(tuple))) { + if (tuple == null || !hasCanonicalJsonShape(json, tuple)) { throw new IllegalStateException("Persisted public transition has a noncanonical shape"); } return tuple; @@ -111,6 +141,14 @@ InitialGameplayReleaseModel.PublicTransitionTuple readPublicTransition(String js } } + private boolean hasCanonicalJsonShape(String json, Object value) throws JacksonException { + return hasCanonicalJsonShape(objectMapper.readTree(json), value); + } + + private boolean hasCanonicalJsonShape(JsonNode persisted, Object value) { + return persisted.equals(objectMapper.valueToTree(value)); + } + InitialGameplayReleaseModel.EffectReadback readEffectReadback(String json) { try { return objectMapper.readValue(json, InitialGameplayReleaseModel.EffectReadback.class); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 5bacf79d01..716187eb7e 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -26,6 +26,7 @@ import org.jooq.DSLContext; import org.jooq.JSONB; import org.jooq.Record; +import org.jooq.conf.Settings; import org.jooq.impl.DSL; /** @@ -41,7 +42,10 @@ public final class JooqInitialGameplayReleaseJournal implements InitialGameplayR public JooqInitialGameplayReleaseJournal( DSLContext dsl, InitialGameplayReleaseTupleCodec tupleCodec) { - this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + Objects.requireNonNull(dsl, "dsl must not be null"); + Settings journalSettings = (Settings) dsl.configuration().settings().clone(); + journalSettings.setExecuteLogging(false); + this.dsl = DSL.using(dsl.configuration().derive(journalSettings)); this.tupleCodec = Objects.requireNonNull(tupleCodec, "tupleCodec must not be null"); } @@ -400,15 +404,25 @@ public Operation recordEffectReadback( && dispatch.state() != EffectOutboxState.AMBIGUOUS)) { throw conflict("effect readback dispatch tuple changed"); } - if (dispatch.lastAttemptId() == null - || !dispatch.lastAttemptId().equals(current.lastAttemptId())) { + if (dispatch.lastAttemptId() == null) { throw conflict("effect readback belongs to another attempt"); } + if (!dispatch.lastAttemptId().equals(current.lastAttemptId())) { + EffectReadback retainedClosure = + findRetainedClosure(tx, current, dispatch.lastAttemptId(), dispatch.attemptCount()); + if (retainedClosure == null) { + throw conflict("effect readback belongs to another attempt"); + } + if (!readback.equals(retainedClosure) || readback.observedAt().isAfter(now)) { + throw conflict("effect readback changed after definitive no effect"); + } + return operation; + } + String readbackDigest = tupleCodec.digest(readback); if (dispatch.attemptCount() != current.attemptCount()) { throw conflict("effect readback dispatch generation changed"); } requireReadbackMatches(readback, current, operationId, effectId); - String readbackDigest = tupleCodec.digest(readback); if (current.state() == EffectOutboxState.ACKNOWLEDGED || current.state() == EffectOutboxState.RETRYABLE) { Record stored = @@ -793,6 +807,11 @@ private void requireTransitionMatchesOperation(PublicTransitionTuple tuple, Oper private boolean hasRetainedClosure( DSLContext tx, OutboxEntry current, UUID attemptId, Integer expectedOrdinal) { + return findRetainedClosure(tx, current, attemptId, expectedOrdinal) != null; + } + + private EffectReadback findRetainedClosure( + DSLContext tx, OutboxEntry current, UUID attemptId, Integer expectedOrdinal) { Record row = tx.fetchOne( """ @@ -802,12 +821,16 @@ private boolean hasRetainedClosure( """, current.outboxId(), attemptId); - if (row == null) return false; + if (row == null) return null; Integer ordinal = row.get("attempt_ordinal", Integer.class); + OffsetDateTime dispatchedAt = row.get("dispatched_at", OffsetDateTime.class); + OffsetDateTime recordedAt = row.get("recorded_at", OffsetDateTime.class); if (ordinal == null || ordinal < 1 || ordinal > current.attemptCount() - || (expectedOrdinal != null && !expectedOrdinal.equals(ordinal))) { + || (expectedOrdinal != null && !expectedOrdinal.equals(ordinal)) + || dispatchedAt == null + || recordedAt == null) { throw conflict("retained effect dispatch generation changed"); } EffectReadback retained = @@ -821,16 +844,14 @@ private boolean hasRetainedClosure( || !current.effect().operationTupleDigest().equals(retained.operationTupleDigest()) || !current.payloadDigest().equals(retained.payloadDigest()) || !tupleCodec.digest(retained).equals(row.get("readback_digest", String.class)) - || retained - .observedAt() - .isBefore(row.get("dispatched_at", OffsetDateTime.class).toInstant()) + || retained.observedAt().isBefore(dispatchedAt.toInstant()) || retained .observedAt() .truncatedTo(java.time.temporal.ChronoUnit.MICROS) - .isAfter(row.get("recorded_at", OffsetDateTime.class).toInstant())) { + .isAfter(recordedAt.toInstant())) { throw conflict("retained attempt closure does not match the exact dispatched tuple"); } - return true; + return retained; } private static boolean hasRetainedOwnerRejection( diff --git a/services/recovery-controller-service/src/main/resources/META-INF/spring.factories b/services/recovery-controller-service/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..7951ef6583 --- /dev/null +++ b/services/recovery-controller-service/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.EnvironmentPostProcessor=net.firedevops.firemud.recovery.config.RecoveryControlDatabaseHostEnvironmentPostProcessor diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 97a8c0dc8f..b8009104eb 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -3,9 +3,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; +import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; @@ -44,13 +49,16 @@ import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.conf.Settings; import org.jooq.impl.DSL; +import org.jooq.tools.LoggerListener; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -61,6 +69,161 @@ class InitialGameplayReleaseJournalPostgresIntegrationTest { private static final String SCHEMA = "recovery_control"; private static final String DIGEST = "b".repeat(64); + private static final UUID V1_OPERATION_ID = + UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final UUID V1_PLAYABLE_NAMESPACE_ID = + UUID.fromString("10000000-0000-0000-0000-000000000003"); + private static final UUID V1_LOCK_IDENTITY = + UUID.fromString("10000000-0000-0000-0000-000000000004"); + private static final UUID V1_OUTBOX_ID = UUID.fromString("10000000-0000-0000-0000-000000000010"); + private static final UUID V1_EFFECT_ID = UUID.fromString("10000000-0000-0000-0000-000000000011"); + private static final UUID V1_PRIOR_ATTEMPT_ID = + UUID.fromString("10000000-0000-0000-0000-000000000012"); + private static final String V1_SCOPE_PAYLOAD = + """ + { + "operationId": "10000000-0000-0000-0000-000000000001", + "canonicalTenantId": "10000000-0000-0000-0000-000000000002", + "targetNamespace": "release-target", + "playableStateNamespaceId": "10000000-0000-0000-0000-000000000003", + "peerStorageBinding": { + "targetNamespace": "release-target", + "clusterIdentity": "cluster-a", + "peerWorkloadIdentity": "recovery-peer", + "storageIdentity": "storage-uid-1", + "storageRevision": "revision-7", + "bindingDigest": "@DIGEST@" + }, + "evidenceRef": "immutable-initial-layout-evidence" + } + """ + .strip() + .replace("@DIGEST@", DIGEST); + private static final String V1_PEER_STORAGE_BINDING_PAYLOAD = + """ + { + "targetNamespace": "release-target", + "clusterIdentity": "cluster-a", + "peerWorkloadIdentity": "recovery-peer", + "storageIdentity": "storage-uid-1", + "storageRevision": "revision-7", + "bindingDigest": "@DIGEST@" + } + """ + .strip() + .replace("@DIGEST@", DIGEST); + private static final String V1_EVIDENCE_PAYLOAD = + """ + { + "evidenceRef": "immutable-initial-layout-evidence", + "evidenceIdentity": "evidence-owner-record-31", + "migration": { + "migrationOperationId": "10000000-0000-0000-0000-000000000005", + "disposition": "VERIFIED", + "storageIdentity": "storage-uid-1", + "inventoryRevision": "writer-inventory-r9", + "inventoryDigest": "@DIGEST@" + }, + "issuerLayout": { + "layoutOperationId": "10000000-0000-0000-0000-000000000006", + "descriptor": { + "descriptorIdentity": "issuer-layout-v1", + "revision": "layout-r4", + "digest": "@DIGEST@", + "partitionIds": [ + 0, + 1 + ] + }, + "accountIssuerSourceIdentity": "account-issuer-source-identity-1", + "operationFence": 101, + "coverageFence": "10000000-0000-0000-0000-000000000007", + "inventoryRevision": "writer-inventory-r9", + "inventoryDigest": "@DIGEST@", + "acknowledgements": [ + { + "partitionId": 0, + "acknowledgementIdentity": "partition-0-ack", + "acknowledgedLayoutDigest": "@DIGEST@", + "readbackDigest": "@DIGEST@", + "capacity": 32 + }, + { + "partitionId": 1, + "acknowledgementIdentity": "partition-1-ack", + "acknowledgedLayoutDigest": "@DIGEST@", + "readbackDigest": "@DIGEST@", + "capacity": 64 + } + ], + "capacityVector": { + "0": 32, + "1": 64 + } + }, + "writerFencing": { + "inventory": { + "revision": "writer-inventory-r9", + "digest": "@DIGEST@", + "legacyWriterIdentity": "legacy-layout-writer", + "applicableWriterIdentities": [ + "writer-a", + "writer-b" + ] + }, + "legacyWriterDisposition": "STOPPED", + "writerAcknowledgements": [ + { + "writerIdentity": "writer-a", + "disposition": "FENCED", + "fenceIdentity": "fence-a", + "inventoryDigest": "@DIGEST@" + }, + { + "writerIdentity": "writer-b", + "disposition": "FENCED", + "fenceIdentity": "fence-b", + "inventoryDigest": "@DIGEST@" + } + ] + }, + "worldInitialization": { + "ownerService": "WORLD_MANAGEMENT", + "initializationOperationId": "10000000-0000-0000-0000-000000000008", + "playableStateNamespaceId": "10000000-0000-0000-0000-000000000003", + "disposition": "VERIFIED", + "sourceIdentity": "world-init-source-1", + "resultDigest": "@DIGEST@" + }, + "entityInitialization": { + "ownerService": "ENTITY_MANAGEMENT", + "initializationOperationId": "10000000-0000-0000-0000-000000000009", + "playableStateNamespaceId": "10000000-0000-0000-0000-000000000003", + "disposition": "VERIFIED", + "sourceIdentity": "entity-init-source-1", + "resultDigest": "@DIGEST@" + }, + "regionLease": { + "regionIdentity": "region-a", + "leaseIdentity": "lease-identity-51", + "executorGeneration": 10 + } + } + """ + .strip() + .replace("@DIGEST@", DIGEST); + private static final String V1_PREPARE_EFFECT_PAYLOAD_TEMPLATE = + """ + { + "operationId": "10000000-0000-0000-0000-000000000001", + "effectId": "10000000-0000-0000-0000-000000000011", + "maintenanceLockIdentity": "10000000-0000-0000-0000-000000000004", + "scope": %s, + "operationTupleDigest": "%s", + "evidenceIdentity": "evidence-owner-record-31" + } + """ + .strip(); @Container private static final PostgreSQLContainer POSTGRES = @@ -114,6 +277,38 @@ void clearJournal() { + "recovery_control.initial_gameplay_release_operation"); } + @Test + void journalDoesNotLogControllerLockIdentityAtDebug() { + Logger logger = (Logger) LoggerFactory.getLogger(LoggerListener.class); + Level priorLevel = logger.getLevel(); + ListAppender logCapture = new ListAppender<>(); + logCapture.start(); + logger.addAppender(logCapture); + logger.setLevel(Level.DEBUG); + try { + DSLContext debugDsl = + DSL.using(dsl.configuration().derive(new Settings().withExecuteLogging(true))); + InitialGameplayReleaseJournal debugJournal = + new JooqInitialGameplayReleaseJournal(debugDsl, tupleCodec); + Scope requested = scope(); + UUID controllerLockIdentity = UUID.randomUUID(); + + Operation created = debugJournal.create(requested, controllerLockIdentity); + assertThat(debugJournal.find(requested.operationId())) + .get() + .extracting(Operation::maintenanceLockIdentity) + .isEqualTo(controllerLockIdentity); + assertThat(created.maintenanceLockIdentity()).isEqualTo(controllerLockIdentity); + assertThat(logCapture.list) + .extracting(ILoggingEvent::getFormattedMessage) + .noneMatch(message -> message.contains(controllerLockIdentity.toString())); + } finally { + logger.detachAppender(logCapture); + logger.setLevel(priorLevel); + logCapture.stop(); + } + } + @Test void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() { Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); @@ -529,8 +724,10 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { assertThat(replacement) .contains( "\"readback_identity\":null", "\"readback_payload\":null", "\"readback_digest\":null"); + assertThat(journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(9))) + .isEqualTo(authorized); assertThatThrownBy( - () -> journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(9))) + () -> journal.recordEffectReadback(dispatched, observedAgain, base.plusSeconds(9))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(replacement); } @@ -583,7 +780,9 @@ void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { UUID nextAttempt = UUID.randomUUID(); journal.claimEffect(operationId, effectId, nextAttempt, base.plusSeconds(8)); String replaced = storedOutbox(operationId, effectId); - assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, closure, base.plusSeconds(9))) + assertThat(journal.recordEffectReadback(dispatched, closure, base.plusSeconds(9))) + .isEqualTo(beforeReplay); + assertThatThrownBy(() -> journal.recordEffectReadback(dispatched, future, base.plusSeconds(9))) .isInstanceOf(InitialGameplayReleaseConflictException.class); assertThat(storedOutbox(operationId, effectId)).isEqualTo(replaced); } @@ -998,20 +1197,37 @@ void durableClosureRejectsReclaimAndLetsOnlyExactDelayedDispatchBecomeSuperseded OutboxEntry a = authorizedDispatch(base); UUID operationId = a.effect().operationId(); UUID effectId = a.effect().effectId(); - journal.recordEffectReadback( - a, + EffectReadback closedAReadback = readbackFor( a, a.lastAttemptId(), EffectReadbackState.PROVEN_NO_EFFECT, "closed-a", - base.plusSeconds(5)), - base.plusSeconds(5)); + base.plusSeconds(5)); + journal.recordEffectReadback(a, closedAReadback, base.plusSeconds(5)); String closedA = storedClosure(a); OutboxEntry b = journal.claimEffect(operationId, effectId, UUID.randomUUID(), base.plusSeconds(6)); assertThat(storedClosure(a)).isEqualTo(closedA); String before = storedOutbox(operationId, effectId); + Operation beforeReplay = journal.find(operationId).orElseThrow(); + assertThat(journal.recordEffectReadback(a, closedAReadback, base.plusSeconds(7))) + .isEqualTo(beforeReplay); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat(journal.findNextEffect(operationId)).contains(b); + EffectReadback alteredAReadback = + readbackFor( + a, + a.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "altered-closed-a", + base.plusSeconds(5)); + assertThatThrownBy(() -> journal.recordEffectReadback(a, alteredAReadback, base.plusSeconds(7))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("effect readback changed after definitive no effect"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(before); + assertThat(storedClosure(a)).isEqualTo(closedA); + assertThat(journal.findNextEffect(operationId)).contains(b); assertThat( journal.recordAmbiguousEffectForDispatch(a, "DELAYED_AMBIGUOUS", base.plusSeconds(7))) .isFalse(); @@ -1161,30 +1377,32 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) try (Connection legacyConnection = DriverManager.getConnection(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword())) { DSLContext legacyDsl = DSL.using(legacyConnection, SQLDialect.POSTGRES); - InitialGameplayReleaseJournal legacy = - new JooqInitialGameplayReleaseJournal(legacyDsl, tupleCodec); Instant base = Instant.parse("2026-09-01T00:00:00Z"); - Scope scope = scope(); - legacy.create(scope, UUID.randomUUID()); - InitialGameplayReleaseEvidence proof = evidence(scope); - Operation ready = - legacy.bindVerifiedEvidence( - scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), base); - Operation awaiting = - legacy.transition(transitionTuple(ready, TransitionVerb.CONTINUE_RECOVERY), base); - legacy.transition(transitionTuple(awaiting, TransitionVerb.RESUME), base); - OutboxEntry pending = legacy.findNextEffect(scope.operationId()).orElseThrow(); - if (claimed) { - assertThat( - legacyDsl.execute( - "UPDATE recovery_control.initial_gameplay_release_outbox " - + "SET state='dispatched', attempt_count=1, last_attempt_id=?, " - + "last_dispatched_at=now() WHERE outbox_id=?", - UUID.randomUUID(), - pending.outboxId())) - .isEqualTo(1); - } - OutboxEntry before = legacy.findNextEffect(scope.operationId()).orElseThrow(); + seedImmutableV1Journal(legacyDsl, claimed, base); + String scopeBefore = + legacyDsl + .fetchSingle( + "SELECT scope_payload::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class); + String bindingBefore = + legacyDsl + .fetchSingle( + "SELECT peer_storage_binding::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class); + String evidenceBefore = + legacyDsl + .fetchSingle( + "SELECT evidence_snapshot::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class); + String payloadBefore = + legacyDsl + .fetchSingle( + "SELECT payload::text FROM recovery_control.initial_gameplay_release_outbox WHERE outbox_id=?", + V1_OUTBOX_ID) + .get(0, String.class); Flyway upgrade = Flyway.configure() .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) @@ -1197,7 +1415,8 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) if (claimed) { assertThatThrownBy(() -> upgrade.migrate()) .hasStackTraceContaining("requires no prior claims"); - assertThat(legacy.findNextEffect(scope.operationId())).contains(before); + assertImmutableV1Payloads( + legacyDsl, scopeBefore, bindingBefore, evidenceBefore, payloadBefore); assertThat( legacyDsl .fetchSingle( @@ -1208,12 +1427,32 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) } else { upgrade.migrate(); assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("2"); - assertThat(legacy.findNextEffect(scope.operationId())).contains(pending); + assertImmutableV1Payloads( + legacyDsl, scopeBefore, bindingBefore, evidenceBefore, payloadBefore); + InitialGameplayReleaseJournal upgradedJournal = + new JooqInitialGameplayReleaseJournal(legacyDsl, tupleCodec); + Operation upgraded = upgradedJournal.find(V1_OPERATION_ID).orElseThrow(); + assertThat(upgraded.maintenanceLockIdentity()).isEqualTo(V1_LOCK_IDENTITY); + assertThat(upgraded.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); + assertThat(upgraded.evidence()).isNotNull(); + assertThat(upgraded.evidence().evidenceIdentity()).isEqualTo("evidence-owner-record-31"); + OutboxEntry pending = upgradedJournal.findNextEffect(V1_OPERATION_ID).orElseThrow(); + assertThat(pending.outboxId()).isEqualTo(V1_OUTBOX_ID); + assertThat(pending.effect().effectId()).isEqualTo(V1_EFFECT_ID); + assertThat(pending.effect().maintenanceLockIdentity()).isEqualTo(V1_LOCK_IDENTITY); + assertThat(pending.payloadDigest()).isEqualTo(tupleCodec.digest(pending.effect())); + assertThat( + legacyDsl + .fetchSingle( + "SELECT payload::text FROM recovery_control.initial_gameplay_release_outbox WHERE outbox_id=?", + V1_OUTBOX_ID) + .get(0, String.class)) + .isEqualTo(payloadBefore); UUID freshAttempt = UUID.randomUUID(); OutboxEntry dispatched = - legacy.claimEffect( - scope.operationId(), pending.effect().effectId(), freshAttempt, base); - assertThat(dispatched.outboxId()).isEqualTo(pending.outboxId()); + upgradedJournal.claimEffect( + V1_OPERATION_ID, pending.effect().effectId(), freshAttempt, base); + assertThat(dispatched.outboxId()).isEqualTo(V1_OUTBOX_ID); assertThat(dispatched.effect()).isEqualTo(pending.effect()); assertThat(dispatched.state()).isEqualTo(EffectOutboxState.DISPATCHED); assertThat(dispatched.lastAttemptId()).isEqualTo(freshAttempt); @@ -1225,6 +1464,105 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) } } + private static void assertImmutableV1Payloads( + DSLContext legacyDsl, + String scopePayload, + String bindingPayload, + String evidencePayload, + String effectPayload) { + assertThat( + legacyDsl + .fetchSingle( + "SELECT scope_payload::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class)) + .isEqualTo(scopePayload); + assertThat( + legacyDsl + .fetchSingle( + "SELECT peer_storage_binding::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class)) + .isEqualTo(bindingPayload); + assertThat( + legacyDsl + .fetchSingle( + "SELECT evidence_snapshot::text FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + V1_OPERATION_ID) + .get(0, String.class)) + .isEqualTo(evidencePayload); + assertThat( + legacyDsl + .fetchSingle( + "SELECT payload::text FROM recovery_control.initial_gameplay_release_outbox WHERE outbox_id=?", + V1_OUTBOX_ID) + .get(0, String.class)) + .isEqualTo(effectPayload); + } + + private static void seedImmutableV1Journal( + DSLContext seedDsl, boolean claimed, Instant timestamp) { + Scope v1Scope = tupleCodec.readScope(V1_SCOPE_PAYLOAD); + InitialGameplayReleaseEvidence v1Evidence = tupleCodec.readEvidence(V1_EVIDENCE_PAYLOAD); + String scopeDigest = tupleCodec.digest(v1Scope); + String evidenceDigest = tupleCodec.digest(v1Evidence); + String operationTupleDigest = + tupleCodec.operationTupleDigest(v1Scope, V1_LOCK_IDENTITY, v1Evidence); + String effectPayload = + V1_PREPARE_EFFECT_PAYLOAD_TEMPLATE.formatted(V1_SCOPE_PAYLOAD, operationTupleDigest); + var effect = + tupleCodec.readEffect( + EffectKind.PREPARE_PLAYABLE_STATE_FENCED.databaseValue(), effectPayload); + String payloadDigest = tupleCodec.digest(effect); + + seedDsl.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_operation ( + operation_id, target_namespace, playable_state_namespace_id, + peer_storage_binding, scope_payload, evidence_ref, scope_digest, + maintenance_lock_identity, phase, evidence_snapshot, evidence_identity, + evidence_digest, revision, created_at, updated_at + ) VALUES (?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, + 'resume_authorized', CAST(? AS jsonb), ?, ?, 4, + CAST(? AS timestamptz), CAST(? AS timestamptz)) + """, + V1_OPERATION_ID, + "release-target", + V1_PLAYABLE_NAMESPACE_ID, + V1_PEER_STORAGE_BINDING_PAYLOAD, + V1_SCOPE_PAYLOAD, + "immutable-initial-layout-evidence", + scopeDigest, + V1_LOCK_IDENTITY, + V1_EVIDENCE_PAYLOAD, + "evidence-owner-record-31", + evidenceDigest, + timestamp.atOffset(ZoneOffset.UTC), + timestamp.atOffset(ZoneOffset.UTC)); + + seedDsl.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_outbox ( + outbox_id, operation_id, effect_id, effect_kind, operation_tuple_digest, + payload_digest, payload, state, attempt_count, last_attempt_id, + last_dispatched_at, created_at, updated_at + ) VALUES (?, ?, ?, 'prepare_playable_state_fenced', ?, ?, CAST(? AS jsonb), + ?, ?, ?, CAST(? AS timestamptz), CAST(? AS timestamptz), CAST(? AS timestamptz)) + """, + V1_OUTBOX_ID, + V1_OPERATION_ID, + V1_EFFECT_ID, + operationTupleDigest, + payloadDigest, + effectPayload, + claimed ? "dispatched" : "pending", + claimed ? 1 : 0, + claimed ? V1_PRIOR_ATTEMPT_ID : null, + claimed ? timestamp.atOffset(ZoneOffset.UTC) : null, + timestamp.atOffset(ZoneOffset.UTC), + timestamp.atOffset(ZoneOffset.UTC)); + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java new file mode 100644 index 0000000000..606c00569d --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.recovery.config; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.mock.env.MockEnvironment; + +class RecoveryControlDatabaseHostEnvironmentPostProcessorTest { + private final RecoveryControlDatabaseHostEnvironmentPostProcessor postProcessor = + new RecoveryControlDatabaseHostEnvironmentPostProcessor(); + + @Test + void rejectsMissingOrBlankRecoveryDatabaseHost() { + assertThatThrownBy(() -> + postProcessor.postProcessEnvironment(new MockEnvironment(), new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("FIREMUD_RECOVERY_CONTROL_DB_HOST"); + + assertThatThrownBy(() -> + postProcessor.postProcessEnvironment( + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, " \t"), + new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("FIREMUD_RECOVERY_CONTROL_DB_HOST"); + } + + @Test + void acceptsExplicitLocalhostForAnIsolatedFixture() { + assertThatCode(() -> + postProcessor.postProcessEnvironment( + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, + "localhost"), + new SpringApplication())) + .doesNotThrowAnyException(); + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java index 678ddec679..098e013d70 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControllerOwnerConfigurationTest.java @@ -1,10 +1,17 @@ package net.firedevops.firemud.recovery.config; 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; import com.zaxxer.hikari.HikariDataSource; import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.UUID; import javax.sql.DataSource; import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; @@ -15,8 +22,11 @@ import net.firedevops.firemud.recovery.service.InitialGameplayReleaseController; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEffectPort; import net.firedevops.firemud.recovery.service.InitialGameplayReleaseEvidenceProvider; +import net.firedevops.firemud.recovery.service.OwnerBoundaryUnavailableException; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.jooq.impl.DataSourceConnectionProvider; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -26,20 +36,23 @@ import org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration; import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.jooq.autoconfigure.JooqAutoConfiguration; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.boot.test.context.TestComponent; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; class RecoveryControllerOwnerConfigurationTest { private ApplicationContextRunner defaults() { return new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RecoveryControllerOwnerConfiguration.class)) - .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withBean(DSLContext.class, () -> DSL.using(SQLDialect.POSTGRES)) .withBean( InitialGameplayReleaseTupleCodec.class, () -> new InitialGameplayReleaseTupleCodec(JsonMapper.builder().build())); @@ -124,6 +137,47 @@ void dedicatedDatasourceOwnsFlywayAndJooq() { }); } + @Test + void configuredJooqTransactionIsRejectedBeforeOwnerEffectDispatch() throws SQLException { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true); + InitialGameplayReleaseJournal journal = mock(InitialGameplayReleaseJournal.class); + InitialGameplayReleaseEffectPort effectPort = mock(InitialGameplayReleaseEffectPort.class); + InitialGameplayReleaseController controller = + new InitialGameplayReleaseController( + journal, + new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()), + mock(InitialGameplayReleaseEvidenceProvider.class), + effectPort); + + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + DataSourceTransactionManagerAutoConfiguration.class, JooqAutoConfiguration.class)) + .withBean(DataSource.class, () -> dataSource) + .withPropertyValues("spring.jooq.sql-dialect=POSTGRES") + .run(context -> { + assertThat(context).hasNotFailed(); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().transactionProvider()) + .isInstanceOf(SpringTransactionProvider.class); + assertThatThrownBy(() -> + dsl.transactionResult(configuration -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThatThrownBy(() -> controller.reconcileNextEffect(UUID.randomUUID())) + .isInstanceOf(OwnerBoundaryUnavailableException.class) + .hasMessageContaining("RECONCILIATION_REQUIRES_NO_CALLER_TRANSACTION"); + throw new IllegalStateException("rollback caller-owned jOOQ transaction"); + })) + .isInstanceOf(RuntimeException.class); + verify(connection).rollback(); + verifyNoInteractions(journal, effectPort); + }); + } + @TestConfiguration(proxyBeanMethods = false) @ImportAutoConfiguration({ DatabaseAutoConfiguration.class, diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index 5e4564eb12..c1b3994403 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -515,6 +515,31 @@ void persistedEvidenceRejectsFractionalOperationFence() { .isInstanceOf(IllegalStateException.class); } + @Test + void persistedEvidenceRejectsNoncanonicalAndDuplicateNormalizedCapacityKeys() { + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); + String json = codec.toJson(evidence(scope(UUID.randomUUID()))); + ObjectNode noncanonical = (ObjectNode) mapper.readTree(json); + ObjectNode noncanonicalCapacity = (ObjectNode) noncanonical.at("/issuerLayout/capacityVector"); + var oneCapacity = noncanonicalCapacity.remove("1"); + noncanonicalCapacity.set("01", oneCapacity); + String noncanonicalJson = mapper.writeValueAsString(noncanonical); + + ObjectNode duplicateNormalized = (ObjectNode) mapper.readTree(json); + ObjectNode duplicateCapacity = + (ObjectNode) duplicateNormalized.at("/issuerLayout/capacityVector"); + duplicateCapacity.set("01", duplicateCapacity.get("1").deepCopy()); + String duplicateNormalizedJson = mapper.writeValueAsString(duplicateNormalized); + + assertThatThrownBy(() -> codec.readEvidence(noncanonicalJson)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("noncanonical shape"); + assertThatThrownBy(() -> codec.readEvidence(duplicateNormalizedJson)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("noncanonical shape"); + } + @Test void journalReadbackRejectsNulInIdentityBeforePersistence() { assertThatThrownBy(() -> From 97e23e895bbc249a198e4267b75185c5158f1047 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:01:01 +1300 Subject: [PATCH 089/199] Make runtime retarget fixtures deterministic on CI runners --- .../tests/pr-retarget-workflow-contract.sh | 68 ++++++++++--------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index c51454e3d9..caddbf8c28 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2412,25 +2412,52 @@ JSON fi EOF chmod +x "$contract_fixture_dir/gh" +# Advance the fixture clock at poll sleeps so API fixture speed cannot govern +# success or timeout. The outer timeout still bounds a broken fixture. +cat >"$contract_fixture_dir/publisher-clock.sh" <<'EOF' +if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then + unset SECONDS + SECONDS=0 + sleep() { + SECONDS=$((SECONDS + 1)) + } + if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then + timeout() { + local timeout_budget="${2:-0}" timeout_status + if command timeout "$@"; then + timeout_status=0 + else + timeout_status=$? + fi + if [[ -f "$CONTRACT_STALLED_LOOKUP_MARKER" && "$timeout_status" -ne 0 ]]; then + SECONDS=$((SECONDS + timeout_budget)) + fi + return "$timeout_status" + } + fi +fi +EOF +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ PATH="$contract_fixture_dir:$PATH" \ GH_TOKEN=contract-token \ GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=5 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ -bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ +timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" \ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/output" require_contains "$contract_fixture_dir/output" 'Matching runtime-images workflow 101 succeeded' require_contains "$contract_fixture_dir/output" 'Trusted PR image publisher 201 succeeded' +BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ CONTRACT_GH_STATE_FILE="$contract_fixture_dir/gh-state" \ PATH="$contract_fixture_dir:$PATH" \ GH_TOKEN=contract-token \ GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=5 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ -bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ +timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" \ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/retry-output" \ @@ -2639,31 +2666,6 @@ many = [{**base, "id": 300 + index, "display_title": f"Publish PR Runtime Images (root / "dispatch-outside-window.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-07-23T00:00:00Z"}]})) (root / "dispatch-invalid-date.json").write_text(json.dumps({"total_count": 1, "workflow_runs": [{**base, "created_at": "2026-02-31T00:00:00Z"}]})) PY_FIXTURES -# Advance the fixture clock at poll sleeps so API fixture speed cannot govern -# success or timeout. The outer timeout still bounds a broken fixture. -cat >"$contract_fixture_dir/publisher-clock.sh" <<'EOF' -if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then - unset SECONDS - SECONDS=0 - sleep() { - SECONDS=$((SECONDS + 1)) - } - if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then - timeout() { - local timeout_budget="${2:-0}" timeout_status - if command timeout "$@"; then - timeout_status=0 - else - timeout_status=$? - fi - if [[ -f "$CONTRACT_STALLED_LOOKUP_MARKER" && "$timeout_status" -ne 0 ]]; then - SECONDS=$((SECONDS + timeout_budget)) - fi - return "$timeout_status" - } - fi -fi -EOF for event in typed native; do source_inventory="duplicate-inventory" publisher_inventory="dispatch-success" @@ -2803,7 +2805,7 @@ for direct_variant in native typed typed-native; do "$contract_fixture_dir/direct-skipped-$direct_variant.error" >&2 exit 1 fi - if rg -q 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/direct-skipped-$direct_variant.output"; then + if grep -Eq 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/direct-skipped-$direct_variant.output"; then echo "A direct publisher with a skipped image step was accepted for $direct_variant" >&2 exit 1 fi @@ -2879,7 +2881,7 @@ CONTRACT_DUPLICATE_EVENT=typed CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ echo "The fixture did not rerun the publisher during source revalidation" >&2 exit 1 } -if rg -q 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/publisher-rerun.output"; then +if grep -Eq 'Trusted PR image publisher .* succeeded' "$contract_fixture_dir/publisher-rerun.output"; then echo "A rerun publisher attempt was accepted using the predecessor attempt's job proof" >&2 exit 1 fi @@ -2938,10 +2940,10 @@ for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do [[ -f "$lookup_marker" ]] || { echo "Publisher lookup was not reached: $variant" >&2; exit 1; } done for fixture in missing-url empty-url; do - if CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$fixture.json" \ + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$fixture.json" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/$fixture.output" 2>"$contract_fixture_dir/$fixture.error"; then echo "$fixture unexpectedly verified publication" >&2 @@ -2959,12 +2961,12 @@ for fixture in dispatch-success dispatch-wrong-source dispatch-wrong-event dispa else source_inventory="" fi - if CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$fixture.json" \ + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$fixture.json" \ CONTRACT_SOURCE_PAYLOAD="$source_inventory" \ PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/$fixture.output" 2>"$contract_fixture_dir/$fixture.error"; then [[ "$fixture" == "dispatch-success" || "$fixture" == "dispatch-second-page" ]] || { echo "$fixture unexpectedly admitted publisher" >&2; exit 1; } From 4c66a4e9fce961f7da3377645260f2626c313030 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:12:42 +1300 Subject: [PATCH 090/199] Keep the stalled publisher fixture within its real watchdog --- .../tests/pr-retarget-workflow-contract.sh | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index caddbf8c28..6ee2421611 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2227,7 +2227,9 @@ if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then fi if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then : >"$CONTRACT_STALLED_LOOKUP_MARKER" - command sleep 12 + # A gh API request is a single process. Keep the blocked fixture so + # the inner timeout does not depend on cleanup of a shell's descendants. + exec sleep 12 fi cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-${CONTRACT_DUPLICATE_JOB:-success}.json"; exit 0 ;; *actions/runs/203/attempts/3/jobs?per_page=100) @@ -2419,22 +2421,14 @@ if [[ "${0##*/}" == "wait-for-runtime-images.sh" ]]; then unset SECONDS SECONDS=0 sleep() { - SECONDS=$((SECONDS + 1)) + # The actual blocked API call runs in a command substitution. Use its + # shared marker to advance the parent shell's clock after it returns. + if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" && -f "$CONTRACT_STALLED_LOOKUP_MARKER" ]]; then + SECONDS=$((SECONDS + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS)) + else + SECONDS=$((SECONDS + 1)) + fi } - if [[ -n "${CONTRACT_STALLED_LOOKUP_MARKER:-}" ]]; then - timeout() { - local timeout_budget="${2:-0}" timeout_status - if command timeout "$@"; then - timeout_status=0 - else - timeout_status=$? - fi - if [[ -f "$CONTRACT_STALLED_LOOKUP_MARKER" && "$timeout_status" -ne 0 ]]; then - SECONDS=$((SECONDS + timeout_budget)) - fi - return "$timeout_status" - } - fi fi EOF BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ @@ -2916,7 +2910,11 @@ BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ timeout 9s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/stalled-publisher.output" 2>"$contract_fixture_dir/stalled-publisher.error" || stalled_status=$? -[[ -f "$contract_fixture_dir/stalled-publisher.lookup" && "$stalled_status" == "1" ]] +if [[ ! -f "$contract_fixture_dir/stalled-publisher.lookup" || "$stalled_status" != "1" ]]; then + echo "Expected a real blocked publisher lookup and waiter exit 1, got $stalled_status" >&2 + cat "$contract_fixture_dir/stalled-publisher.output" "$contract_fixture_dir/stalled-publisher.error" >&2 + exit 1 +fi require_contains "$contract_fixture_dir/stalled-publisher.error" 'Timed out waiting for runtime-images workflow' for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do From cb90543acf8c68245566628bfc987025d8ed700a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:27:42 +1300 Subject: [PATCH 091/199] Give preview image-tag fixture exact publisher attempt evidence --- .../tests/preview-merge-image-tag-contract.sh | 86 +++++++++++++------ 1 file changed, 58 insertions(+), 28 deletions(-) diff --git a/dev-tools/tests/preview-merge-image-tag-contract.sh b/dev-tools/tests/preview-merge-image-tag-contract.sh index f48717969e..658b8e19d3 100644 --- a/dev-tools/tests/preview-merge-image-tag-contract.sh +++ b/dev-tools/tests/preview-merge-image-tag-contract.sh @@ -71,27 +71,42 @@ case "${GH_FIXTURE:-}" in branch_wrong) printf '[{"workflow_runs":[{"id":104,"status":"completed","conclusion":"success","event":"workflow_run","head_sha":"dddddddddddddddddddddddddddddddddddddd","html_url":"https://example.test/runtime/104","display_title":"Build Runtime Images trusted-branch branch-main sha-%s","created_at":"2026-09-21T00:02:00Z"}]}]' "$head_sha" ;; - success_runs) - if [[ "$*" == *publish-pr-runtime-images.yml* ]]; then - if [[ "$*" == *event=repository_dispatch* ]]; then - printf '%s' '{"total_count":0,"workflow_runs":[]}' - exit 0 - fi - printf '{"total_count":1,"workflow_runs":[{"id":102,"event":"workflow_run","status":"completed","conclusion":"success","display_title":"Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-7 base-%s head-%s merge-%s mode-required","created_at":"2026-09-21T00:01:00Z"}]}' "$base_sha" "$head_sha" "$merge_sha" - else - printf '[{"workflow_runs":[{"id":101,"status":"completed","conclusion":"success","event":"pull_request","head_sha":"%s","html_url":"https://example.test/runtime/101","display_title":"Build Runtime Images secure-pr-artifact pr-7 base-%s head-%s merge-%s mode-required","created_at":"2026-09-21T00:00:00Z"}]}]' "$head_sha" "$base_sha" "$head_sha" "$merge_sha" + success_runs|wrong_runs) + source_title="Build Runtime Images secure-pr-artifact pr-7 base-${base_sha} head-${head_sha} merge-${merge_sha} mode-required" + publisher_merge="$merge_sha" + if [[ "$GH_FIXTURE" == wrong_runs ]]; then + publisher_merge=dddddddddddddddddddddddddddddddddddddddd fi - ;; - wrong_runs) - if [[ "$*" == *publish-pr-runtime-images.yml* ]]; then - if [[ "$*" == *event=repository_dispatch* ]]; then + publisher_title="Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-7 base-${base_sha} head-${head_sha} merge-${publisher_merge} mode-required" + source="$(printf '{"id":101,"run_attempt":1,"status":"completed","conclusion":"success","event":"pull_request","head_sha":"%s","html_url":"https://example.test/runtime/101","display_title":"%s","created_at":"2026-09-21T00:00:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$head_sha" "$source_title")" + publisher="$(printf '{"id":102,"run_attempt":2,"status":"completed","conclusion":"success","event":"workflow_run","display_title":"%s","created_at":"2026-09-21T00:01:00Z","path":".github/workflows/publish-pr-runtime-images.yml","head_branch":"develop","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$publisher_title")" + case "$*" in + "api repos/example/firemud") + printf '%s' '{"full_name":"example/firemud","default_branch":"develop"}' + ;; + *actions/runs/101) + printf '%s' "$source" + ;; + *actions/runs/102) + printf '%s' "$publisher" + ;; + *actions/runs/102/attempts/2/jobs?per_page=100) + printf '%s' '{"total_count":1,"jobs":[{"run_id":102,"run_attempt":2,"name":"Publish Fixed PR Merge Image Tags","status":"completed","conclusion":"success","steps":[{"name":"Publish fixed PR image tags","status":"completed","conclusion":"success"}]}]}' + ;; + *actions/workflows/publish-pr-runtime-images.yml/runs?*event=workflow_run*) + printf '{"total_count":1,"workflow_runs":[%s]}' "$publisher" + ;; + *actions/workflows/publish-pr-runtime-images.yml/runs?*event=repository_dispatch*) printf '%s' '{"total_count":0,"workflow_runs":[]}' - exit 0 - fi - printf '{"total_count":1,"workflow_runs":[{"id":102,"event":"workflow_run","status":"completed","conclusion":"success","display_title":"Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-7 base-%s head-%s merge-dddddddddddddddddddddddddddddddddddddddd mode-required","created_at":"2026-09-21T00:01:00Z"}]}' "$base_sha" "$head_sha" - else - printf '[{"workflow_runs":[{"id":101,"status":"completed","conclusion":"success","event":"pull_request","head_sha":"%s","html_url":"https://example.test/runtime/101","display_title":"Build Runtime Images secure-pr-artifact pr-7 base-%s head-%s merge-%s mode-required","created_at":"2026-09-21T00:00:00Z"}]}]' "$head_sha" "$base_sha" "$head_sha" "$merge_sha" - fi + ;; + *actions/workflows/runtime-images.yml/runs?*) + printf '[{"workflow_runs":[%s]}]' "$source" + ;; + *) + echo "Unexpected runtime-image API request in $GH_FIXTURE fixture" >&2 + exit 2 + ;; + esac ;; *) echo "unknown GH_FIXTURE=${GH_FIXTURE:-}" >&2 @@ -138,35 +153,50 @@ if GH_FIXTURE=stale_head bash "$RESOLVER" "$merge_sha" 7 "$base_sha" >/dev/null exit 1 fi +cat >"$TEMP_DIR/waiter-clock.sh" <<'EOF' +if [[ "${0##*/}" == wait-for-runtime-images.sh ]]; then + unset SECONDS + SECONDS=0 + sleep() { + SECONDS=$((SECONDS + 1)) + } +fi +EOF +export BASH_ENV="$TEMP_DIR/waiter-clock.sh" + GH_FIXTURE=success_runs \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" >/dev/null + timeout 15s bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" >"$TEMP_DIR/publisher-success.out" +grep -Fq 'Trusted PR image publisher 102 succeeded' "$TEMP_DIR/publisher-success.out" # A publisher with a mismatched merge token must not satisfy the PR wait. -if GH_FIXTURE=wrong_runs \ - HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ - HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS=1 \ - HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha"; then +if wrong_merge_output="$( + GH_FIXTURE=wrong_runs \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ + HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS=1 \ + HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ + timeout 15s bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" 2>&1 +)"; then echo "waiter accepted a publisher for a different merge identity" >&2 exit 1 fi +grep -Fq 'No trusted PR image publisher appeared' <<<"$wrong_merge_output" GH_FIXTURE=branch_runs \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - bash "$WAITER" "$head_sha" >/dev/null + timeout 15s bash "$WAITER" "$head_sha" >/dev/null if branch_timeout_output="$( GH_FIXTURE=branch_wrong \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - bash "$WAITER" "$head_sha" 2>&1 + timeout 15s bash "$WAITER" "$head_sha" 2>&1 )"; then echo "branch waiter accepted a non-develop runtime image run" >&2 exit 1 From 868ce8a465829944557da4474275ce301dfabe92 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 21 Nov 2026 22:11:30 +1300 Subject: [PATCH 092/199] Recheck preview capacity before declining a request --- .github/workflows/preview-reconciler.yml | 11 ++++++-- dev-tools/tests/preview-priority-contract.sh | 29 +++++++++++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index ff2804f8a5..7b9e1c6dd3 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -305,8 +305,15 @@ jobs: return 1 fi if [[ "$priority" != true && "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is full." - return 1 + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + return 1 + fi fi return 0 fi diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index fbe2a43245..34ab633c6f 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -162,7 +162,7 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && *) printf '%s' "${1:-}" ;; esac } - snapshot_head="$(canonical_head "${FAKE_PR_901_HEAD:-}")" + snapshot_head="$(canonical_head "${FAKE_PR_901_SNAPSHOT_HEAD:-${FAKE_PR_901_HEAD:-}}")" snapshot_requested_head="$(canonical_head "${FAKE_PR_901_REQUESTED_HEAD:-}")" if [[ "$count" -gt 1 ]]; then if [[ -v FAKE_PR_901_RECHECK_HEAD ]]; then @@ -3092,6 +3092,33 @@ for namespace_count_sequence in 2,1 2,2; do fi done +for namespace_count_sequence in 2,1 2,2; do + reset_case + reconciler_capacity_refresh_output="$TEMP_DIR/reconciler-final-capacity-refresh-${namespace_count_sequence//,/-}.out" + export FAKE_NAMESPACE_COUNT_SEQUENCE="$namespace_count_sequence" + ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_PRIORITY=false \ + FAKE_PR_901_SNAPSHOT_HEAD=dddddddddddddddddddddddddddddddddddddddd \ + FAKE_PR_901_NAMESPACE_ABSENT_ON_RECHECK=true \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$reconciler_capacity_refresh_output" + test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 + test "$(<"$FAKE_NAMESPACE_LIST_CALLS")" -eq 2 + test ! -e "$FAKE_ANNOTATE_LOG" + if [[ "$namespace_count_sequence" == 2,1 ]]; then + grep -Fq 'Dispatching preview render for PR #901' "$reconciler_capacity_refresh_output" + test -s "$FAKE_DISPATCH_LOG" + else + grep -Fq 'Skipping ordinary PR #901: preview capacity is still full after refresh.' \ + "$reconciler_capacity_refresh_output" + test ! -e "$FAKE_DISPATCH_LOG" + fi +done + reset_case reconciler_preserved_proof_retry_output="$TEMP_DIR/reconciler-preserved-proof-retry.out" ( From 2df1383ec8cb18f6bc365c29390e8f27607afad0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:35:16 +1300 Subject: [PATCH 093/199] Pin the recovery upgrade fixture to its V1 writer --- ...ReleaseJournalPostgresIntegrationTest.java | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index b8009104eb..e1e2390ae8 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -79,6 +79,17 @@ class InitialGameplayReleaseJournalPostgresIntegrationTest { private static final UUID V1_EFFECT_ID = UUID.fromString("10000000-0000-0000-0000-000000000011"); private static final UUID V1_PRIOR_ATTEMPT_ID = UUID.fromString("10000000-0000-0000-0000-000000000012"); + // Fixed digests from the V1 writer at a066429d194f3ec6d54038f9581183c4943c82ed. + // Its canonical digest envelope predates the SQL V2 migration. + // Keep the inputs independent of the codec under test so the upgrade catches writer drift. + private static final String V1_SCOPE_DIGEST = + "ef9bbb81842b83253fcc6e6be7032ee744e563d109e4d0aab35146af85fe2c8f"; + private static final String V1_EVIDENCE_DIGEST = + "3c811a041f71b88c21c1d023b3fa3f489054c14603e333f8ae9edc32f34ef79e"; + private static final String V1_OPERATION_TUPLE_DIGEST = + "926bf0c737455039923849ac17a926440637204c2a4fa7a408f22dcac7c263cf"; + private static final String V1_PREPARE_EFFECT_PAYLOAD_DIGEST = + "2df3d23d85b96b45a6740be38a5edd357bddf15fc5c346cdc921911ecc3b7b63"; private static final String V1_SCOPE_PAYLOAD = """ { @@ -1502,18 +1513,8 @@ private static void assertImmutableV1Payloads( private static void seedImmutableV1Journal( DSLContext seedDsl, boolean claimed, Instant timestamp) { - Scope v1Scope = tupleCodec.readScope(V1_SCOPE_PAYLOAD); - InitialGameplayReleaseEvidence v1Evidence = tupleCodec.readEvidence(V1_EVIDENCE_PAYLOAD); - String scopeDigest = tupleCodec.digest(v1Scope); - String evidenceDigest = tupleCodec.digest(v1Evidence); - String operationTupleDigest = - tupleCodec.operationTupleDigest(v1Scope, V1_LOCK_IDENTITY, v1Evidence); String effectPayload = - V1_PREPARE_EFFECT_PAYLOAD_TEMPLATE.formatted(V1_SCOPE_PAYLOAD, operationTupleDigest); - var effect = - tupleCodec.readEffect( - EffectKind.PREPARE_PLAYABLE_STATE_FENCED.databaseValue(), effectPayload); - String payloadDigest = tupleCodec.digest(effect); + V1_PREPARE_EFFECT_PAYLOAD_TEMPLATE.formatted(V1_SCOPE_PAYLOAD, V1_OPERATION_TUPLE_DIGEST); seedDsl.execute( """ @@ -1532,11 +1533,11 @@ private static void seedImmutableV1Journal( V1_PEER_STORAGE_BINDING_PAYLOAD, V1_SCOPE_PAYLOAD, "immutable-initial-layout-evidence", - scopeDigest, + V1_SCOPE_DIGEST, V1_LOCK_IDENTITY, V1_EVIDENCE_PAYLOAD, "evidence-owner-record-31", - evidenceDigest, + V1_EVIDENCE_DIGEST, timestamp.atOffset(ZoneOffset.UTC), timestamp.atOffset(ZoneOffset.UTC)); @@ -1552,8 +1553,8 @@ private static void seedImmutableV1Journal( V1_OUTBOX_ID, V1_OPERATION_ID, V1_EFFECT_ID, - operationTupleDigest, - payloadDigest, + V1_OPERATION_TUPLE_DIGEST, + V1_PREPARE_EFFECT_PAYLOAD_DIGEST, effectPayload, claimed ? "dispatched" : "pending", claimed ? 1 : 0, From c78857f14ce9de0959c5abc72c3273df0437a20e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:07:35 +1300 Subject: [PATCH 094/199] Exercise exact direct publisher steps in skipped-step fixtures --- dev-tools/tests/pr-retarget-workflow-contract.sh | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 6ee2421611..0108130f91 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2215,6 +2215,9 @@ fi if [[ -n "${CONTRACT_DUPLICATE_DIR:-}" ]]; then case "$*" in *actions/runs/201/attempts/2/jobs?per_page=100) + if [[ -n "${CONTRACT_DIRECT_JOB_MARKER:-}" ]]; then + : >"$CONTRACT_DIRECT_JOB_MARKER" + fi if [[ "${CONTRACT_DUPLICATE_DIRECT_JOB:-success}" == "skipped" ]]; then cat "$CONTRACT_DUPLICATE_DIR/duplicate-jobs-201-skipped.json" else @@ -2556,7 +2559,7 @@ direct_typed_source = {**typed_source, "id": 104, "status": "completed", "conclu (root / "direct-typed-success-sources.json").write_text(json.dumps({ "workflow_runs": [direct_typed_source, typed_source], })) -direct_typed_publisher = {**alternate_publisher, "event": "repository_dispatch", +direct_typed_publisher = {**direct_publisher, "event": "repository_dispatch", "display_title": "Publish PR Runtime Images source-run-104"} (root / "duplicate-publisher-201-typed.json").write_text(json.dumps(direct_typed_publisher)) native_typed_direct_publisher = {**direct_publisher, "event": "workflow_run", @@ -2781,6 +2784,7 @@ for direct_variant in native typed typed-native; do if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT="$direct_event" \ CONTRACT_DUPLICATE_DIRECT_EVENT="$direct_event" CONTRACT_DUPLICATE_DIRECT_JOB=skipped \ CONTRACT_DUPLICATE_DIRECT_PUBLISHER="$direct_publisher_variant" \ + CONTRACT_DIRECT_JOB_MARKER="$contract_fixture_dir/direct-skipped-$direct_variant.checked" \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/$source_inventory.json" \ CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-publisher-only-$direct_variant.json" \ @@ -2793,7 +2797,11 @@ for direct_variant in native typed typed-native; do echo "A successful direct $direct_variant publisher workflow with a skipped image step must not be accepted" >&2 exit 1 fi - if ! grep -Fq 'Timed out waiting for trusted PR image publisher' \ + [[ -f "$contract_fixture_dir/direct-skipped-$direct_variant.checked" ]] || { + echo "The skipped-step fixture did not reach the exact publisher job for $direct_variant" >&2 + exit 1 + } + if ! grep -Eq 'Timed out waiting for trusted PR image publisher|Publisher coverage unavailable at the wait deadline' \ "$contract_fixture_dir/direct-skipped-$direct_variant.error"; then cat "$contract_fixture_dir/direct-skipped-$direct_variant.output" \ "$contract_fixture_dir/direct-skipped-$direct_variant.error" >&2 From 7d14718bab8297f5fe076606d77ea7331319e28b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:05:58 +1300 Subject: [PATCH 095/199] Close the retained review gaps in standalone foundations --- .github/workflows/ci.yml | 6 +- .github/workflows/preview-reconciler.yml | 219 +++++++++++++----- .github/workflows/smoke.yml | 22 +- .../infrastructure/deployment-environments.md | 2 +- .../preview/validate-preview-artifact.py | 8 +- .../hosted/shared/wait-for-runtime-images.sh | 41 +++- .../tests/ci-lightweight-scope-contract.sh | 10 +- .../pr-required-gate-context-contract.sh | 19 +- .../tests/pr-retarget-workflow-contract.sh | 50 ++-- .../pr-runtime-image-publication-contract.sh | 3 +- .../tests/preview-merge-image-tag-contract.sh | 30 ++- dev-tools/tests/preview-priority-contract.sh | 209 +++++++++++++++-- .../preview-runner-isolation-contract.sh | 32 +++ ...otected-pod-admission-workflow-contract.sh | 11 +- .../tests/static-analysis-summary-contract.sh | 4 +- dev-tools/validation/check-flyway-versions.py | 106 ++++++++- .../test_validate_preview_artifact.py | 13 ++ ...lDatabaseHostEnvironmentPostProcessor.java | 10 +- .../JooqInitialGameplayReleaseJournal.java | 6 + ...ReleaseJournalPostgresIntegrationTest.java | 211 ++++++++++++++++- ...abaseHostEnvironmentPostProcessorTest.java | 25 ++ 21 files changed, 900 insertions(+), 137 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 819c5f4053..f0a3c18900 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,6 +116,7 @@ jobs: // lightweight lane. Unrecognized service and runtime inputs keep full proof. let lightweightFallback = false; let fallbackPython = false; + let fallbackDesignDocs = false; if (!moduleScopeAvailable && scope.lightweightOnly === true && context.eventName === "pull_request") { try { @@ -134,6 +135,7 @@ jobs: const knownDoc = path => path === "README.md" || (typeof path === "string" && /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && !path.split("/").includes("..")); + const knownDesignDoc = path => knownDoc(path) && path.startsWith("design/"); const knownValidationPython = path => typeof path === "string" && /^dev-tools\/validation\/[A-Za-z0-9_./-]+\.py$/.test(path) && !path.split("/").includes("..") && @@ -151,6 +153,8 @@ jobs: (entry.previous_filename === undefined || knownLightweightPath(entry.previous_filename))); fallbackPython = lightweightFallback && entries.some(entry => knownValidationPython(entry.filename) || knownValidationPython(entry.previous_filename)); + fallbackDesignDocs = lightweightFallback && entries.some(entry => + knownDesignDoc(entry.filename) || knownDesignDoc(entry.previous_filename)); } catch { // Missing or incomplete native evidence keeps the full fallback. } @@ -163,7 +167,7 @@ jobs: docs_changed: scope.docsChanged, frontend_changed: scope.frontendChanged, python_changed: scope.pythonChanged || fallbackPython, - design_docs_changed: scope.designDocsChanged, + design_docs_changed: scope.designDocsChanged || fallbackDesignDocs, validation_python_changed: scope.validationPythonChanged || fallbackPython, postgres_runtime_proof_changed: scope.postgresRuntimeProofChanged === undefined ? true : scope.postgresRuntimeProofChanged, diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 7b9e1c6dd3..d161a7d147 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -255,6 +255,7 @@ jobs: local image_tag="$6" local require_deployed_tuple="$7" local priority="$8" + local expected_namespace_uid="$9" local fresh_namespace_json local fresh_namespace_tuple local current_base_sha @@ -326,6 +327,11 @@ jobs: proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "$require_deployed_tuple" == true && + ( -z "$expected_namespace_uid" || "$namespace_uid" != "$expected_namespace_uid" ) ]]; then + echo "Skipping PR #${pr_number}: namespace ${namespace} was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 + return 1 + fi if [[ "${current_base_sha}" != "${base_sha}" || "${current_head_sha}" != "${head_sha}" || "${current_merge_sha}" != "${merge_sha}" || @@ -474,9 +480,21 @@ jobs: } dispatch_sent=false completed_preview_source_updated_at="" + preview_source_skipped_render() { + local run_id="$1" attempt="$2" head="$3" + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + [.jobs[] | select(.name == "Render Sanitized Preview Artifact")] as $renders + | ($renders | length) <= 1 + and all($renders[]; .run_id == $id + and ((has("run_attempt") | not) or .run_attempt == $attempt) + and .head_sha == $head and .status == "completed" and .conclusion == "skipped") + ' + } + automatic_preview_has_tuple() { local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true - local event_tuple="${tuple/Preview resolved tuple /Preview event tuple }" + local dispatch_tuple="${tuple#Preview resolved tuple }" + local dispatch_title="Preview dispatch ${dispatch_tuple// /-}" # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 @@ -490,17 +508,83 @@ jobs: and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) and (if .status == "completed" then (.conclusion | type == "string" and length > 0) else true end) ' <<<"$latest" >/dev/null || return 2 - jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" ' - .id == $id and .head_sha == $head - and .event == $event and .workflow_id == $workflow_id - and .repository.full_name == $repository and .head_repository.full_name == $repository - and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 - and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) - ' <<<"$latest" >/dev/null || return 1 + if [[ "$event" == repository_dispatch ]]; then + jq -e --argjson id "$run_id" --arg head "$head" --arg title "$dispatch_title" \ + --arg event "$event" --arg workflow_name "$preview_workflow_name" \ + --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ + --arg default_branch "$DEFAULT_BRANCH" ' + .id == $id and .head_sha == $head + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch and .display_title == $title + and (.name == $workflow_name or .name == .display_title) + and (.path | IN(".github/workflows/preview.yml", + ".github/workflows/preview.yml@" + $default_branch, + ".github/workflows/preview.yml@refs/heads/" + $default_branch)) + ' <<<"$latest" >/dev/null || return 1 + else + jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" \ + --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ + --arg pr_title "PR preview ${pr}" ' + .id == $id and .head_sha == $head + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 + and .display_title == $pr_title + and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) + ' <<<"$latest" >/dev/null || return 1 + fi if jq -e '.status == "completed" and .conclusion != "success"' <<<"$latest" >/dev/null; then return 1; fi - if [[ "$event" == pull_request_target ]]; then return 2; fi [[ "$jobs_available" == true ]] || return 2 jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 + if [[ "$event" == repository_dispatch ]]; then + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) + and all($jobs[]; type == "object" and (.name | type == "string") + and (.run_id | type == "number" and . > 0 and . == floor) + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.status | type == "string") and (.conclusion | type == "string")) + and ([$jobs[] | select(.name == "Preview Plan")] | length) == 1 + and any($jobs[]; .name == "Preview Plan" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name == "Explain preview skip")] | length) <= 1) + ' <<<"$jobs" >/dev/null || return 2 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && + jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 + # A completed, successful, explicitly explained no-op cannot still hand off a render. + return 1 + fi + if ! jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | ([$jobs[] | select(.name == "Render Sanitized Preview Artifact")] | length) == 1 + and any($jobs[]; .name == "Render Sanitized Preview Artifact" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name == "Upload sanitized render artifact")] | length) == 1 + and any(.steps[]; .name == "Upload sanitized render artifact" + and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null; then + return 2 + fi + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" + return 3 + fi + return 0 + fi + if [[ "$event" == pull_request_target ]]; then return 2; fi jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' .jobs as $jobs | (($jobs | type) == "array") and (.total_count == ($jobs | length)) @@ -524,6 +608,14 @@ jobs: and .status == "completed" and .conclusion == "success") end)) ' <<<"$jobs" >/dev/null || return 2 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && + jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 + return 1 + fi if jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) ' <<<"$jobs" >/dev/null; then @@ -534,16 +626,6 @@ jobs: and .status == "completed" and .conclusion == "success") ' <<<"$jobs" >/dev/null; then return 1 - elif jq -e --arg tuple "$event_tuple" ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - .name == $tuple - and .status == "completed" and .conclusion == "success") - and any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") - ' <<<"$jobs" >/dev/null && - jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then - # A completed successful plan with its successful skip explanation proves no deployable plan ran. - return 1 elif jq -e --arg prefix "Preview event tuple pr-${pr} base-" ' any(.jobs[] | select(.name == "Preview Plan") | .steps[]; (.name | startswith($prefix)) and .status == "completed" and .conclusion == "success") @@ -564,62 +646,91 @@ jobs: fi } + completed_preview_inventory() { + local event="$1" filter="$2" pages + # The handoff window measures completion (updated_at), not + # creation. An older run can finish or be rerun just before the scan. + pages="$(timeout 30s gh api --method GET --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ + -f "event=${event}" -f status=completed -f per_page=100 -f "$filter")" || return 1 + jq -ce --argjson workflow_id "$preview_workflow_id" --arg event "$event" ' + select(type == "array" and length > 0 and length <= 10) + | .[0].total_count as $count + | select(($count | type) == "number" and $count >= 0 and $count < 1000 + and $count == ($count | floor)) + | select(all(.[]; type == "object" and .total_count == $count + and (.workflow_runs | type == "array" and length <= 100))) + | [.[].workflow_runs[]] as $runs + | select(($runs | length) == $count + and ([$runs[].id] | unique | length) == $count + and all($runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) + and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) + and .event == $event and .status == "completed" + and (.conclusion | type == "string") and (.name | type == "string") + and (.display_title | type == "string") and (.head_branch | type == "string") + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | type == "string") + and (.updated_at | type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")) + and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") + and (if $event == "pull_request" then (.pull_requests | type == "array") else true end))) + | {workflow_runs: $runs} + ' <<<"$pages" + } + recent_successful_source_handoff() { local pr_number="$1" head_sha="$2" tuple_step="$3" - local source_runs source_candidates source_candidate_count source_inventory_now + local source_runs dispatch_source_runs source_candidates source_candidate_count source_inventory_now local run_id run_attempt run_event run_head run_updated_at lookup_status source_updated_epoch now_epoch source_age local consumer_runs consumer_candidates consumer_candidate_count local consumer_run_id consumer_attempt consumer_head consumer_status consumer_created_after local run_name="Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" local pr_title="PR preview ${pr_number}" - if ! source_runs="$(gh api --method GET \ - "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ - -f event=pull_request -f status=completed -f per_page=100 -f "head_sha=${head_sha}")"; then - echo "Unable to inspect recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 - return 2 - fi - if ! jq -e --argjson workflow_id "$preview_workflow_id" 'type == "object" - and (.total_count | type == "number" and . >= 0 and . == floor) - and (.workflow_runs | type == "array" and length <= 100) - and (.total_count == (.workflow_runs | length)) - and all(.workflow_runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) - and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) - and (.event | type == "string") and (.status | type == "string") - and (.conclusion | type == "string") and (.name | type == "string") - and (.display_title | type == "string") and (.head_branch | type == "string") - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.path | type == "string") - and (.updated_at | type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")) - and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") - and (.pull_requests | type == "array"))' <<<"$source_runs" >/dev/null; then - echo "Recent completed preview-source inventory is malformed or truncated; retry budget unchanged." >&2 + source_inventory_now="$(date -u +%s)" + if ! source_runs="$(completed_preview_inventory pull_request "head_sha=${head_sha}")" || + ! dispatch_source_runs="$(completed_preview_inventory repository_dispatch "branch=${DEFAULT_BRANCH}")"; then + echo "Recent completed preview-source inventory is unavailable, malformed, or truncated; retry budget unchanged." >&2 return 2 fi - source_inventory_now="$(date -u +%s)" - if ! source_candidates="$(jq -r \ + if ! source_candidates="$(printf '%s\n' "$source_runs" "$dispatch_source_runs" | jq -r -s \ --arg repository "$GITHUB_REPOSITORY" --arg head "$head_sha" \ - --arg workflow_name "$preview_workflow_name" --arg pr_title "$pr_title" \ - --arg run_name "$run_name" --argjson workflow_id "$preview_workflow_id" \ + --arg default_branch "$DEFAULT_BRANCH" --arg workflow_name "$preview_workflow_name" \ + --arg pr_title "$pr_title" --arg run_name "$run_name" \ + --argjson workflow_id "$preview_workflow_id" \ --argjson now "$source_inventory_now" --argjson window "$preview_handoff_window_seconds" \ --argjson pr_number "$pr_number" ' def positive_int: type == "number" and . > 0 and . == floor; - [ .workflow_runs[] + [ (.[0].workflow_runs[] | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) and .workflow_id == $workflow_id and .event == "pull_request" and .status == "completed" and .conclusion == "success" and (.name == $workflow_name or .name == .display_title) - and (.display_title == $pr_title or .display_title == $run_name) + and .display_title == $pr_title and .repository.full_name == $repository and .head_repository.full_name == $repository and .head_sha == $head and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) - | (.updated_at | fromdateiso8601) as $updated + | [.id, .run_attempt, .event, .head_sha, .updated_at]), + (.[1].workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "repository_dispatch" + and .status == "completed" and .conclusion == "success" + and (.name == $workflow_name or .name == .display_title) + and .display_title == $run_name + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch + and (.path | IN(".github/workflows/preview.yml", + ".github/workflows/preview.yml@" + $default_branch, + ".github/workflows/preview.yml@refs/heads/" + $default_branch))) + | [.id, .run_attempt, .event, .head_sha, .updated_at]) + ] + | map(.[4] as $updated_at + | ($updated_at | fromdateiso8601) as $updated | select($updated <= $now and ($now - $updated) < $window) - | [.id, .run_attempt, .event, .head_sha, .updated_at] - ] | sort_by(.[0]) | reverse | .[] | @tsv - ' <<<"$source_runs")"; then + | .) + | sort_by(.[0]) | reverse | .[] | @tsv + ')"; then echo "Unable to parse recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 return 2 fi @@ -633,7 +744,7 @@ jobs: [[ -n "$run_id" ]] || continue completed_preview_source_updated_at="" lookup_status=0 - automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? if [[ "$lookup_status" -eq 2 ]]; then echo "Recent preview-source attempt ${run_id} could not be verified; retry budget unchanged." >&2 return 2 @@ -1051,7 +1162,7 @@ jobs: if [[ "$run_event" == workflow_run ]]; then trusted_consumer_has_tuple "$run_id" "$run_attempt" "$run_head" "$consumer_tuple" || lookup_status=$? else - automatic_preview_has_tuple "$run_id" "$run_attempt" "$head_sha" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? fi if [[ "$lookup_status" -eq 0 ]]; then active_preview_run_id="$run_id" @@ -1118,7 +1229,7 @@ jobs: local proof_retry_reservation_merge_sha="" local proof_retry_reservation_image_tag="" prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ - "$require_deployed_tuple" "$priority" || continue + "$require_deployed_tuple" "$priority" "$namespace_uid" || continue echo "Dispatching preview render for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag}) from trusted ref ${DEFAULT_BRANCH}" dispatch_exit=0 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 242bd12d3c..de86eb380e 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1182,15 +1182,15 @@ jobs: retryPrimary: retryPrimary?.identity === identityKey(currentIdentity) ? retryPrimary : null, }; retryPrimary = null; - async function resumePendingPrimary(message) { + async function retryExactSelection(message, { requirePendingPrimary = true } = {}) { const remainingMs = timeoutMs - (Date.now() - started); - if (!selection.pendingPrimary || remainingMs <= 0) return false; + if (remainingMs <= 0 || (requirePendingPrimary && !selection.pendingPrimary)) return false; core.warning(message); - retryPrimary = { + retryPrimary = selection.pendingPrimary ? { id: selection.pendingPrimary.id, run_attempt: selection.pendingPrimary.run_attempt, identity: identityKey(currentIdentity), - }; + } : null; await new Promise((resolve) => setTimeout(resolve, Math.min(sleepMs, remainingMs))); return true; } @@ -1375,7 +1375,7 @@ jobs: } catch (error) { // Re-read the pending comparison on the next bounded poll. No // partial evidence from this alternative carries into that poll. - if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( + if (isTransientOptionalGitHubError(error) && await retryExactSelection( `Runtime alternative ${matching.id} jobs are temporarily unavailable; retry exact primary selection.` )) continue smokeGatePolling; throw error; @@ -1430,7 +1430,7 @@ jobs: )); continue; } - if (await resumePendingPrimary( + if (await retryExactSelection( `Runtime alternative ${matching.id} never exposed a complete smoke snapshot; retry exact primary selection.` )) continue smokeGatePolling; // With no pending primary, only the same run's provably newer attempt warrants reselection. @@ -1533,8 +1533,9 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) )); } catch (error) { - if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( - `Runtime alternative ${matching.id} final attempt is temporarily unavailable; retry exact primary selection.` + if (isTransientOptionalGitHubError(error) && await retryExactSelection( + `Runtime run ${matching.id} final attempt is temporarily unavailable; retry exact selection.`, + { requirePendingPrimary: false } )) continue smokeGatePolling; throw error; } @@ -1563,8 +1564,9 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) )); } catch (error) { - if (isTransientOptionalGitHubError(error) && await resumePendingPrimary( - `Runtime alternative ${matching.id} final current-base attempt is temporarily unavailable; retry exact primary selection.` + if (isTransientOptionalGitHubError(error) && await retryExactSelection( + `Runtime run ${matching.id} final current-base attempt is temporarily unavailable; retry exact selection.`, + { requirePendingPrimary: false } )) continue smokeGatePolling; throw error; } diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 8afab81148..7e76cfe31c 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -357,7 +357,7 @@ The hosted identity controller's egress boundary is exact-destination and operat - Preview deploys currently reset the namespace before each Helm apply, then reseed the minimum bootstrap state needed for reviewer proof. Within one deployed preview instance, PostgreSQL, MinIO/object storage, and other stateful components persist across normal pod restarts and VM reboot, but preview state does not currently persist across preview redeploys. - Preview state is not backed up and is not durable beyond the single preview node. If the node or its attached storage is lost, preview state is lost. - The initial Hetzner/k3s sizing target is one reliably usable full-stack preview on an 8 GB shared-CPU x86 VM. A second concurrent preview is best-effort only and may fail to deploy if capacity is exhausted. -- Hosted dev and preview app services share one JVM footprint profile owned by `previewStack.jvm` in the [hosted Helm chart values](../../../k8s/helm/firemud/values.yaml): C1-only JIT, a 64 MiB reserved code cache, 512 KiB thread stacks, and two glibc malloc arenas. It trades peak JIT throughput for lower resident memory and does not apply to the player-facing Kustomize overlays. +- Hosted dev and preview app services share one JVM footprint profile owned by `previewStack.jvm` in the [hosted Helm chart values](../../../k8s/helm/firemud/values.yaml): C1-only JIT, a 64 MiB reserved code cache, 512 KiB thread stacks, and two glibc malloc arenas. It trades peak JIT throughput for lower resident memory and does not apply to the player-facing Kustomize overlays. The trusted preview validator also accepts the exact Gateway environment from supported merge bases that omit both footprint settings. Both forms require the same identity, routing, and trust wiring. - Open, mergeable, non-dependency-bot same-repository pull requests targeting `main` or `develop` request preview allocation automatically. A stacked pull request whose base is another current branch in the same repository is eligible only while it carries the maintainer-controlled `preview:priority` label; forks and dependency-bot updates remain ineligible. Ordinary allocation in the bounded two-slot pool is first-come at the serialized allocation boundary while capacity remains available; GitHub's raw job-scheduling order is not itself an allocation guarantee. The priority label lets a later priority request claim a free slot or reclaim the oldest ordinary preview, but never another currently priority-labelled preview. Allocation, deployment, hosted proof, reclaim, and cleanup share one durable bounded non-cancelling lifecycle queue so a running proof is not deleted underneath itself and normal waiting lifecycle work uses GitHub's expanded queue instead of its replaceable single pending slot. Both target and victim label state are re-read immediately before reclaim. Removing the label from an ordinary `main`/`develop` pull request returns its environment to ordinary status; removing it from a stacked pull request makes that preview ineligible and permits trusted cleanup. A displaced pull request keeps its ordinary CI and historical preview result, while its current hosted status reports that no environment is allocated. - Each successfully allocated eligible preview receives its own namespace and holds a bounded renewable visible lease. An ordinary active lease is protected except for the explicit priority rule above; a priority-labelled active lease is not silently evicted, while an expired lease may be reclaimed even if the pull request remains open. A request that is eligible but not allocated, including because capacity is exhausted or every slot is priority-protected, reports `preview_unavailable`, not passed. - Any review claiming hosted proof requires successful evidence for its current base SHA, head SHA, two-parent merge SHA, and selected immutable image tag. A parent advance invalidates the prior proof even when the child head is unchanged. diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 5212ba9b34..4821271bcf 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -931,7 +931,13 @@ def _expected_gateway_container_env(expected_namespace: str) -> list[dict]: def _validate_gateway_container_environment(container: dict, expected_namespace: str) -> None: - if container.get("env") != _expected_gateway_container_env(expected_namespace): + expected = _expected_gateway_container_env(expected_namespace) + # The default-branch validator can receive a supported merge base whose + # Gateway chart predates the two JVM footprint settings. + without_footprint_tuning = [ + entry for entry in expected if entry["name"] not in {"JAVA_TOOL_OPTIONS", "MALLOC_ARENA_MAX"} + ] + if container.get("env") not in (expected, without_footprint_tuning): fail("Deployment/spring-cloud-gateway has an unsafe container env") if container.get("envFrom") != EXPECTED_GATEWAY_ENV_FROM: fail("Deployment/spring-cloud-gateway has an unsafe envFrom contract") diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 93e3890cb3..990aa9fdc3 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -434,6 +434,36 @@ find_completed_alternate_publication() { return 1 } +branch_publication_attempt() { + jq -er --argjson id "$1" --arg repo "$GITHUB_REPOSITORY" ' + select(.id == $id and .repository.full_name == $repo and .head_repository.full_name == $repo + and .status == "completed" and .conclusion == "success") + | .run_attempt | select(type == "number" and . >= 1 and floor == .) + ' +} + +verify_branch_publication() { + local run_id="$1" selected_state="$2" endpoint run attempt jobs latest + endpoint="repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}" + run="$(fetch_alternate_run_metadata "$deadline" "$endpoint")" || return 1 + [[ "$(jq -c '{workflow_runs:[.]}' <<<"$run" | read_run_state)" == "$selected_state" ]] || return 1 + attempt="$(branch_publication_attempt "$run_id" <<<"$run")" || return 1 + jobs="$(fetch_alternate_run_metadata "$deadline" "${endpoint}/attempts/${attempt}/jobs?per_page=100")" || return 1 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" ' + (.jobs | type == "array") and (.total_count == (.jobs | length)) and + ([.jobs[] | select(.name == "Promote Smoke-Tested Runtime Images")] as $jobs | + ($jobs | length) == 1 and ($jobs[0] | + .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and + .status == "completed" and .conclusion == "success" and + ([.steps[] | select(.name == "Promote smoke-tested service digests")] as $steps | + ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) + ' <<<"$jobs" >/dev/null || return 1 + latest="$(fetch_alternate_run_metadata "$deadline" "$endpoint")" || return 1 + [[ "$(branch_publication_attempt "$run_id" <<<"$latest")" == "$attempt" && + "$(jq -c '{workflow_runs:[.]}' <<<"$latest" | read_run_state)" == "$selected_state" ]] && + (( SECONDS < deadline )) +} + wait_for_pr_publisher() { local source_state="$1" local alternate_sources="$2" @@ -482,11 +512,13 @@ wait_for_pr_publisher() { if [[ "${fetch_failed}" == "false" ]] && publisher_state="$(read_publisher_state "${source_run_id}" "${source_state_event}" <<<"${publisher_payload}")"; then IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" - if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then + if [[ "${run_status}" == "completed" ]]; then if use_completed_duplicate_publication "$source_state" "$publisher_deadline" direct; then return 0 fi - direct_success_unproven=true + if [[ "${run_conclusion}" == "success" ]]; then + direct_success_unproven=true + fi fi fi local refreshed_source_payload refreshed_alternates @@ -595,6 +627,11 @@ while (( SECONDS < deadline )); do fi if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then + if [[ "${wait_mode}" == "branch" ]] && ! verify_branch_publication "$run_id" "$run_state"; then + printf 'Trusted branch runtime-image run %s has no verified promotion for %s yet.\n' "$run_id" "$image_tag" >&2 + sleep "${sleep_seconds}" + continue + fi 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 diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index c083534b57..ffef54fc56 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -43,9 +43,10 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput assert.deepEqual(JSON.parse(outputs.bootable_modules), compatible ? ["account-service"] : [...BOOTABLE_MODULES]); } - for (const [entries, count, expected, drift, expectsPython = false] of [ - [[{filename: "design/README.md"}], 1, true], + for (const [entries, count, expected, drift, expectsPython = false, expectsDesignDocs = false] of [ + [[{filename: "design/README.md"}], 1, true, undefined, false, true], [[{filename: "README.md"}], 1, true], + [[{filename: "README.md", status: "renamed", previous_filename: "design/guide.md"}], 1, true, undefined, false, true], [[{filename: "dev-tools/validation/check-flyway-versions.py"}], 1, true, undefined, true], [[{filename: "dev-tools/validation/gradle-run-supervisor.py"}], 1, false], [[{filename: "services/recovery-controller-service/src/main/java/Example.java"}], 1, false], @@ -58,13 +59,13 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput [[{filename: "services/new-service/README.md"}], 1, false], [[{filename: "design/README.md", previous_filename: "services/new-service/Main.java"}], 1, false], [[{filename: "design/../services/Main.md"}], 1, false], - [[{filename: "design/README.md", previous_filename: "docs/old.md"}], 1, true], + [[{filename: "design/README.md", previous_filename: "docs/old.md"}], 1, true, undefined, false, true], ]) { const outputs = {}; await execute(name => name === "node:fs" ? {existsSync: () => true} : { ALL_MODULES: ALL_MODULES.filter(module => module !== "recovery-controller-service"), classifyGithubChangeScope: async () => ({runAll: false, affectedModules: [], - bootableModules: [], affectedServices: [], lightweightOnly: true}), + bootableModules: [], affectedServices: [], lightweightOnly: true, designDocsChanged: false}), }, {rest: {pulls: {listFiles() {}, get: (() => { let calls = 0; return async () => { const call = calls++; return ({data: {number: 42, changed_files: count, @@ -79,6 +80,7 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput assert.equal(outputs.lightweight_only, String(expected)); assert.equal(outputs.validation_python_changed, String(expectsPython)); assert.equal(outputs.python_changed, String(expectsPython)); + assert.equal(outputs.design_docs_changed, String(expectsDesignDocs)); assert.equal(outputs.run_all, String(!expected)); assert.deepEqual(JSON.parse(outputs.affected_modules), expected ? [] : ALL_MODULES); assert.deepEqual(JSON.parse(outputs.bootable_modules), expected ? [] : [...BOOTABLE_MODULES]); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 36d9b4b0f4..9d287e9cb3 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -195,6 +195,8 @@ def isolates_metadata_group(group, run_scoped): substantive = [effective_group(group, action, base_ref) for action, base_ref in ( ("edited", "develop"), ("opened", None), ("synchronize", None), ("reopened", None), )] + if len({name.casefold() for name in substantive}) != 1: + return False return metadata.endswith(expected_suffix) and all( name != metadata and name.endswith("-required") for name in substantive ) @@ -551,6 +553,7 @@ const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); async function scenario(outcome, completedAtMinutes, selectionCase = "single") { let now = 1000; + let runLookups = 0; const start = now; const failures = []; const cancelledReads = new Set(); @@ -573,9 +576,14 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, 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: cancelledReads.has(run_id) ? "cancelled" : "success"}}) }, + getWorkflowRun: async ({run_id}) => { + runLookups += 1; + if (selectionCase === "sole-final-attempt-transient" && runLookups <= 4) { + throw Object.assign(new Error("final attempt temporarily unavailable"), {status: 503}); + } + return {data: {id: run_id, run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1, + status: "completed", conclusion: cancelledReads.has(run_id) ? "cancelled" : "success"}}; + } }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); assert.equal(input.attempt_number, 1); @@ -644,12 +652,15 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { 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, runLookups }; } (async () => { const success = await scenario("success", 30); assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); assert.equal(success.minutes, 30); + const recovered = await scenario("success", 0, "sole-final-attempt-transient"); + assert.deepEqual(recovered.failures, [], "the sole exact producer may recover after bounded final-read retries"); + assert.equal(recovered.runLookups, 5, "reselection must perform a new final exact-attempt check"); const failed = await scenario("failure", 30); assert.equal(failed.failures.length, 1); assert.match(failed.failures[0], /did not complete successfully/); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 0108130f91..36b562d40e 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2389,6 +2389,9 @@ import sys payload = json.load(open(sys.argv[1])) event = re.search(r"event=([^&]+)", sys.argv[2]).group(1) page_number = int(re.search(r"&page=([0-9]+)", sys.argv[2]).group(1)) +if isinstance(payload, dict) and "fixture_events" in payload: + payload = payload["fixture_events"].get(event, {"total_count": 0, "workflow_runs": []}) + payload["fixture_event"] = event pages = payload if isinstance(payload, list) else [payload] page = pages[min(page_number - 1, len(pages) - 1)] if page.get("fixture_event", "repository_dispatch") != event: @@ -2571,6 +2574,12 @@ old_native_typed_publisher = {**native_typed_direct_publisher, (root / "duplicate-publisher-201-typed-native.json").write_text(json.dumps(native_typed_direct_publisher)) (root / "duplicate-publisher-201-typed-native-old.json").write_text(json.dumps(old_native_typed_publisher)) (root / "duplicate-publisher-typed-native.json").write_text(json.dumps(native_typed_alternate_publisher)) +(root / "typed-failed-after-native.json").write_text(json.dumps({"fixture_events": { + "workflow_run": {"total_count": 1, "workflow_runs": [native_typed_direct_publisher]}, + "repository_dispatch": {"total_count": 1, "workflow_runs": [ + {**direct_typed_publisher, "id": 205, "conclusion": "failure", "created_at": "2026-07-24T00:08:00Z"}, + ]}, +}})) for event, publisher_run, fixture_event in [ ("native", direct_publisher, "workflow_run"), ("typed", direct_typed_publisher, "repository_dispatch"), @@ -2813,22 +2822,24 @@ for direct_variant in native typed typed-native; do fi done -BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ - CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native \ - CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_DIRECT_JOB=success \ - CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ - CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/direct-publisher-only-typed-native.json" \ - PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ - HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ - timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ - >"$contract_fixture_dir/typed-native-direct.output" 2>"$contract_fixture_dir/typed-native-direct.error" || { - cat "$contract_fixture_dir/typed-native-direct.output" "$contract_fixture_dir/typed-native-direct.error" >&2 - exit 1 - } -require_contains "$contract_fixture_dir/typed-native-direct.output" \ - 'Trusted PR image publisher 201 succeeded for pr-merge-' -require_contains "$contract_fixture_dir/typed-native-direct.output" 'as the direct source' +for publisher_fixture in direct-publisher-only-typed-native typed-failed-after-native; do + BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native \ + CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_DIRECT_JOB=success \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$publisher_fixture.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/typed-native-direct.output" 2>"$contract_fixture_dir/typed-native-direct.error" || { + cat "$contract_fixture_dir/typed-native-direct.output" "$contract_fixture_dir/typed-native-direct.error" >&2 + exit 1 + } + require_contains "$contract_fixture_dir/typed-native-direct.output" \ + 'Trusted PR image publisher 201 succeeded for pr-merge-' + require_contains "$contract_fixture_dir/typed-native-direct.output" 'as the direct source' +done if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native-old \ @@ -2868,6 +2879,7 @@ require_contains "$contract_fixture_dir/cached-refresh.output" \ 'Trusted PR image publisher 202 succeeded for pr-merge-' require_contains "$contract_fixture_dir/cached-refresh.output" 'via an alternate producer' +publisher_rerun_status=0 CONTRACT_DUPLICATE_EVENT=typed CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ CONTRACT_RERUN_PUBLISHER_ON_SOURCE_RECHECK="$contract_fixture_dir/publisher-rerun-marker" \ CONTRACT_SOURCE_READ_STATE="$contract_fixture_dir/source-read-state" \ @@ -2878,7 +2890,11 @@ CONTRACT_DUPLICATE_EVENT=typed CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ BASH_ENV="$contract_fixture_dir/publisher-clock.sh" \ timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ - >"$contract_fixture_dir/publisher-rerun.output" 2>"$contract_fixture_dir/publisher-rerun.error" || : + >"$contract_fixture_dir/publisher-rerun.output" 2>"$contract_fixture_dir/publisher-rerun.error" || publisher_rerun_status=$? +[[ "$publisher_rerun_status" == 1 ]] || { + echo "Expected the runtime waiter to exit 1 after rejecting the superseded attempt, got $publisher_rerun_status" >&2 + exit 1 +} [[ -f "$contract_fixture_dir/publisher-rerun-marker" ]] || { echo "The fixture did not rerun the publisher during source revalidation" >&2 exit 1 diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1202ef6402..976dbb46a6 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -45,6 +45,7 @@ with tempfile.TemporaryDirectory() as temporary: 'printf "%s\\n" "$FIXTURE_LIVE_HEAD"\n') stub.chmod(0o755) for event in ("workflow_run", "workflow_dispatch"): + event_sha = "c" * 40 if event == "workflow_run" else branch_head script = meta for expression, value in { "github.event_name": event, "github.event.workflow_run.event": "push", @@ -55,7 +56,7 @@ with tempfile.TemporaryDirectory() as temporary: output.write_text("") environment = { **os.environ, "PATH": temporary + ":" + os.environ["PATH"], - "GITHUB_REPOSITORY": "owner/repo", "GITHUB_SHA": branch_head, + "GITHUB_REPOSITORY": "owner/repo", "GITHUB_SHA": event_sha, "GITHUB_REF_NAME": "develop", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1", "GITHUB_OUTPUT": str(output), "FIXTURE_LIVE_HEAD": live_head, "EVENT_HEAD_BRANCH": "develop", "EVENT_HEAD_SHA": "", diff --git a/dev-tools/tests/preview-merge-image-tag-contract.sh b/dev-tools/tests/preview-merge-image-tag-contract.sh index 658b8e19d3..079daec647 100644 --- a/dev-tools/tests/preview-merge-image-tag-contract.sh +++ b/dev-tools/tests/preview-merge-image-tag-contract.sh @@ -65,8 +65,25 @@ case "${GH_FIXTURE:-}" in empty) printf '%s' '[[]]' ;; - branch_runs) - printf '[{"workflow_runs":[{"id":103,"status":"completed","conclusion":"success","event":"workflow_run","head_sha":"dddddddddddddddddddddddddddddddddddddd","html_url":"https://example.test/runtime/103","display_title":"Build Runtime Images trusted-branch branch-develop sha-%s","created_at":"2026-09-21T00:02:00Z"}]}]' "$head_sha" + branch_runs|branch_obsolete) + source="$(printf '{"id":103,"run_attempt":2,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/103","display_title":"Build Runtime Images trusted-branch branch-develop sha-%s","created_at":"2026-09-21T00:02:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$head_sha")" + case "$*" in + *actions/runs/103) + printf '%s' "$source" + ;; + *actions/runs/103/attempts/2/jobs?per_page=100) + conclusion=success + [[ "$GH_FIXTURE" != branch_obsolete ]] || conclusion=skipped + printf '{"total_count":1,"jobs":[{"run_id":103,"run_attempt":2,"name":"Promote Smoke-Tested Runtime Images","status":"completed","conclusion":"%s","steps":[{"name":"Promote smoke-tested service digests","status":"completed","conclusion":"%s"}]}]}' "$conclusion" "$conclusion" + ;; + *actions/workflows/runtime-images.yml/runs?*) + printf '[{"workflow_runs":[%s]}]' "$source" + ;; + *) + echo "Unexpected branch runtime-image API request in $GH_FIXTURE fixture" >&2 + exit 2 + ;; + esac ;; branch_wrong) printf '[{"workflow_runs":[{"id":104,"status":"completed","conclusion":"success","event":"workflow_run","head_sha":"dddddddddddddddddddddddddddddddddddddd","html_url":"https://example.test/runtime/104","display_title":"Build Runtime Images trusted-branch branch-main sha-%s","created_at":"2026-09-21T00:02:00Z"}]}]' "$head_sha" @@ -191,6 +208,15 @@ GH_FIXTURE=branch_runs \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ timeout 15s bash "$WAITER" "$head_sha" >/dev/null +if branch_obsolete_output="$( + GH_FIXTURE=branch_obsolete HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 15s bash "$WAITER" "$head_sha" 2>&1 +)"; then + echo "branch waiter accepted a successful obsolete run without promotion" >&2 + exit 1 +fi +grep -Fq 'Trusted branch runtime-image run 103 has no verified promotion' <<<"$branch_obsolete_output" + if branch_timeout_output="$( GH_FIXTURE=branch_wrong \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 34ab633c6f..2359641880 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -185,6 +185,9 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_requested_image="" fi snapshot_uid="${FAKE_PR_901_NAMESPACE_UID:-uid-pr-901}" + if [[ "$count" -gt 1 && -v FAKE_PR_901_RECHECK_NAMESPACE_UID ]]; then + snapshot_uid="$FAKE_PR_901_RECHECK_NAMESPACE_UID" + fi snapshot_retry_count="${FAKE_PR_901_PROOF_RETRY_COUNT:-}" snapshot_retry_base="${FAKE_PR_901_PROOF_RETRY_BASE_SHA:-}" snapshot_retry_head="${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" @@ -551,25 +554,30 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/hos exit 0 fi if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/173511323/runs' ]]; then - if [[ "$*" != *"--method GET"* || "$*" != *"event=pull_request"* || - "$*" != *"status=completed"* || "$*" != *"head_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* || - "$*" == *"head="* ]]; then - echo "recent source inventory did not use bounded GET/head_sha query parameters: $*" >&2 + if [[ "$*" != *"--method GET"* || "$*" != *"status=completed"* || + "$*" != *"per_page=100"* || "$*" != *"--paginate --slurp"* || + "$*" == *"created="* || "$*" == *"head="* ]]; then + echo "recent source inventory must paginate without a creation-time cutoff: $*" >&2 exit 1 fi if [[ "$*" == *"event=pull_request"* ]]; then - if [[ -v FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON ]]; then - printf '%s' "$FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON" - else - printf '%s' '{"total_count":0,"workflow_runs":[]}' + if [[ "$*" != *"head_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* ]]; then + echo "recent pull_request inventory omitted its exact head SHA filter: $*" >&2 + exit 1 fi - else - if [[ -v FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON ]]; then - printf '%s' "$FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON" - else - printf '%s' '{"total_count":0,"workflow_runs":[]}' + payload="${FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON:-}" + elif [[ "$*" == *"event=repository_dispatch"* ]]; then + if [[ "$*" != *"branch=develop"* || "$*" == *"head_sha="* ]]; then + echo "recent repository_dispatch inventory did not use the trusted default-branch filter: $*" >&2 + exit 1 fi + payload="${FAKE_RECENT_PREVIEW_DISPATCH_RUNS_JSON:-}" + else + echo "recent source inventory used an unexpected event filter: $*" >&2 + exit 1 fi + [[ -n "$payload" ]] || payload='{"total_count":0,"workflow_runs":[]}' + jq -c 'if type == "array" then . else [.] end' <<<"$payload" exit 0 fi if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/357129350/runs' ]]; then @@ -633,6 +641,14 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5254' ]] printf '%s' "${FAKE_PREVIEW_SOURCE_LATEST_JSON:-null}" exit 0 fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5255/attempts/1/jobs?per_page=100' ]]; then + printf '%s' "${FAKE_PREVIEW_DISPATCH_JOBS_JSON:-null}" + exit 0 +fi +if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/runs/5255' ]]; then + printf '%s' "${FAKE_PREVIEW_DISPATCH_LATEST_JSON:-null}" + exit 0 +fi if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9])/attempts/1/jobs\?per_page=100$ ]]; then [[ "${FAKE_TRUSTED_CONSUMER_JOBS_FAIL:-false}" != true ]] || exit 1 run_id="${BASH_REMATCH[1]}" @@ -1218,8 +1234,12 @@ reset_case() { export FAKE_PRIORITY_CANDIDATE_NAMESPACE_LOOKUP_ERROR=false export FAKE_PRIORITY_CANDIDATE_NAMESPACE_ABSENT=false export FAKE_ACTIVE_PREVIEW_RUNS_JSON='[]' + unset FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON='{"total_count":0,"workflow_runs":[]}' + export FAKE_RECENT_PREVIEW_DISPATCH_RUNS_JSON='{"total_count":0,"workflow_runs":[]}' export FAKE_RECENT_TRUSTED_CONSUMER_RUNS_JSON='{"total_count":0,"workflow_runs":[]}' + export FAKE_PREVIEW_DISPATCH_JOBS_JSON=null + export FAKE_PREVIEW_DISPATCH_LATEST_JSON=null export FAKE_PR_901_OWNER='' export FAKE_PR_901_HEAD="$priority_candidate_head" export FAKE_PR_901_BASE_REF=develop @@ -1230,6 +1250,7 @@ reset_case() { export FAKE_PR_901_NAMESPACE_ABSENT=false export FAKE_PR_901_NAMESPACE_ABSENT_ON_RECHECK=false unset FAKE_PR_901_RECHECK_HEAD FAKE_PR_901_RECHECK_REQUESTED_HEAD \ + FAKE_PR_901_RECHECK_NAMESPACE_UID \ FAKE_PR_901_BASE_SHA FAKE_PR_901_MERGE_SHA FAKE_PR_901_IMAGE_TAG \ FAKE_PR_901_REQUESTED_BASE_SHA FAKE_PR_901_REQUESTED_MERGE_SHA \ FAKE_PR_901_REQUESTED_IMAGE_TAG @@ -2761,6 +2782,25 @@ grep -Fqx \ "$reconciler_missing_proof_output" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" +reset_case +reconciler_recreated_namespace_output="$TEMP_DIR/reconciler-recreated-namespace.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_NAMESPACE_UID=uid-observed \ + FAKE_PR_901_RECHECK_NAMESPACE_UID=uid-recreated \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_recreated_namespace_output" 2>&1 +grep -Fq \ + 'namespace pr-901 was recreated before proof retry dispatch; refusing to charge its retry budget.' \ + "$reconciler_recreated_namespace_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + reset_case reconciler_unrelated_consumer_output="$TEMP_DIR/reconciler-trusted-consumer.out" ( @@ -2798,7 +2838,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple completed_noop; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple completed_noop completed_old_noop active_noop; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2814,7 +2854,8 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att elif $variant == "completed_success_old_tuple" then [step($old)] elif $variant == "ambiguous" then [step($tuple),step($old)] elif $variant == "event_only" then [step($tuple | sub("resolved"; "event"))] - elif $variant == "completed_noop" then [step($tuple | sub("resolved"; "event")),step("Explain preview skip")] + elif $variant == "completed_noop" or $variant == "active_noop" then [step($tuple | sub("resolved"; "event")),step("Explain preview skip")] + elif $variant == "completed_old_noop" then [step($old | sub("resolved"; "event")),step("Explain preview skip")] elif $variant == "old_event_current_plan" then [step($old | sub("resolved"; "event")),step($tuple)] else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] | if $variant == "job_attempt_missing" then map(del(.run_attempt)) else . end | @@ -2824,11 +2865,11 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att else {jobs:.,total_count:length} end')" latest_source="$(jq -cn --arg head "$preview_head_sha" --arg variant "$tuple_case" ' {id:5254,run_attempt:(if $variant == "stale_attempt" or $variant == "stale_attempt_old_tuple" then 3 else 2 end), - head_sha:$head,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:173511323,repository:{full_name:(if $variant == "wrong_latest_repo" then "example/Other" else "example/FireMUD" end)},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} + head_sha:$head,event:(if $variant == "target" then "pull_request_target" else "pull_request" end),workflow_id:173511323,display_title:"PR preview 901",repository:{full_name:(if $variant == "wrong_latest_repo" then "example/Other" else "example/FireMUD" end)},head_repository:{full_name:"example/FireMUD"},pull_requests:[{number:901}],path:(if $variant == "qualified" then ".github/workflows/preview.yml@refs/pull/901/merge" elif $variant == "wrong_latest_path" then ".github/workflows/preview.yml@refs/pull/902/merge" else ".github/workflows/preview.yml" end),status:"in_progress"} | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) elif $variant == "completed_failed_plan" then .status = "completed" | .conclusion = "failure" - elif $variant == "completed_success" or $variant == "completed_success_old_tuple" or $variant == "completed_noop" then .status = "completed" | .conclusion = "success" + elif $variant == "completed_success" or $variant == "completed_success_old_tuple" or $variant == "completed_noop" or $variant == "completed_old_noop" then .status = "completed" | .conclusion = "success" else . end')" ( cd "$ROOT_DIR" @@ -2850,7 +2891,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" - elif [[ "$tuple_case" == target || "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null ]]; then + elif [[ "$tuple_case" == target || "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null || "$tuple_case" == active_noop ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_pull_request_output" @@ -2881,7 +2922,7 @@ make_recent_source_evidence() { {id:5254,run_attempt:2,head_sha:$head,event:"pull_request",workflow_id:173511323, repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, pull_requests:[{number:901}],path:".github/workflows/preview.yml",status:"completed", - conclusion:"success",updated_at:$updated_at}')" + display_title:"PR preview 901",conclusion:"success",updated_at:$updated_at}')" export FAKE_PREVIEW_SOURCE_LATEST_JSON FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON="$(jq -cn --arg head "$preview_head_sha" \ --arg updated_at "$updated_at" ' @@ -2889,10 +2930,40 @@ make_recent_source_evidence() { status:"completed",conclusion:"success",name:"PR preview 901",display_title:"PR preview 901", head_branch:"feature-preview",head_sha:$head,path:".github/workflows/preview.yml", repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, - pull_requests:[{number:901}],updated_at:$updated_at}]}')" + pull_requests:[{number:901}],created_at:"2026-01-01T00:00:00Z",updated_at:$updated_at}]}')" export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON } +make_recent_dispatch_source_evidence() { + local updated_at="$1" outcome="${2:-render}" + local dispatch_title="Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" + FAKE_PREVIEW_DISPATCH_JOBS_JSON="$(jq -cn --arg head "$preview_base_sha" --arg outcome "$outcome" ' + def step($name): {name:$name,status:"completed",conclusion:"success"}; + [{name:"Preview Plan",run_id:5255,run_attempt:1,head_sha:$head,status:"completed",conclusion:"success", + steps:(if $outcome == "skip" then [step("Explain preview skip")] else [] end)}] + + (if $outcome == "render" then [{name:"Render Sanitized Preview Artifact",run_id:5255, + run_attempt:1,head_sha:$head,status:"completed",conclusion:"success", + steps:[step("Upload sanitized render artifact")]}] else [] end) + | {jobs:.,total_count:length}')" + export FAKE_PREVIEW_DISPATCH_JOBS_JSON + FAKE_PREVIEW_DISPATCH_LATEST_JSON="$(jq -cn --arg head "$preview_base_sha" \ + --arg title "$dispatch_title" --arg updated_at "$updated_at" ' + {id:5255,run_attempt:1,head_sha:$head,event:"repository_dispatch",workflow_id:173511323, + name:"PR Preview Environment",display_title:$title,head_branch:"develop", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + pull_requests:[],path:".github/workflows/preview.yml",status:"completed",conclusion:"success", + updated_at:$updated_at}')" + export FAKE_PREVIEW_DISPATCH_LATEST_JSON + FAKE_RECENT_PREVIEW_DISPATCH_RUNS_JSON="$(jq -cn --arg head "$preview_base_sha" \ + --arg title "$dispatch_title" --arg updated_at "$updated_at" ' + {total_count:1,workflow_runs:[{id:5255,run_attempt:1,workflow_id:173511323,event:"repository_dispatch", + status:"completed",conclusion:"success",name:"PR Preview Environment",display_title:$title, + head_branch:"develop",head_sha:$head,path:".github/workflows/preview.yml", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + pull_requests:[],updated_at:$updated_at}]}')" + export FAKE_RECENT_PREVIEW_DISPATCH_RUNS_JSON +} + reset_case recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" make_recent_source_evidence "$recent_source_updated_at" @@ -2914,6 +2985,94 @@ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" test -s "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" +reset_case +recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +make_recent_dispatch_source_evidence "$recent_source_updated_at" render +reconciler_recent_dispatch_handoff_output="$TEMP_DIR/reconciler-recent-dispatch-handoff.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_recent_dispatch_handoff_output" +grep -Fqx \ + 'Deferring proof retry for PR #901: exact successful preview source run 5255 is within the 600-second trusted-consumer handoff window.' \ + "$reconciler_recent_dispatch_handoff_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + +reset_case +recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +make_recent_dispatch_source_evidence "$recent_source_updated_at" skip +reconciler_completed_dispatch_skip_output="$TEMP_DIR/reconciler-completed-dispatch-skip.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_completed_dispatch_skip_output" +grep -Fqx \ + "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ + "$reconciler_completed_dispatch_skip_output" +test -s "$FAKE_ANNOTATE_LOG" +test -s "$FAKE_DISPATCH_LOG" + +reset_case +recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +make_recent_dispatch_source_evidence "$recent_source_updated_at" unproven +reconciler_unproven_dispatch_output="$TEMP_DIR/reconciler-unproven-dispatch.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_unproven_dispatch_output" 2>&1 +grep -Fq \ + 'Skipping proof retry for PR #901: recent preview handoff lookup unavailable; retry budget unchanged.' \ + "$reconciler_unproven_dispatch_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + +reset_case +make_recent_dispatch_source_evidence "$(date -u +%Y-%m-%dT%H:%M:%SZ)" unproven +dispatch_title="Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" +FAKE_PREVIEW_DISPATCH_LATEST_JSON="$(jq -c 'del(.conclusion,.updated_at) | .status = "in_progress"' \ + <<<"$FAKE_PREVIEW_DISPATCH_LATEST_JSON")" +export FAKE_PREVIEW_DISPATCH_LATEST_JSON +FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON="$(jq -cn --arg title "$dispatch_title" --arg head "$preview_base_sha" ' + [{workflow_runs:[{id:5255,run_attempt:1,workflow_id:173511323,event:"repository_dispatch", + repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, + path:".github/workflows/preview.yml",head_branch:"develop",head_sha:$head, + name:"PR Preview Environment",display_title:$title,status:"in_progress"}]}]')" +export FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON +reconciler_active_unproven_dispatch_output="$TEMP_DIR/reconciler-active-unproven-dispatch.out" +( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_active_unproven_dispatch_output" 2>&1 +grep -Fq \ + "Skipping proof retry for PR #901: preview source or trusted consumer run 5255 for ${preview_base_sha}/${preview_head_sha}/${preview_merge_sha} is already queued or in progress." \ + "$reconciler_active_unproven_dispatch_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + reset_case recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" make_recent_source_evidence "$recent_source_updated_at" @@ -2944,13 +3103,17 @@ test ! -e "$FAKE_DISPATCH_LOG" reset_case recent_source_updated_at="$(date -u -d '20 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" make_recent_source_evidence "$recent_source_updated_at" +# Keep the exact qualifying run 5254 in the inventory and change only its age; +# older matching runs must not overflow the handoff candidate bound. FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON="$(jq -cn --arg head "$preview_head_sha" \ - --arg updated_at "$recent_source_updated_at" '[range(5250;5254) as $id | { - id:$id,run_attempt:1,workflow_id:173511323,event:"pull_request",status:"completed", + --arg updated_at "$recent_source_updated_at" '[range(5154;5255) as $id | { + id:$id,run_attempt:(if $id == 5254 then 2 else 1 end),workflow_id:173511323,event:"pull_request",status:"completed", conclusion:"success",name:"PR preview 901",display_title:"PR preview 901", head_branch:"feature-preview",head_sha:$head,path:".github/workflows/preview.yml", repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, - pull_requests:[{number:901}],updated_at:$updated_at}] | {total_count:length,workflow_runs:.}')" + pull_requests:[{number:901}],updated_at:$updated_at}] as $runs + | [{total_count:($runs | length),workflow_runs:$runs[:100]}, + {total_count:($runs | length),workflow_runs:$runs[100:]}]')" export FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON reconciler_expired_source_output="$TEMP_DIR/reconciler-expired-source.out" ( diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 2f0c8b822f..4be98093d3 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -555,6 +555,38 @@ render_text = text(preview_jobs["preview-render"]) for required in ("git -C candidate", "candidate/k8s/helm/firemud", "python3 ./dev-tools/hosted/preview/"): if required not in render_text: raise AssertionError(f"preview render lost isolated trusted-tools/candidate-data boundary: {required}") +render_step = next( + step for step in preview_jobs["preview-render"]["steps"] + if step.get("name") == "Render and sanitize preview without credentials" +) +assert render_step["env"]["PLANNED_MERGE_SHA"] == "${{ needs.preview-plan.outputs.merge_sha }}" +assert render_step["env"]["BASE_SHA"] == "${{ needs.preview-plan.outputs.base_sha }}" +assert render_step["env"]["HEAD_SHA"] == "${{ needs.preview-plan.outputs.head_sha }}" +render_guard, marker, _ = render_step["run"].partition('values="$RUNNER_TEMP/preview-values.yaml"') +assert marker, "preview merge comparison must run before reading candidate values" +merge_sha, base_sha, head_sha, moved_sha = (digit * 40 for digit in "abcf") +fixture_git = r''' +git() { + case "$*" in + "-C candidate rev-parse --verify HEAD^{commit}") printf '%s\n' "$CANDIDATE" ;; + "-C candidate rev-list --parents -n 1 $CANDIDATE") printf '%s %s\n' "$CANDIDATE" "$PARENTS" ;; + *) return 2 ;; + esac +} +''' +for candidate, parents, expected in ( + (merge_sha, f"{base_sha} {head_sha}", 0), + (moved_sha, f"{base_sha} {head_sha}", 1), + (merge_sha, f"{head_sha} {base_sha}", 1), +): + result = subprocess.run( + ["bash", "-c", fixture_git + render_guard], capture_output=True, text=True, + env={"CANDIDATE": candidate, "PARENTS": parents, "PLANNED_MERGE_SHA": merge_sha, + "BASE_SHA": base_sha, "HEAD_SHA": head_sha}, timeout=5, + ) + assert result.returncode == expected, (candidate, parents, result.stderr) + if expected: + assert "Stale preview merge ref" in result.stderr if re.search(r"(?:uses:|bash|python3)\s+(?:\./)?candidate/", render_text): raise AssertionError("preview render executes candidate tools or local actions") for job_name, job in preview_jobs.items(): diff --git a/dev-tools/tests/protected-pod-admission-workflow-contract.sh b/dev-tools/tests/protected-pod-admission-workflow-contract.sh index 91610ba41e..8cea826a3b 100644 --- a/dev-tools/tests/protected-pod-admission-workflow-contract.sh +++ b/dev-tools/tests/protected-pod-admission-workflow-contract.sh @@ -42,10 +42,12 @@ calls=p.read_text().splitlines() if p.exists() else [] n=len(calls) p.write_text("\\n".join([*calls, policy]) + "\\n") if os.environ["CASE"]=="api-error":sys.exit(1) -ready=os.environ["CASE"] in ("ready", "warnings", "ignore") or (os.environ["CASE"]=="late" and n>0) +case=os.environ["CASE"] +ready=(case in ("ready", "warnings", "ignore") or (case=="late" and n>0) + or (case=="shared-deadline" and n==2 and policy=="firemud-trust-runtime-namespace-boundary")) print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Ignore" if os.environ["CASE"]=="ignore" else "Fail"},"status":{"observedGeneration":2 if ready else 1,"typeChecking":{"expressionWarnings":["bad"] if os.environ["CASE"]=="warnings" else []}}})) ''') - for case, success in [("ready", True), ("late", True), ("stale", False), ("warnings", False), ("ignore", False), ("api-error", False)]: + for case, success in [("ready", True), ("late", True), ("stale", False), ("warnings", False), ("ignore", False), ("api-error", False), ("shared-deadline", False)]: for name in ("clock", "calls"): (tmp/name).unlink(missing_ok=True) env = dict(os.environ, PATH=str(tmp)+":"+os.environ["PATH"], CASE=case, @@ -62,5 +64,10 @@ print(json.dumps({"metadata":{"generation":2},"spec":{"failurePolicy":"Ignore" i assert len(calls) == (5 if case == "late" else 4) else: assert "policy_readiness=timeout" in result.stderr + if case == "shared-deadline": + first = "firemud-trust-runtime-namespace-boundary" + second = "firemud-trust-runtime-binding-boundary" + assert (tmp/"calls").read_text().splitlines() == [first, first, first, second] + assert f"policy_readiness=timeout policy={second}" in result.stderr print("Protected Pod workflow bounded cleanup/readiness contract passed") PY diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 295890337b..274d8b4044 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -577,7 +577,7 @@ async function assertAssociationSelection() { for (const associations of [[{number: 42}, {number: 42}], [{number: 99}], null]) { reset(); source.pull_requests = associations; await run(github, context, core); - if (pullRequestReads || calls.paginate.length || calls.updated.length || calls.deleted.length) { + if (pullRequestReads || calls.paginate.length || calls.created.length || calls.updated.length || calls.deleted.length) { throw new Error("missing or duplicate matching association must fail before provider reads"); } } @@ -585,7 +585,7 @@ async function assertAssociationSelection() { for (const [repository, branch] of [[null, "feature"], [{id: 0}, "feature"], [{id: 123}, ""], [{id: 456}, "feature"], [{id: 123}, "different"]]) { reset(); source.head_repository = repository; source.head_branch = branch; await run(github, context, core); - if (calls.paginate.length || calls.updated.length || calls.deleted.length) { + if (calls.paginate.length || calls.created.length || calls.updated.length || calls.deleted.length) { throw new Error("invalid or mismatched concurrency identity must not publish"); } } diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 23e9013293..9a34b243bf 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -154,21 +154,72 @@ def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], def recovery_location_configured(snapshot: Snapshot, project: str) -> bool: + def flatten_properties( + value: object, + prefix: tuple[str, ...], + properties: dict[str, object], + ambiguous: set[str], + ) -> None: + if not isinstance(value, dict): + return + for key, child in value.items(): + if not isinstance(key, str): + continue + parts = tuple(re.sub(r"[-_]", "", part).lower() for part in key.split(".")) + path = ".".join((*prefix, *parts)) + if path in properties and properties[path] != child: + ambiguous.add(path) + properties[path] = child + flatten_properties(child, (*prefix, *parts), properties, ambiguous) + flyway = {} # Spring Boot gives .yml properties precedence over same-location .yaml. for extension in ("yaml", "yml"): config_path = f"services/{project}/src/main/resources/application.{extension}" try: - settings = yaml.safe_load(snapshot.get(config_path, b"")) or {} + documents = list(yaml.safe_load_all(snapshot.get(config_path, b""))) except yaml.YAMLError as error: raise ValueError(f"{config_path}: invalid packaged Spring configuration: {error}") from error - for section in ("spring", "flyway"): - if not isinstance(settings, dict): + + for document in documents: + if document is None: + continue + if not isinstance(document, dict): + return False + properties: dict[str, object] = {} + ambiguous: set[str] = set() + flatten_properties(document, (), properties, ambiguous) + enabled_path = "spring.flyway.enabled" + locations_path = "spring.flyway.locations" + guard_paths = { + path for path in properties + if path in {enabled_path, locations_path} + or path.startswith((enabled_path + ".", enabled_path + "[", + locations_path + ".", locations_path + "[")) + } + if not guard_paths: + # Other documents, including profile-activated documents with no + # Flyway guard properties, do not affect this static qualification. + continue + if guard_paths & ambiguous or any(path not in {enabled_path, locations_path} for path in guard_paths): + return False + + activation = properties.get("spring.config.activate") + legacy_profile_activation = ( + "spring.profiles" in properties + and not isinstance(properties["spring.profiles"], dict) + ) + if (isinstance(activation, dict) and activation) or any( + path.startswith("spring.config.activate.") for path in properties + ) or legacy_profile_activation: + # The checker cannot prove which profile/cloud-activated property + # source wins at runtime, so a conditional override of either guard + # property is not accepted. return False - settings = settings.get(section) or {} - if not isinstance(settings, dict): - return False - flyway.update(settings) + + for path in guard_paths: + flyway[path.rsplit(".", 1)[-1]] = properties[path] + if str(flyway.get("enabled", True)).strip().lower() not in {"true", "on", "yes", "1"}: return False locations = flyway.get("locations", []) @@ -314,8 +365,49 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str b"spring:\n flyway:\n enabled: true\n locations:\n" b" - classpath:db/recovery-control-migration\n" ) + yml_locations_override = b"spring:\n flyway:\n locations:\n - classpath:db/migration\n" + check("application.yml replaces application.yaml locations list", { + recovery + "V1__journal.sql": b"-- journal", + yaml_config: recovery_list_settings, + recovery_config: yml_locations_override, + }, recovery_history, "historical effective migration no longer applied") check("equivalent enabled list recovery history", {**recovery_history, recovery_config: recovery_list_settings}, recovery_history, None) + dotted_recovery_settings = ( + b"spring.flyway.enabled: true\n" + b"spring.flyway.locations: classpath:db/recovery-control-migration\n" + ) + check("dotted Spring Flyway recovery properties", + {**recovery_history, recovery_config: dotted_recovery_settings}, recovery_history, None) + dotted_disabled_settings = dotted_recovery_settings.replace( + b"spring.flyway.enabled: true", b"spring.flyway.enabled: false" + ) + check("dotted Spring Flyway disable fails closed", + {**recovery_history, recovery_config: dotted_disabled_settings}, recovery_history, + "historical effective migration no longer applied") + harmless_second_document = recovery_settings + b"---\ncustom:\n setting: value\n" + check("unrelated second YAML document", + {**recovery_history, recovery_config: harmless_second_document}, recovery_history, None) + changed_second_document = recovery_list_settings + ( + b"---\nspring:\n flyway:\n locations:\n - classpath:db/migration\n" + ) + check("changed second-document Flyway location fails closed", + {**recovery_history, recovery_config: changed_second_document}, recovery_history, + "historical effective migration no longer applied") + conditional_second_document = recovery_settings + ( + b"---\nspring:\n config:\n activate:\n on-profile: production\n" + b" flyway:\n locations: classpath:db/migration\n" + ) + check("conditional Flyway override fails closed", + {**recovery_history, recovery_config: conditional_second_document}, recovery_history, + "historical effective migration no longer applied") + profile_only_recovery = ( + b"---\nspring:\n config:\n activate:\n on-profile: recovery\n" + b" flyway:\n locations: classpath:db/recovery-control-migration\n" + ) + check("recovery location requiring active profile fails closed", + {**recovery_history, recovery_config: profile_only_recovery}, recovery_history, + "historical effective migration no longer applied") for disabled in ( recovery_settings.replace(b" locations:", b" enabled: false\n locations:"), recovery_list_settings.replace(b"enabled: true", b'enabled: "false"'), diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 58fa060525..abf08cd1be 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -2661,6 +2661,19 @@ def test_gateway_exact_environment_contract_is_accepted(self): [self._gateway_document()], "pr-42" ) + def test_gateway_accepts_exact_environment_from_before_footprint_tuning(self): + document = self._gateway_document() + container = document["spec"]["template"]["spec"]["containers"][0] + expected = container["env"] + tuning = {"JAVA_TOOL_OPTIONS", "MALLOC_ARENA_MAX"} + with patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}): + container["env"] = [entry for entry in expected if entry["name"] not in tuning] + self.validator.validate_service_consumers([document], "pr-42") + for missing in ("JAVA_TOOL_OPTIONS", "MALLOC_ARENA_MAX", "SPRING_FLYWAY_TABLE"): + with self.subTest(missing=missing), self.assertRaisesRegex(ValueError, "unsafe container env"): + container["env"] = [entry for entry in expected if entry["name"] != missing] + self.validator.validate_service_consumers([document], "pr-42") + def test_gateway_rejects_unsafe_gameplay_mount(self): for option, value in (("readOnly", False), ("subPath", "tls.key")): with self.subTest(option=option): diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java index 2a6f0995b3..d46ec9c6a1 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java @@ -5,7 +5,7 @@ import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; -/** Rejects an implicit or empty recovery-control database endpoint before datasource setup. */ +/** Rejects an implicit or multi-host recovery-control database endpoint before datasource setup. */ public final class RecoveryControlDatabaseHostEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final String HOST_PROPERTY = "FIREMUD_RECOVERY_CONTROL_DB_HOST"; @@ -14,8 +14,12 @@ public final class RecoveryControlDatabaseHostEnvironmentPostProcessor public void postProcessEnvironment( ConfigurableEnvironment environment, SpringApplication application) { String host = environment.getProperty(HOST_PROPERTY); - if (host == null || host.isBlank()) { - throw new IllegalStateException(HOST_PROPERTY + " must name the isolated recovery database"); + if (host == null + || host.isBlank() + || host.indexOf(',') >= 0 + || host.chars().anyMatch(Character::isWhitespace)) { + throw new IllegalStateException( + HOST_PROPERTY + " must name the isolated recovery database using exactly one host"); } } diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 716187eb7e..4990d7f34a 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -435,11 +435,13 @@ public Operation recordEffectReadback( String storedDigest = stored == null ? null : stored.get("readback_digest", String.class); if (current.state() == EffectOutboxState.ACKNOWLEDGED) { if (readbackDigest.equals(storedDigest)) { + requireSuccessfulReadbackState(readback, current.effect().kind()); requireValidExactStoredReadback(readback, stored, storedDigest, current); requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } if (stored != null && sameRetainedOutcome(readback, stored, storedDigest)) { + requireSuccessfulReadbackState(readback, current.effect().kind()); requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } @@ -693,6 +695,10 @@ private Operation toOperation(Record record) { } InitialGameplayReleaseEvidence evidence = evidenceJson == null ? null : tupleCodec.readEvidence(evidenceJson.data()); + if (evidenceJson != null && evidence == null) { + throw new IllegalStateException( + "Persisted initial gameplay release evidence is inconsistent"); + } if (evidence != null && (!evidence.evidenceIdentity().equals(record.get("evidence_identity", String.class)) || !tupleCodec.digest(evidence).equals(record.get("evidence_digest", String.class)))) { diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index e1e2390ae8..8f1086ae5b 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -86,6 +86,8 @@ class InitialGameplayReleaseJournalPostgresIntegrationTest { "ef9bbb81842b83253fcc6e6be7032ee744e563d109e4d0aab35146af85fe2c8f"; private static final String V1_EVIDENCE_DIGEST = "3c811a041f71b88c21c1d023b3fa3f489054c14603e333f8ae9edc32f34ef79e"; + private static final String V1_RESUME_TRANSITION_DIGEST = + "814d6a36a4c1046394985096a1ea82b498d445dd69eb19a1284a264e252e4e55"; private static final String V1_OPERATION_TUPLE_DIGEST = "926bf0c737455039923849ac17a926440637204c2a4fa7a408f22dcac7c263cf"; private static final String V1_PREPARE_EFFECT_PAYLOAD_DIGEST = @@ -235,6 +237,21 @@ class InitialGameplayReleaseJournalPostgresIntegrationTest { } """ .strip(); + // Historical V1 writer payload for the retained resume tuple seeded by the migration fixture. + private static final String V1_RESUME_TRANSITION_PAYLOAD_TEMPLATE = + """ + { + "operationId": "10000000-0000-0000-0000-000000000001", + "scopeDigest": "%s", + "verb": "RESUME", + "expectedPhase": "AWAITING_RESUME", + "maintenanceLockIdentity": "10000000-0000-0000-0000-000000000004", + "evidenceRef": "immutable-initial-layout-evidence", + "evidenceIdentity": "evidence-owner-record-31", + "evidenceDigest": "%s" + } + """ + .strip(); @Container private static final PostgreSQLContainer POSTGRES = @@ -310,6 +327,10 @@ void journalDoesNotLogControllerLockIdentityAtDebug() { .extracting(Operation::maintenanceLockIdentity) .isEqualTo(controllerLockIdentity); assertThat(created.maintenanceLockIdentity()).isEqualTo(controllerLockIdentity); + debugDsl.fetch("SELECT 'journal-log-redaction-positive-control'::text"); + assertThat(logCapture.list) + .extracting(ILoggingEvent::getFormattedMessage) + .anyMatch(message -> message.contains("journal-log-redaction-positive-control")); assertThat(logCapture.list) .extracting(ILoggingEvent::getFormattedMessage) .noneMatch(message -> message.contains(controllerLockIdentity.toString())); @@ -950,6 +971,29 @@ void scopeReaderRejectsResealedScopeForAnotherRowKey() { .hasMessageContaining("Persisted initial gameplay release scope is inconsistent"); } + @Test + void evidenceReaderRejectsJsonbNullButAcceptsSqlNullForCollectingOperation() { + Scope scope = scope(); + Operation collecting = journal.create(scope, UUID.randomUUID()); + assertThat(collecting.phase()).isEqualTo(Phase.COLLECTING); + assertThat(collecting.evidence()).isNull(); + assertThat(journal.find(scope.operationId())).contains(collecting); + + InitialGameplayReleaseEvidence proof = evidence(scope); + journal.bindVerifiedEvidence( + scope, tupleCodec.digest(scope), proof, tupleCodec.digest(proof), Instant.now()); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_operation " + + "SET evidence_snapshot=CAST('null' AS jsonb) WHERE operation_id=?", + scope.operationId())) + .isEqualTo(1); + + assertThatThrownBy(() -> journal.find(scope.operationId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Persisted initial gameplay release evidence is inconsistent"); + } + @Test void outboxReadersRejectResealedPayloadForAnotherOperationRowKey() { Instant base = Instant.parse("2026-09-01T00:00:00Z"); @@ -1057,6 +1101,71 @@ void exactReadbackReplayVerifiesRetainedPayloadInBothClosedStates() { } } + @Test + void acknowledgedReadbackReplayRequiresTheEffectKindsSuccessfulStateInBothReplayBranches() { + for (EffectKind effectKind : EffectKind.values()) { + for (boolean exactReplay : List.of(true, false)) { + clearJournal(); + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry dispatched = authorizedDispatch(effectKind, base); + UUID operationId = dispatched.effect().operationId(); + UUID effectId = dispatched.effect().effectId(); + Instant observedAt = + base.plusSeconds(effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED ? 5 : 7); + EffectReadbackState wrongState = + effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED + ? EffectReadbackState.OWNER_HANDOFF_APPLIED + : EffectReadbackState.PREPARED_FENCED; + EffectReadback wrongStateReadback = + readbackFor( + dispatched, + dispatched.lastAttemptId(), + wrongState, + "wrong-effect-kind-state", + observedAt); + Operation acknowledged = + journal.recordEffectReadback( + dispatched, + readbackFor( + dispatched, + dispatched.lastAttemptId(), + effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED + ? EffectReadbackState.PREPARED_FENCED + : EffectReadbackState.OWNER_HANDOFF_APPLIED, + "successful-readback", + observedAt), + observedAt.plusSeconds(1)); + assertThat( + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox " + + "SET readback_payload=CAST(? AS jsonb), readback_digest=? " + + "WHERE operation_id=? AND effect_id=?", + tupleCodec.toJson(wrongStateReadback), + tupleCodec.digest(wrongStateReadback), + operationId, + effectId)) + .isEqualTo(1); + String corrupted = storedOutbox(operationId, effectId); + EffectReadback replay = + exactReplay + ? wrongStateReadback + : readbackFor( + dispatched, + dispatched.lastAttemptId(), + wrongState, + "wrong-effect-kind-state", + observedAt.plusSeconds(2)); + + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatched, replay, observedAt.plusSeconds(3))) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessageContaining("did not prove its exact durable outcome"); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(corrupted); + assertThat(journal.find(operationId)).contains(acknowledged); + } + } + } + @Test void definitiveOwnerRejectionRequiresFreshAttemptEvenAfterReplacement() { Instant base = Instant.parse("2026-09-01T00:00:00Z"); @@ -1414,6 +1523,18 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) "SELECT payload::text FROM recovery_control.initial_gameplay_release_outbox WHERE outbox_id=?", V1_OUTBOX_ID) .get(0, String.class); + String transitionPayloadBefore = + legacyDsl + .fetchSingle( + "SELECT tuple_payload::text FROM recovery_control.initial_gameplay_release_transition WHERE operation_id=? AND verb='resume'", + V1_OPERATION_ID) + .get(0, String.class); + String transitionDigestBefore = + legacyDsl + .fetchSingle( + "SELECT tuple_digest FROM recovery_control.initial_gameplay_release_transition WHERE operation_id=? AND verb='resume'", + V1_OPERATION_ID) + .get(0, String.class); Flyway upgrade = Flyway.configure() .dataSource(legacyUrl, POSTGRES.getUsername(), POSTGRES.getPassword()) @@ -1427,7 +1548,13 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) assertThatThrownBy(() -> upgrade.migrate()) .hasStackTraceContaining("requires no prior claims"); assertImmutableV1Payloads( - legacyDsl, scopeBefore, bindingBefore, evidenceBefore, payloadBefore); + legacyDsl, + scopeBefore, + bindingBefore, + evidenceBefore, + payloadBefore, + transitionPayloadBefore, + transitionDigestBefore); assertThat( legacyDsl .fetchSingle( @@ -1439,10 +1566,27 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) upgrade.migrate(); assertThat(upgrade.info().current().getVersion().getVersion()).isEqualTo("2"); assertImmutableV1Payloads( - legacyDsl, scopeBefore, bindingBefore, evidenceBefore, payloadBefore); + legacyDsl, + scopeBefore, + bindingBefore, + evidenceBefore, + payloadBefore, + transitionPayloadBefore, + transitionDigestBefore); InitialGameplayReleaseJournal upgradedJournal = new JooqInitialGameplayReleaseJournal(legacyDsl, tupleCodec); Operation upgraded = upgradedJournal.find(V1_OPERATION_ID).orElseThrow(); + PublicTransitionTuple v1Resume = v1ResumeTransition(); + assertThat(upgradedJournal.findTransition(v1Resume)).contains(upgraded); + assertThat(upgradedJournal.transition(v1Resume, base.plusSeconds(1))).isEqualTo(upgraded); + assertImmutableV1Payloads( + legacyDsl, + scopeBefore, + bindingBefore, + evidenceBefore, + payloadBefore, + transitionPayloadBefore, + transitionDigestBefore); assertThat(upgraded.maintenanceLockIdentity()).isEqualTo(V1_LOCK_IDENTITY); assertThat(upgraded.phase()).isEqualTo(Phase.RESUME_AUTHORIZED); assertThat(upgraded.evidence()).isNotNull(); @@ -1480,7 +1624,9 @@ private static void assertImmutableV1Payloads( String scopePayload, String bindingPayload, String evidencePayload, - String effectPayload) { + String effectPayload, + String transitionPayload, + String transitionDigest) { assertThat( legacyDsl .fetchSingle( @@ -1509,12 +1655,28 @@ private static void assertImmutableV1Payloads( V1_OUTBOX_ID) .get(0, String.class)) .isEqualTo(effectPayload); + assertThat( + legacyDsl + .fetchSingle( + "SELECT tuple_payload::text FROM recovery_control.initial_gameplay_release_transition WHERE operation_id=? AND verb='resume'", + V1_OPERATION_ID) + .get(0, String.class)) + .isEqualTo(transitionPayload); + assertThat( + legacyDsl + .fetchSingle( + "SELECT tuple_digest FROM recovery_control.initial_gameplay_release_transition WHERE operation_id=? AND verb='resume'", + V1_OPERATION_ID) + .get(0, String.class)) + .isEqualTo(transitionDigest); } private static void seedImmutableV1Journal( DSLContext seedDsl, boolean claimed, Instant timestamp) { String effectPayload = V1_PREPARE_EFFECT_PAYLOAD_TEMPLATE.formatted(V1_SCOPE_PAYLOAD, V1_OPERATION_TUPLE_DIGEST); + String resumePayload = + V1_RESUME_TRANSITION_PAYLOAD_TEMPLATE.formatted(V1_SCOPE_DIGEST, V1_EVIDENCE_DIGEST); seedDsl.execute( """ @@ -1541,6 +1703,16 @@ private static void seedImmutableV1Journal( timestamp.atOffset(ZoneOffset.UTC), timestamp.atOffset(ZoneOffset.UTC)); + seedDsl.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_transition ( + operation_id, verb, tuple_digest, tuple_payload, expected_phase, result_phase + ) VALUES (?, 'resume', ?, CAST(? AS jsonb), 'awaiting_resume', 'resume_authorized') + """, + V1_OPERATION_ID, + V1_RESUME_TRANSITION_DIGEST, + resumePayload); + seedDsl.execute( """ INSERT INTO recovery_control.initial_gameplay_release_outbox ( @@ -1564,6 +1736,18 @@ private static void seedImmutableV1Journal( timestamp.atOffset(ZoneOffset.UTC)); } + private static PublicTransitionTuple v1ResumeTransition() { + return new PublicTransitionTuple( + V1_OPERATION_ID, + V1_SCOPE_DIGEST, + TransitionVerb.RESUME, + Phase.AWAITING_RESUME, + V1_LOCK_IDENTITY, + "immutable-initial-layout-evidence", + "evidence-owner-record-31", + V1_EVIDENCE_DIGEST); + } + private static OutboxEntry authorizedDispatch(Instant base) { Scope scope = scope(); journal.create(scope, UUID.randomUUID()); @@ -1580,6 +1764,27 @@ private static OutboxEntry authorizedDispatch(Instant base) { scope.operationId(), pending.effect().effectId(), UUID.randomUUID(), base.plusSeconds(4)); } + private static OutboxEntry authorizedDispatch(EffectKind effectKind, Instant base) { + OutboxEntry prepare = authorizedDispatch(base); + if (effectKind == EffectKind.PREPARE_PLAYABLE_STATE_FENCED) { + return prepare; + } + EffectReadback prepared = + readbackFor( + prepare, + prepare.lastAttemptId(), + EffectReadbackState.PREPARED_FENCED, + "prepare-readback-for-handoff", + base.plusSeconds(5)); + journal.recordEffectReadback(prepare, prepared, base.plusSeconds(5)); + OutboxEntry handoff = journal.findNextEffect(prepare.effect().operationId()).orElseThrow(); + return journal.claimEffect( + handoff.effect().operationId(), + handoff.effect().effectId(), + UUID.randomUUID(), + base.plusSeconds(6)); + } + private static String storedClosure(OutboxEntry dispatch) { return java.util.Objects.requireNonNull( dsl.fetchOne( diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java index 606c00569d..74cc2ceaee 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java @@ -39,4 +39,29 @@ void acceptsExplicitLocalhostForAnIsolatedFixture() { new SpringApplication())) .doesNotThrowAnyException(); } + + @Test + void rejectsCommaSeparatedRecoveryDatabaseHosts() { + assertThatThrownBy(() -> + postProcessor.postProcessEnvironment( + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, + "recovery-control.invalid,localhost"), + new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exactly one host"); + } + + @Test + void acceptsAnExplicitSingleRecoveryDatabaseHostname() { + assertThatCode(() -> + postProcessor.postProcessEnvironment( + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, + "recovery-control.invalid"), + new SpringApplication())) + .doesNotThrowAnyException(); + } } From 9c9f9632e4acfaca6aa39a5225acb96c3b1e7609 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:31:52 +1300 Subject: [PATCH 096/199] Keep preview reconciler shell lint out of workflow stdin --- .github/workflows/preview-reconciler.yml | 1339 +---------------- .../preview/reconcile-preview-deploys.sh | 1335 ++++++++++++++++ dev-tools/tests/preview-priority-contract.sh | 76 +- 3 files changed, 1375 insertions(+), 1375 deletions(-) create mode 100644 dev-tools/hosted/preview/reconcile-preview-deploys.sh diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index d161a7d147..1ad97e2196 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -29,7 +29,8 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: ${{ github.event.repository.default_branch }} + # Use the same trusted revision for the workflow and its checked-in script. + ref: ${{ github.workflow_sha }} persist-credentials: false - name: Set up canonical Python @@ -64,1341 +65,7 @@ jobs: PREVIEW_MAX_ACTIVE: ${{ vars.PREVIEW_MAX_ACTIVE }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig - run: | - set -euo pipefail - preview_workflow_name="PR Preview Environment" - eligibility_script="./dev-tools/hosted/preview/preview-eligibility.py" - max_active="${PREVIEW_MAX_ACTIVE:-2}" - preview_handoff_window_seconds=600 - - parse_namespace_tuple() { - jq -er ' - def annotation($annotations; $name): - ($annotations[$name] // "") - | if type != "string" then - error("namespace preview annotation is not a string") - elif test("[|\\r\\n]") then - error("namespace preview annotation contains an unsafe delimiter") - else - . - end; - def metadata_field($metadata; $name): - ($metadata[$name] // "") - | if type != "string" then - error("namespace metadata field is not a string") - elif test("[|\\r\\n]") then - error("namespace metadata field contains an unsafe delimiter") - else - . - end; - if type != "object" or (.metadata | type) != "object" then - error("namespace snapshot is not an object with metadata") - elif ((.metadata.annotations // {}) | type) != "object" then - error("namespace annotations are not an object") - else - (.metadata.annotations // {}) as $annotations - | [ - annotation($annotations; "firemud.dev/last-preview-base-sha"), - annotation($annotations; "firemud.dev/last-preview-head-sha"), - annotation($annotations; "firemud.dev/last-preview-merge-sha"), - annotation($annotations; "firemud.dev/last-preview-image-tag"), - annotation($annotations; "firemud.dev/requested-preview-base-sha"), - annotation($annotations; "firemud.dev/requested-preview-head-sha"), - annotation($annotations; "firemud.dev/requested-preview-merge-sha"), - annotation($annotations; "firemud.dev/requested-preview-image-tag"), - annotation($annotations; "firemud.dev/proof-preview-base-sha"), - annotation($annotations; "firemud.dev/proof-preview-head-sha"), - annotation($annotations; "firemud.dev/proof-preview-merge-sha"), - annotation($annotations; "firemud.dev/proof-preview-image-tag"), - annotation($annotations; "firemud.dev/proof-preview-namespace-uid"), - annotation($annotations; "firemud.dev/proof-retry-count"), - annotation($annotations; "firemud.dev/proof-retry-base-sha"), - annotation($annotations; "firemud.dev/proof-retry-head-sha"), - annotation($annotations; "firemud.dev/proof-retry-merge-sha"), - annotation($annotations; "firemud.dev/proof-retry-image-tag"), - metadata_field(.metadata; "uid"), - metadata_field(.metadata; "resourceVersion") - ] - | if ( - (.[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") - or ( - (.[13] | test("^[0-3]$")) - and (.[14] | test("^[0-9a-fA-F]{40}$")) - and (.[15] | test("^[0-9a-fA-F]{40}$")) - and (.[16] | test("^[0-9a-fA-F]{40}$")) - and (.[17] | test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) - ) - ) then . else error("namespace proof-retry evidence is malformed") end - | join("|") - end - ' <<<"$1" - } - - readonly repair_success=0 - readonly repair_skip=10 - readonly repair_dispatch=11 - readonly repair_abort=20 - - repair_requested_tuple() { - local namespace="$1" - local pr_number="$2" - local base_sha="$3" - local head_sha="$4" - local merge_sha="$5" - local image_tag="$6" - local requested_base_sha="$7" - local requested_head_sha="$8" - local requested_merge_sha="$9" - local requested_image_tag="${10}" - local fresh_namespace_json - local fresh_namespace_tuple - local fresh_last_base_sha - local fresh_last_head_sha - local fresh_last_merge_sha - local fresh_last_image_tag - local fresh_requested_base_sha - local fresh_requested_head_sha - local fresh_requested_merge_sha - local fresh_requested_image_tag - local fresh_proof_base_sha - local fresh_proof_head_sha - local fresh_proof_merge_sha - local fresh_proof_image_tag - local fresh_proof_namespace_uid - local fresh_namespace_uid - local fresh_namespace_resource_version - local annotation_failure_namespace_json - - if ! fresh_namespace_json="$( - kubectl get namespace "${namespace}" --ignore-not-found -o json - )"; then - echo "Unable to recheck namespace ${namespace} before annotation repair." >&2 - return "$repair_abort" - fi - if [[ -z "${fresh_namespace_json}" ]]; then - return "$repair_dispatch" - fi - if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then - echo "Skipping PR #${pr_number}: unable to parse namespace ${namespace} recheck." >&2 - return "$repair_skip" - fi - IFS='|' read -r fresh_last_base_sha fresh_last_head_sha fresh_last_merge_sha fresh_last_image_tag \ - fresh_requested_base_sha fresh_requested_head_sha fresh_requested_merge_sha fresh_requested_image_tag \ - fresh_proof_base_sha fresh_proof_head_sha fresh_proof_merge_sha fresh_proof_image_tag \ - fresh_proof_namespace_uid _ _ _ _ _ \ - fresh_namespace_uid \ - fresh_namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "${fresh_last_base_sha}" != "${base_sha}" || - "${fresh_last_head_sha}" != "${head_sha}" || - "${fresh_last_merge_sha}" != "${merge_sha}" || - "${fresh_last_image_tag}" != "${image_tag}" ]]; then - echo "Skipping preview repair for PR #${pr_number}: deployed preview tuple changed during annotation repair check." - return "$repair_skip" - fi - if [[ "${fresh_proof_base_sha}" != "${base_sha}" || - "${fresh_proof_head_sha}" != "${head_sha}" || - "${fresh_proof_merge_sha}" != "${merge_sha}" || - "${fresh_proof_image_tag}" != "${image_tag}" || - -z "${fresh_namespace_uid}" || - "${fresh_proof_namespace_uid}" != "${fresh_namespace_uid}" ]]; then - echo "Preview ${namespace} deployed tuple is missing proof for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}; dispatching retry." - return "$repair_dispatch" - fi - if [[ "${fresh_requested_base_sha}" == "${base_sha}" && - "${fresh_requested_head_sha}" == "${head_sha}" && - "${fresh_requested_merge_sha}" == "${merge_sha}" && - "${fresh_requested_image_tag}" == "${image_tag}" ]]; then - echo "Preview ${namespace} already aligned to ${base_sha}/${head_sha}/${merge_sha}/${image_tag}" - return "$repair_success" - fi - if [[ "${fresh_requested_base_sha}" != "${requested_base_sha}" || - "${fresh_requested_head_sha}" != "${requested_head_sha}" || - "${fresh_requested_merge_sha}" != "${requested_merge_sha}" || - "${fresh_requested_image_tag}" != "${requested_image_tag}" ]]; then - echo "Skipping preview repair for PR #${pr_number}: requested preview tuple changed during annotation repair check." - return "$repair_skip" - fi - if ! kubectl annotate namespace "${namespace}" \ - "firemud.dev/requested-preview-base-sha=${base_sha}" \ - "firemud.dev/requested-preview-head-sha=${head_sha}" \ - "firemud.dev/requested-preview-merge-sha=${merge_sha}" \ - "firemud.dev/requested-preview-image-tag=${image_tag}" \ - --overwrite \ - --resource-version "${fresh_namespace_resource_version}" >/dev/null; then - if ! annotation_failure_namespace_json="$( - kubectl get namespace "${namespace}" --ignore-not-found -o json - )"; then - echo "Unable to recheck namespace ${namespace} after annotation failure; refusing preview reconcile." >&2 - return "$repair_abort" - fi - if [[ -n "${annotation_failure_namespace_json}" ]]; then - echo "Skipping PR #${pr_number}: unable to annotate namespace ${namespace}; namespace still exists." >&2 - return "$repair_skip" - fi - echo "Namespace ${namespace} was deleted during requested-head repair; dispatching replacement." - return "$repair_dispatch" - fi - if [[ -z "${requested_base_sha}${requested_head_sha}${requested_merge_sha}${requested_image_tag}" ]]; then - echo "Repaired missing requested preview tuple for ${namespace}" - else - echo "Repaired stale requested preview tuple for ${namespace}" - fi - return "$repair_success" - } - - prepare_preview_dispatch() { - local namespace="$1" - local pr_number="$2" - local base_sha="$3" - local head_sha="$4" - local merge_sha="$5" - local image_tag="$6" - local require_deployed_tuple="$7" - local priority="$8" - local expected_namespace_uid="$9" - local fresh_namespace_json - local fresh_namespace_tuple - local current_base_sha - local current_head_sha - local current_merge_sha - local current_image_tag - local requested_base_sha - local requested_head_sha - local requested_merge_sha - local requested_image_tag - local proof_base_sha - local proof_head_sha - local proof_merge_sha - local proof_image_tag - local proof_namespace_uid - local retry_count - local retry_base_sha - local retry_head_sha - local retry_merge_sha - local retry_image_tag - local namespace_uid - local namespace_resource_version - local next_retry_count - local reservation_namespace_json - - proof_retry_reservation_count="" - proof_retry_previous_count="" - proof_retry_previous_base_sha="" - proof_retry_previous_head_sha="" - proof_retry_previous_merge_sha="" - proof_retry_previous_image_tag="" - proof_retry_reservation_namespace_uid="" - proof_retry_reservation_resource_version="" - proof_retry_reservation_base_sha="" - proof_retry_reservation_head_sha="" - proof_retry_reservation_merge_sha="" - proof_retry_reservation_image_tag="" - - if ! fresh_namespace_json="$( - kubectl get namespace "${namespace}" --ignore-not-found -o json - )"; then - echo "Unable to recheck namespace ${namespace} before preview dispatch." >&2 - return 1 - fi - if [[ -z "${fresh_namespace_json}" ]]; then - if [[ "$require_deployed_tuple" == true ]]; then - echo "Skipping PR #${pr_number}: namespace ${namespace} disappeared before proof retry dispatch." >&2 - return 1 - fi - if [[ "$priority" != true && "$available_slots" -le 0 ]]; then - if ! refresh_available_slots; then - echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 - dispatch_outcome_failed=true - return 1 - fi - if [[ "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." - return 1 - fi - fi - return 0 - fi - if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then - echo "Skipping PR #${pr_number}: malformed namespace proof-retry evidence; refusing dispatch." >&2 - return 1 - fi - IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ - requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ - proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ - retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ - namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "$require_deployed_tuple" == true && - ( -z "$expected_namespace_uid" || "$namespace_uid" != "$expected_namespace_uid" ) ]]; then - echo "Skipping PR #${pr_number}: namespace ${namespace} was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 - return 1 - fi - if [[ "${current_base_sha}" != "${base_sha}" || - "${current_head_sha}" != "${head_sha}" || - "${current_merge_sha}" != "${merge_sha}" || - "${current_image_tag}" != "${image_tag}" ]]; then - if [[ "$require_deployed_tuple" == true ]]; then - echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 - return 1 - fi - return 0 - fi - if [[ "${proof_base_sha}" == "${base_sha}" && - "${proof_head_sha}" == "${head_sha}" && - "${proof_merge_sha}" == "${merge_sha}" && - "${proof_image_tag}" == "${image_tag}" && - -n "${namespace_uid}" && - "${proof_namespace_uid}" == "${namespace_uid}" ]]; then - echo "Skipping PR #${pr_number}: proof completed before retry dispatch." >&2 - return 2 - fi - if [[ "${retry_base_sha}" == "${base_sha}" && - "${retry_head_sha}" == "${head_sha}" && - "${retry_merge_sha}" == "${merge_sha}" && - "${retry_image_tag}" == "${image_tag}" ]]; then - next_retry_count=$((10#${retry_count} + 1)) - else - next_retry_count=1 - fi - if (( next_retry_count > 3 )); then - echo "Skipping PR #${pr_number}: proof retry budget exhausted for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}." >&2 - return 3 - fi - if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ - "firemud.dev/proof-retry-count=${next_retry_count}" \ - "firemud.dev/proof-retry-base-sha=${base_sha}" \ - "firemud.dev/proof-retry-head-sha=${head_sha}" \ - "firemud.dev/proof-retry-merge-sha=${merge_sha}" \ - "firemud.dev/proof-retry-image-tag=${image_tag}" \ - --overwrite \ - --resource-version "${namespace_resource_version}" -o json)"; then - echo "Skipping PR #${pr_number}: Namespace ${namespace} changed before proof retry evidence could be recorded." >&2 - return 1 - fi - proof_retry_reservation_count="${next_retry_count}" - proof_retry_previous_count="${retry_count}" - proof_retry_previous_base_sha="${retry_base_sha}" - proof_retry_previous_head_sha="${retry_head_sha}" - proof_retry_previous_merge_sha="${retry_merge_sha}" - proof_retry_previous_image_tag="${retry_image_tag}" - proof_retry_reservation_namespace_uid="${namespace_uid}" - proof_retry_reservation_resource_version="$(jq -er --arg uid "${namespace_uid}" \ - '.metadata | select(.uid == $uid) | .resourceVersion | select(type == "string" and length > 0)' \ - <<<"${reservation_namespace_json}" 2>/dev/null || true)" - proof_retry_reservation_base_sha="${base_sha}" - proof_retry_reservation_head_sha="${head_sha}" - proof_retry_reservation_merge_sha="${merge_sha}" - proof_retry_reservation_image_tag="${image_tag}" - echo "Recorded proof retry ${next_retry_count}/3 for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag})." - return 0 - } - - compensate_rejected_proof_retry() { - local namespace="$1" - local pr_number="$2" - local fresh_namespace_json - local fresh_namespace_tuple - local current_base_sha - local current_head_sha - local current_merge_sha - local current_image_tag - local retry_count - local retry_base_sha - local retry_head_sha - local retry_merge_sha - local retry_image_tag - local namespace_uid - local namespace_resource_version - local -a annotations=() - - if [[ -z "${proof_retry_reservation_count}" ]]; then - return 0 - fi - if ! fresh_namespace_json="$(kubectl get namespace "${namespace}" --ignore-not-found -o json)"; then - echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 - return 1 - fi - if [[ -z "${fresh_namespace_json}" ]] || - ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then - echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 - return 1 - fi - IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ - _ _ _ _ _ _ _ _ _ retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ - namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "${namespace_uid}" != "${proof_retry_reservation_namespace_uid}" || - -z "${proof_retry_reservation_resource_version}" || - "${namespace_resource_version}" != "${proof_retry_reservation_resource_version}" || - "${current_base_sha}" != "${proof_retry_reservation_base_sha}" || - "${current_head_sha}" != "${proof_retry_reservation_head_sha}" || - "${current_merge_sha}" != "${proof_retry_reservation_merge_sha}" || - "${current_image_tag}" != "${proof_retry_reservation_image_tag}" || - "${retry_count}" != "${proof_retry_reservation_count}" || - "${retry_base_sha}" != "${proof_retry_reservation_base_sha}" || - "${retry_head_sha}" != "${proof_retry_reservation_head_sha}" || - "${retry_merge_sha}" != "${proof_retry_reservation_merge_sha}" || - "${retry_image_tag}" != "${proof_retry_reservation_image_tag}" || - -z "${namespace_resource_version}" ]]; then - echo "Proof-retry reservation for PR #${pr_number} changed before confirmed-rejection compensation; leaving its budget charged." >&2 - return 1 - fi - - if [[ -n "${proof_retry_previous_count}" ]]; then - annotations+=( - "firemud.dev/proof-retry-count=${proof_retry_previous_count}" - "firemud.dev/proof-retry-base-sha=${proof_retry_previous_base_sha}" - "firemud.dev/proof-retry-head-sha=${proof_retry_previous_head_sha}" - "firemud.dev/proof-retry-merge-sha=${proof_retry_previous_merge_sha}" - "firemud.dev/proof-retry-image-tag=${proof_retry_previous_image_tag}" - ) - else - annotations+=( - firemud.dev/proof-retry-count- - firemud.dev/proof-retry-base-sha- - firemud.dev/proof-retry-head-sha- - firemud.dev/proof-retry-merge-sha- - firemud.dev/proof-retry-image-tag- - ) - fi - if ! kubectl annotate namespace "${namespace}" "${annotations[@]}" \ - --overwrite --resource-version "${namespace_resource_version}" >/dev/null; then - echo "Unable to release rejected proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 - return 1 - fi - echo "Released proof-retry reservation for PR #${pr_number} after GitHub confirmed dispatch rejection." - } - - active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" - available_slots=$((max_active - active_count)) - dispatch_outcome_failed=false - refresh_available_slots() { - local live_namespaces live_count - if ! live_namespaces="$(kubectl get namespaces -l firemud.dev/preview=true -o name)"; then - return 1 - fi - live_count="$(printf '%s\n' "$live_namespaces" | sed '/^$/d' | wc -l)" - available_slots=$((max_active - live_count)) - } - dispatch_sent=false - completed_preview_source_updated_at="" - preview_source_skipped_render() { - local run_id="$1" attempt="$2" head="$3" - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - [.jobs[] | select(.name == "Render Sanitized Preview Artifact")] as $renders - | ($renders | length) <= 1 - and all($renders[]; .run_id == $id - and ((has("run_attempt") | not) or .run_attempt == $attempt) - and .head_sha == $head and .status == "completed" and .conclusion == "skipped") - ' - } - - automatic_preview_has_tuple() { - local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true - local dispatch_tuple="${tuple#Preview resolved tuple }" - local dispatch_title="Preview dispatch ${dispatch_tuple// /-}" - # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false - latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 - jq -e ' - type == "object" - and (.id | type == "number" and . > 0 and . == floor) - and (.run_attempt | type == "number" and . > 0 and . == floor) - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.event | type == "string" and length > 0) - and (.path | type == "string" and length > 0) - and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) - and (if .status == "completed" then (.conclusion | type == "string" and length > 0) else true end) - ' <<<"$latest" >/dev/null || return 2 - if [[ "$event" == repository_dispatch ]]; then - jq -e --argjson id "$run_id" --arg head "$head" --arg title "$dispatch_title" \ - --arg event "$event" --arg workflow_name "$preview_workflow_name" \ - --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ - --arg default_branch "$DEFAULT_BRANCH" ' - .id == $id and .head_sha == $head - and .event == $event and .workflow_id == $workflow_id - and .repository.full_name == $repository and .head_repository.full_name == $repository - and .head_branch == $default_branch and .display_title == $title - and (.name == $workflow_name or .name == .display_title) - and (.path | IN(".github/workflows/preview.yml", - ".github/workflows/preview.yml@" + $default_branch, - ".github/workflows/preview.yml@refs/heads/" + $default_branch)) - ' <<<"$latest" >/dev/null || return 1 - else - jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" \ - --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ - --arg pr_title "PR preview ${pr}" ' - .id == $id and .head_sha == $head - and .event == $event and .workflow_id == $workflow_id - and .repository.full_name == $repository and .head_repository.full_name == $repository - and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 - and .display_title == $pr_title - and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) - ' <<<"$latest" >/dev/null || return 1 - fi - if jq -e '.status == "completed" and .conclusion != "success"' <<<"$latest" >/dev/null; then return 1; fi - [[ "$jobs_available" == true ]] || return 2 - jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 - if [[ "$event" == repository_dispatch ]]; then - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - .jobs as $jobs - | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) - and all($jobs[]; type == "object" and (.name | type == "string") - and (.run_id | type == "number" and . > 0 and . == floor) - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.status | type == "string") and (.conclusion | type == "string")) - and ([$jobs[] | select(.name == "Preview Plan")] | length) == 1 - and any($jobs[]; .name == "Preview Plan" and .run_id == $id - and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed" and .conclusion == "success" - and (.steps | type == "array") - and all(.steps[]; type == "object" and (.name | type == "string") - and (.status | type == "string") and (.conclusion | type == "string")) - and ([.steps[] | select(.name == "Explain preview skip")] | length) <= 1) - ' <<<"$jobs" >/dev/null || return 2 - if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && - jq -e ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") - ' <<<"$jobs" >/dev/null; then - preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 - # A completed, successful, explicitly explained no-op cannot still hand off a render. - return 1 - fi - if ! jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - .jobs as $jobs - | ([$jobs[] | select(.name == "Render Sanitized Preview Artifact")] | length) == 1 - and any($jobs[]; .name == "Render Sanitized Preview Artifact" and .run_id == $id - and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed" and .conclusion == "success" - and (.steps | type == "array") - and all(.steps[]; type == "object" and (.name | type == "string") - and (.status | type == "string") and (.conclusion | type == "string")) - and ([.steps[] | select(.name == "Upload sanitized render artifact")] | length) == 1 - and any(.steps[]; .name == "Upload sanitized render artifact" - and .status == "completed" and .conclusion == "success")) - ' <<<"$jobs" >/dev/null; then - return 2 - fi - if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then - completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" - return 3 - fi - return 0 - fi - if [[ "$event" == pull_request_target ]]; then return 2; fi - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - .jobs as $jobs - | (($jobs | type) == "array") and (.total_count == ($jobs | length)) - and (.total_count < 100) - and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) - and any($jobs[]; - .name == "Preview Plan" and .run_id == $id - and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed" and .conclusion == "success" - and (.steps | type == "array") - and all(.steps[]; type == "object" and (.name | type == "string") - and (.status | type == "string") and (.conclusion | type == "string")) - and ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length <= 1) - and ([.steps[] | select(.name | startswith("Preview event tuple "))] | length <= 1) - and ([.steps[] | select(.name == "Explain preview skip")] | length <= 1) - and (if ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length) == 1 then - any(.steps[]; (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) - and .status == "completed" and .conclusion == "success") - else - any(.steps[]; (.name | test("^Preview event tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) - and .status == "completed" and .conclusion == "success") - end)) - ' <<<"$jobs" >/dev/null || return 2 - if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && - jq -e ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") - ' <<<"$jobs" >/dev/null; then - preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 - return 1 - fi - if jq -e --arg tuple "$tuple" ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) - ' <<<"$jobs" >/dev/null; then - : - elif jq -e ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) - and .status == "completed" and .conclusion == "success") - ' <<<"$jobs" >/dev/null; then - return 1 - elif jq -e --arg prefix "Preview event tuple pr-${pr} base-" ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; - (.name | startswith($prefix)) and .status == "completed" and .conclusion == "success") - ' <<<"$jobs" >/dev/null; then - # An event marker alone cannot establish either a deployable plan or a completed no-op. - return 2 - else - return 2 - fi - jq -e --arg tuple "$tuple" ' - any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) - ' <<<"$jobs" >/dev/null || return 1 - if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then - completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" - # The trusted consumer may be queued after the active-run inventory. - # Defer one cycle after an exact successful source completion. - return 3 - fi - } - - completed_preview_inventory() { - local event="$1" filter="$2" pages - # The handoff window measures completion (updated_at), not - # creation. An older run can finish or be rerun just before the scan. - pages="$(timeout 30s gh api --method GET --paginate --slurp \ - "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ - -f "event=${event}" -f status=completed -f per_page=100 -f "$filter")" || return 1 - jq -ce --argjson workflow_id "$preview_workflow_id" --arg event "$event" ' - select(type == "array" and length > 0 and length <= 10) - | .[0].total_count as $count - | select(($count | type) == "number" and $count >= 0 and $count < 1000 - and $count == ($count | floor)) - | select(all(.[]; type == "object" and .total_count == $count - and (.workflow_runs | type == "array" and length <= 100))) - | [.[].workflow_runs[]] as $runs - | select(($runs | length) == $count - and ([$runs[].id] | unique | length) == $count - and all($runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) - and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) - and .event == $event and .status == "completed" - and (.conclusion | type == "string") and (.name | type == "string") - and (.display_title | type == "string") and (.head_branch | type == "string") - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.path | type == "string") - and (.updated_at | type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")) - and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") - and (if $event == "pull_request" then (.pull_requests | type == "array") else true end))) - | {workflow_runs: $runs} - ' <<<"$pages" - } - - recent_successful_source_handoff() { - local pr_number="$1" head_sha="$2" tuple_step="$3" - local source_runs dispatch_source_runs source_candidates source_candidate_count source_inventory_now - local run_id run_attempt run_event run_head run_updated_at lookup_status source_updated_epoch now_epoch source_age - local consumer_runs consumer_candidates consumer_candidate_count - local consumer_run_id consumer_attempt consumer_head consumer_status consumer_created_after - local run_name="Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" - local pr_title="PR preview ${pr_number}" - - source_inventory_now="$(date -u +%s)" - if ! source_runs="$(completed_preview_inventory pull_request "head_sha=${head_sha}")" || - ! dispatch_source_runs="$(completed_preview_inventory repository_dispatch "branch=${DEFAULT_BRANCH}")"; then - echo "Recent completed preview-source inventory is unavailable, malformed, or truncated; retry budget unchanged." >&2 - return 2 - fi - if ! source_candidates="$(printf '%s\n' "$source_runs" "$dispatch_source_runs" | jq -r -s \ - --arg repository "$GITHUB_REPOSITORY" --arg head "$head_sha" \ - --arg default_branch "$DEFAULT_BRANCH" --arg workflow_name "$preview_workflow_name" \ - --arg pr_title "$pr_title" --arg run_name "$run_name" \ - --argjson workflow_id "$preview_workflow_id" \ - --argjson now "$source_inventory_now" --argjson window "$preview_handoff_window_seconds" \ - --argjson pr_number "$pr_number" ' - def positive_int: type == "number" and . > 0 and . == floor; - [ (.[0].workflow_runs[] - | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) - and .workflow_id == $workflow_id and .event == "pull_request" - and .status == "completed" and .conclusion == "success" - and (.name == $workflow_name or .name == .display_title) - and .display_title == $pr_title - and .repository.full_name == $repository and .head_repository.full_name == $repository - and .head_sha == $head - and (.path == ".github/workflows/preview.yml" - or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) - and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) - | [.id, .run_attempt, .event, .head_sha, .updated_at]), - (.[1].workflow_runs[] - | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) - and .workflow_id == $workflow_id and .event == "repository_dispatch" - and .status == "completed" and .conclusion == "success" - and (.name == $workflow_name or .name == .display_title) - and .display_title == $run_name - and .repository.full_name == $repository and .head_repository.full_name == $repository - and .head_branch == $default_branch - and (.path | IN(".github/workflows/preview.yml", - ".github/workflows/preview.yml@" + $default_branch, - ".github/workflows/preview.yml@refs/heads/" + $default_branch))) - | [.id, .run_attempt, .event, .head_sha, .updated_at]) - ] - | map(.[4] as $updated_at - | ($updated_at | fromdateiso8601) as $updated - | select($updated <= $now and ($now - $updated) < $window) - | .) - | sort_by(.[0]) | reverse | .[] | @tsv - ')"; then - echo "Unable to parse recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 - return 2 - fi - source_candidate_count="$(printf '%s\n' "$source_candidates" | sed '/^$/d' | wc -l)" - if (( source_candidate_count > 3 )); then - echo "Recent completed preview-source lookup exceeded its three-run bound; retry budget unchanged." >&2 - return 2 - fi - - while IFS=$'\t' read -r run_id run_attempt run_event run_head run_updated_at; do - [[ -n "$run_id" ]] || continue - completed_preview_source_updated_at="" - lookup_status=0 - automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? - if [[ "$lookup_status" -eq 2 ]]; then - echo "Recent preview-source attempt ${run_id} could not be verified; retry budget unchanged." >&2 - return 2 - fi - [[ "$lookup_status" -eq 3 ]] || continue - if [[ "$completed_preview_source_updated_at" != "$run_updated_at" ]]; then - echo "Recent preview-source inventory changed during exact-attempt lookup; retry budget unchanged." >&2 - return 2 - fi - if [[ ! "$completed_preview_source_updated_at" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] || - ! source_updated_epoch="$(date -u -d "$completed_preview_source_updated_at" +%s 2>/dev/null)" || - ! now_epoch="$(date -u +%s)"; then - echo "Recent preview-source completion time is unavailable; retry budget unchanged." >&2 - return 2 - fi - source_age=$((now_epoch - source_updated_epoch)) - if (( source_age < 0 )); then - echo "Recent preview-source completion time is in the future; retry budget unchanged." >&2 - return 2 - fi - if (( source_age >= preview_handoff_window_seconds )); then - continue - fi - - consumer_created_after="$(date -u -d "@$((now_epoch - preview_handoff_window_seconds))" +%Y-%m-%dT%H:%M:%SZ)" - if ! consumer_runs="$(gh api --method GET \ - "repos/${GITHUB_REPOSITORY}/actions/workflows/${consumer_workflow_id}/runs" \ - -f event=workflow_run -f per_page=100 -f "branch=${DEFAULT_BRANCH}" \ - -f "created=>=${consumer_created_after}")"; then - echo "Unable to recheck trusted consumers after recent source completion; retry budget unchanged." >&2 - return 2 - fi - if ! jq -e --argjson workflow_id "$consumer_workflow_id" 'type == "object" - and (.total_count | type == "number" and . >= 0 and . == floor) - and (.workflow_runs | type == "array" and length <= 100) - and (.total_count == (.workflow_runs | length)) - and all(.workflow_runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) - and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) - and (.event | type == "string") and (.status | type == "string") - and (.name | type == "string") and (.display_title | type == "string") - and (.head_branch | type == "string") - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.path | type == "string") - and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string"))' <<<"$consumer_runs" >/dev/null; then - echo "Fresh trusted-consumer inventory is malformed or truncated; retry budget unchanged." >&2 - return 2 - fi - if ! consumer_candidates="$(jq -r \ - --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" \ - --arg pr_title "$pr_title" --arg run_name "$run_name" \ - --argjson workflow_id "$consumer_workflow_id" ' - def positive_int: type == "number" and . > 0 and . == floor; - [ .workflow_runs[] - | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) - and .workflow_id == $workflow_id and .event == "workflow_run" - and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) - and .head_branch == $default_branch - and .repository.full_name == $repository and .head_repository.full_name == $repository - and (.path | IN(".github/workflows/hosted-identity-request.yml", - ".github/workflows/hosted-identity-request.yml@" + $default_branch, - ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) - and (.display_title == $pr_title or .display_title == $run_name)) - | [.id, .run_attempt, .head_sha] - ] | sort_by(.[0]) | reverse | .[] | @tsv - ' <<<"$consumer_runs")"; then - echo "Unable to parse fresh trusted-consumer inventory; retry budget unchanged." >&2 - return 2 - fi - consumer_candidate_count="$(printf '%s\n' "$consumer_candidates" | sed '/^$/d' | wc -l)" - if (( consumer_candidate_count > 3 )); then - echo "Fresh trusted-consumer lookup exceeded its three-run bound; retry budget unchanged." >&2 - return 2 - fi - while IFS=$'\t' read -r consumer_run_id consumer_attempt consumer_head; do - [[ -n "$consumer_run_id" ]] || continue - consumer_status=0 - trusted_consumer_has_tuple "$consumer_run_id" "$consumer_attempt" "$consumer_head" \ - "Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" || consumer_status=$? - if [[ "$consumer_status" -eq 0 ]]; then - echo "Skipping proof retry for PR #${pr_number}: trusted consumer run ${consumer_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." - return 0 - elif [[ "$consumer_status" -eq 2 ]]; then - echo "Fresh trusted-consumer run ${consumer_run_id} could not be verified; retry budget unchanged." >&2 - return 2 - fi - done <<<"$consumer_candidates" - echo "Deferring proof retry for PR #${pr_number}: exact successful preview source run ${run_id} is within the ${preview_handoff_window_seconds}-second trusted-consumer handoff window." - return 3 - done <<<"$source_candidates" - return 1 - } - - trusted_consumer_has_tuple() { - local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest jobs_available=true - # A workflow_run display title is inherited from its source. Use the - # trusted validator's completed attempt evidence to bind the tuple. - jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false - latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 - jq -e --argjson id "$run_id" --argjson workflow_id "$consumer_workflow_id" \ - --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" --arg head "$run_head" ' - .id == $id and .workflow_id == $workflow_id and .event == "workflow_run" and .head_sha == $head - and (.run_attempt | type == "number" and . > 0 and . == floor) - and .repository.full_name == $repository and .head_repository.full_name == $repository - and .head_branch == $default_branch - and (.path | IN(".github/workflows/hosted-identity-request.yml", - ".github/workflows/hosted-identity-request.yml@" + $default_branch, - ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) - and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) - ' <<<"$latest" >/dev/null || return 2 - if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi - [[ "$jobs_available" == true ]] || return 2 - jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 - jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$run_head" ' - .jobs as $jobs - | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) - and ([$jobs[] | select(.name == "Validate Trusted Preview Target")] | length == 1) - and any($jobs[]; .name == "Validate Trusted Preview Target" and .run_id == $id - and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed") - ' <<<"$jobs" >/dev/null || return 2 - jq -e --arg tuple "$tuple" ' - any(.jobs[] | select(.name == "Validate Trusted Preview Target" and .conclusion == "success"); - ([.steps[]? | select(.name | startswith("Trusted preview deploy tuple "))] | length) == 1 - and any(.steps[]?; .name == $tuple and .status == "completed" and .conclusion == "success")) - ' <<<"$jobs" >/dev/null || return 1 - } - - dispatch_candidates() { - while IFS=$'\t' read -r _ pr_number head_sha pr_author pr_base_ref pr_state labels_json_base64; do - if ! labels_json="$(printf '%s' "$labels_json_base64" | base64 --decode 2>/dev/null)" || - [[ -z "$labels_json" ]] || - ! jq -e 'type == "array"' <<<"$labels_json" >/dev/null; then - echo "Skipping PR #${pr_number}: label metadata could not be decoded as a JSON array." >&2 - continue - fi - if ! live_pr_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${pr_number}")" || - [[ "$(jq -r '.state // empty' <<<"${live_pr_json}")" != open ]] || - [[ "$(jq -r '.head.repo.full_name // empty' <<<"${live_pr_json}")" != "${GITHUB_REPOSITORY}" ]] || - [[ "$(jq -r '.base.repo.full_name // empty' <<<"${live_pr_json}")" != "${GITHUB_REPOSITORY}" ]]; then - echo "Skipping PR #${pr_number}: current pull-request ownership or state is not trusted." >&2 - continue - fi - if ! head_sha="$(jq -er '.head.sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${live_pr_json}")" || - ! pr_base_ref="$(jq -er '.base.ref | select(type == "string" and test("^[A-Za-z0-9._/-]+$"))' <<<"${live_pr_json}")" || - ! pr_author="$(jq -er '.user.login | select(type == "string" and length > 0)' <<<"${live_pr_json}")" || - ! live_labels_json="$(jq -c '.labels | if type == "array" then [.[] | {name: .name}] else empty end' <<<"${live_pr_json}")"; then - echo "Skipping PR #${pr_number}: current pull-request identity or labels are malformed." >&2 - continue - fi - head_sha="${head_sha,,}" - if ! jq -e 'type == "array"' <<<"${live_labels_json}" >/dev/null; then - echo "Skipping PR #${pr_number}: current label metadata is malformed." >&2 - continue - fi - labels_json="${live_labels_json}" - pr_state=open - eligibility_output="$( - python3 "$eligibility_script" \ - --operation deploy \ - --state "$pr_state" \ - --base-ref "$pr_base_ref" \ - --author "$pr_author" \ - --labels-json "$labels_json" - )" - eligible="$(sed -n 's/^eligible=//p' <<<"$eligibility_output")" - reason="$(sed -n 's/^reason=//p' <<<"$eligibility_output")" - priority="$(sed -n 's/^priority=//p' <<<"$eligibility_output")" - if [[ "$eligible" != "true" ]]; then - echo "Skipping preview reconcile for PR #${pr_number}: not preview-eligible (reason=${reason}, author=${pr_author}, base=${pr_base_ref})" - continue - fi - - if [[ "$dispatch_sent" == "true" ]]; then - echo "Skipping PR #${pr_number}: the preview dispatch cycle already stopped after a request attempt." - continue - fi - - namespace="pr-${pr_number}" - namespace_exists=false - current_base_sha="" - current_head_sha="" - current_merge_sha="" - current_image_tag="" - requested_base_sha="" - requested_head_sha="" - requested_merge_sha="" - requested_image_tag="" - proof_base_sha="" - proof_head_sha="" - proof_merge_sha="" - proof_image_tag="" - proof_namespace_uid="" - namespace_uid="" - if ! namespace_json="$( - kubectl get namespace "${namespace}" --ignore-not-found -o json - )"; then - echo "Unable to inspect namespace ${namespace}; refusing preview reconcile." >&2 - exit 1 - fi - if [[ -n "${namespace_json}" ]]; then - namespace_exists=true - if ! namespace_tuple="$(parse_namespace_tuple "${namespace_json}")"; then - echo "Skipping PR #${pr_number}: unable to parse namespace ${namespace} snapshot." >&2 - continue - fi - IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ - requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ - proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ - _ _ _ _ _ \ - namespace_uid _ <<<"${namespace_tuple}" - elif [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then - if ! refresh_available_slots; then - echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 - dispatch_outcome_failed=true - continue - fi - if [[ "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." - continue - fi - fi - - mergeable="$(jq -r 'if (.mergeable | type) == "boolean" then (.mergeable | tostring) else "invalid" end' <<<"${live_pr_json}")" - mergeable_state="$(jq -r 'if (.mergeable_state | type) == "string" then .mergeable_state else "invalid" end' <<<"${live_pr_json}")" - if [[ "${mergeable}" != true || "${mergeable_state}" == invalid || - "${mergeable_state}" == unknown || "${mergeable_state}" == dirty || - "${mergeable_state}" == conflicting ]]; then - echo "Skipping preview reconcile for PR #${pr_number}: current base/head merge is not ready (mergeable=${mergeable}, state=${mergeable_state})." - continue - fi - if ! base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${pr_base_ref}")" || - ! base_sha="$(jq -er '.object.sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${base_ref_json}")" || - ! merge_sha="$(jq -er '.merge_commit_sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${live_pr_json}")"; then - echo "Skipping preview reconcile for PR #${pr_number}: current base ref or merge SHA is unavailable." >&2 - continue - fi - base_sha="${base_sha,,}" - merge_sha="${merge_sha,,}" - if ! merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${merge_sha}")" || - ! jq -e \ - --arg merge_sha "${merge_sha}" \ - --arg base_sha "${base_sha}" \ - --arg head_sha "${head_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; then - echo "Skipping preview reconcile for PR #${pr_number}: current merge SHA does not have the exact base/head parents." >&2 - continue - fi - if ! image_tag="$(bash ./dev-tools/hosted/preview/resolve-preview-image-tag.sh \ - "${merge_sha}" "${pr_number}" "${base_sha}")"; then - echo "Skipping preview reconcile for PR #${pr_number}: runtime image identity could not be resolved." >&2 - continue - fi - - if [[ "${current_base_sha}" == "${base_sha}" && - "${current_head_sha}" == "${head_sha}" && - "${current_merge_sha}" == "${merge_sha}" && - "${current_image_tag}" == "${image_tag}" && - "${proof_base_sha}" == "${base_sha}" && - "${proof_head_sha}" == "${head_sha}" && - "${proof_merge_sha}" == "${merge_sha}" && - "${proof_image_tag}" == "${image_tag}" && - -n "${namespace_uid}" && - "${proof_namespace_uid}" == "${namespace_uid}" ]]; then - if [[ "${requested_base_sha}" != "${base_sha}" || - "${requested_head_sha}" != "${head_sha}" || - "${requested_merge_sha}" != "${merge_sha}" || - "${requested_image_tag}" != "${image_tag}" ]]; then - repair_status="$repair_success" - if repair_requested_tuple \ - "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ - "$requested_base_sha" "$requested_head_sha" "$requested_merge_sha" "$requested_image_tag"; then - repair_status="$repair_success" - else - repair_status=$? - fi - case "$repair_status" in - "$repair_success" | "$repair_skip") - continue - ;; - "$repair_dispatch") - namespace_exists=false - ;; - "$repair_abort") - exit 1 - ;; - *) - echo "Unexpected requested-head repair status: ${repair_status}" >&2 - exit 1 - ;; - esac - else - echo "Preview ${namespace} already aligned to ${base_sha}/${head_sha}/${merge_sha}/${image_tag}" - continue - fi - fi - - if [[ "${current_base_sha}" == "${base_sha}" && - "${current_head_sha}" == "${head_sha}" && - "${current_merge_sha}" == "${merge_sha}" && - "${current_image_tag}" == "${image_tag}" ]]; then - echo "Preview ${namespace} deployed tuple is missing proof for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}; dispatching retry." - fi - - if [[ "$namespace_exists" != "true" ]]; then - if [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then - if ! refresh_available_slots; then - echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 - dispatch_outcome_failed=true - continue - fi - if [[ "$available_slots" -le 0 ]]; then - echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." - continue - fi - fi - fi - - if ! preview_candidates="$( - jq -c \ - --arg workflow_name "${preview_workflow_name}" \ - --argjson workflow_id "$preview_workflow_id" \ - --argjson consumer_workflow_id "$consumer_workflow_id" \ - --arg repository "$GITHUB_REPOSITORY" \ - --arg default_branch "${DEFAULT_BRANCH}" \ - --arg pr_title "PR preview ${pr_number}" \ - --argjson pr_number "$pr_number" \ - --arg head_sha "$head_sha" \ - --arg run_name "Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" ' - if type != "array" then - error("workflow runs are not an array") - else - if any(.[]; - (type != "object") - or ((.id | type) != "number") - or ((.name | type) != "string") - or ((.head_branch | type) != "string") - or ((.display_title | type) != "string") - or ((.status | type) != "string") - or ((.firemud_reconciler_branch_filtered | type) != "boolean") - ) then - error("workflow run entry is malformed") - else - def positive_int: type == "number" and . > 0 and . == floor; - def native_same_repo: - .repository.full_name == $repository - and .head_repository.full_name == $repository - and (.id | positive_int) and (.run_attempt | positive_int); - def native_preview: - native_same_repo and .workflow_id == $workflow_id - and (.name == $workflow_name or .name == .display_title); - def trusted_dispatch: - native_preview and .event == "repository_dispatch" - and .head_branch == $default_branch - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@" + $default_branch) - or .path == (".github/workflows/preview.yml@refs/heads/" + $default_branch)) - and .display_title == $run_name; - def provisional_pr: - native_preview and (.event == "pull_request" or .event == "pull_request_target") - and (.path == ".github/workflows/preview.yml" - or (.event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge"))) - and (.display_title == $pr_title or (.event == "pull_request" and .display_title == $run_name)) - and .head_sha == $head_sha - and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1; - def trusted_consumer: - native_same_repo and .workflow_id == $consumer_workflow_id and .event == "workflow_run" - and .head_branch == $default_branch - and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) - and (.path | IN(".github/workflows/hosted-identity-request.yml", - ".github/workflows/hosted-identity-request.yml@" + $default_branch, - ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) - and (.display_title == $pr_title or .display_title == $run_name); - .[] - | select( - ( - (.firemud_reconciler_branch_filtered == false) - or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) - ) - and (trusted_dispatch or provisional_pr or trusted_consumer) - and ( - .status == "requested" - or .status == "queued" - or .status == "in_progress" - or .status == "waiting" - or .status == "pending" - ) - ) - | if trusted_dispatch then {id, exact: true} - else {id, run_attempt, event, head_sha, exact: false} end - end - end - ' <<<"${active_preview_runs_json}" - )"; then - echo "Unable to parse active preview workflow runs; refusing preview reconcile." >&2 - exit 1 - fi - - active_preview_run_id="$(jq -rs '[.[] | select(.exact)][0].id // empty' <<<"$preview_candidates")" - active_preview_lookup_unknown=false - completed_preview_handoff_run_id="" - if [[ -z "$active_preview_run_id" ]]; then - # A same-head title is not proof: the base can move independently. - tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" - consumer_tuple="Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" - lookup_count=0 - while IFS=$'\t' read -r run_id run_attempt run_event run_head; do - [[ -n "$run_id" ]] || continue - if (( lookup_count >= 3 )); then - active_preview_lookup_unknown=true - break - fi - lookup_count=$((lookup_count + 1)) - lookup_status=0 - if [[ "$run_event" == workflow_run ]]; then - trusted_consumer_has_tuple "$run_id" "$run_attempt" "$run_head" "$consumer_tuple" || lookup_status=$? - else - automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? - fi - if [[ "$lookup_status" -eq 0 ]]; then - active_preview_run_id="$run_id" - break - elif [[ "$lookup_status" -eq 3 ]]; then - completed_preview_handoff_run_id="$run_id" - break - elif [[ "$lookup_status" -eq 2 ]]; then - active_preview_lookup_unknown=true - fi - done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[] | [.id, .run_attempt, .event, .head_sha] | @tsv' <<<"$preview_candidates") - fi - - if [[ -n "${active_preview_run_id}" ]]; then - echo "Skipping proof retry for PR #${pr_number}: preview source or trusted consumer run ${active_preview_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." - continue - fi - if [[ -n "${completed_preview_handoff_run_id}" ]]; then - echo "Deferring proof retry for PR #${pr_number}: successful exact preview source run ${completed_preview_handoff_run_id} may still be handing off to the trusted consumer." - continue - fi - if [[ "$active_preview_lookup_unknown" == true ]]; then - echo "Skipping proof retry for PR #${pr_number}: active preview tuple lookup unavailable; retry budget unchanged." - continue - fi - - recent_handoff_status=0 - recent_successful_source_handoff "$pr_number" "$head_sha" "$tuple_step" || recent_handoff_status=$? - case "$recent_handoff_status" in - 0 | 3) - continue - ;; - 2) - echo "Skipping proof retry for PR #${pr_number}: recent preview handoff lookup unavailable; retry budget unchanged." >&2 - continue - ;; - 1) - ;; - *) - echo "Unexpected recent preview handoff status: ${recent_handoff_status}" >&2 - exit 1 - ;; - esac - - require_deployed_tuple=false - if [[ "${namespace_exists}" == "true" && - "${current_base_sha}" == "${base_sha}" && - "${current_head_sha}" == "${head_sha}" && - "${current_merge_sha}" == "${merge_sha}" && - "${current_image_tag}" == "${image_tag}" ]]; then - require_deployed_tuple=true - fi - # A consumer may finish deployment and proof during the active-run lookup. - local proof_retry_reservation_count="" - local proof_retry_previous_count="" - local proof_retry_previous_base_sha="" - local proof_retry_previous_head_sha="" - local proof_retry_previous_merge_sha="" - local proof_retry_previous_image_tag="" - local proof_retry_reservation_namespace_uid="" - local proof_retry_reservation_resource_version="" - local proof_retry_reservation_base_sha="" - local proof_retry_reservation_head_sha="" - local proof_retry_reservation_merge_sha="" - local proof_retry_reservation_image_tag="" - prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ - "$require_deployed_tuple" "$priority" "$namespace_uid" || continue - - echo "Dispatching preview render for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag}) from trusted ref ${DEFAULT_BRANCH}" - dispatch_exit=0 - if dispatch_response="$(gh api --include \ - --method POST \ - "repos/${GITHUB_REPOSITORY}/dispatches" \ - -f event_type=preview-deploy \ - -f 'client_payload[action]=deploy' \ - -f "client_payload[pr_number]=${pr_number}" \ - -f "client_payload[head_sha]=${head_sha}" \ - -f "client_payload[base_ref]=${pr_base_ref}" \ - -f "client_payload[base_sha]=${base_sha}" \ - -f "client_payload[merge_sha]=${merge_sha}" \ - -f "client_payload[image_tag]=${image_tag}" \ - -f 'client_payload[preview_domain]=preview.firedevops.net')"; then - dispatch_exit=0 - else - dispatch_exit=$? - fi - dispatch_status_line_count="$(grep -cE '^HTTP/[0-9.]+ [0-9]{3} ' <<<"${dispatch_response}" || true)" - dispatch_http_status="$(awk '/^HTTP\/[0-9.]+ [0-9][0-9][0-9] / { print $2; exit }' <<<"${dispatch_response}")" - dispatch_retry_after="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^retry-after:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" - dispatch_rate_remaining="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-remaining:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" - dispatch_rate_reset="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-reset:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" - dispatch_error_body="$(awk 'BEGIN { body=0 } { sub(/\r$/, ""); if (!body && $0 == "") { body=1; next } if (body) print }' <<<"${dispatch_response}")" - dispatch_rate_limit_body=false - if jq -e 'type == "object" and ((.message // "") | type == "string" and test("rate limit"; "i"))' \ - <<<"${dispatch_error_body}" >/dev/null 2>&1; then - dispatch_rate_limit_body=true - fi - rate_limited_dispatch=false - if [[ "${dispatch_http_status}" == 429 ]] || - [[ "${dispatch_http_status}" == 403 && - ( "${dispatch_retry_after}" =~ ^[0-9]+$ || - "${dispatch_rate_remaining}" == 0 || - "${dispatch_rate_limit_body}" == true ) ]]; then - rate_limited_dispatch=true - fi - if [[ "${dispatch_exit}" -eq 0 && "${dispatch_status_line_count}" -eq 1 && - "${dispatch_http_status}" == 204 ]]; then - dispatch_sent=true - elif [[ "${dispatch_status_line_count}" -eq 1 && "${dispatch_http_status}" =~ ^4[0-9][0-9]$ ]]; then - dispatch_outcome_failed=true - echo "GitHub confirmed preview dispatch rejection for PR #${pr_number} (HTTP ${dispatch_http_status})." - if ! compensate_rejected_proof_retry "$namespace" "$pr_number"; then - echo "The rejected dispatch could not be safely compensated; its proof-retry budget remains charged." >&2 - fi - if [[ "${rate_limited_dispatch}" == true ]]; then - rate_limit_wait_seconds=60 - if [[ "${dispatch_retry_after}" =~ ^[0-9]+$ ]]; then - rate_limit_wait_seconds=$((10#${dispatch_retry_after})) - elif [[ "${dispatch_rate_remaining}" == 0 && "${dispatch_rate_reset}" =~ ^[0-9]+$ ]]; then - current_epoch="$(date -u +%s)" - rate_limit_wait_seconds=$((10#${dispatch_rate_reset} - current_epoch)) - (( rate_limit_wait_seconds > 0 )) || rate_limit_wait_seconds=60 - fi - echo "GitHub rate-limited preview dispatch; stopping this cycle and waiting ${rate_limit_wait_seconds} seconds before another attempt." - dispatch_sent=true - sleep "${rate_limit_wait_seconds}" - fi - else - dispatch_outcome_failed=true - echo "Preview dispatch outcome for PR #${pr_number} is ambiguous (gh=${dispatch_exit}, HTTP=${dispatch_http_status:-unknown}); proof-retry budget remains charged." >&2 - dispatch_sent=true - fi - done - } - - candidate_rows="$( - gh api --paginate "repos/${GITHUB_REPOSITORY}/pulls?state=open&per_page=100" \ - --jq '.[] | [(if (.labels | map(.name) | any(. == "preview:priority")) then 0 else 1 end), .number, .head.sha, .user.login, .base.ref, .state, (.labels | map({name: .name}) | tojson | @base64)] | @tsv' \ - | sort -t $'\t' -k1,1n -k2,2n - )" - if [[ -n "$candidate_rows" ]]; then - active_preview_run_sets=() - for active_status in requested queued in_progress waiting pending; do - for active_run_scope in branch pull_request pull_request_target workflow_run; do - if [[ "$active_run_scope" == branch ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" - active_run_branch_filtered=true - elif [[ "$active_run_scope" == pull_request || "$active_run_scope" == pull_request_target ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100" - active_run_branch_filtered=false - else - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=workflow_run&status=${active_status}&per_page=100" - active_run_branch_filtered=false - fi - if ! active_preview_run_pages_json="$(gh api --paginate --slurp "$active_run_query")"; then - echo "Unable to inspect active preview workflow runs; refusing preview reconcile." >&2 - exit 1 - fi - if ! active_preview_runs_for_query="$( - jq -c \ - --argjson branch_filtered "$active_run_branch_filtered" ' - if type != "array" then - error("workflow run pages are not an array") - else - [ - .[] as $page - | if ($page | type) != "object" or ($page.workflow_runs | type) != "array" then - error("workflow run page is malformed") - else - $page.workflow_runs[] - end - | if type != "object" then - error("workflow run entry is malformed") - else - . + {firemud_reconciler_branch_filtered: $branch_filtered} - end - ] - end - ' <<<"$active_preview_run_pages_json" - )"; then - echo "Unable to normalize active preview workflow runs; refusing preview reconcile." >&2 - exit 1 - fi - active_preview_run_sets+=("$active_preview_runs_for_query") - done - done - if ! active_preview_runs_json="$( - printf '%s\n' "${active_preview_run_sets[@]}" | jq -c -s ' - if any(.[]; type != "array") then - error("active preview workflow run result is not an array") - else - add - | group_by(.id) - | map( - . as $runs - | if any($runs[]; - .name != $runs[0].name - or .head_branch != $runs[0].head_branch - or .display_title != $runs[0].display_title - ) then - error("active preview workflow run metadata differs between query scopes") - else - $runs[0] + { - firemud_reconciler_branch_filtered: all( - $runs[]; - .firemud_reconciler_branch_filtered == true - ) - } - end - ) - end - ' - )"; then - echo "Unable to merge active preview workflow runs; refusing preview reconcile." >&2 - exit 1 - fi - if ! preview_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/preview.yml" | jq -er --arg name "$preview_workflow_name" ' - select(.name == $name and .path == ".github/workflows/preview.yml") - | .id | select(type == "number" and . > 0 and . == floor) - ')"; then - echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 - exit 1 - fi - if ! consumer_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/hosted-identity-request.yml" | jq -er ' - select(.name == "Trusted Hosted Identity Request" and .path == ".github/workflows/hosted-identity-request.yml") - | .id | select(type == "number" and . > 0 and . == floor) - ')"; then - echo "Unable to establish canonical trusted preview consumer identity; refusing preview reconcile." >&2 - exit 1 - fi - dispatch_candidates <<<"$candidate_rows" - fi - if [[ "$dispatch_outcome_failed" == true ]]; then - echo "One or more preview dispatch outcomes or capacity checks failed; review this job before another repair cycle." >&2 - exit 1 - fi + run: bash ./dev-tools/hosted/preview/reconcile-preview-deploys.sh - name: Remove preview kubeconfig if: ${{ always() }} diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh new file mode 100644 index 0000000000..c8b8202e7b --- /dev/null +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -0,0 +1,1335 @@ +#!/usr/bin/env bash +set -euo pipefail +preview_workflow_name="PR Preview Environment" +eligibility_script="./dev-tools/hosted/preview/preview-eligibility.py" +max_active="${PREVIEW_MAX_ACTIVE:-2}" +preview_handoff_window_seconds=600 + +parse_namespace_tuple() { + jq -er ' + def annotation($annotations; $name): + ($annotations[$name] // "") + | if type != "string" then + error("namespace preview annotation is not a string") + elif test("[|\\r\\n]") then + error("namespace preview annotation contains an unsafe delimiter") + else + . + end; + def metadata_field($metadata; $name): + ($metadata[$name] // "") + | if type != "string" then + error("namespace metadata field is not a string") + elif test("[|\\r\\n]") then + error("namespace metadata field contains an unsafe delimiter") + else + . + end; + if type != "object" or (.metadata | type) != "object" then + error("namespace snapshot is not an object with metadata") + elif ((.metadata.annotations // {}) | type) != "object" then + error("namespace annotations are not an object") + else + (.metadata.annotations // {}) as $annotations + | [ + annotation($annotations; "firemud.dev/last-preview-base-sha"), + annotation($annotations; "firemud.dev/last-preview-head-sha"), + annotation($annotations; "firemud.dev/last-preview-merge-sha"), + annotation($annotations; "firemud.dev/last-preview-image-tag"), + annotation($annotations; "firemud.dev/requested-preview-base-sha"), + annotation($annotations; "firemud.dev/requested-preview-head-sha"), + annotation($annotations; "firemud.dev/requested-preview-merge-sha"), + annotation($annotations; "firemud.dev/requested-preview-image-tag"), + annotation($annotations; "firemud.dev/proof-preview-base-sha"), + annotation($annotations; "firemud.dev/proof-preview-head-sha"), + annotation($annotations; "firemud.dev/proof-preview-merge-sha"), + annotation($annotations; "firemud.dev/proof-preview-image-tag"), + annotation($annotations; "firemud.dev/proof-preview-namespace-uid"), + annotation($annotations; "firemud.dev/proof-retry-count"), + annotation($annotations; "firemud.dev/proof-retry-base-sha"), + annotation($annotations; "firemud.dev/proof-retry-head-sha"), + annotation($annotations; "firemud.dev/proof-retry-merge-sha"), + annotation($annotations; "firemud.dev/proof-retry-image-tag"), + metadata_field(.metadata; "uid"), + metadata_field(.metadata; "resourceVersion") + ] + | if ( + (.[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") + or ( + (.[13] | test("^[0-3]$")) + and (.[14] | test("^[0-9a-fA-F]{40}$")) + and (.[15] | test("^[0-9a-fA-F]{40}$")) + and (.[16] | test("^[0-9a-fA-F]{40}$")) + and (.[17] | test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) + ) + ) then . else error("namespace proof-retry evidence is malformed") end + | join("|") + end + ' <<<"$1" +} + +readonly repair_success=0 +readonly repair_skip=10 +readonly repair_dispatch=11 +readonly repair_abort=20 + +repair_requested_tuple() { + local namespace="$1" + local pr_number="$2" + local base_sha="$3" + local head_sha="$4" + local merge_sha="$5" + local image_tag="$6" + local requested_base_sha="$7" + local requested_head_sha="$8" + local requested_merge_sha="$9" + local requested_image_tag="${10}" + local fresh_namespace_json + local fresh_namespace_tuple + local fresh_last_base_sha + local fresh_last_head_sha + local fresh_last_merge_sha + local fresh_last_image_tag + local fresh_requested_base_sha + local fresh_requested_head_sha + local fresh_requested_merge_sha + local fresh_requested_image_tag + local fresh_proof_base_sha + local fresh_proof_head_sha + local fresh_proof_merge_sha + local fresh_proof_image_tag + local fresh_proof_namespace_uid + local fresh_namespace_uid + local fresh_namespace_resource_version + local annotation_failure_namespace_json + + if ! fresh_namespace_json="$( + kubectl get namespace "${namespace}" --ignore-not-found -o json + )"; then + echo "Unable to recheck namespace ${namespace} before annotation repair." >&2 + return "$repair_abort" + fi + if [[ -z "${fresh_namespace_json}" ]]; then + return "$repair_dispatch" + fi + if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then + echo "Skipping PR #${pr_number}: unable to parse namespace ${namespace} recheck." >&2 + return "$repair_skip" + fi + IFS='|' read -r fresh_last_base_sha fresh_last_head_sha fresh_last_merge_sha fresh_last_image_tag \ + fresh_requested_base_sha fresh_requested_head_sha fresh_requested_merge_sha fresh_requested_image_tag \ + fresh_proof_base_sha fresh_proof_head_sha fresh_proof_merge_sha fresh_proof_image_tag \ + fresh_proof_namespace_uid _ _ _ _ _ \ + fresh_namespace_uid \ + fresh_namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "${fresh_last_base_sha}" != "${base_sha}" || + "${fresh_last_head_sha}" != "${head_sha}" || + "${fresh_last_merge_sha}" != "${merge_sha}" || + "${fresh_last_image_tag}" != "${image_tag}" ]]; then + echo "Skipping preview repair for PR #${pr_number}: deployed preview tuple changed during annotation repair check." + return "$repair_skip" + fi + if [[ "${fresh_proof_base_sha}" != "${base_sha}" || + "${fresh_proof_head_sha}" != "${head_sha}" || + "${fresh_proof_merge_sha}" != "${merge_sha}" || + "${fresh_proof_image_tag}" != "${image_tag}" || + -z "${fresh_namespace_uid}" || + "${fresh_proof_namespace_uid}" != "${fresh_namespace_uid}" ]]; then + echo "Preview ${namespace} deployed tuple is missing proof for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}; dispatching retry." + return "$repair_dispatch" + fi + if [[ "${fresh_requested_base_sha}" == "${base_sha}" && + "${fresh_requested_head_sha}" == "${head_sha}" && + "${fresh_requested_merge_sha}" == "${merge_sha}" && + "${fresh_requested_image_tag}" == "${image_tag}" ]]; then + echo "Preview ${namespace} already aligned to ${base_sha}/${head_sha}/${merge_sha}/${image_tag}" + return "$repair_success" + fi + if [[ "${fresh_requested_base_sha}" != "${requested_base_sha}" || + "${fresh_requested_head_sha}" != "${requested_head_sha}" || + "${fresh_requested_merge_sha}" != "${requested_merge_sha}" || + "${fresh_requested_image_tag}" != "${requested_image_tag}" ]]; then + echo "Skipping preview repair for PR #${pr_number}: requested preview tuple changed during annotation repair check." + return "$repair_skip" + fi + if ! kubectl annotate namespace "${namespace}" \ + "firemud.dev/requested-preview-base-sha=${base_sha}" \ + "firemud.dev/requested-preview-head-sha=${head_sha}" \ + "firemud.dev/requested-preview-merge-sha=${merge_sha}" \ + "firemud.dev/requested-preview-image-tag=${image_tag}" \ + --overwrite \ + --resource-version "${fresh_namespace_resource_version}" >/dev/null; then + if ! annotation_failure_namespace_json="$( + kubectl get namespace "${namespace}" --ignore-not-found -o json + )"; then + echo "Unable to recheck namespace ${namespace} after annotation failure; refusing preview reconcile." >&2 + return "$repair_abort" + fi + if [[ -n "${annotation_failure_namespace_json}" ]]; then + echo "Skipping PR #${pr_number}: unable to annotate namespace ${namespace}; namespace still exists." >&2 + return "$repair_skip" + fi + echo "Namespace ${namespace} was deleted during requested-head repair; dispatching replacement." + return "$repair_dispatch" + fi + if [[ -z "${requested_base_sha}${requested_head_sha}${requested_merge_sha}${requested_image_tag}" ]]; then + echo "Repaired missing requested preview tuple for ${namespace}" + else + echo "Repaired stale requested preview tuple for ${namespace}" + fi + return "$repair_success" +} + +prepare_preview_dispatch() { + local namespace="$1" + local pr_number="$2" + local base_sha="$3" + local head_sha="$4" + local merge_sha="$5" + local image_tag="$6" + local require_deployed_tuple="$7" + local priority="$8" + local expected_namespace_uid="$9" + local fresh_namespace_json + local fresh_namespace_tuple + local current_base_sha + local current_head_sha + local current_merge_sha + local current_image_tag + local requested_base_sha + local requested_head_sha + local requested_merge_sha + local requested_image_tag + local proof_base_sha + local proof_head_sha + local proof_merge_sha + local proof_image_tag + local proof_namespace_uid + local retry_count + local retry_base_sha + local retry_head_sha + local retry_merge_sha + local retry_image_tag + local namespace_uid + local namespace_resource_version + local next_retry_count + local reservation_namespace_json + + proof_retry_reservation_count="" + proof_retry_previous_count="" + proof_retry_previous_base_sha="" + proof_retry_previous_head_sha="" + proof_retry_previous_merge_sha="" + proof_retry_previous_image_tag="" + proof_retry_reservation_namespace_uid="" + proof_retry_reservation_resource_version="" + proof_retry_reservation_base_sha="" + proof_retry_reservation_head_sha="" + proof_retry_reservation_merge_sha="" + proof_retry_reservation_image_tag="" + + if ! fresh_namespace_json="$( + kubectl get namespace "${namespace}" --ignore-not-found -o json + )"; then + echo "Unable to recheck namespace ${namespace} before preview dispatch." >&2 + return 1 + fi + if [[ -z "${fresh_namespace_json}" ]]; then + if [[ "$require_deployed_tuple" == true ]]; then + echo "Skipping PR #${pr_number}: namespace ${namespace} disappeared before proof retry dispatch." >&2 + return 1 + fi + if [[ "$priority" != true && "$available_slots" -le 0 ]]; then + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + return 1 + fi + fi + return 0 + fi + if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then + echo "Skipping PR #${pr_number}: malformed namespace proof-retry evidence; refusing dispatch." >&2 + return 1 + fi + IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ + requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ + proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ + retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ + namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "$require_deployed_tuple" == true && + ( -z "$expected_namespace_uid" || "$namespace_uid" != "$expected_namespace_uid" ) ]]; then + echo "Skipping PR #${pr_number}: namespace ${namespace} was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 + return 1 + fi + if [[ "${current_base_sha}" != "${base_sha}" || + "${current_head_sha}" != "${head_sha}" || + "${current_merge_sha}" != "${merge_sha}" || + "${current_image_tag}" != "${image_tag}" ]]; then + if [[ "$require_deployed_tuple" == true ]]; then + echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 + return 1 + fi + return 0 + fi + if [[ "${proof_base_sha}" == "${base_sha}" && + "${proof_head_sha}" == "${head_sha}" && + "${proof_merge_sha}" == "${merge_sha}" && + "${proof_image_tag}" == "${image_tag}" && + -n "${namespace_uid}" && + "${proof_namespace_uid}" == "${namespace_uid}" ]]; then + echo "Skipping PR #${pr_number}: proof completed before retry dispatch." >&2 + return 2 + fi + if [[ "${retry_base_sha}" == "${base_sha}" && + "${retry_head_sha}" == "${head_sha}" && + "${retry_merge_sha}" == "${merge_sha}" && + "${retry_image_tag}" == "${image_tag}" ]]; then + next_retry_count=$((10#${retry_count} + 1)) + else + next_retry_count=1 + fi + if (( next_retry_count > 3 )); then + echo "Skipping PR #${pr_number}: proof retry budget exhausted for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}." >&2 + return 3 + fi + if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ + "firemud.dev/proof-retry-count=${next_retry_count}" \ + "firemud.dev/proof-retry-base-sha=${base_sha}" \ + "firemud.dev/proof-retry-head-sha=${head_sha}" \ + "firemud.dev/proof-retry-merge-sha=${merge_sha}" \ + "firemud.dev/proof-retry-image-tag=${image_tag}" \ + --overwrite \ + --resource-version "${namespace_resource_version}" -o json)"; then + echo "Skipping PR #${pr_number}: Namespace ${namespace} changed before proof retry evidence could be recorded." >&2 + return 1 + fi + proof_retry_reservation_count="${next_retry_count}" + proof_retry_previous_count="${retry_count}" + proof_retry_previous_base_sha="${retry_base_sha}" + proof_retry_previous_head_sha="${retry_head_sha}" + proof_retry_previous_merge_sha="${retry_merge_sha}" + proof_retry_previous_image_tag="${retry_image_tag}" + proof_retry_reservation_namespace_uid="${namespace_uid}" + proof_retry_reservation_resource_version="$(jq -er --arg uid "${namespace_uid}" \ + '.metadata | select(.uid == $uid) | .resourceVersion | select(type == "string" and length > 0)' \ + <<<"${reservation_namespace_json}" 2>/dev/null || true)" + proof_retry_reservation_base_sha="${base_sha}" + proof_retry_reservation_head_sha="${head_sha}" + proof_retry_reservation_merge_sha="${merge_sha}" + proof_retry_reservation_image_tag="${image_tag}" + echo "Recorded proof retry ${next_retry_count}/3 for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag})." + return 0 +} + +compensate_rejected_proof_retry() { + local namespace="$1" + local pr_number="$2" + local fresh_namespace_json + local fresh_namespace_tuple + local current_base_sha + local current_head_sha + local current_merge_sha + local current_image_tag + local retry_count + local retry_base_sha + local retry_head_sha + local retry_merge_sha + local retry_image_tag + local namespace_uid + local namespace_resource_version + local -a annotations=() + + if [[ -z "${proof_retry_reservation_count}" ]]; then + return 0 + fi + if ! fresh_namespace_json="$(kubectl get namespace "${namespace}" --ignore-not-found -o json)"; then + echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + if [[ -z "${fresh_namespace_json}" ]] || + ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then + echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ + _ _ _ _ _ _ _ _ _ retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ + namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "${namespace_uid}" != "${proof_retry_reservation_namespace_uid}" || + -z "${proof_retry_reservation_resource_version}" || + "${namespace_resource_version}" != "${proof_retry_reservation_resource_version}" || + "${current_base_sha}" != "${proof_retry_reservation_base_sha}" || + "${current_head_sha}" != "${proof_retry_reservation_head_sha}" || + "${current_merge_sha}" != "${proof_retry_reservation_merge_sha}" || + "${current_image_tag}" != "${proof_retry_reservation_image_tag}" || + "${retry_count}" != "${proof_retry_reservation_count}" || + "${retry_base_sha}" != "${proof_retry_reservation_base_sha}" || + "${retry_head_sha}" != "${proof_retry_reservation_head_sha}" || + "${retry_merge_sha}" != "${proof_retry_reservation_merge_sha}" || + "${retry_image_tag}" != "${proof_retry_reservation_image_tag}" || + -z "${namespace_resource_version}" ]]; then + echo "Proof-retry reservation for PR #${pr_number} changed before confirmed-rejection compensation; leaving its budget charged." >&2 + return 1 + fi + + if [[ -n "${proof_retry_previous_count}" ]]; then + annotations+=( + "firemud.dev/proof-retry-count=${proof_retry_previous_count}" + "firemud.dev/proof-retry-base-sha=${proof_retry_previous_base_sha}" + "firemud.dev/proof-retry-head-sha=${proof_retry_previous_head_sha}" + "firemud.dev/proof-retry-merge-sha=${proof_retry_previous_merge_sha}" + "firemud.dev/proof-retry-image-tag=${proof_retry_previous_image_tag}" + ) + else + annotations+=( + firemud.dev/proof-retry-count- + firemud.dev/proof-retry-base-sha- + firemud.dev/proof-retry-head-sha- + firemud.dev/proof-retry-merge-sha- + firemud.dev/proof-retry-image-tag- + ) + fi + if ! kubectl annotate namespace "${namespace}" "${annotations[@]}" \ + --overwrite --resource-version "${namespace_resource_version}" >/dev/null; then + echo "Unable to release rejected proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + return 1 + fi + echo "Released proof-retry reservation for PR #${pr_number} after GitHub confirmed dispatch rejection." +} + +active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" +available_slots=$((max_active - active_count)) +dispatch_outcome_failed=false +refresh_available_slots() { + local live_namespaces live_count + if ! live_namespaces="$(kubectl get namespaces -l firemud.dev/preview=true -o name)"; then + return 1 + fi + live_count="$(printf '%s\n' "$live_namespaces" | sed '/^$/d' | wc -l)" + available_slots=$((max_active - live_count)) +} +dispatch_sent=false +completed_preview_source_updated_at="" +preview_source_skipped_render() { + local run_id="$1" attempt="$2" head="$3" + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + [.jobs[] | select(.name == "Render Sanitized Preview Artifact")] as $renders + | ($renders | length) <= 1 + and all($renders[]; .run_id == $id + and ((has("run_attempt") | not) or .run_attempt == $attempt) + and .head_sha == $head and .status == "completed" and .conclusion == "skipped") + ' +} + +automatic_preview_has_tuple() { + local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true + local dispatch_tuple="${tuple#Preview resolved tuple }" + local dispatch_title="Preview dispatch ${dispatch_tuple// /-}" + # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 + jq -e ' + type == "object" + and (.id | type == "number" and . > 0 and . == floor) + and (.run_attempt | type == "number" and . > 0 and . == floor) + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.event | type == "string" and length > 0) + and (.path | type == "string" and length > 0) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) + and (if .status == "completed" then (.conclusion | type == "string" and length > 0) else true end) + ' <<<"$latest" >/dev/null || return 2 + if [[ "$event" == repository_dispatch ]]; then + jq -e --argjson id "$run_id" --arg head "$head" --arg title "$dispatch_title" \ + --arg event "$event" --arg workflow_name "$preview_workflow_name" \ + --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ + --arg default_branch "$DEFAULT_BRANCH" ' + .id == $id and .head_sha == $head + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch and .display_title == $title + and (.name == $workflow_name or .name == .display_title) + and (.path | IN(".github/workflows/preview.yml", + ".github/workflows/preview.yml@" + $default_branch, + ".github/workflows/preview.yml@refs/heads/" + $default_branch)) + ' <<<"$latest" >/dev/null || return 1 + else + jq -e --argjson id "$run_id" --arg head "$head" --arg pr "$pr" --arg event "$event" \ + --argjson workflow_id "$preview_workflow_id" --arg repository "$GITHUB_REPOSITORY" \ + --arg pr_title "PR preview ${pr}" ' + .id == $id and .head_sha == $head + and .event == $event and .workflow_id == $workflow_id + and .repository.full_name == $repository and .head_repository.full_name == $repository + and ([.pull_requests[]? | select(.number == ($pr | tonumber))] | length) == 1 + and .display_title == $pr_title + and (.path == ".github/workflows/preview.yml" or ($event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + $pr + "/merge"))) + ' <<<"$latest" >/dev/null || return 1 + fi + if jq -e '.status == "completed" and .conclusion != "success"' <<<"$latest" >/dev/null; then return 1; fi + [[ "$jobs_available" == true ]] || return 2 + jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 + if [[ "$event" == repository_dispatch ]]; then + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) + and all($jobs[]; type == "object" and (.name | type == "string") + and (.run_id | type == "number" and . > 0 and . == floor) + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.status | type == "string") and (.conclusion | type == "string")) + and ([$jobs[] | select(.name == "Preview Plan")] | length) == 1 + and any($jobs[]; .name == "Preview Plan" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name == "Explain preview skip")] | length) <= 1) + ' <<<"$jobs" >/dev/null || return 2 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && + jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 + # A completed, successful, explicitly explained no-op cannot still hand off a render. + return 1 + fi + if ! jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | ([$jobs[] | select(.name == "Render Sanitized Preview Artifact")] | length) == 1 + and any($jobs[]; .name == "Render Sanitized Preview Artifact" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name == "Upload sanitized render artifact")] | length) == 1 + and any(.steps[]; .name == "Upload sanitized render artifact" + and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null; then + return 2 + fi + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" + return 3 + fi + return 0 + fi + if [[ "$event" == pull_request_target ]]; then return 2; fi + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) + and (.total_count < 100) + and ([$jobs[] | select(.name == "Preview Plan")] | length == 1) + and any($jobs[]; + .name == "Preview Plan" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length <= 1) + and ([.steps[] | select(.name | startswith("Preview event tuple "))] | length <= 1) + and ([.steps[] | select(.name == "Explain preview skip")] | length <= 1) + and (if ([.steps[] | select(.name | startswith("Preview resolved tuple "))] | length) == 1 then + any(.steps[]; (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + else + any(.steps[]; (.name | test("^Preview event tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + end)) + ' <<<"$jobs" >/dev/null || return 2 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null && + jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + .name == "Explain preview skip" and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + preview_source_skipped_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 + return 1 + fi + if jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) + ' <<<"$jobs" >/dev/null; then + : + elif jq -e ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + (.name | test("^Preview resolved tuple pr-[1-9][0-9]* base-[0-9a-f]{40} head-[0-9a-f]{40} merge-[0-9a-f]{40}$")) + and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + return 1 + elif jq -e --arg prefix "Preview event tuple pr-${pr} base-" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; + (.name | startswith($prefix)) and .status == "completed" and .conclusion == "success") + ' <<<"$jobs" >/dev/null; then + # An event marker alone cannot establish either a deployable plan or a completed no-op. + return 2 + else + return 2 + fi + jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) + ' <<<"$jobs" >/dev/null || return 1 + if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" + # The trusted consumer may be queued after the active-run inventory. + # Defer one cycle after an exact successful source completion. + return 3 + fi +} + +completed_preview_inventory() { + local event="$1" filter="$2" pages + # The handoff window measures completion (updated_at), not + # creation. An older run can finish or be rerun just before the scan. + pages="$(timeout 30s gh api --method GET --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ + -f "event=${event}" -f status=completed -f per_page=100 -f "$filter")" || return 1 + jq -ce --argjson workflow_id "$preview_workflow_id" --arg event "$event" ' + select(type == "array" and length > 0 and length <= 10) + | .[0].total_count as $count + | select(($count | type) == "number" and $count >= 0 and $count < 1000 + and $count == ($count | floor)) + | select(all(.[]; type == "object" and .total_count == $count + and (.workflow_runs | type == "array" and length <= 100))) + | [.[].workflow_runs[]] as $runs + | select(($runs | length) == $count + and ([$runs[].id] | unique | length) == $count + and all($runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) + and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) + and .event == $event and .status == "completed" + and (.conclusion | type == "string") and (.name | type == "string") + and (.display_title | type == "string") and (.head_branch | type == "string") + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | type == "string") + and (.updated_at | type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")) + and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") + and (if $event == "pull_request" then (.pull_requests | type == "array") else true end))) + | {workflow_runs: $runs} + ' <<<"$pages" +} + +recent_successful_source_handoff() { + local pr_number="$1" head_sha="$2" tuple_step="$3" + local source_runs dispatch_source_runs source_candidates source_candidate_count source_inventory_now + local run_id run_attempt run_event run_head run_updated_at lookup_status source_updated_epoch now_epoch source_age + local consumer_runs consumer_candidates consumer_candidate_count + local consumer_run_id consumer_attempt consumer_head consumer_status consumer_created_after + local run_name="Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" + local pr_title="PR preview ${pr_number}" + + source_inventory_now="$(date -u +%s)" + if ! source_runs="$(completed_preview_inventory pull_request "head_sha=${head_sha}")" || + ! dispatch_source_runs="$(completed_preview_inventory repository_dispatch "branch=${DEFAULT_BRANCH}")"; then + echo "Recent completed preview-source inventory is unavailable, malformed, or truncated; retry budget unchanged." >&2 + return 2 + fi + if ! source_candidates="$(printf '%s\n' "$source_runs" "$dispatch_source_runs" | jq -r -s \ + --arg repository "$GITHUB_REPOSITORY" --arg head "$head_sha" \ + --arg default_branch "$DEFAULT_BRANCH" --arg workflow_name "$preview_workflow_name" \ + --arg pr_title "$pr_title" --arg run_name "$run_name" \ + --argjson workflow_id "$preview_workflow_id" \ + --argjson now "$source_inventory_now" --argjson window "$preview_handoff_window_seconds" \ + --argjson pr_number "$pr_number" ' + def positive_int: type == "number" and . > 0 and . == floor; + [ (.[0].workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "pull_request" + and .status == "completed" and .conclusion == "success" + and (.name == $workflow_name or .name == .display_title) + and .display_title == $pr_title + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_sha == $head + and (.path == ".github/workflows/preview.yml" + or .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge")) + and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1) + | [.id, .run_attempt, .event, .head_sha, .updated_at]), + (.[1].workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "repository_dispatch" + and .status == "completed" and .conclusion == "success" + and (.name == $workflow_name or .name == .display_title) + and .display_title == $run_name + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch + and (.path | IN(".github/workflows/preview.yml", + ".github/workflows/preview.yml@" + $default_branch, + ".github/workflows/preview.yml@refs/heads/" + $default_branch))) + | [.id, .run_attempt, .event, .head_sha, .updated_at]) + ] + | map(.[4] as $updated_at + | ($updated_at | fromdateiso8601) as $updated + | select($updated <= $now and ($now - $updated) < $window) + | .) + | sort_by(.[0]) | reverse | .[] | @tsv + ')"; then + echo "Unable to parse recent completed preview sources for PR #${pr_number}; retry budget unchanged." >&2 + return 2 + fi + source_candidate_count="$(printf '%s\n' "$source_candidates" | sed '/^$/d' | wc -l)" + if (( source_candidate_count > 3 )); then + echo "Recent completed preview-source lookup exceeded its three-run bound; retry budget unchanged." >&2 + return 2 + fi + + while IFS=$'\t' read -r run_id run_attempt run_event run_head run_updated_at; do + [[ -n "$run_id" ]] || continue + completed_preview_source_updated_at="" + lookup_status=0 + automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + if [[ "$lookup_status" -eq 2 ]]; then + echo "Recent preview-source attempt ${run_id} could not be verified; retry budget unchanged." >&2 + return 2 + fi + [[ "$lookup_status" -eq 3 ]] || continue + if [[ "$completed_preview_source_updated_at" != "$run_updated_at" ]]; then + echo "Recent preview-source inventory changed during exact-attempt lookup; retry budget unchanged." >&2 + return 2 + fi + if [[ ! "$completed_preview_source_updated_at" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] || + ! source_updated_epoch="$(date -u -d "$completed_preview_source_updated_at" +%s 2>/dev/null)" || + ! now_epoch="$(date -u +%s)"; then + echo "Recent preview-source completion time is unavailable; retry budget unchanged." >&2 + return 2 + fi + source_age=$((now_epoch - source_updated_epoch)) + if (( source_age < 0 )); then + echo "Recent preview-source completion time is in the future; retry budget unchanged." >&2 + return 2 + fi + if (( source_age >= preview_handoff_window_seconds )); then + continue + fi + + consumer_created_after="$(date -u -d "@$((now_epoch - preview_handoff_window_seconds))" +%Y-%m-%dT%H:%M:%SZ)" + if ! consumer_runs="$(gh api --method GET \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/${consumer_workflow_id}/runs" \ + -f event=workflow_run -f per_page=100 -f "branch=${DEFAULT_BRANCH}" \ + -f "created=>=${consumer_created_after}")"; then + echo "Unable to recheck trusted consumers after recent source completion; retry budget unchanged." >&2 + return 2 + fi + if ! jq -e --argjson workflow_id "$consumer_workflow_id" 'type == "object" + and (.total_count | type == "number" and . >= 0 and . == floor) + and (.workflow_runs | type == "array" and length <= 100) + and (.total_count == (.workflow_runs | length)) + and all(.workflow_runs[]; type == "object" and (.id | type == "number" and . > 0 and . == floor) + and .workflow_id == $workflow_id and (.run_attempt | type == "number" and . > 0 and . == floor) + and (.event | type == "string") and (.status | type == "string") + and (.name | type == "string") and (.display_title | type == "string") + and (.head_branch | type == "string") + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | type == "string") + and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string"))' <<<"$consumer_runs" >/dev/null; then + echo "Fresh trusted-consumer inventory is malformed or truncated; retry budget unchanged." >&2 + return 2 + fi + if ! consumer_candidates="$(jq -r \ + --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" \ + --arg pr_title "$pr_title" --arg run_name "$run_name" \ + --argjson workflow_id "$consumer_workflow_id" ' + def positive_int: type == "number" and . > 0 and . == floor; + [ .workflow_runs[] + | select(type == "object" and (.id | positive_int) and (.run_attempt | positive_int) + and .workflow_id == $workflow_id and .event == "workflow_run" + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending")) + and .head_branch == $default_branch + and .repository.full_name == $repository and .head_repository.full_name == $repository + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.display_title == $pr_title or .display_title == $run_name)) + | [.id, .run_attempt, .head_sha] + ] | sort_by(.[0]) | reverse | .[] | @tsv + ' <<<"$consumer_runs")"; then + echo "Unable to parse fresh trusted-consumer inventory; retry budget unchanged." >&2 + return 2 + fi + consumer_candidate_count="$(printf '%s\n' "$consumer_candidates" | sed '/^$/d' | wc -l)" + if (( consumer_candidate_count > 3 )); then + echo "Fresh trusted-consumer lookup exceeded its three-run bound; retry budget unchanged." >&2 + return 2 + fi + while IFS=$'\t' read -r consumer_run_id consumer_attempt consumer_head; do + [[ -n "$consumer_run_id" ]] || continue + consumer_status=0 + trusted_consumer_has_tuple "$consumer_run_id" "$consumer_attempt" "$consumer_head" \ + "Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" || consumer_status=$? + if [[ "$consumer_status" -eq 0 ]]; then + echo "Skipping proof retry for PR #${pr_number}: trusted consumer run ${consumer_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." + return 0 + elif [[ "$consumer_status" -eq 2 ]]; then + echo "Fresh trusted-consumer run ${consumer_run_id} could not be verified; retry budget unchanged." >&2 + return 2 + fi + done <<<"$consumer_candidates" + echo "Deferring proof retry for PR #${pr_number}: exact successful preview source run ${run_id} is within the ${preview_handoff_window_seconds}-second trusted-consumer handoff window." + return 3 + done <<<"$source_candidates" + return 1 +} + +trusted_consumer_has_tuple() { + local run_id="$1" attempt="$2" run_head="$3" tuple="$4" jobs latest jobs_available=true + # A workflow_run display title is inherited from its source. Use the + # trusted validator's completed attempt evidence to bind the tuple. + jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false + latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 + jq -e --argjson id "$run_id" --argjson workflow_id "$consumer_workflow_id" \ + --arg repository "$GITHUB_REPOSITORY" --arg default_branch "$DEFAULT_BRANCH" --arg head "$run_head" ' + .id == $id and .workflow_id == $workflow_id and .event == "workflow_run" and .head_sha == $head + and (.run_attempt | type == "number" and . > 0 and . == floor) + and .repository.full_name == $repository and .head_repository.full_name == $repository + and .head_branch == $default_branch + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.status | IN("requested", "queued", "in_progress", "waiting", "pending", "completed")) + ' <<<"$latest" >/dev/null || return 2 + if jq -e '.status == "completed"' <<<"$latest" >/dev/null; then return 1; fi + [[ "$jobs_available" == true ]] || return 2 + jq -e --argjson attempt "$attempt" '.run_attempt == $attempt' <<<"$latest" >/dev/null || return 2 + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$run_head" ' + .jobs as $jobs + | (($jobs | type) == "array") and (.total_count == ($jobs | length)) and (.total_count < 100) + and ([$jobs[] | select(.name == "Validate Trusted Preview Target")] | length == 1) + and any($jobs[]; .name == "Validate Trusted Preview Target" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed") + ' <<<"$jobs" >/dev/null || return 2 + jq -e --arg tuple "$tuple" ' + any(.jobs[] | select(.name == "Validate Trusted Preview Target" and .conclusion == "success"); + ([.steps[]? | select(.name | startswith("Trusted preview deploy tuple "))] | length) == 1 + and any(.steps[]?; .name == $tuple and .status == "completed" and .conclusion == "success")) + ' <<<"$jobs" >/dev/null || return 1 +} + +dispatch_candidates() { + while IFS=$'\t' read -r _ pr_number head_sha pr_author pr_base_ref pr_state labels_json_base64; do + if ! labels_json="$(printf '%s' "$labels_json_base64" | base64 --decode 2>/dev/null)" || + [[ -z "$labels_json" ]] || + ! jq -e 'type == "array"' <<<"$labels_json" >/dev/null; then + echo "Skipping PR #${pr_number}: label metadata could not be decoded as a JSON array." >&2 + continue + fi + if ! live_pr_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${pr_number}")" || + [[ "$(jq -r '.state // empty' <<<"${live_pr_json}")" != open ]] || + [[ "$(jq -r '.head.repo.full_name // empty' <<<"${live_pr_json}")" != "${GITHUB_REPOSITORY}" ]] || + [[ "$(jq -r '.base.repo.full_name // empty' <<<"${live_pr_json}")" != "${GITHUB_REPOSITORY}" ]]; then + echo "Skipping PR #${pr_number}: current pull-request ownership or state is not trusted." >&2 + continue + fi + if ! head_sha="$(jq -er '.head.sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${live_pr_json}")" || + ! pr_base_ref="$(jq -er '.base.ref | select(type == "string" and test("^[A-Za-z0-9._/-]+$"))' <<<"${live_pr_json}")" || + ! pr_author="$(jq -er '.user.login | select(type == "string" and length > 0)' <<<"${live_pr_json}")" || + ! live_labels_json="$(jq -c '.labels | if type == "array" then [.[] | {name: .name}] else empty end' <<<"${live_pr_json}")"; then + echo "Skipping PR #${pr_number}: current pull-request identity or labels are malformed." >&2 + continue + fi + head_sha="${head_sha,,}" + if ! jq -e 'type == "array"' <<<"${live_labels_json}" >/dev/null; then + echo "Skipping PR #${pr_number}: current label metadata is malformed." >&2 + continue + fi + labels_json="${live_labels_json}" + pr_state=open + eligibility_output="$( + python3 "$eligibility_script" \ + --operation deploy \ + --state "$pr_state" \ + --base-ref "$pr_base_ref" \ + --author "$pr_author" \ + --labels-json "$labels_json" + )" + eligible="$(sed -n 's/^eligible=//p' <<<"$eligibility_output")" + reason="$(sed -n 's/^reason=//p' <<<"$eligibility_output")" + priority="$(sed -n 's/^priority=//p' <<<"$eligibility_output")" + if [[ "$eligible" != "true" ]]; then + echo "Skipping preview reconcile for PR #${pr_number}: not preview-eligible (reason=${reason}, author=${pr_author}, base=${pr_base_ref})" + continue + fi + + if [[ "$dispatch_sent" == "true" ]]; then + echo "Skipping PR #${pr_number}: the preview dispatch cycle already stopped after a request attempt." + continue + fi + + namespace="pr-${pr_number}" + namespace_exists=false + current_base_sha="" + current_head_sha="" + current_merge_sha="" + current_image_tag="" + requested_base_sha="" + requested_head_sha="" + requested_merge_sha="" + requested_image_tag="" + proof_base_sha="" + proof_head_sha="" + proof_merge_sha="" + proof_image_tag="" + proof_namespace_uid="" + namespace_uid="" + if ! namespace_json="$( + kubectl get namespace "${namespace}" --ignore-not-found -o json + )"; then + echo "Unable to inspect namespace ${namespace}; refusing preview reconcile." >&2 + exit 1 + fi + if [[ -n "${namespace_json}" ]]; then + namespace_exists=true + if ! namespace_tuple="$(parse_namespace_tuple "${namespace_json}")"; then + echo "Skipping PR #${pr_number}: unable to parse namespace ${namespace} snapshot." >&2 + continue + fi + IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ + requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ + proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ + _ _ _ _ _ \ + namespace_uid _ <<<"${namespace_tuple}" + elif [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + continue + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + continue + fi + fi + + mergeable="$(jq -r 'if (.mergeable | type) == "boolean" then (.mergeable | tostring) else "invalid" end' <<<"${live_pr_json}")" + mergeable_state="$(jq -r 'if (.mergeable_state | type) == "string" then .mergeable_state else "invalid" end' <<<"${live_pr_json}")" + if [[ "${mergeable}" != true || "${mergeable_state}" == invalid || + "${mergeable_state}" == unknown || "${mergeable_state}" == dirty || + "${mergeable_state}" == conflicting ]]; then + echo "Skipping preview reconcile for PR #${pr_number}: current base/head merge is not ready (mergeable=${mergeable}, state=${mergeable_state})." + continue + fi + if ! base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${pr_base_ref}")" || + ! base_sha="$(jq -er '.object.sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${base_ref_json}")" || + ! merge_sha="$(jq -er '.merge_commit_sha | select(type == "string" and test("^[0-9a-fA-F]{40}$"))' <<<"${live_pr_json}")"; then + echo "Skipping preview reconcile for PR #${pr_number}: current base ref or merge SHA is unavailable." >&2 + continue + fi + base_sha="${base_sha,,}" + merge_sha="${merge_sha,,}" + if ! merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${merge_sha}")" || + ! jq -e \ + --arg merge_sha "${merge_sha}" \ + --arg base_sha "${base_sha}" \ + --arg head_sha "${head_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; then + echo "Skipping preview reconcile for PR #${pr_number}: current merge SHA does not have the exact base/head parents." >&2 + continue + fi + if ! image_tag="$(bash ./dev-tools/hosted/preview/resolve-preview-image-tag.sh \ + "${merge_sha}" "${pr_number}" "${base_sha}")"; then + echo "Skipping preview reconcile for PR #${pr_number}: runtime image identity could not be resolved." >&2 + continue + fi + + if [[ "${current_base_sha}" == "${base_sha}" && + "${current_head_sha}" == "${head_sha}" && + "${current_merge_sha}" == "${merge_sha}" && + "${current_image_tag}" == "${image_tag}" && + "${proof_base_sha}" == "${base_sha}" && + "${proof_head_sha}" == "${head_sha}" && + "${proof_merge_sha}" == "${merge_sha}" && + "${proof_image_tag}" == "${image_tag}" && + -n "${namespace_uid}" && + "${proof_namespace_uid}" == "${namespace_uid}" ]]; then + if [[ "${requested_base_sha}" != "${base_sha}" || + "${requested_head_sha}" != "${head_sha}" || + "${requested_merge_sha}" != "${merge_sha}" || + "${requested_image_tag}" != "${image_tag}" ]]; then + repair_status="$repair_success" + if repair_requested_tuple \ + "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ + "$requested_base_sha" "$requested_head_sha" "$requested_merge_sha" "$requested_image_tag"; then + repair_status="$repair_success" + else + repair_status=$? + fi + case "$repair_status" in + "$repair_success" | "$repair_skip") + continue + ;; + "$repair_dispatch") + namespace_exists=false + ;; + "$repair_abort") + exit 1 + ;; + *) + echo "Unexpected requested-head repair status: ${repair_status}" >&2 + exit 1 + ;; + esac + else + echo "Preview ${namespace} already aligned to ${base_sha}/${head_sha}/${merge_sha}/${image_tag}" + continue + fi + fi + + if [[ "${current_base_sha}" == "${base_sha}" && + "${current_head_sha}" == "${head_sha}" && + "${current_merge_sha}" == "${merge_sha}" && + "${current_image_tag}" == "${image_tag}" ]]; then + echo "Preview ${namespace} deployed tuple is missing proof for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}; dispatching retry." + fi + + if [[ "$namespace_exists" != "true" ]]; then + if [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then + if ! refresh_available_slots; then + echo "Unable to refresh preview capacity for ordinary PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + continue + fi + if [[ "$available_slots" -le 0 ]]; then + echo "Skipping ordinary PR #${pr_number}: preview capacity is still full after refresh." + continue + fi + fi + fi + + if ! preview_candidates="$( + jq -c \ + --arg workflow_name "${preview_workflow_name}" \ + --argjson workflow_id "$preview_workflow_id" \ + --argjson consumer_workflow_id "$consumer_workflow_id" \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg default_branch "${DEFAULT_BRANCH}" \ + --arg pr_title "PR preview ${pr_number}" \ + --argjson pr_number "$pr_number" \ + --arg head_sha "$head_sha" \ + --arg run_name "Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" ' + if type != "array" then + error("workflow runs are not an array") + else + if any(.[]; + (type != "object") + or ((.id | type) != "number") + or ((.name | type) != "string") + or ((.head_branch | type) != "string") + or ((.display_title | type) != "string") + or ((.status | type) != "string") + or ((.firemud_reconciler_branch_filtered | type) != "boolean") + ) then + error("workflow run entry is malformed") + else + def positive_int: type == "number" and . > 0 and . == floor; + def native_same_repo: + .repository.full_name == $repository + and .head_repository.full_name == $repository + and (.id | positive_int) and (.run_attempt | positive_int); + def native_preview: + native_same_repo and .workflow_id == $workflow_id + and (.name == $workflow_name or .name == .display_title); + def trusted_dispatch: + native_preview and .event == "repository_dispatch" + and .head_branch == $default_branch + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path == ".github/workflows/preview.yml" or .path == (".github/workflows/preview.yml@" + $default_branch) + or .path == (".github/workflows/preview.yml@refs/heads/" + $default_branch)) + and .display_title == $run_name; + def provisional_pr: + native_preview and (.event == "pull_request" or .event == "pull_request_target") + and (.path == ".github/workflows/preview.yml" + or (.event == "pull_request" and .path == (".github/workflows/preview.yml@refs/pull/" + ($pr_number | tostring) + "/merge"))) + and (.display_title == $pr_title or (.event == "pull_request" and .display_title == $run_name)) + and .head_sha == $head_sha + and ([.pull_requests[]? | select(.number == $pr_number)] | length) == 1; + def trusted_consumer: + native_same_repo and .workflow_id == $consumer_workflow_id and .event == "workflow_run" + and .head_branch == $default_branch + and (.head_sha | type == "string" and test("^[0-9a-f]{40}$")) + and (.path | IN(".github/workflows/hosted-identity-request.yml", + ".github/workflows/hosted-identity-request.yml@" + $default_branch, + ".github/workflows/hosted-identity-request.yml@refs/heads/" + $default_branch)) + and (.display_title == $pr_title or .display_title == $run_name); + .[] + | select( + ( + (.firemud_reconciler_branch_filtered == false) + or (.firemud_reconciler_branch_filtered == true and .head_branch == $default_branch) + ) + and (trusted_dispatch or provisional_pr or trusted_consumer) + and ( + .status == "requested" + or .status == "queued" + or .status == "in_progress" + or .status == "waiting" + or .status == "pending" + ) + ) + | if trusted_dispatch then {id, exact: true} + else {id, run_attempt, event, head_sha, exact: false} end + end + end + ' <<<"${active_preview_runs_json}" + )"; then + echo "Unable to parse active preview workflow runs; refusing preview reconcile." >&2 + exit 1 + fi + + active_preview_run_id="$(jq -rs '[.[] | select(.exact)][0].id // empty' <<<"$preview_candidates")" + active_preview_lookup_unknown=false + completed_preview_handoff_run_id="" + if [[ -z "$active_preview_run_id" ]]; then + # A same-head title is not proof: the base can move independently. + tuple_step="Preview resolved tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + consumer_tuple="Trusted preview deploy tuple pr-${pr_number} base-${base_sha} head-${head_sha} merge-${merge_sha}" + lookup_count=0 + while IFS=$'\t' read -r run_id run_attempt run_event run_head; do + [[ -n "$run_id" ]] || continue + if (( lookup_count >= 3 )); then + active_preview_lookup_unknown=true + break + fi + lookup_count=$((lookup_count + 1)) + lookup_status=0 + if [[ "$run_event" == workflow_run ]]; then + trusted_consumer_has_tuple "$run_id" "$run_attempt" "$run_head" "$consumer_tuple" || lookup_status=$? + else + automatic_preview_has_tuple "$run_id" "$run_attempt" "$run_head" "$tuple_step" "$pr_number" "$run_event" || lookup_status=$? + fi + if [[ "$lookup_status" -eq 0 ]]; then + active_preview_run_id="$run_id" + break + elif [[ "$lookup_status" -eq 3 ]]; then + completed_preview_handoff_run_id="$run_id" + break + elif [[ "$lookup_status" -eq 2 ]]; then + active_preview_lookup_unknown=true + fi + done < <(jq -rs '[.[] | select(.exact | not)] | sort_by(.id) | reverse | .[] | [.id, .run_attempt, .event, .head_sha] | @tsv' <<<"$preview_candidates") + fi + + if [[ -n "${active_preview_run_id}" ]]; then + echo "Skipping proof retry for PR #${pr_number}: preview source or trusted consumer run ${active_preview_run_id} for ${base_sha}/${head_sha}/${merge_sha} is already queued or in progress." + continue + fi + if [[ -n "${completed_preview_handoff_run_id}" ]]; then + echo "Deferring proof retry for PR #${pr_number}: successful exact preview source run ${completed_preview_handoff_run_id} may still be handing off to the trusted consumer." + continue + fi + if [[ "$active_preview_lookup_unknown" == true ]]; then + echo "Skipping proof retry for PR #${pr_number}: active preview tuple lookup unavailable; retry budget unchanged." + continue + fi + + recent_handoff_status=0 + recent_successful_source_handoff "$pr_number" "$head_sha" "$tuple_step" || recent_handoff_status=$? + case "$recent_handoff_status" in + 0 | 3) + continue + ;; + 2) + echo "Skipping proof retry for PR #${pr_number}: recent preview handoff lookup unavailable; retry budget unchanged." >&2 + continue + ;; + 1) + ;; + *) + echo "Unexpected recent preview handoff status: ${recent_handoff_status}" >&2 + exit 1 + ;; + esac + + require_deployed_tuple=false + if [[ "${namespace_exists}" == "true" && + "${current_base_sha}" == "${base_sha}" && + "${current_head_sha}" == "${head_sha}" && + "${current_merge_sha}" == "${merge_sha}" && + "${current_image_tag}" == "${image_tag}" ]]; then + require_deployed_tuple=true + fi + # A consumer may finish deployment and proof during the active-run lookup. + local proof_retry_reservation_count="" + local proof_retry_previous_count="" + local proof_retry_previous_base_sha="" + local proof_retry_previous_head_sha="" + local proof_retry_previous_merge_sha="" + local proof_retry_previous_image_tag="" + local proof_retry_reservation_namespace_uid="" + local proof_retry_reservation_resource_version="" + local proof_retry_reservation_base_sha="" + local proof_retry_reservation_head_sha="" + local proof_retry_reservation_merge_sha="" + local proof_retry_reservation_image_tag="" + prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ + "$require_deployed_tuple" "$priority" "$namespace_uid" || continue + + echo "Dispatching preview render for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag}) from trusted ref ${DEFAULT_BRANCH}" + dispatch_exit=0 + if dispatch_response="$(gh api --include \ + --method POST \ + "repos/${GITHUB_REPOSITORY}/dispatches" \ + -f event_type=preview-deploy \ + -f 'client_payload[action]=deploy' \ + -f "client_payload[pr_number]=${pr_number}" \ + -f "client_payload[head_sha]=${head_sha}" \ + -f "client_payload[base_ref]=${pr_base_ref}" \ + -f "client_payload[base_sha]=${base_sha}" \ + -f "client_payload[merge_sha]=${merge_sha}" \ + -f "client_payload[image_tag]=${image_tag}" \ + -f 'client_payload[preview_domain]=preview.firedevops.net')"; then + dispatch_exit=0 + else + dispatch_exit=$? + fi + dispatch_status_line_count="$(grep -cE '^HTTP/[0-9.]+ [0-9]{3} ' <<<"${dispatch_response}" || true)" + dispatch_http_status="$(awk '/^HTTP\/[0-9.]+ [0-9][0-9][0-9] / { print $2; exit }' <<<"${dispatch_response}")" + dispatch_retry_after="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^retry-after:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_rate_remaining="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-remaining:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_rate_reset="$(awk 'BEGIN { IGNORECASE=1 } { sub(/\r$/, "") } tolower($0) ~ /^x-ratelimit-reset:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' <<<"${dispatch_response}")" + dispatch_error_body="$(awk 'BEGIN { body=0 } { sub(/\r$/, ""); if (!body && $0 == "") { body=1; next } if (body) print }' <<<"${dispatch_response}")" + dispatch_rate_limit_body=false + if jq -e 'type == "object" and ((.message // "") | type == "string" and test("rate limit"; "i"))' \ + <<<"${dispatch_error_body}" >/dev/null 2>&1; then + dispatch_rate_limit_body=true + fi + rate_limited_dispatch=false + if [[ "${dispatch_http_status}" == 429 ]] || + [[ "${dispatch_http_status}" == 403 && + ( "${dispatch_retry_after}" =~ ^[0-9]+$ || + "${dispatch_rate_remaining}" == 0 || + "${dispatch_rate_limit_body}" == true ) ]]; then + rate_limited_dispatch=true + fi + if [[ "${dispatch_exit}" -eq 0 && "${dispatch_status_line_count}" -eq 1 && + "${dispatch_http_status}" == 204 ]]; then + dispatch_sent=true + elif [[ "${dispatch_status_line_count}" -eq 1 && "${dispatch_http_status}" =~ ^4[0-9][0-9]$ ]]; then + dispatch_outcome_failed=true + echo "GitHub confirmed preview dispatch rejection for PR #${pr_number} (HTTP ${dispatch_http_status})." + if ! compensate_rejected_proof_retry "$namespace" "$pr_number"; then + echo "The rejected dispatch could not be safely compensated; its proof-retry budget remains charged." >&2 + fi + if [[ "${rate_limited_dispatch}" == true ]]; then + rate_limit_wait_seconds=60 + if [[ "${dispatch_retry_after}" =~ ^[0-9]+$ ]]; then + rate_limit_wait_seconds=$((10#${dispatch_retry_after})) + elif [[ "${dispatch_rate_remaining}" == 0 && "${dispatch_rate_reset}" =~ ^[0-9]+$ ]]; then + current_epoch="$(date -u +%s)" + rate_limit_wait_seconds=$((10#${dispatch_rate_reset} - current_epoch)) + (( rate_limit_wait_seconds > 0 )) || rate_limit_wait_seconds=60 + fi + echo "GitHub rate-limited preview dispatch; stopping this cycle and waiting ${rate_limit_wait_seconds} seconds before another attempt." + dispatch_sent=true + sleep "${rate_limit_wait_seconds}" + fi + else + dispatch_outcome_failed=true + echo "Preview dispatch outcome for PR #${pr_number} is ambiguous (gh=${dispatch_exit}, HTTP=${dispatch_http_status:-unknown}); proof-retry budget remains charged." >&2 + dispatch_sent=true + fi + done +} + +candidate_rows="$( + gh api --paginate "repos/${GITHUB_REPOSITORY}/pulls?state=open&per_page=100" \ + --jq '.[] | [(if (.labels | map(.name) | any(. == "preview:priority")) then 0 else 1 end), .number, .head.sha, .user.login, .base.ref, .state, (.labels | map({name: .name}) | tojson | @base64)] | @tsv' \ + | sort -t $'\t' -k1,1n -k2,2n +)" +if [[ -n "$candidate_rows" ]]; then + active_preview_run_sets=() + for active_status in requested queued in_progress waiting pending; do + for active_run_scope in branch pull_request pull_request_target workflow_run; do + if [[ "$active_run_scope" == branch ]]; then + active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" + active_run_branch_filtered=true + elif [[ "$active_run_scope" == pull_request || "$active_run_scope" == pull_request_target ]]; then + active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100" + active_run_branch_filtered=false + else + active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=workflow_run&status=${active_status}&per_page=100" + active_run_branch_filtered=false + fi + if ! active_preview_run_pages_json="$(gh api --paginate --slurp "$active_run_query")"; then + echo "Unable to inspect active preview workflow runs; refusing preview reconcile." >&2 + exit 1 + fi + if ! active_preview_runs_for_query="$( + jq -c \ + --argjson branch_filtered "$active_run_branch_filtered" ' + if type != "array" then + error("workflow run pages are not an array") + else + [ + .[] as $page + | if ($page | type) != "object" or ($page.workflow_runs | type) != "array" then + error("workflow run page is malformed") + else + $page.workflow_runs[] + end + | if type != "object" then + error("workflow run entry is malformed") + else + . + {firemud_reconciler_branch_filtered: $branch_filtered} + end + ] + end + ' <<<"$active_preview_run_pages_json" + )"; then + echo "Unable to normalize active preview workflow runs; refusing preview reconcile." >&2 + exit 1 + fi + active_preview_run_sets+=("$active_preview_runs_for_query") + done + done + if ! active_preview_runs_json="$( + printf '%s\n' "${active_preview_run_sets[@]}" | jq -c -s ' + if any(.[]; type != "array") then + error("active preview workflow run result is not an array") + else + add + | group_by(.id) + | map( + . as $runs + | if any($runs[]; + .name != $runs[0].name + or .head_branch != $runs[0].head_branch + or .display_title != $runs[0].display_title + ) then + error("active preview workflow run metadata differs between query scopes") + else + $runs[0] + { + firemud_reconciler_branch_filtered: all( + $runs[]; + .firemud_reconciler_branch_filtered == true + ) + } + end + ) + end + ' + )"; then + echo "Unable to merge active preview workflow runs; refusing preview reconcile." >&2 + exit 1 + fi + if ! preview_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/preview.yml" | jq -er --arg name "$preview_workflow_name" ' + select(.name == $name and .path == ".github/workflows/preview.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 + exit 1 + fi + if ! consumer_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/hosted-identity-request.yml" | jq -er ' + select(.name == "Trusted Hosted Identity Request" and .path == ".github/workflows/hosted-identity-request.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical trusted preview consumer identity; refusing preview reconcile." >&2 + exit 1 + fi + dispatch_candidates <<<"$candidate_rows" +fi +if [[ "$dispatch_outcome_failed" == true ]]; then + echo "One or more preview dispatch outcomes or capacity checks failed; review this job before another repair cycle." >&2 + exit 1 +fi diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 2359641880..91967a8dc3 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -2684,7 +2684,7 @@ test ! -e "$FAKE_DELETE_LOG" trusted_workflow="$ROOT_DIR/.github/workflows/hosted-identity-request.yml" reconciler_workflow="$ROOT_DIR/.github/workflows/preview-reconciler.yml" eligibility_script="$ROOT_DIR/dev-tools/hosted/preview/preview-eligibility.py" -RECONCILER_RUN="$TEMP_DIR/preview-reconciler.sh" +RECONCILER_RUN="$ROOT_DIR/dev-tools/hosted/preview/reconcile-preview-deploys.sh" preview_base_sha=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb preview_head_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa preview_merge_sha=cccccccccccccccccccccccccccccccccccccccc @@ -2694,10 +2694,6 @@ preview_merge_sha=cccccccccccccccccccccccccccccccccccccccc preview_image_tag="${preview_base_sha}" stacked_preview_image_tag="pr-merge-${preview_merge_sha}" export DEFAULT_BRANCH=develop -extract_workflow_step_run \ - "$reconciler_workflow" \ - "Dispatch preview deploys for drifted PRs" \ - "$RECONCILER_RUN" grep -Fq 'set -euo pipefail' "$RECONCILER_RUN" grep -Fq 'repair_requested_tuple() {' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal shell and jq expressions in workflow source. @@ -4322,6 +4318,7 @@ fi if grep -Eq 'def labels_valid:|all\(\.labels\[\]\?; \(type == "object"\)' \ "$trusted_workflow" \ "$reconciler_workflow" \ + "$RECONCILER_RUN" \ "$ROOT_DIR/dev-tools/hosted/preview/allocate-preview-capacity.sh" \ "$ROOT_DIR/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh"; then echo "A live preview callsite duplicates the centralized label predicate" >&2 @@ -4357,6 +4354,15 @@ assert set(preview["jobs"]) == { } assert trusted["jobs"]["destroy-runtime"]["timeout-minutes"] == 60 assert reconciler["jobs"]["reconcile-previews"]["timeout-minutes"] == 60 +reconciler_steps = reconciler["jobs"]["reconcile-previews"]["steps"] +checkout = reconciler_steps[0] +assert checkout["uses"].startswith("actions/checkout@") +assert checkout["with"] == { + "ref": "${{ github.workflow_sha }}", + "persist-credentials": False, +} +dispatch = next(step for step in reconciler_steps if step.get("name") == "Dispatch preview deploys for drifted PRs") +assert dispatch["run"] == "bash ./dev-tools/hosted/preview/reconcile-preview-deploys.sh" reconciler_manager_write = next( step for step in reconciler["jobs"]["reconcile-previews"]["steps"] @@ -4383,34 +4389,34 @@ assert not any( ) PY grep -q -- '--retire-terminal-identities' "$ROOT_DIR/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh" -grep -q 'Skipping ordinary PR #' "$reconciler_workflow" -grep -q 'preview dispatch cycle already stopped after a request attempt' "$reconciler_workflow" +grep -q 'Skipping ordinary PR #' "$RECONCILER_RUN" +grep -q 'preview dispatch cycle already stopped after a request attempt' "$RECONCILER_RUN" # Proof repair is bounded by the exact deployed tuple and must not duplicate an # active source or trusted consumer run. -grep -Fq 'firemud.dev/proof-retry-count' "$reconciler_workflow" -grep -Fq 'firemud.dev/proof-retry-base-sha' "$reconciler_workflow" -grep -Fq 'firemud.dev/proof-retry-head-sha' "$reconciler_workflow" -grep -Fq 'firemud.dev/proof-retry-merge-sha' "$reconciler_workflow" -grep -Fq 'firemud.dev/proof-retry-image-tag' "$reconciler_workflow" -grep -Fq 'namespace proof-retry evidence is malformed' "$reconciler_workflow" -grep -Fq 'proof retry budget exhausted' "$reconciler_workflow" +grep -Fq 'firemud.dev/proof-retry-count' "$RECONCILER_RUN" +grep -Fq 'firemud.dev/proof-retry-base-sha' "$RECONCILER_RUN" +grep -Fq 'firemud.dev/proof-retry-head-sha' "$RECONCILER_RUN" +grep -Fq 'firemud.dev/proof-retry-merge-sha' "$RECONCILER_RUN" +grep -Fq 'firemud.dev/proof-retry-image-tag' "$RECONCILER_RUN" +grep -Fq 'namespace proof-retry evidence is malformed' "$RECONCILER_RUN" +grep -Fq 'proof retry budget exhausted' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal resource-version fencing. -grep -Fq -- '--resource-version "${namespace_resource_version}"' "$reconciler_workflow" +grep -Fq -- '--resource-version "${namespace_resource_version}"' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert canonical workflow lookup and native custody. -grep -Fq -- 'actions/workflows/preview.yml" | jq' "$reconciler_workflow" +grep -Fq -- 'actions/workflows/preview.yml" | jq' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the literal jq workflow and repository checks. -grep -Fq -- '.workflow_id == $workflow_id' "$reconciler_workflow" +grep -Fq -- '.workflow_id == $workflow_id' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the literal jq head repository check. -grep -Fq -- '.head_repository.full_name == $repository' "$reconciler_workflow" -grep -Fq 'Skipping proof retry for PR #' "$reconciler_workflow" +grep -Fq -- '.head_repository.full_name == $repository' "$RECONCILER_RUN" +grep -Fq 'Skipping proof retry for PR #' "$RECONCILER_RUN" grep -Fq "run-name: \${{ github.event_name == 'workflow_run' && github.event.workflow_run.display_title" "$trusted_workflow" # shellcheck disable=SC2016 # Assert one fail-closed JSON snapshot feeds each namespace decision. grep -Fq 'kubectl get namespace "${namespace}" --ignore-not-found -o json' \ - "$reconciler_workflow" + "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the initial, repair, pre-dispatch, and compensation snapshots. -test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$reconciler_workflow")" -eq 5 +test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$RECONCILER_RUN")" -eq 5 # shellcheck disable=SC2016 # Assert the fresh namespace snapshot fences repair. -grep -Fq 'requested preview tuple changed during annotation repair check' "$reconciler_workflow" +grep -Fq 'requested preview tuple changed during annotation repair check' "$RECONCILER_RUN" # The janitor keeps explicit kubeconfig selection on the consuming kubectl steps; # no preceding restore step may imply a different runner-wide kubeconfig. if grep -Fq 'Restore preview runtime kubeconfig' "$janitor_workflow"; then @@ -4420,31 +4426,23 @@ fi # shellcheck disable=SC2016 # Assert explicit kubeconfig selection on janitor consumers. grep -Fq 'KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig' "$janitor_workflow" # shellcheck disable=SC2016 # Assert labels are encoded as one safe row field. -grep -Fq '(.labels | map({name: .name}) | tojson | @base64)' "$reconciler_workflow" +grep -Fq '(.labels | map({name: .name}) | tojson | @base64)' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert decoded labels reach the centralized parser. -grep -Fq -- '--labels-json "$labels_json"' "$reconciler_workflow" +grep -Fq -- '--labels-json "$labels_json"' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert capacity uses centralized validated priority. grep -Fq -- 'priority="$(sed -n '\''s/^priority=//p'\'' <<<"$eligibility_output")"' \ - "$reconciler_workflow" + "$RECONCILER_RUN" # Reject the redundant transported raw-priority field and read placeholder while # retaining the leading numeric key used only for stable priority ordering. -if grep -Fq '_sort_priority' "$reconciler_workflow"; then +if grep -Fq '_sort_priority' "$RECONCILER_RUN"; then echo "reconciler retained a redundant transported raw-priority field" >&2 exit 1 fi -python3 - "$reconciler_workflow" <<'PY' +python3 - "$RECONCILER_RUN" <<'PY' import sys from pathlib import Path -import yaml - -workflow = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) -step = next( - step - for step in workflow["jobs"]["reconcile-previews"]["steps"] - if step.get("name") == "Dispatch preview deploys for drifted PRs" -) -run = step["run"] +run = Path(sys.argv[1]).read_text(encoding="utf-8") assert run.count('any(. == "preview:priority")') == 1 assert "then 0 else 1 end" in run assert "sort -t $'\\t' -k1,1n -k2,2n" in run @@ -4471,11 +4469,11 @@ assert eligible_guard < dispatch_guard < namespace_snapshot < base_ref_resolutio PY # shellcheck disable=SC2016 # Assert malformed label metadata fails closed before eligibility. grep -Fq -- 'if ! labels_json="$(printf '\''%s'\'' "$labels_json_base64" | base64 --decode 2>/dev/null)" ||' \ - "$reconciler_workflow" + "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal shell source in the workflow. -grep -Fq -- '[[ -z "$labels_json" ]] ||' "$reconciler_workflow" +grep -Fq -- '[[ -z "$labels_json" ]] ||' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal shell source in the workflow. grep -Fq -- '! jq -e '\''type == "array"'\'' <<<"$labels_json" >/dev/null' \ - "$reconciler_workflow" + "$RECONCILER_RUN" echo "preview priority contract checks passed" From a8ed6073f1113dca83324de15f3cce1d76f31f49 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:51:24 +1300 Subject: [PATCH 097/199] Serialize exact PR runtime refresh requests Keep completed or unproved comparisons eligible for repair and verify the new receiver before releasing the tuple reservation. Update the remaining preview contracts for the checked-in reconciler script and preserve its default-branch checkout. --- .github/scripts/admit-pr-runtime-refresh.cjs | 232 ++++++++++++++++++ .../workflows/admit-pr-runtime-refresh.yml | 52 ++++ .github/workflows/preview-reconciler.yml | 3 +- .github/workflows/preview-runtime-refresh.yml | 2 +- .github/workflows/runtime-images.yml | 2 +- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 4 +- .../tests/pr-retarget-workflow-contract.sh | 94 +++---- dev-tools/tests/preview-priority-contract.sh | 2 +- .../preview-runner-isolation-contract.sh | 7 +- .../tests/preview-runtime-refresh.test.cjs | 137 ++++++++++- 11 files changed, 477 insertions(+), 60 deletions(-) create mode 100644 .github/scripts/admit-pr-runtime-refresh.cjs create mode 100644 .github/workflows/admit-pr-runtime-refresh.yml diff --git a/.github/scripts/admit-pr-runtime-refresh.cjs b/.github/scripts/admit-pr-runtime-refresh.cjs new file mode 100644 index 0000000000..e0905f84ac --- /dev/null +++ b/.github/scripts/admit-pr-runtime-refresh.cjs @@ -0,0 +1,232 @@ +module.exports = async function admitPrRuntimeRefresh({ + github, + context, + core, + input, + sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)), +}) { + const runtimePath = '.github/workflows/runtime-images.yml'; + const requiredFields = ['pr_number', 'base_ref', 'base_sha', 'head_sha', 'merge_sha']; + const shaPattern = /^[0-9a-f]{40}$/; + const activeStatuses = new Set(['queued', 'waiting', 'requested', 'pending', 'in_progress']); + const inventoryEvents = ['pull_request', 'repository_dispatch']; + + const fail = message => { throw new Error(message); }; + const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value); + const isPositiveInteger = value => Number.isSafeInteger(value) && value > 0; + const isSafeBranchRef = value => { + if (typeof value !== 'string' || value.length === 0 || value === '@' || + value.startsWith('/') || value.endsWith('/') || value.endsWith('.') || + value.includes('//') || value.includes('..') || value.includes('@{') || + /[\u0000-\u0020\u007f~^:?*\\\[]/.test(value)) return false; + return value.split('/').every(part => part.length > 0 && part[0] !== '.' && !part.endsWith('.lock')); + }; + const isNotFound = error => error?.status === 404 || error?.response?.status === 404; + const dataOf = response => response && isRecord(response.data) ? response.data : null; + + if (!isRecord(input) || Reflect.ownKeys(input).length !== requiredFields.length || + requiredFields.some(field => !Object.prototype.hasOwnProperty.call(input, field))) { + fail('Invalid runtime refresh input.'); + } + if (requiredFields.some(field => typeof input[field] !== 'string')) fail('Invalid runtime refresh input.'); + if (!/^[1-9][0-9]*$/.test(input.pr_number) || !Number.isSafeInteger(Number(input.pr_number)) || + Number(input.pr_number) <= 0 || !isSafeBranchRef(input.base_ref) || + !shaPattern.test(input.base_sha) || !shaPattern.test(input.head_sha) || !shaPattern.test(input.merge_sha)) { + fail('Invalid runtime refresh input.'); + } + + const repository = context?.payload?.repository; + const contextRepo = context?.repo; + if (!isRecord(repository) || !isRecord(contextRepo) || + typeof contextRepo.owner !== 'string' || contextRepo.owner.length === 0 || + typeof contextRepo.repo !== 'string' || contextRepo.repo.length === 0 || + repository.full_name !== `${contextRepo.owner}/${contextRepo.repo}` || + !isSafeBranchRef(repository.default_branch)) { + fail('Repository identity or default branch is unavailable.'); + } + const fullName = repository.full_name; + const defaultBranch = repository.default_branch; + const pullNumber = Number(input.pr_number); + + const currentIdentity = async () => { + let pullResponse; + try { + pullResponse = await github.rest.pulls.get({...contextRepo, pull_number: pullNumber}); + } catch (error) { + if (isNotFound(error)) return false; + throw error; + } + const pull = dataOf(pullResponse); + if (!pull || pull.number !== pullNumber || pull.state !== 'open' || + pull.head?.repo?.full_name !== fullName || pull.base?.repo?.full_name !== fullName || + pull.head?.sha !== input.head_sha || pull.base?.ref !== input.base_ref || + pull.mergeable !== true || typeof pull.mergeable_state !== 'string' || + ['dirty', 'conflicting', 'unknown'].includes(pull.mergeable_state) || + pull.merge_commit_sha !== input.merge_sha) return false; + + let refResponse; + try { + refResponse = await github.rest.git.getRef({...contextRepo, ref: `heads/${input.base_ref}`}); + } catch (error) { + if (isNotFound(error)) return false; + throw error; + } + const ref = dataOf(refResponse); + if (ref?.ref !== `refs/heads/${input.base_ref}` || ref.object?.sha !== input.base_sha) return false; + + let commitResponse; + try { + commitResponse = await github.rest.repos.getCommit({...contextRepo, ref: input.merge_sha}); + } catch (error) { + if (isNotFound(error)) return false; + throw error; + } + const commit = dataOf(commitResponse); + return commit?.sha === input.merge_sha && Array.isArray(commit.parents) && + commit.parents.length === 2 && commit.parents[0]?.sha === input.base_sha && + commit.parents[1]?.sha === input.head_sha; + }; + + if (!await currentIdentity()) { + core.info('Runtime refresh tuple is obsolete; no dispatch.'); + return 'obsolete'; + } + + const {data: runtimeWorkflow} = await github.rest.actions.getWorkflow({ + ...contextRepo, + workflow_id: 'runtime-images.yml', + }); + if (runtimeWorkflow?.path !== runtimePath || !isPositiveInteger(runtimeWorkflow.id)) { + fail('Runtime workflow identity is unproven.'); + } + + const expectedTitle = 'Build Runtime Images secure-pr-artifact ' + + `pr-${input.pr_number} base-${input.base_sha} head-${input.head_sha} merge-${input.merge_sha} mode-required`; + const exactNativeTuple = run => { + if (!isRecord(run) || run.workflow_id !== runtimeWorkflow.id || + run.display_title !== expectedTitle || run.repository?.full_name !== fullName || + run.head_repository?.full_name !== fullName) return false; + + const barePath = run.path === runtimePath; + if (run.event === 'repository_dispatch') { + return (barePath || run.path === `${runtimePath}@${defaultBranch}` || + run.path === `${runtimePath}@refs/heads/${defaultBranch}`) && + run.head_branch === defaultBranch; + } + if (run.event === 'pull_request') { + const associations = run.pull_requests; + return (barePath || run.path === `${runtimePath}@refs/pull/${pullNumber}/merge`) && + run.head_sha === input.head_sha && Array.isArray(associations) && associations.length === 1 && + associations[0]?.number === pullNumber && associations[0]?.head?.sha === input.head_sha && + associations[0]?.base?.sha === input.base_sha; + } + return false; + }; + const validChronology = 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 isExactActiveRun = run => exactNativeTuple(run) && + isPositiveInteger(run.id) && isPositiveInteger(run.run_attempt) && + activeStatuses.has(run.status) && run.conclusion == null && validChronology(run.created_at); + const secondsUtc = timestamp => new Date(timestamp).toISOString().replace(/\.\d{3}Z$/, 'Z'); + + let inventoryComplete = true; + let newestExact = null; + const observedRunIds = new Set(); + const createdSince = secondsUtc(Date.now() - 30 * 60 * 1000); + try { + const exactRuns = []; + for (const event of inventoryEvents) { + const {data: inventory} = await github.rest.actions.listWorkflowRuns({ + ...contextRepo, + workflow_id: runtimeWorkflow.id, + event, + created: `${createdSince}..*`, + per_page: 100, + page: 1, + }); + if (!Number.isSafeInteger(inventory?.total_count) || inventory.total_count < 0 || + inventory.total_count > 100 || !Array.isArray(inventory.workflow_runs) || + inventory.workflow_runs.length !== inventory.total_count) { + throw new Error('Incomplete runtime run inventory.'); + } + for (const run of inventory.workflow_runs) { + if (run?.event !== event) throw new Error('Runtime inventory contains an unexpected event.'); + if (!exactNativeTuple(run)) continue; + if (!isPositiveInteger(run.id) || !isPositiveInteger(run.run_attempt) || + !validChronology(run.created_at) || Date.parse(run.created_at) < Date.parse(createdSince)) { + throw new Error('Exact runtime run has invalid native chronology.'); + } + const identity = `${run.event}:${run.id}:${run.run_attempt}`; + if (observedRunIds.has(identity)) throw new Error('Duplicate exact runtime run identity.'); + observedRunIds.add(identity); + if (activeStatuses.has(run.status)) { + if (run.conclusion != null) throw new Error('Active runtime run has a conclusion.'); + } else if (run.status !== 'completed' || typeof run.conclusion !== 'string' || run.conclusion.length === 0) { + throw new Error('Exact runtime run status is unclear.'); + } + exactRuns.push(run); + } + } + + exactRuns.sort((left, right) => Date.parse(right.created_at) - Date.parse(left.created_at)); + if (exactRuns.length > 0) { + if (exactRuns.length > 1 && Date.parse(exactRuns[0].created_at) === Date.parse(exactRuns[1].created_at)) { + throw new Error('Newest exact runtime runs have equal chronology.'); + } + newestExact = exactRuns[0]; + } + } catch { + inventoryComplete = false; + core.warning('Runtime active-run inventory was incomplete or ambiguous; preserving the required refresh fallback.'); + } + + if (!await currentIdentity()) { + core.info('Runtime refresh tuple changed during admission; no dispatch.'); + return 'obsolete'; + } + if (inventoryComplete && newestExact && isExactActiveRun(newestExact)) { + core.info('The unique newest exact runtime producer is already active; no dispatch.'); + return 'already-active'; + } + + const dispatchCreatedSince = secondsUtc(Date.now()); + await github.rest.repos.createDispatchEvent({ + ...contextRepo, + event_type: 'pr-runtime-base-refresh', + client_payload: { + pr_number: input.pr_number, + base_ref: input.base_ref, + base_sha: input.base_sha, + head_sha: input.head_sha, + merge_sha: input.merge_sha, + image_tag: `pr-merge-${input.merge_sha}`, + }, + }); + + for (let observation = 0; observation < 8; observation += 1) { + try { + const {data: inventory} = await github.rest.actions.listWorkflowRuns({ + ...contextRepo, + workflow_id: runtimeWorkflow.id, + event: 'repository_dispatch', + created: `${dispatchCreatedSince}..*`, + per_page: 100, + page: 1, + }); + if (Array.isArray(inventory?.workflow_runs) && + inventory.workflow_runs.some(run => isExactActiveRun(run) && + run.event === 'repository_dispatch' && Date.parse(run.created_at) >= Date.parse(dispatchCreatedSince) && + !observedRunIds.has(`${run.event}:${run.id}:${run.run_attempt}`))) { + core.info('The dispatched runtime refresh is visible as an exact active producer.'); + return 'dispatched-observed'; + } + } catch { + core.warning('Runtime refresh registration is not yet observable.'); + } + if (observation < 7) await sleep(2000); + } + + core.warning('Runtime refresh was dispatched but remained unconfirmed after bounded polling.'); + return 'dispatched-unconfirmed'; +}; diff --git a/.github/workflows/admit-pr-runtime-refresh.yml b/.github/workflows/admit-pr-runtime-refresh.yml new file mode 100644 index 0000000000..ae4823b3eb --- /dev/null +++ b/.github/workflows/admit-pr-runtime-refresh.yml @@ -0,0 +1,52 @@ +name: Admit PR Runtime Refresh + +on: + repository_dispatch: + types: [pr-runtime-base-refresh-request] + +permissions: {} + +jobs: + dispatch: + name: Admit Exact Runtime Tuple + if: ${{ github.event.action == 'pr-runtime-base-refresh-request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + # Both trusted callbacks reserve the same tuple before observing or dispatching. + concurrency: + group: admit-pr-runtime-refresh-${{ github.event.client_payload.pr_number }}-${{ github.event.client_payload.base_sha }}-${{ github.event.client_payload.head_sha }}-${{ github.event.client_payload.merge_sha }} + cancel-in-progress: false + runs-on: ubuntu-latest + timeout-minutes: 4 + 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: Check out the trusted admission workflow revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Revalidate and admit the current tuple + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + PR_NUMBER: ${{ github.event.client_payload.pr_number }} + BASE_REF: ${{ github.event.client_payload.base_ref }} + BASE_SHA: ${{ github.event.client_payload.base_sha }} + HEAD_SHA: ${{ github.event.client_payload.head_sha }} + MERGE_SHA: ${{ github.event.client_payload.merge_sha }} + with: + script: | + const admit = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/admit-pr-runtime-refresh.cjs`); + await admit({ github, context, core, input: { + pr_number: process.env.PR_NUMBER, + base_ref: process.env.BASE_REF, + base_sha: process.env.BASE_SHA, + head_sha: process.env.HEAD_SHA, + merge_sha: process.env.MERGE_SHA, + } }); diff --git a/.github/workflows/preview-reconciler.yml b/.github/workflows/preview-reconciler.yml index 1ad97e2196..c58f470f9b 100644 --- a/.github/workflows/preview-reconciler.yml +++ b/.github/workflows/preview-reconciler.yml @@ -29,8 +29,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - # Use the same trusted revision for the workflow and its checked-in script. - ref: ${{ github.workflow_sha }} + ref: ${{ github.event.repository.default_branch }} persist-credentials: false - name: Set up canonical Python diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index 517ece850e..ff665f2ec9 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -268,7 +268,7 @@ jobs: return; } await github.rest.repos.createDispatchEvent({ - ...context.repo, event_type: 'pr-runtime-base-refresh', + ...context.repo, event_type: 'pr-runtime-base-refresh-request', client_payload: { pr_number: String(pr.number), base_ref: pr.base.ref, base_sha: base.object.sha, head_sha: pr.head.sha, diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 67139d4a7d..ab8d9a59da 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1002,7 +1002,7 @@ 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}).`); await github.rest.repos.createDispatchEvent({ ...context.repo, - event_type: "pr-runtime-base-refresh", + event_type: "pr-runtime-base-refresh-request", client_payload: { pr_number: tuple.prNumber, base_ref: tuple.baseRef, diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index de86eb380e..c408666e46 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -572,7 +572,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "c1ef3c564568f2b7f96f6fa88a90581a87990db29ebd0459fdc869743bcc1eba"; + const canonicalRuntimeWorkflowSha256 = "48de05024423cf754e5da10dcb9034558bf64807fb59b8ea02931044c3704617"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 5622c01ede..f073eb7324 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -66,7 +66,7 @@ The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -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 its executed substantive Validation Gate enforcement 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. Runtime producers group by exact PR/base/head/merge tuple. An old-head rerun uses a separate group, and a duplicate request cannot cancel an already-running producer. With the default GitHub single-pending queue, a later matching request can still replace a pending producer. The refresh observer checks a bounded inventory of active canonical runtime producers and reuses an exact current tuple rather than knowingly dispatching another; the inventory check and dispatch are not atomic. 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. +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 its executed substantive Validation Gate enforcement 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. Runtime producers group by exact PR/base/head/merge tuple. An old-head rerun uses a separate group, and a duplicate request cannot cancel an already-running producer. With the default GitHub single-pending queue, a later matching request can still replace a pending producer. The two trusted observers submit an exact refresh request to one default-branch admission workflow. Admission serializes each PR/base/head/merge tuple, independently verifies the current comparison, and rechecks for a visible active producer before sending the existing runtime dispatch. After dispatch it holds the same tuple's reservation for a bounded visibility check. Completed, failed, or unverifiable attempts leave the tuple eligible for repair. 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. @@ -230,7 +230,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and emits only the existing typed runtime-image refresh request. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata and requires both the immutable event tuple and the eligible deployment plan’s resolved tuple. It binds them to the native run head and unique PR association, independently verifies the recorded and current merge parents, and uses the branch ref for current base authority. A failed render can still trigger repair after a successful eligible plan. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and submits the typed runtime-image refresh request to the shared admission workflow. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata and requires both the immutable event tuple and the eligible deployment plan’s resolved tuple. It binds them to the native run head and unique PR association, independently verifies the recorded and current merge parents, and uses the branch ref for current base authority. A failed render can still trigger repair after a successful eligible plan. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate the additive path-specific policy update: retain `pull_request_target` and `repository_dispatch` and add `pull_request`. Verify fresh natural PR and manual-dispatch events against the merged code; the documentation change itself neither grants authorization nor changes that policy. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 36b562d40e..cf647e491e 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -322,7 +322,7 @@ smoke_path="$ROOT_DIR/.github/workflows/smoke.yml" image_wait_path="$ROOT_DIR/dev-tools/hosted/shared/wait-for-runtime-images.sh" preview_path="$ROOT_DIR/.github/workflows/preview.yml" trusted_preview_path="$ROOT_DIR/.github/workflows/hosted-identity-request.yml" -preview_reconciler_path="$ROOT_DIR/.github/workflows/preview-reconciler.yml" +preview_reconciler_script="$ROOT_DIR/dev-tools/hosted/preview/reconcile-preview-deploys.sh" preview_comment_publisher_path="$ROOT_DIR/dev-tools/hosted/preview/publish-preview-comment.js" preview_comment_test_path="$ROOT_DIR/dev-tools/tests/publish-preview-comment.test.cjs" @@ -1101,7 +1101,7 @@ async function runDispatcher({ (async () => { const tuple = tupleFor(101, "a", "c"); - const runtimeDispatches = (result) => result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh"); + const runtimeDispatches = (result) => result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request"); const previewDispatches = (result) => result.dispatches.filter((item) => item.event_type === "preview-deploy"); const source = { ...tuple, headRef: "feature/parent" }; const child = { ...tupleFor(102, "d", "e", source.headSha), baseRef: source.headRef }; @@ -1266,7 +1266,7 @@ async function runDispatcher({ tuples: [tuple], inventories: { [event]: [producer(tuple, event, status)] }, }); - assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 0, `${event} ${status} exact producer must suppress duplicate runtime dispatch`); assert.equal(result.dispatches.filter((item) => item.event_type === "preview-deploy").length, 1, "runtime deduplication must retain preview reconciliation"); @@ -1285,7 +1285,7 @@ async function runDispatcher({ tuples: [tuple], inventories: { [event]: [producer(tuple, event, "completed", "success")] }, }); - assert.equal(completedSuccess.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(completedSuccess.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, `${event} completed source success must preserve recovery dispatch for missing or expired publication`); } @@ -1301,7 +1301,7 @@ async function runDispatcher({ path: `.github/workflows/runtime-images.yml@${validRef}`, })] }, }); - assert.equal(refSuffixedPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + assert.equal(refSuffixedPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"]) { @@ -1311,7 +1311,7 @@ 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, + assert.equal(invalidRefPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, `an invalid Git ref ${invalidRef} must not suppress the required dispatch`); } const wrongWorkflowPath = await runDispatcher({ @@ -1320,7 +1320,7 @@ 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, + assert.equal(wrongWorkflowPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1333,7 +1333,7 @@ async function runDispatcher({ tuples: [tuple], inventories: { pull_request: [producer(tuple, "pull_request", status, conclusion)] }, }); - assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, `${conclusion} producer must allow an exact-tuple retry`); } @@ -1354,7 +1354,7 @@ async function runDispatcher({ const newestFailure = await orderedProducerInventory( ["completed", "success"], ["completed", conclusion], conclusion ); - assert.equal(newestFailure.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(newestFailure.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, `newer ${conclusion} producer must allow refresh despite an older success`); } for (const [olderStatus, olderConclusion, newestStatus, newestConclusion, suppress] of [ @@ -1365,7 +1365,7 @@ async function runDispatcher({ const newestUsable = await orderedProducerInventory( [olderStatus, olderConclusion], [newestStatus, newestConclusion], newestConclusion ); - assert.equal(newestUsable.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, + assert.equal(newestUsable.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, suppress ? 0 : 1, `newer ${newestStatus}/${newestConclusion} producer must determine whether runtime recovery dispatches`); } @@ -1376,7 +1376,7 @@ 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, + assert.equal(ambiguousNewest.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1386,7 +1386,7 @@ async function runDispatcher({ tuples: [tuple], inventories: { repository_dispatch: [producer(staleTuple, "repository_dispatch", "completed", "success")] }, }); - assert.equal(stale.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(stale.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, "stale base tuple must not suppress a current runtime refresh"); const changedBaseTuple = tupleFor(101, "a", "c", sha("e")); @@ -1394,7 +1394,7 @@ async function runDispatcher({ tuples: [changedBaseTuple], inventories: { pull_request: [producer(tuple, "pull_request", "completed", "success")] }, }); - assert.equal(changedBase.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(changedBase.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").length, 1, "a changed base requires a fresh exact tuple producer"); const sibling = tupleFor(102, "f", "d"); @@ -1407,7 +1407,7 @@ async function runDispatcher({ }, }); const independentRefreshNumbers = independent.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") + .filter((item) => item.event_type === "pr-runtime-base-refresh-request") .map((item) => item.client_payload.pr_number) .sort(); assert.deepEqual(independentRefreshNumbers, ["102"], @@ -1437,7 +1437,7 @@ async function runDispatcher({ }, }); const truncatedRefreshNumbers = truncatedPositive.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") + .filter((item) => item.event_type === "pr-runtime-base-refresh-request") .map((item) => item.client_payload.pr_number) .sort(); assert.deepEqual(truncatedRefreshNumbers, ["103"], @@ -1470,7 +1470,7 @@ async function runDispatcher({ repository_dispatch: [], }, }); - assert.equal(refinedSiblingReuse.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + assert.equal(refinedSiblingReuse.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1495,7 +1495,7 @@ async function runDispatcher({ repository_dispatch: [], }, }); - assert.equal(truncatedRefinement.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(truncatedRefinement.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1514,7 +1514,7 @@ async function runDispatcher({ repository_dispatch: [], }, }); - assert.equal(completedTruncated.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(completedTruncated.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1537,7 +1537,7 @@ async function runDispatcher({ }, }, }); - assert.equal(crossEventHiddenNewer.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(crossEventHiddenNewer.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1557,7 +1557,7 @@ async function runDispatcher({ }, }, }); - assert.equal(safelyOlderOmitted.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + assert.equal(safelyOlderOmitted.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1574,7 +1574,7 @@ async function runDispatcher({ }, }); const relevantMalformedRefreshNumbers = relevantMalformed.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") + .filter((item) => item.event_type === "pr-runtime-base-refresh-request") .map((item) => item.client_payload.pr_number) .sort(); assert.deepEqual(relevantMalformedRefreshNumbers, ["101"], @@ -1598,7 +1598,7 @@ async function runDispatcher({ })] }, }), ]) { - assert.equal(uncertain.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, + assert.equal(uncertain.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh-request").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"); @@ -1654,7 +1654,7 @@ assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'currentBaseRe assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'parents.length !== 2' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'parents[0] !== baseSha' assert_job_excludes runtime-images.yml dispatch-pr-base-refreshes '.base.sha' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'event_type: "pr-runtime-base-refresh"' +assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'event_type: "pr-runtime-base-refresh-request"' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'pr_number: tuple.prNumber' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'base_sha: tuple.baseSha' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'head_sha: tuple.headSha' @@ -1878,28 +1878,28 @@ for job in prepare-runtime deploy-runtime destroy-runtime retire-identity; do assert_job_contains hosted-identity-request.yml "$job" 'self-hosted' assert_job_contains hosted-identity-request.yml "$job" 'environment: trusted-hosted-cluster' done -require_contains "$preview_reconciler_path" 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' -require_contains "$preview_reconciler_path" 'gh api --paginate --slurp' -require_contains "$preview_reconciler_path" '.display_title == $run_name' -require_contains "$preview_reconciler_path" '"Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}"' -require_contains "$preview_reconciler_path" '"repos/${GITHUB_REPOSITORY}/dispatches"' -require_contains "$preview_reconciler_path" '-f event_type=preview-deploy' -require_contains "$preview_reconciler_path" 'client_payload[head_sha]=${head_sha}' -require_contains "$preview_reconciler_path" 'client_payload[base_ref]=${pr_base_ref}' -require_contains "$preview_reconciler_path" 'client_payload[base_sha]=${base_sha}' -require_contains "$preview_reconciler_path" 'client_payload[merge_sha]=${merge_sha}' -require_contains "$preview_reconciler_path" 'client_payload[image_tag]=${image_tag}' -require_contains "$preview_reconciler_path" 'client_payload[action]=deploy' -require_contains "$preview_reconciler_path" 'dispatch_candidates() {' -require_contains "$preview_reconciler_path" 'candidate_rows="$(' -require_contains "$preview_reconciler_path" 'dispatch_candidates <<<"$candidate_rows"' -if python3 - "$preview_reconciler_path" <<'PY' +require_contains "$preview_reconciler_script" 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' +require_contains "$preview_reconciler_script" 'gh api --paginate --slurp' +require_contains "$preview_reconciler_script" '.display_title == $run_name' +require_contains "$preview_reconciler_script" '"Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}"' +require_contains "$preview_reconciler_script" '"repos/${GITHUB_REPOSITORY}/dispatches"' +require_contains "$preview_reconciler_script" '-f event_type=preview-deploy' +require_contains "$preview_reconciler_script" 'client_payload[head_sha]=${head_sha}' +require_contains "$preview_reconciler_script" 'client_payload[base_ref]=${pr_base_ref}' +require_contains "$preview_reconciler_script" 'client_payload[base_sha]=${base_sha}' +require_contains "$preview_reconciler_script" 'client_payload[merge_sha]=${merge_sha}' +require_contains "$preview_reconciler_script" 'client_payload[image_tag]=${image_tag}' +require_contains "$preview_reconciler_script" 'client_payload[action]=deploy' +require_contains "$preview_reconciler_script" 'dispatch_candidates() {' +require_contains "$preview_reconciler_script" 'candidate_rows="$(' +require_contains "$preview_reconciler_script" 'dispatch_candidates <<<"$candidate_rows"' +if python3 - "$preview_reconciler_script" <<'PY' import re import sys from pathlib import Path -workflow = Path(sys.argv[1]).read_text(encoding="utf-8") -if any(re.search(r"\|\s*(?:IFS=[^;]+\s+)?while\b", line) for line in workflow.splitlines()): +script = Path(sys.argv[1]).read_text(encoding="utf-8") +if any(re.search(r"\|\s*(?:IFS=[^;]+\s+)?while\b", line) for line in script.splitlines()): raise SystemExit("preview reconciler must not pipe candidate rows directly into while") PY then @@ -1909,11 +1909,11 @@ else exit 1 fi -if grep -Fq 'desired_image_tag=' "$preview_reconciler_path"; then +if grep -Fq 'desired_image_tag=' "$preview_reconciler_script"; then echo "Preview reconciler must not retain an unused desired image tag" >&2 exit 1 fi -require_contains "$preview_reconciler_path" 'resolve-preview-image-tag.sh' +require_contains "$preview_reconciler_script" 'resolve-preview-image-tag.sh' for annotation in \ 'firemud.dev/last-preview-base-sha' \ 'firemud.dev/last-preview-head-sha' \ @@ -1923,12 +1923,12 @@ for annotation in \ 'firemud.dev/requested-preview-head-sha' \ 'firemud.dev/requested-preview-merge-sha' \ 'firemud.dev/requested-preview-image-tag'; do - require_contains "$preview_reconciler_path" "$annotation" + require_contains "$preview_reconciler_script" "$annotation" done -require_contains "$preview_reconciler_path" 'mergeable_state' +require_contains "$preview_reconciler_script" 'mergeable_state' require_contains "$ROOT_DIR/dev-tools/hosted/preview/revalidate-preview-source-binding.sh" '.mergeable == true' -if grep -Fq 'actions/workflows/preview.yml/dispatches' "$preview_reconciler_path" || - grep -Fq 'inputs[ref]=' "$preview_reconciler_path"; then +if grep -Fq 'actions/workflows/preview.yml/dispatches' "$preview_reconciler_script" || + grep -Fq 'inputs[ref]=' "$preview_reconciler_script"; then echo "Preview reconciler must use typed repository_dispatch from the default branch" >&2 exit 1 fi diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 91967a8dc3..ca0d2c2352 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -4358,7 +4358,7 @@ reconciler_steps = reconciler["jobs"]["reconcile-previews"]["steps"] checkout = reconciler_steps[0] assert checkout["uses"].startswith("actions/checkout@") assert checkout["with"] == { - "ref": "${{ github.workflow_sha }}", + "ref": "${{ github.event.repository.default_branch }}", "persist-credentials": False, } dispatch = next(step for step in reconciler_steps if step.get("name") == "Dispatch preview deploys for drifted PRs") diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 4be98093d3..bf81c5d7d3 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -32,6 +32,7 @@ workflow_dir = root / ".github" / "workflows" preview_path = workflow_dir / "preview.yml" trusted_path = workflow_dir / "hosted-identity-request.yml" reconciler_path = workflow_dir / "preview-reconciler.yml" +reconciler_script_path = root / "dev-tools/hosted/preview/reconcile-preview-deploys.sh" janitor_path = workflow_dir / "preview-janitor.yml" dev_demo_path = workflow_dir / "dev-demo.yml" dev_demo_reconciler_path = workflow_dir / "dev-demo-reconciler.yml" @@ -99,7 +100,7 @@ else: # Exercise the reconciler's actual active-run filter, not a duplicate predicate. -reconciler_source = reconciler_path.read_text() +reconciler_source = reconciler_script_path.read_text(encoding="utf-8") active_filter = re.search( r'--arg run_name [^\n]+ \'\n(.*?)\' <<<"\$\{active_preview_runs_json\}"', reconciler_source, re.S, @@ -316,7 +317,6 @@ if "workflow_dispatch" in preview_source or "pull_request_target:" in preview_so raise AssertionError("preview.yml retains a branch-selectable source trigger") if '"$EVENT_NAME" == repository_dispatch && "$GITHUB_REF" != "refs/heads/$DEFAULT_BRANCH"' not in preview_source: raise AssertionError("preview.yml dispatch lacks a default-branch ref guard") -reconciler_source = reconciler_path.read_text(encoding="utf-8") if ( '"repos/${GITHUB_REPOSITORY}/dispatches"' not in reconciler_source or "event_type=preview-deploy" not in reconciler_source @@ -703,11 +703,10 @@ if "CLEANUP_STATE=open" not in trusted_text or "RETIRE_IDENTITY=true" not in tru if "preview-allocation-lifecycle" not in trusted_text: raise AssertionError("trusted deploy/cleanup lifecycle lost its allocation lock") -reconciler_text = reconciler_path.read_text(encoding="utf-8") allocator_text = (root / "dev-tools/hosted/preview/allocate-preview-capacity.sh").read_text( encoding="utf-8" ) -if "preview:priority" not in reconciler_text or "preview:priority" not in allocator_text: +if "preview:priority" not in reconciler_source or "preview:priority" not in allocator_text: raise AssertionError("preview priority allocation gates are missing") if "preview-allocation-lifecycle" not in janitor_path.read_text(encoding="utf-8"): raise AssertionError("preview janitor lost the shared allocation lifecycle lock") diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 9751b96d5f..f281d0ba68 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -3,6 +3,7 @@ const {execFileSync} = require('node:child_process'); const {test} = require('node:test'); const path = require('node:path'); const root = path.resolve(__dirname, '../..'); +const admitRuntimeRefresh = require('../../.github/scripts/admit-pr-runtime-refresh.cjs'); const workflow = JSON.parse(execFileSync('python3', ['-c', 'import yaml,json,sys; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))', path.join(root, '.github/workflows/preview-runtime-refresh.yml')], {encoding: 'utf8'})); @@ -10,6 +11,140 @@ const script = workflow.jobs.refresh.steps[1].with.script; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const E = 'e'.repeat(40); const A = 'a'.repeat(40), B = 'b'.repeat(40), C = 'c'.repeat(40), D = 'd'.repeat(40); + +function admissionFixture() { + const input = {pr_number: '7', base_ref: 'develop', base_sha: B, head_sha: C, merge_sha: A}; + const repository = 'example/FireMUD'; + const runtimePath = '.github/workflows/runtime-images.yml'; + const makeRun = (overrides = {}) => ({ + id: 300, run_attempt: 1, workflow_id: 42, event: 'repository_dispatch', status: 'queued', + conclusion: null, path: runtimePath, head_branch: 'develop', repository: {full_name: repository}, + head_repository: {full_name: repository}, created_at: new Date().toISOString(), + display_title: `Build Runtime Images secure-pr-artifact pr-7 base-${B} head-${C} merge-${A} mode-required`, + ...overrides, + }); + const sent = []; + const warnings = []; + const runs = []; + const state = {base: B, mergeParents: [B, C], keepHidden: false, afterInventory: null, nextId: 301}; + const github = {rest: { + pulls: {get: async ({pull_number}) => { + assert.equal(pull_number, 7); + return {data: {number: 7, state: 'open', head: {sha: C, repo: {full_name: repository}}, + base: {ref: 'develop', repo: {full_name: repository}}, mergeable: true, + mergeable_state: 'clean', merge_commit_sha: A}}; + }}, + git: { + getRef: async ({ref}) => { + assert.equal(ref, 'heads/develop'); + return {data: {ref: 'refs/heads/develop', object: {sha: state.base}}}; + }, + }, + actions: { + getWorkflow: async ({workflow_id}) => { + assert.equal(workflow_id, 'runtime-images.yml'); + return {data: {id: 42, path: runtimePath}}; + }, + listWorkflowRuns: async ({workflow_id, status, event, page}) => { + assert.equal(workflow_id, 42); + assert.ok(page <= 3); + state.afterInventory?.(); + const workflow_runs = runs.filter(run => (!status || run.status === status) && (!event || run.event === event)); + return {data: {workflow_runs, total_count: workflow_runs.length}}; + }, + }, + repos: { + getCommit: async ({ref}) => { + assert.equal(ref, A); + return {data: {sha: A, parents: state.mergeParents.map(sha => ({sha}))}}; + }, + createDispatchEvent: async payload => { + sent.push(payload); + state.newRun = makeRun({id: state.nextId++}); + }, + }, + }}; + const admission = {github, input, context: {repo: {owner: 'example', repo: 'FireMUD'}, + payload: {repository: {full_name: repository, default_branch: 'develop'}}}, + core: {warning: value => warnings.push(value), info() {}}, sleep: async () => { + if (!state.keepHidden && state.newRun && !runs.includes(state.newRun)) runs.push(state.newRun); + }}; + return {admission, makeRun, runs, sent, state, warnings}; +} + +test('serialized admission waits for the first exact receiver before releasing the permit', async () => { + const f = admissionFixture(); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); + assert.deepEqual(f.sent, [{owner: 'example', repo: 'FireMUD', event_type: 'pr-runtime-base-refresh', + client_payload: {...f.admission.input, image_tag: `pr-merge-${A}`}}]); +}); + +test('completed producers still permit an exact repair', async () => { + for (const conclusion of ['success', 'failure']) { + const f = admissionFixture(); + f.runs.push(f.makeRun({status: 'completed', conclusion})); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); + } +}); + +test('a newer failed exact producer keeps the tuple eligible despite an older active run', async () => { + const f = admissionFixture(); + f.runs.push(f.makeRun({id: 299, event: 'pull_request', head_sha: C, + pull_requests: [{number: 7, head: {sha: C}, base: {sha: B}}], + created_at: new Date(Date.now() - 120000).toISOString()})); + f.runs.push(f.makeRun({id: 300, status: 'completed', conclusion: 'failure', + created_at: new Date(Date.now() - 60000).toISOString()})); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); +}); + +test('admission refuses a base that moves after the inventory read', async () => { + const f = admissionFixture(); + f.state.afterInventory = () => { f.state.base = D; }; + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); + assert.deepEqual(f.sent, []); +}); + +test('admission refuses the exact merge SHA when its ordered parents disagree', async () => { + const f = admissionFixture(); + f.state.mergeParents = [C, B]; + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); + assert.deepEqual(f.sent, []); +}); + +test('an active run from a different repository cannot suppress the repair', async () => { + const f = admissionFixture(); + f.runs.push(f.makeRun({head_repository: {full_name: 'example/Other'}})); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); +}); + +test('indeterminate dispatch visibility does not silently consume a repair or cause an immediate duplicate', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + assert.equal(f.sent.length, 1); + assert.ok(f.warnings.length > 0); +}); + +test('both wake inputs are serialized by one exact tuple group on the default branch', () => { + const admissionWorkflow = JSON.parse(execFileSync('python3', ['-c', + 'import yaml,json,sys; print(json.dumps(yaml.load(open(sys.argv[1]), Loader=yaml.BaseLoader)))', + path.join(root, '.github/workflows/admit-pr-runtime-refresh.yml')], {encoding: 'utf8'})); + assert.deepEqual(admissionWorkflow.on, {repository_dispatch: {types: ['pr-runtime-base-refresh-request']}}); + const job = admissionWorkflow.jobs.dispatch; + assert.equal(job.if, "${{ github.event.action == 'pr-runtime-base-refresh-request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}"); + assert.deepEqual(job.concurrency, { + group: 'admit-pr-runtime-refresh-${{ github.event.client_payload.pr_number }}-${{ github.event.client_payload.base_sha }}-${{ github.event.client_payload.head_sha }}-${{ github.event.client_payload.merge_sha }}', + 'cancel-in-progress': 'false', + }); + assert.deepEqual(job.permissions, {actions: 'read', contents: 'write', 'pull-requests': 'read'}); + assert.deepEqual(job.steps.find(step => step.uses.startsWith('actions/checkout@')).with, + {ref: '${{ github.workflow_sha }}', 'persist-credentials': 'false'}); +}); + const tupleStep = (kind, base, merge) => ({ name: `Preview ${kind} tuple pr-7 base-${base} head-${C} merge-${merge}`, status: 'completed', conclusion: 'success', @@ -89,7 +224,7 @@ async function execute(f, sent = []) { test('exact stale-base current tuple produces only the typed refresh', async () => { const f = fixture(); assert.deepEqual(await execute(f), [{owner: 'example', repo: 'FireMUD', - event_type: 'pr-runtime-base-refresh', client_payload: {pr_number: '7', base_ref: 'develop', + event_type: 'pr-runtime-base-refresh-request', client_payload: {pr_number: '7', base_ref: 'develop', base_sha: B, head_sha: C, merge_sha: A, image_tag: `pr-merge-${A}`}}]); assert.deepEqual(f.mergeReads, [E, A]); }); From 1d14a9e200323ac623eedc9b92771a5ac2af0b9b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 13:00:06 +1300 Subject: [PATCH 098/199] Fix static analysis summary status and tighten review fixtures --- .github/workflows/static-analysis-summary.yml | 4 ++-- .../tests/pr-retarget-workflow-contract.sh | 2 +- .../tests/preview-merge-image-tag-contract.sh | 9 +++++--- .../tests/static-analysis-summary-contract.sh | 23 +++++++++++++++++-- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 5a884f5616..7e3f1d229a 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -142,7 +142,7 @@ jobs: if (value === "success") return "✅"; if (value === "cancelled") return "⚪"; if (terminalFailure.has(value)) return "❌"; - if (value === "pending" || value === "in_progress" || value === "queued" || value === "unavailable") return "⏳"; + if (value === "pending" || value === "requested" || value === "in_progress" || value === "queued" || value === "unavailable") return "⏳"; return "⏭️"; }; @@ -285,7 +285,7 @@ jobs: terminalFailure.has(result) ); const pendingChecks = gateResults.filter(([, result]) => - ["pending", "in_progress", "queued"].includes(result) + ["pending", "requested", "in_progress", "queued"].includes(result) ); const unavailableChecks = gateResults.filter(([, result]) => result === "unavailable"); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index cf647e491e..43708644e8 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -780,7 +780,7 @@ for branch in ("main", "develop"): selector=runtime["concurrency"]["cancel-in-progress"]) == "False" assert callback_group("feature/parent", 7101, 1, "push") != callback_group("feature/parent", 7102, 1, "push") assert callback_group("feature/parent", 7101, 1, "push", selector=runtime["concurrency"]["cancel-in-progress"]) == "False" -assert callback_group("main", 7101, 1, "push") != callback_group("develop", 7102, 1, "push"), "protected publication branches must remain separate" +assert callback_group("main", 7101, 1, "push") != callback_group("develop", 7101, 1, "push"), "protected publication branches must remain separate when only the branch differs" PY diff --git a/dev-tools/tests/preview-merge-image-tag-contract.sh b/dev-tools/tests/preview-merge-image-tag-contract.sh index 079daec647..af752e384f 100644 --- a/dev-tools/tests/preview-merge-image-tag-contract.sh +++ b/dev-tools/tests/preview-merge-image-tag-contract.sh @@ -208,14 +208,17 @@ GH_FIXTURE=branch_runs \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ timeout 15s bash "$WAITER" "$head_sha" >/dev/null -if branch_obsolete_output="$( +branch_obsolete_status=0 +branch_obsolete_output="$( GH_FIXTURE=branch_obsolete HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ timeout 15s bash "$WAITER" "$head_sha" 2>&1 -)"; then - echo "branch waiter accepted a successful obsolete run without promotion" >&2 +)" || branch_obsolete_status=$? +if [[ "$branch_obsolete_status" != 1 ]]; then + printf 'obsolete branch waiter must exit with its own status 1, got %s\n' "$branch_obsolete_status" >&2 exit 1 fi grep -Fq 'Trusted branch runtime-image run 103 has no verified promotion' <<<"$branch_obsolete_output" +grep -Fq "Timed out waiting for runtime-images workflow for ${head_sha} after" <<<"$branch_obsolete_output" if branch_timeout_output="$( GH_FIXTURE=branch_wrong \ diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 274d8b4044..0958f8e1bc 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -835,6 +835,24 @@ run(github, context, core).then(async () => { } } github.paginate = savedPaginate; + github.request = async (route, input) => { + const response = await savedRequest(route, input); + if (input.run_id === 200) { + const gate = response.data.jobs.find(job => job.name === "CodeQL Gate"); + gate.status = "requested"; + gate.conclusion = null; + } + return response; + }; + const requestedStart = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(requestedStart).some(row => + row.body.includes("Static analysis checks are still running") && + row.body.includes("⏳ CodeQL gate: `requested`")) || + calls.updated.slice(requestedStart).some(row => row.body.includes("checks passed"))) { + throw new Error("a requested exact gate must display as pending"); + } + github.request = savedRequest; const savedActions = github.rest.actions; const staleBefore = mutationCounts(); github.rest.actions = {...savedActions, getWorkflowRun: async (input) => { @@ -863,13 +881,14 @@ run(github, context, core).then(async () => { const {data} = await savedActions.getWorkflowRun(input); return {data: input.run_id === 200 ? {...data, run_attempt: currentAttempt} : data}; }}; - for (const duplicate of [false, true]) { + for (const fault of ["attempt", "duplicate", "head"]) { github.request = async (route, input) => { const response = await savedRequest(route, input); if (input.run_id !== 200) return response; const jobs = response.data.jobs; const gate = jobs.find(job => job.name === "CodeQL Gate"); - if (duplicate) jobs.push({...gate, id: gate.id + 50000}); + if (fault === "duplicate") jobs.push({...gate, id: gate.id + 50000}); + else if (fault === "head") gate.head_sha = "e".repeat(40); else gate.run_attempt = input.attempt_number + 1; return {data: {jobs, total_count: jobs.length}}; }; From 89c3e211f12ff910a8f13dcdc2c0c95b5afa663c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 13:36:05 +1300 Subject: [PATCH 099/199] Strengthen required gate and preview command contracts --- .../pr-required-gate-context-contract.sh | 46 ++++++++++++++++--- dev-tools/tests/preview-priority-contract.sh | 25 ++++++---- 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 9d287e9cb3..f75cdafa45 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -75,6 +75,31 @@ def literal_format(pattern, *args): return "".join((*parts, tail)) +def selector_equal(left, right): + # GitHub Actions compares like kinds directly and coerces unlike kinds + # to numbers. This model supports only the interpreter's scalar kinds. + if type(left) is type(right): + if isinstance(left, str): + return left.casefold() == right.casefold() + return left == right + + def to_number(value): + if value is None: + return 0 + if type(value) in (bool, int): + return int(value) + if type(value) is str: + if not value: + return 0 + number = value.strip(" \t\r\n") + if re.fullmatch(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", number): + return float(number) + return float("nan") + raise ValueError("Unsupported concurrency comparison operand") + + return to_number(left) == to_number(right) + + def interpret_selector(node): if isinstance(node, ast.Constant) and type(node.value) in (str, int, bool, type(None)): return node.value @@ -88,11 +113,9 @@ def interpret_selector(node): return value if (isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], (ast.Eq, ast.NotEq))): - values = interpret_selector(node.left), interpret_selector(node.comparators[0]) - # Actions compares strings without regard to case. - if all(type(value) is str for value in values): - values = tuple(value.casefold() for value in values) - return (values[0] == values[1]) == isinstance(node.ops[0], ast.Eq) + left = interpret_selector(node.left) + right = interpret_selector(node.comparators[0]) + return selector_equal(left, right) == isinstance(node.ops[0], ast.Eq) if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "format" and not node.keywords and node.args and isinstance(node.args[0], ast.Constant)): @@ -100,7 +123,16 @@ def interpret_selector(node): raise ValueError("Unsupported concurrency selector") -for expression, expected in (("'Develop' == 'develop'", True), ("'Develop' != 'develop'", False)): +for expression, expected in ( + ("'Develop' == 'develop'", True), + ("'Develop' != 'develop'", False), + ("12 == '12'", True), + ("12 != ' 1.2e1 '", False), + ("False == 0", True), + ("None == 0", True), + ("1 == 'one'", False), + ("1 == '01'", False), +): assert interpret_selector(ast.parse(expression, mode="eval").body) is expected @@ -849,6 +881,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal return {data: exactPrimary}; } if (kind === "optional-final-acceptance-transient" && input.run_id === 44) { + assert.equal(input.attempt_number, source.run_attempt); return {data: {...source, id: 44, event: "repository_dispatch", head_sha: defaultSha, head_branch: "develop", status: "completed", conclusion: "success"}}; } @@ -871,6 +904,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } if (kind === "optional-final-acceptance-transient" && input.run_id === 44) { + assert.equal(input.attempt_number, source.run_attempt); return [{...job, run_id: 44, head_sha: defaultSha, steps: [...job.steps, {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index ca0d2c2352..30e1b6ad89 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -526,11 +526,14 @@ cat > "$TEMP_DIR/bin/gh" <<'EOF' set -euo pipefail resource="" has_jq=false +has_include=false for arg in "$@"; do if [[ "$arg" == repos/* ]]; then resource="$arg" elif [[ "$arg" == "--jq" ]]; then has_jq=true + elif [[ "$arg" == "--include" ]]; then + has_include=true fi done @@ -684,17 +687,19 @@ if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then 404) dispatch_reason='Not Found' ;; *) dispatch_reason='Test Status' ;; esac - printf 'HTTP/2.0 %s %s\n' "$dispatch_status" "$dispatch_reason" - if [[ -n "${FAKE_DISPATCH_RETRY_AFTER:-}" ]]; then - printf 'Retry-After: %s\n' "$FAKE_DISPATCH_RETRY_AFTER" - fi - if [[ -n "${FAKE_DISPATCH_RATE_REMAINING:-}" ]]; then - printf 'X-RateLimit-Remaining: %s\n' "$FAKE_DISPATCH_RATE_REMAINING" - fi - if [[ -n "${FAKE_DISPATCH_RATE_RESET:-}" ]]; then - printf 'X-RateLimit-Reset: %s\n' "$FAKE_DISPATCH_RATE_RESET" + if [[ "$has_include" == true ]]; then + printf 'HTTP/2.0 %s %s\n' "$dispatch_status" "$dispatch_reason" + if [[ -n "${FAKE_DISPATCH_RETRY_AFTER:-}" ]]; then + printf 'Retry-After: %s\n' "$FAKE_DISPATCH_RETRY_AFTER" + fi + if [[ -n "${FAKE_DISPATCH_RATE_REMAINING:-}" ]]; then + printf 'X-RateLimit-Remaining: %s\n' "$FAKE_DISPATCH_RATE_REMAINING" + fi + if [[ -n "${FAKE_DISPATCH_RATE_RESET:-}" ]]; then + printf 'X-RateLimit-Reset: %s\n' "$FAKE_DISPATCH_RATE_RESET" + fi + printf '\n' fi - printf '\n' if [[ "$dispatch_status" != 204 ]]; then jq -cn --arg message "${FAKE_DISPATCH_ERROR_MESSAGE:-Forbidden}" '{message:$message}' fi From 7b57f0fdd6d8d2df36de0594cd213995b318a08b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 14:28:03 +1300 Subject: [PATCH 100/199] Cover digest stability for raw ordered capacity maps --- .../firemud/recovery/model/InitialGameplayReleaseModelTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index c1b3994403..a310c2c895 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -361,6 +361,7 @@ void readinessAndDigestIgnoreCapacityMapIterationOrder() { InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); assertThat(codec.digest(reordered)).isEqualTo(codec.digest(original)); + assertThat(codec.digest(reversed)).isEqualTo(codec.digest(forward)); assertThatThrownBy(() -> reordered.issuerLayout().capacityVector().put(2, 1)) .isInstanceOf(UnsupportedOperationException.class); } From f12934eb2f27a21a754876d304c4bf6afc7c625e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 16:24:24 +1300 Subject: [PATCH 101/199] Sample preview inventory time after both source reads --- dev-tools/hosted/preview/reconcile-preview-deploys.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh index c8b8202e7b..06e91a466d 100644 --- a/dev-tools/hosted/preview/reconcile-preview-deploys.sh +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -620,12 +620,12 @@ recent_successful_source_handoff() { local run_name="Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}" local pr_title="PR preview ${pr_number}" - source_inventory_now="$(date -u +%s)" if ! source_runs="$(completed_preview_inventory pull_request "head_sha=${head_sha}")" || ! dispatch_source_runs="$(completed_preview_inventory repository_dispatch "branch=${DEFAULT_BRANCH}")"; then echo "Recent completed preview-source inventory is unavailable, malformed, or truncated; retry budget unchanged." >&2 return 2 fi + source_inventory_now="$(date -u +%s)" if ! source_candidates="$(printf '%s\n' "$source_runs" "$dispatch_source_runs" | jq -r -s \ --arg repository "$GITHUB_REPOSITORY" --arg head "$head_sha" \ --arg default_branch "$DEFAULT_BRANCH" --arg workflow_name "$preview_workflow_name" \ From 4527af1bfb3e2c1f19c931506c6d0127dacf0f67 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:18:48 +1300 Subject: [PATCH 102/199] Apply standalone foundations review fixes --- .github/scripts/admit-pr-runtime-refresh.cjs | 123 ++++++-- .../workflows/admit-pr-runtime-refresh.yml | 14 +- .github/workflows/ci.yml | 2 +- .github/workflows/preview-runtime-refresh.yml | 147 ++++------ .github/workflows/smoke.yml | 20 +- .github/workflows/static-analysis-summary.yml | 25 +- .../spring-cloud-gateway/configuration.md | 2 +- .../architecture/system-architecture-cicd.md | 2 +- .../preview/reconcile-preview-deploys.sh | 126 ++++++-- .../hosted/shared/wait-for-runtime-images.sh | 50 ++-- .../pr-required-gate-context-contract.sh | 66 ++++- .../tests/pr-retarget-workflow-contract.sh | 83 +++++- dev-tools/tests/preview-priority-contract.sh | 162 ++++++++-- .../tests/preview-runtime-refresh.test.cjs | 277 ++++++++++++++---- .../tests/static-analysis-summary-contract.sh | 111 ++++++- dev-tools/validation/check-flyway-versions.py | 48 ++- ...lDatabaseHostEnvironmentPostProcessor.java | 7 + .../InitialGameplayReleaseTupleCodec.java | 6 + ...itial_gameplay_release_attempt_closure.sql | 1 + ...ReleaseJournalPostgresIntegrationTest.java | 79 ++++- ...abaseHostEnvironmentPostProcessorTest.java | 28 ++ .../InitialGameplayReleaseModelTest.java | 34 +-- 22 files changed, 1113 insertions(+), 300 deletions(-) diff --git a/.github/scripts/admit-pr-runtime-refresh.cjs b/.github/scripts/admit-pr-runtime-refresh.cjs index e0905f84ac..997ac1809b 100644 --- a/.github/scripts/admit-pr-runtime-refresh.cjs +++ b/.github/scripts/admit-pr-runtime-refresh.cjs @@ -1,3 +1,6 @@ +const {execFileSync} = require('node:child_process'); +const {resolve} = require('node:path'); + module.exports = async function admitPrRuntimeRefresh({ github, context, @@ -24,8 +27,10 @@ module.exports = async function admitPrRuntimeRefresh({ const isNotFound = error => error?.status === 404 || error?.response?.status === 404; const dataOf = response => response && isRecord(response.data) ? response.data : null; - if (!isRecord(input) || Reflect.ownKeys(input).length !== requiredFields.length || - requiredFields.some(field => !Object.prototype.hasOwnProperty.call(input, field))) { + if (!isRecord(input) || + Reflect.ownKeys(input).some(field => !requiredFields.includes(field) && field !== 'preview_only') || + requiredFields.some(field => !Object.hasOwn(input, field)) || + (Object.hasOwn(input, 'preview_only') && input.preview_only !== true)) { fail('Invalid runtime refresh input.'); } if (requiredFields.some(field => typeof input[field] !== 'string')) fail('Invalid runtime refresh input.'); @@ -48,7 +53,7 @@ module.exports = async function admitPrRuntimeRefresh({ const defaultBranch = repository.default_branch; const pullNumber = Number(input.pr_number); - const currentIdentity = async () => { + const observeIdentity = async () => { let pullResponse; try { pullResponse = await github.rest.pulls.get({...contextRepo, pull_number: pullNumber}); @@ -60,9 +65,9 @@ module.exports = async function admitPrRuntimeRefresh({ if (!pull || pull.number !== pullNumber || pull.state !== 'open' || pull.head?.repo?.full_name !== fullName || pull.base?.repo?.full_name !== fullName || pull.head?.sha !== input.head_sha || pull.base?.ref !== input.base_ref || - pull.mergeable !== true || typeof pull.mergeable_state !== 'string' || - ['dirty', 'conflicting', 'unknown'].includes(pull.mergeable_state) || - pull.merge_commit_sha !== input.merge_sha) return false; + (pull.mergeable !== true && pull.mergeable !== null) || + typeof pull.mergeable_state !== 'string' || + ['dirty', 'conflicting'].includes(pull.mergeable_state)) return false; let refResponse; try { @@ -74,17 +79,49 @@ module.exports = async function admitPrRuntimeRefresh({ const ref = dataOf(refResponse); if (ref?.ref !== `refs/heads/${input.base_ref}` || ref.object?.sha !== input.base_sha) return false; + const reportedMerge = pull.merge_commit_sha; + if (pull.mergeable === null || pull.mergeable_state === 'unknown' || reportedMerge === null) return null; + if (typeof reportedMerge !== 'string' || !shaPattern.test(reportedMerge)) return false; + let commitResponse; try { - commitResponse = await github.rest.repos.getCommit({...contextRepo, ref: input.merge_sha}); + commitResponse = await github.rest.repos.getCommit({...contextRepo, ref: reportedMerge}); } catch (error) { - if (isNotFound(error)) return false; + if (isNotFound(error)) return null; throw error; } const commit = dataOf(commitResponse); - return commit?.sha === input.merge_sha && Array.isArray(commit.parents) && - commit.parents.length === 2 && commit.parents[0]?.sha === input.base_sha && - commit.parents[1]?.sha === input.head_sha; + if (commit?.sha !== reportedMerge || !Array.isArray(commit.parents) || + commit.parents.length !== 2 || commit.parents[1]?.sha !== input.head_sha) return false; + const mergeBase = commit.parents[0]?.sha; + if (reportedMerge !== input.merge_sha) { + // GitHub can still report an older test merge while the pinned base is live. + return typeof mergeBase === 'string' && shaPattern.test(mergeBase) && + mergeBase !== input.base_sha ? null : false; + } + if (mergeBase !== input.base_sha) return false; + if (Object.hasOwn(input, 'preview_only')) { + try { + execFileSync('python3', [ + resolve(__dirname, '../../dev-tools/hosted/preview/preview-eligibility.py'), '--revalidate-deploy', + '--expected-repository', fullName, '--expected-head-sha', input.head_sha, + ], {input: JSON.stringify(pull), encoding: 'utf8'}); + } catch (error) { + if (error.status !== 1) throw error; + core.info('Canonical preview eligibility refused the current PR; no dispatch.'); + return false; + } + } + return true; + }; + + const currentIdentity = async () => { + for (let observation = 0; observation < 6; observation++) { + const result = await observeIdentity(); + if (result !== null) return result; + if (observation < 5) await sleep(2000); + } + return false; }; if (!await currentIdentity()) { @@ -133,28 +170,30 @@ module.exports = async function admitPrRuntimeRefresh({ let inventoryComplete = true; let newestExact = null; const observedRunIds = new Set(); - const createdSince = secondsUtc(Date.now() - 30 * 60 * 1000); - try { - const exactRuns = []; - for (const event of inventoryEvents) { + const exactRuns = []; + const collectInventory = async (event, status, createdSince) => { + let total; + let seen = 0; + for (let page = 1; page <= 3; page++) { const {data: inventory} = await github.rest.actions.listWorkflowRuns({ - ...contextRepo, - workflow_id: runtimeWorkflow.id, - event, - created: `${createdSince}..*`, - per_page: 100, - page: 1, + ...contextRepo, workflow_id: runtimeWorkflow.id, event, status, per_page: 100, page, + ...(createdSince ? {created: `${createdSince}..*`} : {}), }); if (!Number.isSafeInteger(inventory?.total_count) || inventory.total_count < 0 || - inventory.total_count > 100 || !Array.isArray(inventory.workflow_runs) || - inventory.workflow_runs.length !== inventory.total_count) { + inventory.total_count > 300 || !Array.isArray(inventory.workflow_runs) || + inventory.workflow_runs.length > 100 || (total !== undefined && inventory.total_count !== total)) { throw new Error('Incomplete runtime run inventory.'); } + total = inventory.total_count; + seen += inventory.workflow_runs.length; for (const run of inventory.workflow_runs) { - if (run?.event !== event) throw new Error('Runtime inventory contains an unexpected event.'); + if (run?.event !== event || run.status !== status) { + throw new Error('Runtime inventory contains an unexpected event or status.'); + } if (!exactNativeTuple(run)) continue; if (!isPositiveInteger(run.id) || !isPositiveInteger(run.run_attempt) || - !validChronology(run.created_at) || Date.parse(run.created_at) < Date.parse(createdSince)) { + !validChronology(run.created_at) || + (createdSince && Date.parse(run.created_at) < Date.parse(createdSince))) { throw new Error('Exact runtime run has invalid native chronology.'); } const identity = `${run.event}:${run.id}:${run.run_attempt}`; @@ -167,9 +206,25 @@ module.exports = async function admitPrRuntimeRefresh({ } exactRuns.push(run); } + if (seen === total) return; + if (seen > total || inventory.workflow_runs.length < 100) break; + } + throw new Error('Incomplete runtime run inventory.'); + }; + const rankRuns = (left, right) => Date.parse(right.created_at) - Date.parse(left.created_at); + try { + for (const event of inventoryEvents) { + for (const status of activeStatuses) await collectInventory(event, status); } - exactRuns.sort((left, right) => Date.parse(right.created_at) - Date.parse(left.created_at)); + exactRuns.sort(rankRuns); + if (exactRuns.length > 0) { + // An older active producer still matters. Only completed runs at least + // as new as the newest active candidate can change that decision. + const createdSince = secondsUtc(Date.parse(exactRuns[0].created_at)); + for (const event of inventoryEvents) await collectInventory(event, 'completed', createdSince); + exactRuns.sort(rankRuns); + } if (exactRuns.length > 0) { if (exactRuns.length > 1 && Date.parse(exactRuns[0].created_at) === Date.parse(exactRuns[1].created_at)) { throw new Error('Newest exact runtime runs have equal chronology.'); @@ -181,11 +236,25 @@ module.exports = async function admitPrRuntimeRefresh({ core.warning('Runtime active-run inventory was incomplete or ambiguous; preserving the required refresh fallback.'); } + let activeProducerVerified = false; + if (inventoryComplete && newestExact && isExactActiveRun(newestExact)) { + try { + const latest = dataOf(await github.rest.actions.getWorkflowRun({ + ...contextRepo, run_id: newestExact.id, + })); + activeProducerVerified = isExactActiveRun(latest) && latest.id === newestExact.id && + latest.run_attempt === newestExact.run_attempt && latest.event === newestExact.event && + latest.head_sha === newestExact.head_sha && + Date.parse(latest.created_at) === Date.parse(newestExact.created_at); + } catch { + core.warning('The exact active runtime producer could not be reread; preserving the required refresh fallback.'); + } + } if (!await currentIdentity()) { core.info('Runtime refresh tuple changed during admission; no dispatch.'); return 'obsolete'; } - if (inventoryComplete && newestExact && isExactActiveRun(newestExact)) { + if (activeProducerVerified) { core.info('The unique newest exact runtime producer is already active; no dispatch.'); return 'already-active'; } diff --git a/.github/workflows/admit-pr-runtime-refresh.yml b/.github/workflows/admit-pr-runtime-refresh.yml index ae4823b3eb..f364cd807e 100644 --- a/.github/workflows/admit-pr-runtime-refresh.yml +++ b/.github/workflows/admit-pr-runtime-refresh.yml @@ -34,19 +34,7 @@ jobs: - name: Revalidate and admit the current tuple uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - PR_NUMBER: ${{ github.event.client_payload.pr_number }} - BASE_REF: ${{ github.event.client_payload.base_ref }} - BASE_SHA: ${{ github.event.client_payload.base_sha }} - HEAD_SHA: ${{ github.event.client_payload.head_sha }} - MERGE_SHA: ${{ github.event.client_payload.merge_sha }} with: script: | const admit = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/admit-pr-runtime-refresh.cjs`); - await admit({ github, context, core, input: { - pr_number: process.env.PR_NUMBER, - base_ref: process.env.BASE_REF, - base_sha: process.env.BASE_SHA, - head_sha: process.env.HEAD_SHA, - merge_sha: process.env.MERGE_SHA, - } }); + await admit({github, context, core, input: context.payload.client_payload}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f0a3c18900..90b7378458 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,7 +132,7 @@ jobs: const entries = await github.paginate(github.rest.pulls.listFiles, { ...context.repo, pull_number: context.payload.pull_request.number, per_page: 100, }, response => response.data); - const knownDoc = path => path === "README.md" || (typeof path === "string" && + const knownDoc = path => path === "README.md" || path === "mkdocs.yml" || (typeof path === "string" && /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && !path.split("/").includes("..")); const knownDesignDoc = path => knownDoc(path) && path.startsWith("design/"); diff --git a/.github/workflows/preview-runtime-refresh.yml b/.github/workflows/preview-runtime-refresh.yml index ff665f2ec9..d7cdd57015 100644 --- a/.github/workflows/preview-runtime-refresh.yml +++ b/.github/workflows/preview-runtime-refresh.yml @@ -124,9 +124,6 @@ jobs: core.info('Recorded preview merge does not prove its base/head tuple; no dispatch.'); return; } - const {data: pr} = await github.rest.pulls.get({ - ...context.repo, pull_number: source.number, - }); // Execute only the checked-out default-branch eligibility policy. const isEligible = (pull) => { try { @@ -141,34 +138,66 @@ jobs: return false; } }; - if (!isEligible(pr)) return; - const isIntegrationBase = ['main', 'develop'].includes(pr.base?.ref); - if (pr.state !== 'open' || pr.head?.repo?.full_name !== repository || - pr.base?.repo?.full_name !== repository || - pr.head.sha !== run.head_sha || source.head?.sha !== run.head_sha || - !/^[A-Za-z0-9._/-]+$/.test(pr.base.ref) || - !sha.test(pr.merge_commit_sha)) { - core.info('Source is stale or ineligible; no dispatch.'); - return; - } - const {data: base} = await github.rest.git.getRef({ - ...context.repo, ref: `heads/${pr.base.ref}`, - }); + const sourcePullMatches = pull => pull?.number === source.number && pull.state === 'open' && + pull.head?.repo?.full_name === repository && pull.base?.repo?.full_name === repository && + pull.head.sha === run.head_sha && source.head?.sha === run.head_sha && + typeof pull.base.ref === 'string' && /^[A-Za-z0-9._/-]+$/.test(pull.base.ref); + const conflicts = pull => pull.mergeable === false || + ['dirty', 'conflicting'].includes(pull.mergeable_state); + const mergeReady = pull => pull.mergeable === true && typeof pull.mergeable_state === 'string' && + pull.mergeable_state !== 'unknown' && + typeof pull.merge_commit_sha === 'string' && sha.test(pull.merge_commit_sha); + const pause = require('node:timers/promises').setTimeout; const eventBaseMatchesMerge = recorded[2] === recordedMerge.parents[0].sha; - if (!sha.test(base.object?.sha) || - (isIntegrationBase && eventBaseMatchesMerge && recorded[2] === base.object.sha)) { - core.info('No stale source base to repair; no dispatch.'); - return; + let current; + let expectedBaseRef; + for (let read = 0; read < 6; read++) { + const {data: pull} = await github.rest.pulls.get({ + ...context.repo, pull_number: source.number, + }); + if (!sourcePullMatches(pull) || conflicts(pull) || + (expectedBaseRef && pull.base.ref !== expectedBaseRef) || !isEligible(pull)) { + core.info('Source is stale, conflicted or ineligible; no dispatch.'); + return; + } + expectedBaseRef = pull.base.ref; + const {data: base} = await github.rest.git.getRef({ + ...context.repo, ref: `heads/${expectedBaseRef}`, + }); + if (!sha.test(base.object?.sha) || + (['main', 'develop'].includes(expectedBaseRef) && + eventBaseMatchesMerge && recorded[2] === base.object.sha)) { + core.info('No stale source base to repair; no dispatch.'); + return; + } + if (mergeReady(pull)) { + let merge; + try { + ({data: merge} = await github.rest.repos.getCommit({ + ...context.repo, ref: pull.merge_commit_sha, + })); + } catch (error) { + if (error?.status !== 404 && error?.response?.status !== 404) throw error; + } + if (merge) { + if (merge.sha !== pull.merge_commit_sha || merge.parents?.length !== 2 || + merge.parents[1]?.sha !== pull.head.sha) { + core.info('Current merge does not prove the source head; no dispatch.'); + return; + } + if (merge.parents[0]?.sha === base.object.sha) { + current = {pr: pull, base, merge}; + break; + } + } + } + if (read < 5) await pause(2000); } - const {data: merge} = await github.rest.repos.getCommit({ - ...context.repo, ref: pr.merge_commit_sha, - }); - if (merge.sha !== pr.merge_commit_sha || merge.parents?.length !== 2 || - merge.parents[0].sha !== base.object.sha || - merge.parents[1].sha !== pr.head.sha) { - core.info('Current merge is not the exact current base/head tuple; no dispatch.'); + if (!current) { + core.info('Current merge did not resolve to the current base/head tuple; no dispatch.'); return; } + const {pr, base, merge} = current; // The event and the plan can observe different base advances. The // resolved plan must independently prove its ordered parents. let resolvedMerge = resolved[4] === recordedMerge.sha ? recordedMerge : merge; @@ -191,54 +220,6 @@ jobs: core.info('Canonical image policy selects base images; no refresh.'); return; } - // Event-driven duplicate suppression, not proof of image publication. - // Bound each active-status inventory; never treat a truncated inventory - // as proof that no producer exists. Completed runs do not suppress repair. - const runtimePath = '.github/workflows/runtime-images.yml'; - const {data: runtimeWorkflow} = await github.rest.actions.getWorkflow({ - ...context.repo, workflow_id: 'runtime-images.yml', - }); - if (runtimeWorkflow.path !== runtimePath || - !Number.isSafeInteger(runtimeWorkflow.id) || runtimeWorkflow.id <= 0) { - throw new Error('Runtime workflow identity is unproven'); - } - const expectedTitle = 'Build Runtime Images secure-pr-artifact ' + - `pr-${pr.number} base-${base.object.sha} head-${pr.head.sha} merge-${merge.sha} mode-required`; - const activeStatuses = ['queued', 'waiting', 'requested', 'pending', 'in_progress']; - for (const status of activeStatuses) { - for (let page = 1; page <= 3; page++) { - const {data: inventory} = await github.rest.actions.listWorkflowRuns({ - ...context.repo, workflow_id: runtimeWorkflow.id, status, per_page: 100, page, - }); - if (!Array.isArray(inventory.workflow_runs)) throw new Error('Invalid runtime run inventory'); - for (const candidate of inventory.workflow_runs) { - const trustedPath = candidate.path === runtimePath || - candidate.path === `${runtimePath}@refs/heads/${context.payload.repository.default_branch}` || - (candidate.event === 'pull_request' && - candidate.path === `${runtimePath}@refs/pull/${pr.number}/merge`); - if (candidate.workflow_id !== runtimeWorkflow.id || !trustedPath || - candidate.repository?.full_name !== repository || - candidate.head_repository?.full_name !== repository || - !activeStatuses.includes(candidate.status) || candidate.conclusion != null || - candidate.display_title !== expectedTitle) continue; - // Dispatch runs execute default-branch workflow code. PR runs - // additionally need native GitHub head/base association, not title alone. - const dispatchRun = candidate.event === 'repository_dispatch' && - candidate.head_branch === context.payload.repository.default_branch; - const prRun = candidate.event === 'pull_request' && - candidate.head_sha === pr.head.sha && candidate.pull_requests?.length === 1 && - candidate.pull_requests[0].number === pr.number && - candidate.pull_requests[0].head?.sha === pr.head.sha && - candidate.pull_requests[0].base?.sha === base.object.sha; - if (dispatchRun || prRun) { - core.info('Exact current runtime tuple already has an active producer; no dispatch.'); - return; - } - } - if (inventory.workflow_runs.length < 100) break; - if (page === 3) throw new Error('Active runtime inventory exceeds bounded lookup'); - } - } const {data: latestRun} = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: run.id, }); @@ -246,25 +227,23 @@ jobs: latestRun.head_sha !== run.head_sha || latestRun.event !== run.event || latestRun.path !== run.path || latestRun.status !== 'completed' || latestRun.conclusion !== run.conclusion) { - core.info('Source attempt changed during runtime lookup; no dispatch.'); + core.info('Source attempt changed during tuple verification; no dispatch.'); return; } const {data: latestPr} = await github.rest.pulls.get({ ...context.repo, pull_number: source.number, }); - if (!isEligible(latestPr) || latestPr.number !== pr.number || - latestPr.state !== 'open' || latestPr.head?.repo?.full_name !== repository || - latestPr.base?.repo?.full_name !== repository || - latestPr.head?.sha !== pr.head.sha || latestPr.base?.ref !== pr.base.ref || - latestPr.merge_commit_sha !== merge.sha) { - core.info('Preview eligibility or exact tuple changed during runtime lookup; no dispatch.'); + if (!sourcePullMatches(latestPr) || conflicts(latestPr) || !mergeReady(latestPr) || + latestPr.base.ref !== pr.base.ref || latestPr.merge_commit_sha !== merge.sha || + !isEligible(latestPr)) { + core.info('Preview eligibility or exact tuple changed during tuple verification; no dispatch.'); return; } const {data: latestBase} = await github.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}`, }); if (latestBase.object?.sha !== base.object.sha) { - core.info('Preview base changed during runtime lookup; no dispatch.'); + core.info('Preview base changed during tuple verification; no dispatch.'); return; } await github.rest.repos.createDispatchEvent({ @@ -272,6 +251,6 @@ jobs: client_payload: { pr_number: String(pr.number), base_ref: pr.base.ref, base_sha: base.object.sha, head_sha: pr.head.sha, - merge_sha: merge.sha, image_tag: `pr-merge-${merge.sha}`, + merge_sha: merge.sha, preview_only: true, }, }); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c408666e46..5f91695242 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1014,7 +1014,7 @@ jobs: ); matchingRuns.sort((left, right) => right.createdAt - left.createdAt || right.run.id - left.run.id); let newestPreExecutionCancellation = null; - for (const candidate of matchingRuns) { + for (const [index, candidate] of matchingRuns.entries()) { const run = candidate.run; if (run.status === "completed" && run.conclusion === "cancelled" && await isPreExecutionCancelledAttempt(run, expectedDisplayTitle, identity)) { @@ -1022,9 +1022,12 @@ jobs: continue; } if (run.status !== "completed" && !isRetryPrimary(selection, run)) { - const completed = matchingRuns.filter(({run: older}) => - older.id !== run.id && older.status === "completed" && older.conclusion === "success"); - for (const {run: older} of completed.slice(0, 3)) { + let checkedSuccesses = 0; + for (const {run: older} of matchingRuns.slice(index + 1)) { + if (older.status !== "completed") continue; + if (older.conclusion === "cancelled" && + await isPreExecutionCancelledAttempt(older, expectedDisplayTitle, identity)) continue; + if (older.conclusion !== "success" || ++checkedSuccesses > 3) break; try { if (await verifyCompletedCanonicalRuntime(older, identity)) { core.info("A verified completed exact runtime producer precedes the pending duplicate."); @@ -1577,6 +1580,15 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + const confirmedIdentity = await resolveCurrentIdentity( + "Stopping stale current-base smoke gate after the final attempt lookup" + ); + if (confirmedIdentity?.obsolete) return; + if (!confirmedIdentity || identityKey(confirmedIdentity) !== identityKey(currentIdentity)) { + currentIdentity = confirmedIdentity; + core.info("Current-base identity changed after the final runtime attempt lookup; resume exact selection."); + continue smokeGatePolling; + } } return; } diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 7e3f1d229a..858a094a0d 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -103,6 +103,10 @@ jobs: if (!baseSha) { throw new Error("The current pull-request base SHA is unavailable."); } + const baseRef = currentPullRequest.base?.ref; + if (typeof baseRef !== "string" || !baseRef.trim()) { + throw new Error("The current pull-request base ref is unavailable."); + } const sourceWorkflowPath = context.payload.workflow_run.path; const sourceWorkflowName = ({ ".github/workflows/codeql.yml": "CodeQL Analysis", @@ -164,6 +168,14 @@ jobs: return numericIdentity(left?.id) - numericIdentity(right?.id); }; + const associatedBaseRef = (run) => { + if (!Array.isArray(run?.pull_requests)) return null; + const associations = run.pull_requests.filter(pr => pr?.number === issueNumber); + if (associations.length !== 1) return null; + const ref = associations[0].base?.ref; + return typeof ref === "string" && ref.trim() ? ref : null; + }; + // Metadata-only edits skip their gate under a non-required name; the // earlier substantive run for the same title remains the result. // GitHub leaves a skipped job's name expression unevaluated, so match @@ -182,6 +194,11 @@ jobs: run?.display_title === expectedTitle && run.event === "pull_request" && run.head_sha === headSha).sort((a, b) => compareWorkflowRuns(b, a)); for (const candidate of candidates) { + // Retargeting can preserve both SHAs in the title. A newer + // candidate without a ref cannot safely yield to older proof. + const candidateBaseRef = associatedBaseRef(candidate); + if (!candidateBaseRef) throw new Error("Static summary candidate base ref is unavailable."); + if (candidateBaseRef !== baseRef) continue; if (!Number.isSafeInteger(candidate.id) || candidate.id <= 0 || !Number.isSafeInteger(candidate.run_attempt) || candidate.run_attempt <= 0) { throw new Error("Static summary candidate identity is unavailable."); @@ -210,7 +227,7 @@ jobs: }); if (currentRun?.id !== candidate.id || currentRun.run_attempt !== candidate.run_attempt || currentRun.event !== "pull_request" || currentRun.head_sha !== headSha || - currentRun.display_title !== expectedTitle) { + currentRun.display_title !== expectedTitle || associatedBaseRef(currentRun) !== baseRef) { throw new Error("Static summary cannot confirm the current workflow attempt."); } return { ...candidate, status: "unavailable", conclusion: null, jobs: [] }; @@ -252,6 +269,8 @@ jobs: return "pending"; } if (checkRun.status !== "completed") return checkRun.status; + if (checkRun.conclusion === "skipped" && + gateChecks.some(([, gateName]) => gateName === checkName)) return "unavailable"; return checkRun.conclusion ?? "pending"; }; @@ -345,7 +364,7 @@ jobs: }); if (current?.id !== run.id || current.run_attempt !== run.run_attempt || current.event !== "pull_request" || current.head_sha !== headSha || - current.display_title !== run.display_title) { + current.display_title !== run.display_title || associatedBaseRef(current) !== baseRef) { core.info("A selected producer attempt changed while static analysis was being summarized."); return; } @@ -369,7 +388,7 @@ jobs: const matches = current.state === "open" && current.head?.repo?.id === sourceRepositoryId && current.head?.ref === sourceBranch && current.head?.sha === headSha && current.base?.sha === baseSha && - current.base?.ref === currentPullRequest.base?.ref; + current.base?.ref === baseRef; if (!matches) core.info("The pull-request base or head changed while static analysis was being summarized."); return matches; }; diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index fad32b6154..7ce1bb0e90 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -31,7 +31,7 @@ For the TCP Proxy -> Gateway WebSocket mTLS hop, the TCP Proxy client identity a The trusted default-branch workflow treats the hosted preview Gateway configuration as an exact contract. The rendered `firemud-config` must match the canonical `previewStack.sharedConfig` values from the trusted Helm values file; only the two source-only MinIO credential entries are removed before the artifact is applied. Unknown, missing, or changed shared configuration is rejected. In particular, Gateway bridge and route URI variables, `SPRING_APPLICATION_JSON`, and `JAVA_TOOL_OPTIONS` are not accepted through the shared ConfigMap. -The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. For hosted preview Gateway artifacts, `previewStack.jvm.javaToolOptions` and `previewStack.jvm.mallocArenaMax` are fixed to the canonical chart defaults; Helm overrides of either value are not supported for this artifact. The trusted validator requires the exact values, even though the shared chart exposes these keys for its other uses. Change the chart defaults and trusted validator together if the hosted preview Gateway settings need to change. +The hosted artifact validator checks the Gateway Deployment's per-container `env` and `envFrom` against the managed listener, trust, and routing settings. For `previewStack.jvm.javaToolOptions` and `previewStack.jvm.mallocArenaMax`, it accepts both values from the [shared JVM profile](../../infrastructure/deployment-environments.md#pr-preview-environment) or both variables absent from the rendered Deployment. Omitting only one variable, supplying a different value, or adding a configuration reference fails validation. Update the trusted Helm defaults and the validator together when adding a legitimate setting. The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Game Session on TCP/8444 for the dedicated authenticated mTLS WebSocket receiver at `/ws/game/tcp`, Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index f073eb7324..652bc5845e 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -240,7 +240,7 @@ Hosted verification waits for the complete readiness tuple defined by the owning Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. -Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. A successful exact source completion during lookup defers one retry cycle while its trusted consumer may enter the queue. A confirmed GitHub dispatch rejection releases only the matching Namespace retry reservation, fenced by the returned resource version. An uncertain dispatch outcome leaves the reservation charged. +Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. A successful exact source completion during lookup defers one retry cycle while its trusted consumer may enter the queue. When GitHub caps the completed-source inventory, the reconciler checks disjoint creation ranges across the history. It still evaluates handoff freshness from completion evidence, including later attempts of older runs, and preserves the retry budget if any range cannot be verified. A confirmed GitHub dispatch rejection releases only the matching Namespace retry reservation, fenced by the returned resource version. An uncertain dispatch outcome leaves the reservation charged. The initial Telnet-first hosted milestone is complete. Continuing preview acceptance follows [ADR 0178](decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md): one shared semantic authenticated, admitted, `LOOK` assertion set is exercised through both the public Telnet path and the deployed first-party browser path. Telnet proves TCP Proxy and bridge/framing behavior. The bounded browser journey proves frontend delivery, HTTPS bootstrap and discovery, connect-token cookie and `/ws/game/**` admission, one reconnect, logout, and non-reuse. Direct backend WebSocket smoke remains CI or diagnostic evidence rather than a substitute or third required hosted path. Dedicated frontend delivery and the browser journey remain implementation gaps, so current TCP/Telnet preview proof is not yet transport-complete. diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh index 06e91a466d..94dc8ad4d6 100644 --- a/dev-tools/hosted/preview/reconcile-preview-deploys.sh +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -56,10 +56,10 @@ parse_namespace_tuple() { | if ( (.[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") or ( - (.[13] | test("^[0-3]$")) - and (.[14] | test("^[0-9a-fA-F]{40}$")) - and (.[15] | test("^[0-9a-fA-F]{40}$")) - and (.[16] | test("^[0-9a-fA-F]{40}$")) + (.[13] | test("^[1-3]$")) + and (.[14] | test("^[0-9a-f]{40}$")) + and (.[15] | test("^[0-9a-f]{40}$")) + and (.[16] | test("^[0-9a-f]{40}$")) and (.[17] | test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) ) ) then . else error("namespace proof-retry evidence is malformed") end @@ -214,6 +214,7 @@ prepare_preview_dispatch() { local namespace_resource_version local next_retry_count local reservation_namespace_json + local exact_retry_tuple=false proof_retry_reservation_count="" proof_retry_previous_count="" @@ -223,6 +224,7 @@ prepare_preview_dispatch() { proof_retry_previous_image_tag="" proof_retry_reservation_namespace_uid="" proof_retry_reservation_resource_version="" + proof_retry_reservation_deployed_tuple="" proof_retry_reservation_base_sha="" proof_retry_reservation_head_sha="" proof_retry_reservation_merge_sha="" @@ -266,6 +268,12 @@ prepare_preview_dispatch() { echo "Skipping PR #${pr_number}: namespace ${namespace} was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 return 1 fi + if [[ "${retry_base_sha}" == "${base_sha}" && + "${retry_head_sha}" == "${head_sha}" && + "${retry_merge_sha}" == "${merge_sha}" && + "${retry_image_tag}" == "${image_tag}" ]]; then + exact_retry_tuple=true + fi if [[ "${current_base_sha}" != "${base_sha}" || "${current_head_sha}" != "${head_sha}" || "${current_merge_sha}" != "${merge_sha}" || @@ -274,7 +282,11 @@ prepare_preview_dispatch() { echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 return 1 fi - return 0 + # A failed namespace recreation can retain the exact retry record before + # the new workload has written its deployed tuple. + if [[ "$exact_retry_tuple" == false ]]; then + return 0 + fi fi if [[ "${proof_base_sha}" == "${base_sha}" && "${proof_head_sha}" == "${head_sha}" && @@ -285,10 +297,7 @@ prepare_preview_dispatch() { echo "Skipping PR #${pr_number}: proof completed before retry dispatch." >&2 return 2 fi - if [[ "${retry_base_sha}" == "${base_sha}" && - "${retry_head_sha}" == "${head_sha}" && - "${retry_merge_sha}" == "${merge_sha}" && - "${retry_image_tag}" == "${image_tag}" ]]; then + if [[ "$exact_retry_tuple" == true ]]; then next_retry_count=$((10#${retry_count} + 1)) else next_retry_count=1 @@ -297,6 +306,10 @@ prepare_preview_dispatch() { echo "Skipping PR #${pr_number}: proof retry budget exhausted for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}." >&2 return 3 fi + if [[ -z "$namespace_uid" || -z "$namespace_resource_version" ]]; then + echo "Skipping PR #${pr_number}: Namespace retry custody is unavailable." >&2 + return 1 + fi if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ "firemud.dev/proof-retry-count=${next_retry_count}" \ "firemud.dev/proof-retry-base-sha=${base_sha}" \ @@ -315,6 +328,7 @@ prepare_preview_dispatch() { proof_retry_previous_merge_sha="${retry_merge_sha}" proof_retry_previous_image_tag="${retry_image_tag}" proof_retry_reservation_namespace_uid="${namespace_uid}" + proof_retry_reservation_deployed_tuple="${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" proof_retry_reservation_resource_version="$(jq -er --arg uid "${namespace_uid}" \ '.metadata | select(.uid == $uid) | .resourceVersion | select(type == "string" and length > 0)' \ <<<"${reservation_namespace_json}" 2>/dev/null || true)" @@ -361,11 +375,7 @@ compensate_rejected_proof_retry() { namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" if [[ "${namespace_uid}" != "${proof_retry_reservation_namespace_uid}" || -z "${proof_retry_reservation_resource_version}" || - "${namespace_resource_version}" != "${proof_retry_reservation_resource_version}" || - "${current_base_sha}" != "${proof_retry_reservation_base_sha}" || - "${current_head_sha}" != "${proof_retry_reservation_head_sha}" || - "${current_merge_sha}" != "${proof_retry_reservation_merge_sha}" || - "${current_image_tag}" != "${proof_retry_reservation_image_tag}" || + "${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" != "${proof_retry_reservation_deployed_tuple}" || "${retry_count}" != "${proof_retry_reservation_count}" || "${retry_base_sha}" != "${proof_retry_reservation_base_sha}" || "${retry_head_sha}" != "${proof_retry_reservation_head_sha}" || @@ -580,13 +590,8 @@ automatic_preview_has_tuple() { fi } -completed_preview_inventory() { - local event="$1" filter="$2" pages - # The handoff window measures completion (updated_at), not - # creation. An older run can finish or be rerun just before the scan. - pages="$(timeout 30s gh api --method GET --paginate --slurp \ - "repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" \ - -f "event=${event}" -f status=completed -f per_page=100 -f "$filter")" || return 1 +parse_completed_preview_pages() { + local event="$1" jq -ce --argjson workflow_id "$preview_workflow_id" --arg event "$event" ' select(type == "array" and length > 0 and length <= 10) | .[0].total_count as $count @@ -608,7 +613,71 @@ completed_preview_inventory() { and (.repository.full_name | type == "string") and (.head_repository.full_name | type == "string") and (if $event == "pull_request" then (.pull_requests | type == "array") else true end))) | {workflow_runs: $runs} - ' <<<"$pages" + ' +} + +completed_preview_inventory() { + local event="$1" filter="$2" pages count + local workflow_runs_path="repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs" + local deadline=$((SECONDS + 30)) + local -a filters=(-f "event=${event}" -f status=completed -f "$filter") + pages="$(timeout 30s gh api --method GET --paginate --slurp \ + "$workflow_runs_path" "${filters[@]}" -f per_page=100)" || return 1 + count="$(jq -er '.[0].total_count | select(type == "number" and . >= 0 and . <= 2147483647 and . == floor)' <<<"$pages")" || return 1 + if (( count < 1000 )); then + parse_completed_preview_pages "$event" <<<"$pages" + return + fi + + # GitHub caps each filtered listing at 1,000. Split the entire creation + # history into disjoint ranges rather than equating creation with completion: + # a run created long ago may have started a new attempt recently. + local range first last midpoint created after before remaining page + local scanned=0 initial_count="$count" + local -a ranges=("0:$(date -u +%s)") inventories=() + while (("${#ranges[@]}")); do + (( ++scanned <= 64 )) || return 1 + range="${ranges[-1]}" + unset 'ranges[-1]' + first="${range%:*}" + last="${range#*:}" + after="$(date -u -d "@$first" +%Y-%m-%dT%H:%M:%SZ)" || return 1 + before="$(date -u -d "@$last" +%Y-%m-%dT%H:%M:%SZ)" || return 1 + created="created=$after..$before" + remaining=$((deadline - SECONDS)) + (( remaining > 0 )) || return 1 + page="$(timeout "${remaining}s" gh api --method GET "$workflow_runs_path" "${filters[@]}" -f "$created" -f per_page=1)" || return 1 + count="$(jq -er '.total_count | select(type == "number" and . >= 0 and . <= 2147483647 and . == floor)' <<<"$page")" || return 1 + if (( count >= 1000 )); then + (( first < last )) || return 1 + midpoint=$(( (first + last) / 2 )) + ranges+=("$first:$midpoint" "$((midpoint + 1)):$last") + continue + fi + if (( count <= 1 )); then + pages="[$page]" + else + remaining=$((deadline - SECONDS)) + (( remaining > 0 )) || return 1 + pages="$(timeout "${remaining}s" gh api --method GET --paginate --slurp \ + "$workflow_runs_path" "${filters[@]}" -f "$created" -f per_page=100)" || return 1 + fi + page="$(parse_completed_preview_pages "$event" <<<"$pages")" || return 1 + # If the provider ignores the bounds or rows moved between reads, a + # potentially incomplete inventory must never become authorization. + jq -e --arg first "$after" --arg last "$before" --argjson count "$count" ' + (.workflow_runs | length) == $count and + all(.workflow_runs[]; .created_at | type == "string" and + test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") and + . >= $first and . <= $last) + ' <<<"$page" >/dev/null || return 1 + inventories+=("$page") + done + printf '%s\n' "${inventories[@]}" | jq -ces --argjson initial "$initial_count" ' + [.[].workflow_runs[]] as $runs + | select(($runs | length) >= $initial and ($runs | length) == ([$runs[].id] | unique | length)) + | {workflow_runs: $runs} + ' } recent_successful_source_handoff() { @@ -623,7 +692,7 @@ recent_successful_source_handoff() { if ! source_runs="$(completed_preview_inventory pull_request "head_sha=${head_sha}")" || ! dispatch_source_runs="$(completed_preview_inventory repository_dispatch "branch=${DEFAULT_BRANCH}")"; then echo "Recent completed preview-source inventory is unavailable, malformed, or truncated; retry budget unchanged." >&2 - return 2 + return 4 fi source_inventory_now="$(date -u +%s)" if ! source_candidates="$(printf '%s\n' "$source_runs" "$dispatch_source_runs" | jq -r -s \ @@ -797,7 +866,8 @@ trusted_consumer_has_tuple() { and ([$jobs[] | select(.name == "Validate Trusted Preview Target")] | length == 1) and any($jobs[]; .name == "Validate Trusted Preview Target" and .run_id == $id and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed") + and .head_sha == $head and .status == "completed" + and (if .conclusion == "success" then (.steps | type == "array" and length > 0) else true end)) ' <<<"$jobs" >/dev/null || return 2 jq -e --arg tuple "$tuple" ' any(.jobs[] | select(.name == "Validate Trusted Preview Target" and .conclusion == "success"); @@ -1133,6 +1203,11 @@ dispatch_candidates() { echo "Skipping proof retry for PR #${pr_number}: recent preview handoff lookup unavailable; retry budget unchanged." >&2 continue ;; + 4) + echo "Skipping proof retry for PR #${pr_number}: completed preview-source inventory read failed." >&2 + dispatch_outcome_failed=true + continue + ;; 1) ;; *) @@ -1158,6 +1233,7 @@ dispatch_candidates() { local proof_retry_previous_image_tag="" local proof_retry_reservation_namespace_uid="" local proof_retry_reservation_resource_version="" + local proof_retry_reservation_deployed_tuple="" local proof_retry_reservation_base_sha="" local proof_retry_reservation_head_sha="" local proof_retry_reservation_merge_sha="" @@ -1330,6 +1406,6 @@ if [[ -n "$candidate_rows" ]]; then dispatch_candidates <<<"$candidate_rows" fi if [[ "$dispatch_outcome_failed" == true ]]; then - echo "One or more preview dispatch outcomes or capacity checks failed; review this job before another repair cycle." >&2 + echo "One or more preview inventory, capacity, or dispatch checks failed." >&2 exit 1 fi diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 990aa9fdc3..4e979991c0 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -293,9 +293,13 @@ if wait_mode == "pull-request": matching_runs.append(run) else: matching_runs = [] -all_candidates = len(sys.argv) > 10 and sys.argv[10] == "all" -if len(sys.argv) > 8: - event, title = sys.argv[8:10] +selectors = sys.argv[8:] +all_candidates = selectors[-1:] == ["all"] +if all_candidates: + selectors.pop() +polling = selectors == ["poll"] +if selectors and not polling: + event, title = selectors matching_runs = [run for run in matching_runs if run.get("event") == event and run.get("display_title") == title and run.get("status") == "completed" and run.get("conclusion") == "success"] @@ -303,7 +307,16 @@ if not matching_runs: print("missing") raise SystemExit(0) -ranked = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True) +def poll_priority(run): + # A completed success still needs exact publication proof. Active runs + # keep the wait open even if a newer sibling publisher has failed. + if run.get("status") != "completed": + return 1 + return 2 if run.get("conclusion") == "success" else 0 + +ranked = sorted(matching_runs, + key=lambda run: (poll_priority(run) if polling else 0, run.get("created_at", "")), + reverse=True) for run in ranked if all_candidates else ranked[:1]: print( "found\t{}\t{}\t{}\t{}".format( @@ -330,6 +343,7 @@ use_completed_duplicate_publication() { local state older_id older_created source_event inventory upper publisher_lines publisher_id publisher_status publisher_conclusion local source_state="$1" lookup_deadline="$2" remaining local proof_origin="${3:-alternate}" + local observed_inventory="${4:-}" local source source_attempt source_title source_latest publisher_event expected_title local run attempt jobs latest publisher_path default_branch repository_info local -a publisher_events=() @@ -364,9 +378,13 @@ use_completed_duplicate_publication() { else expected_title="Publish PR Runtime Images source-run-${older_id}" fi - remaining=$((lookup_deadline - SECONDS)) - (( remaining > 0 )) || break - inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || continue + if [[ -n "$observed_inventory" ]]; then + inventory="$observed_inventory" + else + remaining=$((lookup_deadline - SECONDS)) + (( remaining > 0 )) || break + inventory="$(fetch_publisher_runs "$publisher_event" "$older_created" "$upper" "$remaining")" || continue + fi publisher_lines="$(read_publisher_state "$older_id" "$source_event" "$publisher_event" "$expected_title" all <<<"$inventory")" || continue [[ "$publisher_lines" != "missing" ]] || continue while IFS=$'\t' read -r state publisher_id publisher_status publisher_conclusion _; do @@ -375,9 +393,10 @@ use_completed_duplicate_publication() { (( SECONDS < lookup_deadline )) || break run="$(fetch_alternate_run_metadata "$lookup_deadline" "repos/${GITHUB_REPOSITORY}/actions/runs/${publisher_id}")" || continue publisher_path="$(jq -er '.path | select(type == "string")' <<<"$run")" || continue - # Either event runs on the default branch; a short path suffix must agree. + # Either event runs on the default branch; a qualified path must agree. [[ "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml" || - "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" ]] || continue + "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@${default_branch}" || + "$publisher_path" == ".github/workflows/publish-pr-runtime-images.yml@refs/heads/${default_branch}" ]] || continue attempt="$(jq -er --argjson id "$publisher_id" --arg repo "$GITHUB_REPOSITORY" --arg path "$publisher_path" --arg branch "$default_branch" \ --arg title "$expected_title" --arg event "$publisher_event" ' select(.id == $id and .event == $event and .display_title == $title @@ -502,23 +521,20 @@ wait_for_pr_publisher() { "${publisher_inventory_remaining}" )"; then fetch_failed=true - break + continue fi publisher_payload+="${publisher_payload:+,}${event_payload}" done local state run_id run_status run_conclusion run_url publisher_payload="[${publisher_payload}]" publisher_state="" - if [[ "${fetch_failed}" == "false" ]] && - publisher_state="$(read_publisher_state "${source_run_id}" "${source_state_event}" <<<"${publisher_payload}")"; then + if publisher_state="$(read_publisher_state "${source_run_id}" "${source_state_event}" poll <<<"${publisher_payload}")"; then IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" - if [[ "${run_status}" == "completed" ]]; then - if use_completed_duplicate_publication "$source_state" "$publisher_deadline" direct; then + if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then + if use_completed_duplicate_publication "$source_state" "$publisher_deadline" direct "$publisher_payload"; then return 0 fi - if [[ "${run_conclusion}" == "success" ]]; then - direct_success_unproven=true - fi + direct_success_unproven=true fi fi local refreshed_source_payload refreshed_alternates diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index f75cdafa45..95cf1272e2 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -2,6 +2,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 -c 'import sys; sys.exit(0 if __debug__ else "Run the required-gate contract without Python optimization")' # Required gates on metadata-only PR edits: a title/body edit (edited with no # base change) skips each required gate under a non-required name, so the @@ -146,15 +147,15 @@ for forbidden in ("{name}", "{0.attr}", "{0[0]}", "{0:04}", "{0!r}", "{{0}}", "{ raise AssertionError(f"Accepted unsupported concurrency format: {forbidden}") -def effective_group(group, action, base_ref, workflow_name="Required Gate", *, push_branch=None): +def effective_group(group, action, base_ref, workflow_name="Required Gate", *, pr_number=42, push_branch=None): values = { "github.event.changes.base.ref": repr(base_ref), - "github.event.pull_request.number": "42", + "github.event.pull_request.number": str(pr_number), "github.event.action": repr(action), "github.event_name": repr("push" if push_branch else "pull_request"), "github.workflow": repr(workflow_name), "github.run_id": "123", - "github.ref": repr(f"refs/heads/{push_branch}" if push_branch else "refs/pull/42/merge"), + "github.ref": repr(f"refs/heads/{push_branch}" if push_branch else f"refs/pull/{pr_number}/merge"), } def render(match): @@ -388,17 +389,21 @@ for workflow, (workflow_name, gate_job, gate_name, change_job, result_step, pr_o raise SystemExit(f"{workflow} must cancel obsolete runs within each namespace") rendered_substantive_groups = [] +workflow_data = {} for workflow, (workflow_name, *_rest) in gates.items(): data = yaml.load((root / ".github/workflows" / workflow).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + workflow_data[workflow] = data group = data["concurrency"]["group"] if data.get("name") != workflow_name: raise SystemExit(f"{workflow} actual name must match its required-gate contract") + pr_group_owners = {} for action, base_ref in (("opened", None), ("synchronize", None), ("reopened", None), ("edited", "develop")): - rendered_substantive_groups.append(( - workflow, - action, - effective_group(group, action, base_ref, workflow_name), - )) + for pr_number in (42, 43, 44): + rendered = effective_group(group, action, base_ref, workflow_name, pr_number=pr_number) + prior_pr = pr_group_owners.setdefault(rendered.casefold(), pr_number) + if prior_pr != pr_number: + raise SystemExit(f"{workflow} PRs {prior_pr} and {pr_number} share concurrency group {rendered!r}") + rendered_substantive_groups.append((workflow, action, rendered)) collisions = cross_workflow_group_collisions(rendered_substantive_groups) if collisions: @@ -409,15 +414,21 @@ if collisions: ) for branch in ("main", "develop"): push_groups = [] - for workflow in ("ci.yml", "security.yml"): - data = yaml.load((root / ".github/workflows" / workflow).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + for workflow, data in workflow_data.items(): + if "push" not in data["on"]: + continue + branches = (data["on"]["push"] or {}).get("branches") + if branches is not None and branch not in branches: + continue push_groups.append(( workflow, "push", effective_group(data["concurrency"]["group"], None, None, data["name"], push_branch=branch), )) - if cross_workflow_group_collisions(push_groups): - raise SystemExit(f"Security and Validation share a push concurrency group on {branch}") + collisions = cross_workflow_group_collisions(push_groups) + if collisions: + first, second = collisions[0] + raise SystemExit(f"{first[0]} and {second[0]} share a push concurrency group on {branch}: {first[2]!r}") assert cross_workflow_group_collisions([ ("validation.yml", "opened", "required-pr-42"), ("smoke.yml", "edited", "REQUIRED-PR-42"), @@ -775,14 +786,19 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const cancelledWithReplacement = kind === "optional-final-read-cancelled-with-replacement"; const finalAttemptError = kind.startsWith("optional-final-read-attempt-"); const duplicatePrimary = kind === "optional-final-read-duplicate"; + const newerFailure = kind === "duplicate-after-newer-failure"; const disappearingSnapshot = kind === "optional-final-read-incomplete-snapshot"; const badStatus = kind.endsWith("-forbidden") ? 403 : kind.endsWith("-missing") ? 404 : 503; const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && badStatus === 503; - const primaryReady = () => primaryCanRecover && primaryInventoryReads > 1; + const primaryReady = () => (primaryCanRecover || newerFailure) && primaryInventoryReads > 1; let alternativeJobsReads = 0, primaryInventoryReads = 0, lookupFailure; let pullRequestLookups = 0, acceptanceLookupArmed = false, acceptanceLookupAttempts = 0; const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); - const tupleAdvanced = () => kind === "trusted-current-base-advances" && currentRunReads >= 2; + const baseAdvanceRead = { + "trusted-current-base-advances": 2, + "trusted-current-base-advances-during-acceptance-attempt": 3, + }[kind] ?? Infinity; + const tupleAdvanced = () => currentRunReads >= baseAdvanceRead; let rerunStartedDuringLatestIdentityRead = false; const failures = [], refs = [], info = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: liveFallback ? null : merge, payload: { @@ -956,10 +972,15 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal yield {data: primaryInventoryReads === 1 ? [pending, completed] : [pending]}; return; } - if (h0 && input.event === "pull_request") { + if ((h0 || newerFailure) && input.event === "pull_request") { primaryInventoryReads += 1; const primary = {...exactPrimary, status: cancelledPrimary || cancelledWithReplacement || primaryReady() ? "completed" : "queued", conclusion: cancelledPrimary || cancelledWithReplacement ? "cancelled" : primaryReady() ? "success" : null}; + if (newerFailure) { + const failed = {...source, id: 44, created_at: "2026-09-01T00:00:00.500Z", conclusion: "failure"}; + yield {data: [primary, failed, source]}; + return; + } yield {data: duplicatePrimary ? [primary, source] : [primary]}; return; } @@ -1070,6 +1091,16 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal for (const kind of ["duplicate-missing-step", "duplicate-nonterminal-step"]) { assert.deepEqual((await scenario(kind)).failures, [], `${kind} preserves canonical fallback`); } + const precedingGreen = await scenario("duplicate-preceding-green"); + assert(precedingGreen.info.some(line => line.includes("verified completed exact runtime producer precedes the pending duplicate")), + "a verified green as the latest completed attempt may satisfy a pending duplicate"); + assert.deepEqual(precedingGreen.failures, []); + const newerFailure = await scenario("duplicate-after-newer-failure"); + assert(newerFailure.info.some(line => line.includes("Found runtime-images run 43 with status=queued")), + "the older green must not bypass the newer completed failure"); + assert(newerFailure.info.some(line => line.includes("Found runtime-images run 43 with status=completed")), + "the pending exact producer must finish before the gate accepts proof"); + assert.deepEqual(newerFailure.failures, []); for (const kind of ["duplicate-terminal-skipped", "duplicate-terminal-failure", "rerun-after-proof"]) { assert.equal((await scenario(kind)).failures.length, 1, `${kind} cannot supply successful proof`); } @@ -1095,6 +1126,11 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(advancedFallback.info.some(line => line.includes("identity changed after the final runtime attempt lookup")), "late base movement cannot accept the old trusted refresh"); assert.match(advancedFallback.failures[0], /Timed out waiting for the exact runtime-images/); + const advancedDuringAcceptanceAttempt = await scenario( + "trusted-current-base-advances-during-acceptance-attempt", "repository_dispatch" + ); + assert.match(advancedDuringAcceptanceAttempt.failures[0], /Timed out waiting for the exact runtime-images/, + "a base move during the last attempt lookup cannot accept the old trusted refresh"); const stale = await scenario("stale-final"); assert.deepEqual(stale.failures, [], "obsolete gate exits without publishing proof for changed base ref"); console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 43708644e8..d2e002ca94 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -3,6 +3,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 -c 'import sys; sys.exit(0 if __debug__ else "Run the retarget contract without Python optimization")' assert_job_condition() { local workflow="$1" @@ -647,7 +648,7 @@ assert set(smoke["on"]["pull_request"]) == {"types"} assert set(runtime["on"]["pull_request"]) == {"types", "paths"} assert "branches" not in runtime["on"]["workflow_run"] -# Exercise the actual shell from these two named steps with ordinary outcomes. +# Exercise the classifier and failure shell steps and bind their output to the tracker. import os import subprocess import tempfile @@ -655,6 +656,10 @@ import tempfile steps = smoke["jobs"]["smoke-gate"]["steps"] classifier = next(step for step in steps if step.get("id") == "smoke_gate_context") failure = next(step for step in steps if step.get("name") == "Fail when smoke dependencies did not succeed") +tracker = next(step for step in steps if step.get("id") == "track-runtime-smoke") +expected_tracker_condition = "${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }}" +if tracker["if"] != expected_tracker_condition: + raise SystemExit("full-stack smoke tracker must run exactly when execution and full smoke are required") assert failure["if"] == "${{ steps.smoke_gate_context.outputs.execute != 'true' }}" assert failure.get("continue-on-error") in (None, "false"), "dependency failure must fail the Smoke Gate job" with tempfile.TemporaryDirectory() as directory: @@ -2580,6 +2585,39 @@ old_native_typed_publisher = {**native_typed_direct_publisher, {**direct_typed_publisher, "id": 205, "conclusion": "failure", "created_at": "2026-07-24T00:08:00Z"}, ]}, }})) +for name, events in { + "typed-active-before-failed-callback": { + "workflow_run": {"total_count": 1, "workflow_runs": [ + {**native_typed_direct_publisher, "id": 205, "conclusion": "failure", + "created_at": "2026-07-24T00:08:00Z"}, + ]}, + "repository_dispatch": {"total_count": 1, "workflow_runs": [ + {**direct_typed_publisher, "status": "in_progress", "conclusion": None}, + ]}, + }, + "typed-queued-after-native": { + "workflow_run": {"total_count": 1, "workflow_runs": [native_typed_direct_publisher]}, + "repository_dispatch": {"total_count": 1, "workflow_runs": [ + {**direct_typed_publisher, "id": 205, "status": "queued", "conclusion": None, + "created_at": "2026-07-24T00:08:00Z"}, + ]}, + }, + "typed-native-with-unavailable-dispatch": { + "workflow_run": {"total_count": 1, "workflow_runs": [native_typed_direct_publisher]}, + "repository_dispatch": {"total_count": 1, "workflow_runs": []}, + }, + "typed-failed-with-unavailable-dispatch": { + "workflow_run": {"total_count": 1, "workflow_runs": [ + {**native_typed_direct_publisher, "conclusion": "failure"}, + ]}, + "repository_dispatch": {"total_count": 1, "workflow_runs": []}, + }, + "typed-explicit-with-unavailable-callback": { + "workflow_run": {"total_count": 1, "workflow_runs": []}, + "repository_dispatch": {"total_count": 1, "workflow_runs": [direct_typed_publisher]}, + }, +}.items(): + (root / f"{name}.json").write_text(json.dumps({"fixture_events": events})) for event, publisher_run, fixture_event in [ ("native", direct_publisher, "workflow_run"), ("typed", direct_typed_publisher, "repository_dispatch"), @@ -2822,9 +2860,14 @@ for direct_variant in native typed typed-native; do fi done -for publisher_fixture in direct-publisher-only-typed-native typed-failed-after-native; do +for publisher_fixture in direct-publisher-only-typed-native typed-failed-after-native \ + typed-queued-after-native typed-native-with-unavailable-dispatch typed-explicit-with-unavailable-callback; do + publisher_variant=typed-native + if [[ "$publisher_fixture" == typed-explicit-with-unavailable-callback ]]; then + publisher_variant=typed + fi BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ - CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native \ + CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER="$publisher_variant" \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" CONTRACT_DUPLICATE_DIRECT_JOB=success \ CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$publisher_fixture.json" \ @@ -2841,6 +2884,36 @@ for publisher_fixture in direct-publisher-only-typed-native typed-failed-after-n require_contains "$contract_fixture_dir/typed-native-direct.output" 'as the direct source' done +for publisher_fixture in typed-active-before-failed-callback typed-failed-with-unavailable-dispatch; do + wait_status=0 + BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ + CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ + CONTRACT_SOURCE_PAYLOAD="$contract_fixture_dir/direct-typed-success-sources.json" \ + CONTRACT_PUBLISHER_PAYLOAD="$contract_fixture_dir/$publisher_fixture.json" \ + PATH="$contract_fixture_dir:$PATH" GH_TOKEN=contract-token GITHUB_REPOSITORY=example/FireMUD \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=3 HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS=3 \ + HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ + >"$contract_fixture_dir/$publisher_fixture.output" \ + 2>"$contract_fixture_dir/$publisher_fixture.error" || wait_status=$? + if [[ "$wait_status" != 1 ]] || grep -Eq 'completed with failure|No trusted PR image publisher appeared' \ + "$contract_fixture_dir/$publisher_fixture.error"; then + cat "$contract_fixture_dir/$publisher_fixture.output" "$contract_fixture_dir/$publisher_fixture.error" >&2 + exit 1 + fi + if [[ "$publisher_fixture" == typed-active-before-failed-callback ]]; then + require_contains "$contract_fixture_dir/$publisher_fixture.output" 'Waiting for trusted PR image publisher 201' + if ! grep -Eq 'Timed out waiting for trusted PR image publisher|Publisher coverage unavailable at the wait deadline' \ + "$contract_fixture_dir/$publisher_fixture.error"; then + cat "$contract_fixture_dir/$publisher_fixture.error" >&2 + exit 1 + fi + else + require_contains "$contract_fixture_dir/$publisher_fixture.error" 'Publisher coverage unavailable at the wait deadline' + fi +done + if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ CONTRACT_DUPLICATE_DIRECT_EVENT=typed CONTRACT_DUPLICATE_DIRECT_PUBLISHER=typed-native-old \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ @@ -2953,10 +3026,10 @@ for variant in qualified wrong-ref wrong-head full-ref wrong-workflow fork; do timeout 20s bash "$image_wait_path" "cccccccccccccccccccccccccccccccccccccccc" \ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \ >"$contract_fixture_dir/publisher-$variant.output" 2>"$contract_fixture_dir/publisher-$variant.error"; then - [[ "$variant" == "qualified" ]] || { echo "Untrusted publisher path bypassed: $variant" >&2; exit 1; } + [[ "$variant" == "qualified" || "$variant" == "full-ref" ]] || { echo "Untrusted publisher path bypassed: $variant" >&2; exit 1; } require_contains "$contract_fixture_dir/publisher-$variant.output" 'Trusted PR image publisher 202 succeeded' else - [[ "$variant" != "qualified" ]] || { cat "$contract_fixture_dir/publisher-$variant.error" >&2; exit 1; } + [[ "$variant" != "qualified" && "$variant" != "full-ref" ]] || { cat "$contract_fixture_dir/publisher-$variant.error" >&2; exit 1; } require_contains "$contract_fixture_dir/publisher-$variant.error" 'Timed out waiting for runtime-images workflow' fi [[ -f "$lookup_marker" ]] || { echo "Publisher lookup was not reached: $variant" >&2; exit 1; } diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 30e1b6ad89..c9359286cc 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -162,7 +162,7 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && *) printf '%s' "${1:-}" ;; esac } - snapshot_head="$(canonical_head "${FAKE_PR_901_SNAPSHOT_HEAD:-${FAKE_PR_901_HEAD:-}}")" + snapshot_head="$(canonical_head "${FAKE_PR_901_SNAPSHOT_HEAD-${FAKE_PR_901_HEAD:-}}")" snapshot_requested_head="$(canonical_head "${FAKE_PR_901_REQUESTED_HEAD:-}")" if [[ "$count" -gt 1 ]]; then if [[ -v FAKE_PR_901_RECHECK_HEAD ]]; then @@ -208,6 +208,12 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" snapshot_resource_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" + if [[ "${FAKE_UNRELATED_NAMESPACE_UPDATE:-false}" == true && "$snapshot_resource_version" == rv-902 ]]; then + jq -c '.resourceVersion = "rv-903"' "$FAKE_PROOF_RETRY_STATE_MARKER" \ + > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" + mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" + snapshot_resource_version=rv-903 + fi proof_complete="${FAKE_PR_901_PROOF_COMPLETE:-true}" if [[ "${FAKE_PR_901_PROOF_COMPLETE_AFTER_CONSUMER_COMPLETION:-false}" == true && -f "${FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER:-}" ]]; then @@ -357,7 +363,7 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" exit 1 fi - if [[ "${3:-}" == pr-901 && ( "$*" == *"firemud.dev/proof-retry-count="* || "$*" == *"--resource-version rv-902"* ) ]]; then + if [[ "${3:-}" == pr-901 && ( "$*" == *"firemud.dev/proof-retry-count="* || "$*" == *"firemud.dev/proof-retry-count-"* ) ]]; then if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then jq -cn \ --arg count "${FAKE_PR_901_PROOF_RETRY_COUNT:-}" \ @@ -369,10 +375,14 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then > "$FAKE_PROOF_RETRY_STATE_MARKER" fi state_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" - expected_version=rv-901 - if [[ "$*" == *"--resource-version rv-902"* ]]; then - expected_version=rv-902 - fi + expected_version="" + annotate_args=("$@") + for ((i = 0; i + 1 < ${#annotate_args[@]}; i++)); do + if [[ "${annotate_args[i]}" == --resource-version ]]; then + expected_version="${annotate_args[i + 1]}" + break + fi + done if [[ "$state_version" != "$expected_version" ]]; then exit 1 fi @@ -399,6 +409,9 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then if [[ "$expected_version" == rv-902 ]]; then state_resource_version=rv-903 : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" + elif [[ "$expected_version" == rv-903 && "${FAKE_UNRELATED_NAMESPACE_UPDATE:-false}" == true ]]; then + state_resource_version=rv-904 + : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" fi jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ --arg merge "$local_merge" --arg image "$local_image" --arg rv "$state_resource_version" \ @@ -557,6 +570,30 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/hos exit 0 fi if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/173511323/runs' ]]; then + if [[ "$*" == *"event=repository_dispatch"* && -n "${FAKE_COMPLETED_RUN_DATA:-}" ]]; then + if [[ "$*" != *"--method GET"* || "$*" != *"status=completed"* || "$*" != *"branch=develop"* ]]; then + echo "completed partition omitted its original query filters: $*" >&2 + exit 1 + fi + range="" + for arg in "$@"; do + [[ "$arg" != created=* ]] || range="${arg#created=}" + done + if [[ -z "$range" ]]; then + printf '%s\n' '[{"total_count":1001,"workflow_runs":[]}]' + exit 0 + fi + jq -c --arg after "${range%..*}" --arg before "${range#*..}" \ + --argjson probe "$( [[ "$*" == *"per_page=1 "* || "$*" == *"per_page=1" ]] && echo true || echo false )" \ + --arg broken "${FAKE_BROKEN_COMPLETED_PARTITION:-false}" ' + map(select(.created_at >= $after and .created_at <= $before)) as $rows + | ($rows|length) as $count + | if $probe then {total_count:$count,workflow_runs:$rows[0:1]} + elif $broken == "true" and $count > 0 then [{total_count:$count,workflow_runs:[]}] + else [range(0; $count; 100) as $i | {total_count:$count,workflow_runs:$rows[$i:$i+100]}] end + ' "$FAKE_COMPLETED_RUN_DATA" + exit 0 + fi if [[ "$*" != *"--method GET"* || "$*" != *"status=completed"* || "$*" != *"per_page=100"* || "$*" != *"--paginate --slurp"* || "$*" == *"created="* || "$*" == *"head="* ]]; then @@ -3006,6 +3043,43 @@ grep -Fqx \ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +# Capped all-history listings split by creation across the full history. The +# matching old-created attempt still counts when it finished this cycle. +completed_history="$TEMP_DIR/completed-history.json" +jq -c ' + .workflow_runs[0] as $current + | [range(1000) as $i | $current | .id=(10000+$i) | + .created_at=(if $i < 500 then "2008-01-01T00:00:00Z" else "2025-01-01T00:00:00Z" end) | + .updated_at="2025-01-01T00:01:00Z"] + + [$current | .created_at="2008-01-02T00:00:00Z"] +' <<<"$FAKE_RECENT_PREVIEW_DISPATCH_RUNS_JSON" > "$completed_history" +for partition in complete broken; do + rm -f -- "$FAKE_ANNOTATE_LOG" "$FAKE_DISPATCH_LOG" + partition_output="$TEMP_DIR/reconciler-completed-partition-$partition.out" + partition_status=0 + ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON='[{"workflow_runs":[]}]' \ + FAKE_COMPLETED_RUN_DATA="$completed_history" \ + FAKE_BROKEN_COMPLETED_PARTITION="$([[ "$partition" == broken ]] && echo true || echo false)" \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$partition_output" 2>&1 || partition_status=$? + if [[ "$partition" == complete ]]; then + [[ "$partition_status" == 0 ]] + grep -Fq 'exact successful preview source run 5255 is within the 600-second trusted-consumer handoff window' "$partition_output" + else + [[ "$partition_status" != 0 ]] + grep -Fq 'completed preview-source inventory read failed' "$partition_output" + fi + test ! -e "$FAKE_ANNOTATE_LOG" + test ! -e "$FAKE_DISPATCH_LOG" +done + reset_case recent_source_updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" make_recent_dispatch_source_evidence "$recent_source_updated_at" skip @@ -3046,6 +3120,25 @@ grep -Fq \ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +reset_case +reconciler_inventory_failed_output="$TEMP_DIR/reconciler-inventory-failed.out" +if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_RECENT_PREVIEW_SOURCE_RUNS_JSON='{"total_count":1,"workflow_runs":[]}' \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_inventory_failed_output" 2>&1; then + echo "incomplete handoff inventory made the reconcile job successful" >&2 + exit 1 +fi +grep -Fq 'completed preview-source inventory read failed.' "$reconciler_inventory_failed_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + reset_case make_recent_dispatch_source_evidence "$(date -u +%Y-%m-%dT%H:%M:%SZ)" unproven dispatch_title="Preview dispatch pr-901-base-${preview_base_sha}-head-${preview_head_sha}-merge-${preview_merge_sha}" @@ -3130,7 +3223,7 @@ reconciler_expired_source_output="$TEMP_DIR/reconciler-expired-source.out" grep -Fq 'Dispatching preview render for PR #901' "$reconciler_expired_source_output" test -s "$FAKE_DISPATCH_LOG" -for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable consumer-job-attempt-missing consumer-job-attempt-mismatch consumer-job-attempt-null; do +for observation_case in duplicate-rows lookup-overflow workflow-run-only consumer-title-only consumer-stale-attempt consumer-finished consumer-finished-without-proof consumer-active-jobs-unavailable consumer-job-attempt-missing consumer-job-attempt-mismatch consumer-job-attempt-null consumer-steps-missing; do reset_case reconciler_active_status_advance_output="$TEMP_DIR/reconciler-active-status-advance-${observation_case}.out" consumer_run="$(jq -cn '{id:5256,run_attempt:1,event:"workflow_run",workflow_id:357129350, @@ -3162,7 +3255,10 @@ fi run_attempt:(if $observation == "consumer-job-attempt-mismatch" then 2 elif $observation == "consumer-job-attempt-null" then null else 1 end), head_sha:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",status:"completed",conclusion:"success", steps:[{name:(if $observation == "consumer-title-only" then "Verify workflow source and immutable PR metadata" else $tuple end), - status:"completed",conclusion:"success"}]}]} | if $observation == "consumer-job-attempt-missing" then .jobs[0] |= del(.run_attempt) else . end')" \ + status:"completed",conclusion:"success"}]}]} + | if $observation == "consumer-job-attempt-missing" then .jobs[0] |= del(.run_attempt) + elif $observation == "consumer-steps-missing" then .jobs[0] |= del(.steps) + else . end')" \ FAKE_TRUSTED_CONSUMER_LATEST_JSON="$(jq -c --arg observation "$observation_case" \ 'if $observation == "consumer-stale-attempt" then .run_attempt = 2 elif $observation | startswith("consumer-finished") then .status = "completed" @@ -3187,7 +3283,7 @@ if [[ "$observation_case" == duplicate-rows || "$observation_case" == workflow-r "$reconciler_active_status_advance_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" -elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == lookup-overflow || "$observation_case" == consumer-active-jobs-unavailable || "$observation_case" == consumer-job-attempt-mismatch || "$observation_case" == consumer-job-attempt-null ]]; then +elif [[ "$observation_case" == consumer-stale-attempt || "$observation_case" == lookup-overflow || "$observation_case" == consumer-active-jobs-unavailable || "$observation_case" == consumer-job-attempt-mismatch || "$observation_case" == consumer-job-attempt-null || "$observation_case" == consumer-steps-missing ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_active_status_advance_output" @@ -3307,8 +3403,27 @@ grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 -reset_case -reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry.out" +for compensation_case in existing-tuple version-moved different-tuple; do +reset_case +reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry-${compensation_case}.out" +namespace_update=false +expected_resource_version=rv-902 +result_resource_version=rv-903 +previous_base="$preview_base_sha" +previous_head="$preview_head_sha" +previous_merge="$preview_merge_sha" +previous_image="$preview_image_tag" +expected_reservation_count=3 +if [[ "$compensation_case" == version-moved ]]; then + namespace_update=true + expected_resource_version=rv-903 + result_resource_version=rv-904 +elif [[ "$compensation_case" == different-tuple ]]; then + previous_head=dddddddddddddddddddddddddddddddddddddddd + previous_merge=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + previous_image=pr-merge-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + expected_reservation_count=1 +fi if ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -3316,11 +3431,12 @@ if ( FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$previous_base" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$previous_head" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$previous_merge" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$previous_image" \ FAKE_DISPATCH_HTTP_STATUS=422 \ + FAKE_UNRELATED_NAMESPACE_UPDATE="$namespace_update" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_rejected_proof_retry_output" 2>&1; then @@ -3331,15 +3447,20 @@ grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 422).' \ "$reconciler_rejected_proof_retry_output" grep -Fq 'Released proof-retry reservation for PR #901 after GitHub confirmed dispatch rejection.' \ "$reconciler_rejected_proof_retry_output" -grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" +grep -Fq -- "firemud.dev/proof-retry-count=${expected_reservation_count}" "$FAKE_ANNOTATE_LOG" grep -Fq -- 'firemud.dev/proof-retry-count=2' "$FAKE_ANNOTATE_LOG" -grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG" +grep -Fq -- "--resource-version ${expected_resource_version}" "$FAKE_ANNOTATE_LOG" test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" -jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ +jq -e --arg expected_count "$expected_reservation_count" --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == $expected_count and .base == $base and .head == $head and .merge == $merge and .image == $image' \ + "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null +jq -e --arg base "$previous_base" --arg head "$previous_head" --arg rv "$result_resource_version" \ + --arg merge "$previous_merge" --arg image "$previous_image" \ '.count == "2" and .base == $base and .head == $head and .merge == $merge - and .image == $image and .resourceVersion == "rv-903"' \ + and .image == $image and .resourceVersion == $rv' \ "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null +done reset_case reconciler_ambiguous_proof_retry_output="$TEMP_DIR/reconciler-ambiguous-proof-retry.out" @@ -3444,12 +3565,14 @@ fi test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 2 test ! -e "$FAKE_SLEEP_LOG" +for deployed_head in head-901 ""; do reset_case reconciler_exhausted_proof_retry_output="$TEMP_DIR/reconciler-exhausted-proof-retry.out" ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_SNAPSHOT_HEAD="$deployed_head" \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ FAKE_PR_901_PROOF_RETRY_COUNT=3 \ @@ -3463,6 +3586,7 @@ PREVIEW_MAX_ACTIVE=2 \ grep -Fq 'proof retry budget exhausted' "$reconciler_exhausted_proof_retry_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +done reset_case reconciler_changed_tuple_retry_output="$TEMP_DIR/reconciler-changed-tuple-retry.out" diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index f281d0ba68..c9083133ce 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -26,18 +26,22 @@ function admissionFixture() { const sent = []; const warnings = []; const runs = []; - const state = {base: B, mergeParents: [B, C], keepHidden: false, afterInventory: null, nextId: 301}; + const state = {base: B, mergeParents: [B, C], keepHidden: false, afterInventory: null, + labels: [{name: 'preview:priority'}], nextId: 301, lookups: [], pullObservations: [], + baseReads: 0, commitRefs: [], missingExactCommitReads: 0, waits: [], producerReads: []}; const github = {rest: { pulls: {get: async ({pull_number}) => { assert.equal(pull_number, 7); return {data: {number: 7, state: 'open', head: {sha: C, repo: {full_name: repository}}, - base: {ref: 'develop', repo: {full_name: repository}}, mergeable: true, - mergeable_state: 'clean', merge_commit_sha: A}}; + base: {ref: input.base_ref, repo: {full_name: repository}}, mergeable: true, + mergeable_state: 'clean', merge_commit_sha: A, labels: state.labels, user: {login: 'developer'}, + ...state.pullObservations.shift()}}; }}, git: { getRef: async ({ref}) => { - assert.equal(ref, 'heads/develop'); - return {data: {ref: 'refs/heads/develop', object: {sha: state.base}}}; + assert.equal(ref, `heads/${input.base_ref}`); + state.baseReads++; + return {data: {ref: `refs/heads/${input.base_ref}`, object: {sha: state.base}}}; }, }, actions: { @@ -45,17 +49,31 @@ function admissionFixture() { assert.equal(workflow_id, 'runtime-images.yml'); return {data: {id: 42, path: runtimePath}}; }, - listWorkflowRuns: async ({workflow_id, status, event, page}) => { + getWorkflowRun: async ({run_id}) => { + state.producerReads.push(run_id); + const run = runs.find(run => run.id === run_id); + return {data: state.refreshProducer ? state.refreshProducer(run) : run}; + }, + listWorkflowRuns: async ({workflow_id, status, event, page, created}) => { assert.equal(workflow_id, 42); assert.ok(page <= 3); + state.lookups.push({status, event, page, created}); state.afterInventory?.(); - const workflow_runs = runs.filter(run => (!status || run.status === status) && (!event || run.event === event)); - return {data: {workflow_runs, total_count: workflow_runs.length}}; + const matching = runs.filter(run => (!status || run.status === status) && run.event === event && + (!created || Date.parse(run.created_at) >= Date.parse(created.split('..')[0]))); + return {data: {workflow_runs: matching.slice((page - 1) * 100, page * 100), + total_count: matching.length}}; }, }, repos: { getCommit: async ({ref}) => { + state.commitRefs.push(ref); + if (state.alternateCommit?.sha === ref) return {data: state.alternateCommit}; assert.equal(ref, A); + if (state.missingExactCommitReads > 0) { + state.missingExactCommitReads--; + throw Object.assign(new Error('merge not yet visible'), {status: 404}); + } return {data: {sha: A, parents: state.mergeParents.map(sha => ({sha}))}}; }, createDispatchEvent: async payload => { @@ -66,7 +84,9 @@ function admissionFixture() { }}; const admission = {github, input, context: {repo: {owner: 'example', repo: 'FireMUD'}, payload: {repository: {full_name: repository, default_branch: 'develop'}}}, - core: {warning: value => warnings.push(value), info() {}}, sleep: async () => { + core: {warning: value => warnings.push(value), info() {}}, sleep: async milliseconds => { + state.waits.push(milliseconds); + state.afterWait?.(); if (!state.keepHidden && state.newRun && !runs.includes(state.newRun)) runs.push(state.newRun); }}; return {admission, makeRun, runs, sent, state, warnings}; @@ -93,13 +113,48 @@ test('a newer failed exact producer keeps the tuple eligible despite an older ac const f = admissionFixture(); f.runs.push(f.makeRun({id: 299, event: 'pull_request', head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: B}}], - created_at: new Date(Date.now() - 120000).toISOString()})); + created_at: new Date(Date.now() - 70 * 60 * 1000).toISOString()})); f.runs.push(f.makeRun({id: 300, status: 'completed', conclusion: 'failure', created_at: new Date(Date.now() - 60000).toISOString()})); assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); assert.equal(f.sent.length, 1); }); +test('a still-active exact producer is not excluded by age or pagination', async () => { + const f = admissionFixture(); + f.runs.push(...Array.from({length: 100}, (_, i) => f.makeRun({ + id: 400 + i, display_title: 'unrelated work', + }))); + f.runs.push(f.makeRun({created_at: '2024-01-01T00:00:00Z'})); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); + assert.deepEqual(f.sent, []); + assert.ok(f.state.lookups.some(call => call.status === 'queued' && call.page === 2 && !call.created)); +}); + +test('serialized admission reapplies preview policy after the inventory read only for preview requests', async () => { + for (const previewOnly of [false, true]) { + const f = admissionFixture(); + f.admission.input.base_ref = 'feature/stack'; + if (previewOnly) f.admission.input.preview_only = true; + f.state.afterInventory = () => { f.state.labels = []; }; + assert.equal(await admitRuntimeRefresh(f.admission), previewOnly ? 'obsolete' : 'dispatched-observed'); + assert.equal(f.sent.length, previewOnly ? 0 : 1); + } +}); + +test('preview marker stays within the admission request and the schema stays closed', async () => { + const f = admissionFixture(); + f.admission.input.preview_only = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(Object.hasOwn(f.sent[0].client_payload, 'preview_only'), false); + for (const invalid of [{preview_only: 'true'}, {preview_only: false}, {preview_only: true, extra: true}]) { + const bad = admissionFixture(); + Object.assign(bad.admission.input, invalid); + await assert.rejects(admitRuntimeRefresh(bad.admission), /Invalid runtime refresh input/); + assert.deepEqual(bad.sent, []); + } +}); + test('admission refuses a base that moves after the inventory read', async () => { const f = admissionFixture(); f.state.afterInventory = () => { f.state.base = D; }; @@ -114,6 +169,89 @@ test('admission refuses the exact merge SHA when its ordered parents disagree', assert.deepEqual(f.sent, []); }); +test('admission rereads PR and base through pending mergeability, a stale base parent and missing test merge', async () => { + const f = admissionFixture(); + f.state.pullObservations = [ + {mergeable: null, merge_commit_sha: null}, + {mergeable_state: 'unknown'}, + {merge_commit_sha: E}, + ]; + f.state.alternateCommit = {sha: E, parents: [{sha: D}, {sha: C}]}; + f.state.missingExactCommitReads = 1; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.deepEqual(f.state.commitRefs, [E, A, A, A]); + assert.equal(f.state.baseReads, 6); + assert.deepEqual(f.state.waits, [2000, 2000, 2000, 2000, 2000]); + assert.equal(f.sent[0].client_payload.merge_sha, A); +}); + +test('admission bounds waiting for merge computation and aborts immediately on definitive drift', async () => { + const pending = {mergeable: null, merge_commit_sha: null}; + for (const [scenario, configure, expectedWaits, expectedRefs] of [ + ['persistent calculation', f => { f.state.pullObservations = Array(6).fill(pending); }, 5, 6], + ['conflict', f => { f.state.pullObservations = [pending, {mergeable: false, mergeable_state: 'dirty'}]; }, 1, 1], + ['changed head', f => { f.state.pullObservations = [pending, + {head: {sha: D, repo: {full_name: 'example/FireMUD'}}}]; }, 1, 1], + ['moved base', f => { + f.state.pullObservations = [pending]; + f.state.afterWait = () => { f.state.base = D; }; + }, 1, 2], + ['different merge for exact parents', f => { + f.state.pullObservations = [{merge_commit_sha: E}]; + f.state.alternateCommit = {sha: E, parents: [{sha: B}, {sha: C}]}; + }, 0, 1], + ]) { + const f = admissionFixture(); + configure(f); + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete', scenario); + assert.deepEqual(f.sent, [], scenario); + assert.deepEqual(f.state.lookups, [], scenario); + assert.equal(f.state.waits.length, expectedWaits, scenario); + assert.equal(f.state.baseReads, expectedRefs, scenario); + } +}); + +test('admission suppresses only when the selected active producer still proves the exact attempt', async () => { + const f = admissionFixture(); + f.runs.push(f.makeRun()); + f.state.refreshProducer = run => ({...run, status: 'in_progress'}); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); + assert.deepEqual(f.state.producerReads, [300]); + assert.deepEqual(f.sent, []); +}); + +test('a stale or unavailable selected producer leaves an exact refresh eligible', async () => { + for (const refreshProducer of [ + () => { throw Object.assign(new Error('missing run'), {status: 404}); }, + () => null, + run => ({...run, id: run.id + 1}), + run => ({...run, run_attempt: run.run_attempt + 1}), + run => ({...run, event: 'pull_request'}), + run => ({...run, display_title: run.display_title.replace(A, E)}), + run => ({...run, status: 'completed', conclusion: 'success'}), + run => ({...run, status: 'completed', conclusion: 'failure'}), + ]) { + const f = admissionFixture(); + f.runs.push(f.makeRun()); + f.state.refreshProducer = refreshProducer; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.deepEqual(f.state.producerReads, [300]); + assert.equal(f.sent.length, 1); + } +}); + +test('admission rereads the pinned comparison after the producer lookup before fallback', async () => { + const f = admissionFixture(); + f.runs.push(f.makeRun()); + f.state.refreshProducer = run => { + f.state.base = D; + return {...run, status: 'completed', conclusion: 'failure'}; + }; + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); + assert.deepEqual(f.state.producerReads, [300]); + assert.deepEqual(f.sent, []); +}); + test('an active run from a different repository cannot suppress the repair', async () => { const f = admissionFixture(); f.runs.push(f.makeRun({head_repository: {full_name: 'example/Other'}})); @@ -143,6 +281,7 @@ test('both wake inputs are serialized by one exact tuple group on the default br assert.deepEqual(job.permissions, {actions: 'read', contents: 'write', 'pull-requests': 'read'}); assert.deepEqual(job.steps.find(step => step.uses.startsWith('actions/checkout@')).with, {ref: '${{ github.workflow_sha }}', 'persist-credentials': 'false'}); + assert.match(job.steps.at(-1).with.script, /input: context.payload.client_payload/); }); const tupleStep = (kind, base, merge) => ({ @@ -156,7 +295,7 @@ function fixture() { head_sha: C, pull_requests: [{number: 7, head: {sha: C}, base: {sha: D}}]}, pr: {number: 7, state: 'open', head: {sha: C, repo: {full_name: 'example/FireMUD'}}, base: {ref: 'develop', repo: {full_name: 'example/FireMUD'}}, - merge_commit_sha: A, labels: [], user: {login: 'developer'}}, + merge_commit_sha: A, mergeable: true, mergeable_state: 'clean', labels: [], user: {login: 'developer'}}, jobs: [{name: 'Preview Plan', run_id: 99, run_attempt: 2, head_sha: C, workflow_name: 'PR Preview Environment', status: 'completed', conclusion: 'success', steps: [tupleStep('event', D, E), tupleStep('resolved', D, E)]}], recordedMerge: {sha: E, parents: [{sha: D}, {sha: C}]}, @@ -176,19 +315,12 @@ async function execute(f, sent = []) { f.runReads = (f.runReads ?? 0) + 1; return {data: f.runReads === 1 ? f.run : f.latestRun ?? f.run}; }, - getWorkflow: async () => ({data: {id: 42, path: '.github/workflows/runtime-images.yml'}}), - listWorkflowRuns: async args => { - assert.equal(args.workflow_id, 42); - assert.equal(args.per_page, 100); - f.lookups = (f.lookups ?? 0) + 1; - return {data: {workflow_runs: f.fullInventory ?? - (f.producers ?? []).filter(run => run.status === args.status)}}; - }, + listWorkflowRuns: async () => assert.fail('only admission may inspect runtime producers'), }, pulls: {get: async ({pull_number}) => { assert.equal(pull_number, f.pr.number); f.pullReads = (f.pullReads ?? 0) + 1; - return {data: f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr}; + return {data: f.pullHistory?.[f.pullReads - 1] ?? (f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr)}; }}, git: {getRef: async ({ref}) => { assert.equal(ref, 'heads/' + f.pr.base.ref); @@ -198,20 +330,25 @@ async function execute(f, sent = []) { repos: { getCommit: async ({ref}) => { (f.mergeReads ??= []).push(ref); - return {data: [f.recordedMerge, f.merge, f.resolvedMerge][f.mergeReads.length - 1]}; + return {data: f.mergeReads.length === 1 ? f.recordedMerge : + f.pendingMerges?.[ref] ?? (ref === f.resolvedMerge?.sha ? f.resolvedMerge : f.merge)}; }, createDispatchEvent: async p => sent.push(p), }, }}; await new AsyncFunction('github', 'context', 'core', 'require', script)(github, {repo: {owner: 'example', repo: 'FireMUD'}, payload: {workflow_run: {id: 99, run_attempt: 2}, repository: {default_branch: 'develop'}}}, {info(message) {(f.messages ??= []).push(message);}}, name => { + if (name === 'node:timers/promises') { + return {setTimeout: async delay => { assert.equal(delay, 2000); f.pauses = (f.pauses ?? 0) + 1; }}; + } assert.equal(name, 'node:child_process'); return {execFileSync(command, args, options) { if (command === 'python3') { assert.deepEqual(args, ['./dev-tools/hosted/preview/preview-eligibility.py', '--revalidate-deploy', '--expected-repository', 'example/FireMUD', '--expected-head-sha', f.run.head_sha]); - assert.deepEqual(JSON.parse(options.input), f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr); + assert.deepEqual(JSON.parse(options.input), + f.pullHistory?.[f.pullReads - 1] ?? (f.pullReads === 1 ? f.pr : f.latestPr ?? f.pr)); return execFileSync(command, args, {...options, cwd: root}); } assert.equal(command, 'bash'); @@ -225,7 +362,7 @@ test('exact stale-base current tuple produces only the typed refresh', async () const f = fixture(); assert.deepEqual(await execute(f), [{owner: 'example', repo: 'FireMUD', event_type: 'pr-runtime-base-refresh-request', client_payload: {pr_number: '7', base_ref: 'develop', - base_sha: B, head_sha: C, merge_sha: A, image_tag: `pr-merge-${A}`}}]); + base_sha: B, head_sha: C, merge_sha: A, preview_only: true}}]); assert.deepEqual(f.mergeReads, [E, A]); }); test('a completed render failure permits repair when the plan was eligible', async () => { @@ -362,18 +499,16 @@ test('older base classifiers cannot omit newly introduced validation modules', a }); function producer(f, event = 'repository_dispatch') { - return {id: 100, workflow_id: 42, path: '.github/workflows/runtime-images.yml', - event, head_branch: 'develop', head_sha: event === 'pull_request' ? C : D, - repository: {full_name: 'example/FireMUD'}, head_repository: {full_name: 'example/FireMUD'}, - status: 'in_progress', conclusion: null, - display_title: `Build Runtime Images secure-pr-artifact pr-7 base-${B} head-${C} merge-${A} mode-required`, - pull_requests: [{number: 7, head: {sha: C}, base: {sha: B}}]}; + return f.makeRun({id: 100, event, head_sha: event === 'pull_request' ? C : D, + status: 'in_progress', pull_requests: [{number: 7, head: {sha: C}, base: {sha: B}}]}); } for (const event of ['repository_dispatch', 'pull_request']) { for (const status of ['queued', 'waiting', 'requested', 'pending', 'in_progress']) { - test(`active exact ${event} ${status} producer suppresses dispatch`, async () => { - const f = fixture(); const run = producer(f, event); run.status = status; f.producers = [run]; - assert.deepEqual(await execute(f), []); + test(`admission suppresses dispatch for an active exact ${event} ${status} producer`, async () => { + const f = admissionFixture(); + f.runs.push({...producer(f, event), status}); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); + assert.deepEqual(f.sent, []); }); } } @@ -391,8 +526,9 @@ for (const [name, mutate] of Object.entries({ completed: r => {r.status = 'completed'; r.conclusion = 'success';}, inconsistentConclusion: r => r.conclusion = 'failure', })) test(`unrelated/untrusted producer cannot suppress recovery: ${name}`, async () => { - const f = fixture(); const r = producer(f); mutate(r); f.producers = [r]; - assert.equal((await execute(f)).length, 1); + const f = admissionFixture(); const r = producer(f); mutate(r); f.runs.push(r); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); }); for (const [name, mutate] of Object.entries({ head: r => r.head_sha = D, @@ -401,34 +537,37 @@ for (const [name, mutate] of Object.entries({ associationBase: r => r.pull_requests[0].base.sha = D, associationHead: r => r.pull_requests[0].head.sha = D, })) test(`PR title alone cannot suppress: ${name}`, async () => { - const f = fixture(); const r = producer(f, 'pull_request'); mutate(r); f.producers = [r]; - assert.equal((await execute(f)).length, 1); + const f = admissionFixture(); const r = producer(f, 'pull_request'); mutate(r); f.runs.push(r); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); }); -test('bounded inventory saturation fails without dispatch or polling', async () => { - const f = fixture(); f.fullInventory = Array.from({length: 100}, () => ({})); - const sent = []; - await assert.rejects(execute(f, sent), /exceeds bounded lookup/); - assert.deepEqual(sent, []); - assert.equal(f.lookups, 3); +test('admission retains the refresh fallback when active inventory exceeds its bound', async () => { + const f = admissionFixture(); + f.runs.push(...Array.from({length: 301}, (_, i) => f.makeRun({ + id: 400 + i, display_title: 'unrelated work', created_at: '2024-01-01T00:00:00Z', + }))); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); + assert.ok(f.warnings.some(warning => warning.includes('inventory was incomplete'))); }); test('qualified trusted default workflow path suppresses exact dispatch', async () => { - const f = fixture(); const r = producer(f); - r.path += '@refs/heads/develop'; f.producers = [r]; - assert.deepEqual(await execute(f), []); + const f = admissionFixture(); const r = producer(f); + r.path += '@refs/heads/develop'; f.runs.push(r); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); }); test('canonical eligibility refuses absent author metadata', async () => { const f = fixture(); delete f.pr.user; assert.deepEqual(await execute(f), []); }); test('qualified exact PR merge workflow path suppresses native producer', async () => { - const f = fixture(); const r = producer(f, 'pull_request'); - r.path += '@refs/pull/7/merge'; f.producers = [r]; - assert.deepEqual(await execute(f), []); + const f = admissionFixture(); const r = producer(f, 'pull_request'); + r.path += '@refs/pull/7/merge'; f.runs.push(r); + assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); }); test('qualified other PR workflow path cannot suppress native producer', async () => { - const f = fixture(); const r = producer(f, 'pull_request'); - r.path += '@refs/pull/8/merge'; f.producers = [r]; - assert.equal((await execute(f)).length, 1); + const f = admissionFixture(); const r = producer(f, 'pull_request'); + r.path += '@refs/pull/8/merge'; f.runs.push(r); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); }); test('immutable title repairs base despite current mutable association', async () => { @@ -444,7 +583,7 @@ test('partial rerun without an exact-attempt plan gives safe full-rerun guidance assert.ok(f.messages.some(message => message.includes('Re-run all jobs'))); }); -test('priority removed during active lookup refuses dispatch', async () => { +test('priority removed before the final observer fence refuses dispatch', async () => { const f = fixture(); f.pr.base.ref = 'feature/stack'; f.pr.labels = [{name: 'preview:priority'}]; @@ -453,6 +592,37 @@ test('priority removed during active lookup refuses dispatch', async () => { assert.equal(f.pullReads, 2); }); +test('observer waits for a pending test merge and rereads a formerly stale merge tuple', async () => { + const f = fixture(); + const stale = 'f'.repeat(40); + f.pullHistory = [{...f.pr, mergeable: null, mergeable_state: 'unknown', merge_commit_sha: null}, + {...f.pr, merge_commit_sha: stale}]; + f.pendingMerges = {[stale]: {sha: stale, parents: [{sha: D}, {sha: C}]}}; + assert.equal((await execute(f)).length, 1); + assert.deepEqual(f.mergeReads, [E, stale, A]); + assert.equal(f.baseReads, 4); + assert.equal(f.pauses, 2); +}); + +test('observer stops waiting on changed head, ineligibility, or an actual merge conflict', async () => { + for (const mutate of [ + pr => { pr.head.sha = D; }, + pr => { pr.labels = []; }, + pr => { pr.mergeable = false; pr.mergeable_state = 'dirty'; }, + ]) { + const f = fixture(); + f.pr.base.ref = 'feature/stack'; + f.pr.labels = [{name: 'preview:priority'}]; + const stopped = structuredClone(f.pr); + mutate(stopped); + f.pullHistory = [{...f.pr, mergeable: null, mergeable_state: 'unknown', merge_commit_sha: null}, stopped]; + assert.deepEqual(await execute(f), []); + assert.equal(f.pullReads, 2); + assert.deepEqual(f.mergeReads, [E]); + assert.equal(f.pauses, 1); + } +}); + test('event base drift can repair the independently revalidated current merge', async () => { const f = fixture(); f.jobs[0].steps = [tupleStep('event', D, A), tupleStep('resolved', B, A)]; @@ -465,7 +635,8 @@ test('event base drift can repair the independently revalidated current merge', moved.recordedMerge = structuredClone(moved.merge); moved.merge.parents[0].sha = D; assert.deepEqual(await execute(moved), []); - assert.deepEqual(moved.mergeReads, [A, A]); + assert.equal(moved.mergeReads.length, 7); + assert.ok(moved.mergeReads.every(sha => sha === A)); }); test('a resolved historical merge can precede a second base advance', async () => { diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 0958f8e1bc..659ab1b895 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -169,6 +169,7 @@ const mutationsChanged = before => mutationCounts().some((count, index) => count const codeqlListWorkflowRuns = async () => undefined; const checksListForRef = async () => undefined; const commentsList = async () => undefined; +const association = (ref, number = 42) => ({number, base: {ref}}); const jobRequests = []; const github = { request: async (route, input) => { @@ -292,7 +293,7 @@ const github = { status: "completed", conclusion: "success", }, - ]; + ].map(row => ({...row, pull_requests: [association("develop", row.id === 250 ? 99 : 42)]})); } return [ { @@ -304,6 +305,7 @@ const github = { run_attempt: 1, status: "completed", conclusion: "success", + pull_requests: [association("develop")], }, ]; } @@ -470,6 +472,7 @@ async function assertCompletionOrders() { return rows.filter((row) => [100, 200, 300].includes(row.id)).map((row) => ({ ...row, id: row.id + runOffset, head_sha: proofHead, + pull_requests: [association(currentBaseRef)], display_title: row.display_title.replace(`base-${baseSha}`, `base-${currentBaseSha}`).replace(`head-${headSha}`, `head-${proofHead}`), status: completed.has(key) ? "completed" : "in_progress", conclusion: completed.has(key) ? "success" : null, @@ -626,6 +629,110 @@ async function assertProducerSelectionRace() { jobRequests.length = 0; } } +async function assertExactBaseRef() { + const originalPaginate = github.paginate; + const originalActions = github.rest.actions; + const originalRequest = github.request; + currentBaseRef = "main"; + try { + const pendingStart = calls.updated.length; + const jobStart = jobRequests.length; + await run(github, context, core); + if (jobRequests.length !== jobStart || + !calls.updated.slice(pendingStart).some(({body}) => + body.includes("CodeQL gate: `pending`") && body.includes("License gate: `pending`"))) { + throw new Error("same-SHA retarget must not read or reuse old-ref jobs"); + } + + github.paginate = async (method, input) => { + const rows = await originalPaginate(method, input); + if (method !== codeqlListWorkflowRuns) return rows; + return rows.map(row => [200, 300].includes(row.id) + ? {...row, conclusion: "success", pull_requests: [association("develop", 99), association("main")]} : row); + }; + github.request = async (route, input) => { + const {data} = await originalRequest(route, input); + return {data: {...data, jobs: data.jobs.map(job => ({...job, conclusion: "success"}))}}; + }; + const passStart = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(passStart).some(({body}) => body.includes("checks passed"))) { + throw new Error("valid producers for the new base ref must qualify after a same-SHA retarget"); + } + + const beforeReadback = mutationCounts(); + github.rest.actions = {...originalActions, getWorkflowRun: async input => { + const {data} = await originalActions.getWorkflowRun(input); + return {data: {...data, pull_requests: [association("develop")]}}; + }}; + await run(github, context, core); + if (mutationsChanged(beforeReadback)) throw new Error("producer ref changes on readback must prevent publication"); + + github.rest.actions = {...originalActions, getWorkflowRun: async input => { + const result = await originalActions.getWorkflowRun(input); + currentBaseRef = "develop"; + return result; + }}; + const beforeLiveChange = mutationCounts(); + await run(github, context, core); + if (mutationsChanged(beforeLiveChange)) throw new Error("a live ref change at the same base SHA must prevent publication"); + + github.rest.actions = originalActions; + const exactPaginate = github.paginate; + currentBaseRef = "main"; + for (const pull_requests of [[], [{number: 42}], [association("main"), association("develop")]]) { + github.paginate = async (method, input) => { + const rows = await exactPaginate(method, input); + return method === codeqlListWorkflowRuns + ? rows.map(row => row.id === 270 ? {...row, pull_requests} : row) : rows; + }; + const before = mutationCounts(); + let refused = false; + try { await run(github, context, core); } catch (error) { + if (!error.message.includes("base ref is unavailable")) throw error; + refused = true; + } + if (!refused || mutationsChanged(before)) { + throw new Error("a newer candidate with no exact ref must prevent falling back to an older pass"); + } + } + } finally { + currentBaseRef = "develop"; + github.paginate = originalPaginate; + github.rest.actions = originalActions; + github.request = originalRequest; + } +} +async function assertSkippedRequiredGates() { + const originalRequest = github.request; + const originalPaginate = github.paginate; + try { + for (const [jobName, label] of [["CodeQL Gate", "CodeQL gate"], ["License Gate", "License gate"]]) { + github.paginate = async (method, input) => { + const rows = await originalPaginate(method, input); + return method === codeqlListWorkflowRuns + ? rows.map(row => row.id === 200 ? {...row, conclusion: "success"} : row) : rows; + }; + github.request = async (route, input) => { + const {data} = await originalRequest(route, input); + if (![200, 300].includes(input.run_id)) return {data}; + return {data: {...data, jobs: data.jobs.map(job => ({...job, + conclusion: [jobName, "CodeQL Analysis (java)"].includes(job.name) ? "skipped" : "success", + }))}}; + }; + const start = calls.updated.length; + await run(github, context, core); + if (!calls.updated.slice(start).some(({body}) => body.includes(label + ": `unavailable`") && + body.includes("Static analysis evidence is unavailable") && + body.includes("CodeQL analysis (java): `skipped`"))) { + throw new Error("a skipped required gate must be unavailable while a skipped detail remains skipped"); + } + } + } finally { + github.request = originalRequest; + github.paginate = originalPaginate; + } +} async function assertInterruptedRecovery() { const originalPaginate = github.paginate; const reset = () => { @@ -745,6 +852,8 @@ run(github, context, core).then(async () => { deleteStatus = null; await assertCompletionOrders(); await assertProducerSelectionRace(); + await assertExactBaseRef(); + await assertSkippedRequiredGates(); await assertInterruptedRecovery(); await assertAssociationSelection(); if (!jobRequests.some(input => input.run_id === 270)) throw new Error("metadata race was not classified from candidate jobs"); diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 9a34b243bf..75fc7b43a0 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -46,13 +46,15 @@ def version_label(version_key: tuple[int, ...]) -> str: def relevant_path(path: str) -> bool: return bool(MIGRATION_PATH_RE.match(path)) or ( path.startswith("services/") - and (path.endswith("/build.gradle.kts") or re.search(r"/src/main/resources/application[^/]*\.ya?ml$", path)) + and (path.endswith("/build.gradle.kts") + or re.search(r"/src/main/resources/(?:config/)?application[^/]*\.ya?ml$", path)) ) or (path.startswith("buildSrc/") and path.endswith((".kt", ".kts"))) def current_snapshot(repo_root: Path) -> Snapshot: paths = [*repo_root.glob("services/*/build.gradle.kts"), *repo_root.glob("services/*/src/main/resources/application*.y*ml"), + *repo_root.glob("services/*/src/main/resources/config/application*.y*ml"), *repo_root.glob("services/*/src/main/resources/db/migration/**/*"), *repo_root.glob("services/*/src/main/java/db/migration/**/*"), *repo_root.glob("services/*/src/main/resources/db/recovery-control-migration/**/*"), @@ -172,10 +174,16 @@ def flatten_properties( properties[path] = child flatten_properties(child, (*prefix, *parts), properties, ambiguous) + resource_root = f"services/{project}/src/main/resources" + # Config in the packaged config/ directory takes precedence over the root. + # Within a location Spring Boot gives .yml precedence over .yaml. + base_paths = [f"{directory}/application.{extension}" + for directory in (resource_root, f"{resource_root}/config") + for extension in ("yaml", "yml")] + profile_pattern = re.compile(rf"{re.escape(resource_root)}/(?:config/)?application-[^/]+\.ya?ml") + profile_paths = sorted(path for path in snapshot if profile_pattern.fullmatch(path)) flyway = {} - # Spring Boot gives .yml properties precedence over same-location .yaml. - for extension in ("yaml", "yml"): - config_path = f"services/{project}/src/main/resources/application.{extension}" + for config_path in [*base_paths, *profile_paths]: try: documents = list(yaml.safe_load_all(snapshot.get(config_path, b""))) except yaml.YAMLError as error: @@ -198,8 +206,8 @@ def flatten_properties( locations_path + ".", locations_path + "[")) } if not guard_paths: - # Other documents, including profile-activated documents with no - # Flyway guard properties, do not affect this static qualification. + # Profile configuration with no Flyway guard properties does not + # affect this static qualification. continue if guard_paths & ambiguous or any(path not in {enabled_path, locations_path} for path in guard_paths): return False @@ -209,12 +217,11 @@ def flatten_properties( "spring.profiles" in properties and not isinstance(properties["spring.profiles"], dict) ) - if (isinstance(activation, dict) and activation) or any( + if config_path in profile_paths or (isinstance(activation, dict) and activation) or any( path.startswith("spring.config.activate.") for path in properties ) or legacy_profile_activation: - # The checker cannot prove which profile/cloud-activated property - # source wins at runtime, so a conditional override of either guard - # property is not accepted. + # The active profile/cloud environment is unknown, so the checker + # cannot qualify an activation-dependent override of either guard. return False for path in guard_paths: @@ -408,6 +415,22 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str check("recovery location requiring active profile fails closed", {**recovery_history, recovery_config: profile_only_recovery}, recovery_history, "historical effective migration no longer applied") + recovery_config_root = recovery_config.rsplit("/", 1)[0] + for profile_path in ( + f"{recovery_config_root}/application-production.yml", + f"{recovery_config_root}/config/application-production.yaml", + ): + check("packaged profile disables recovery history", + {**recovery_history, profile_path: b"spring.flyway.enabled: false\n"}, + recovery_history, "historical effective migration no longer applied") + check("packaged profile replaces recovery location", + {**recovery_history, profile_path: yml_locations_override}, recovery_history, + "historical effective migration no longer applied") + check("unrelated packaged profile leaves recovery history unchanged", + {**recovery_history, profile_path: b"server.port: 9000\n"}, recovery_history, None) + check("recovery location in a profile cannot qualify the default history", + {recovery + "V1__journal.sql": b"-- journal", profile_path: recovery_settings}, + recovery_history, "historical effective migration no longer applied") for disabled in ( recovery_settings.replace(b" locations:", b" enabled: false\n locations:"), recovery_list_settings.replace(b"enabled: true", b'enabled: "false"'), @@ -426,7 +449,10 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str (root / recovery).mkdir(parents=True) (root / recovery / "V1__journal.sql").write_bytes(b"-- journal") (root / recovery_config).write_bytes(recovery_settings) - if current_snapshot(root) != recovery_history or not all(map(relevant_path, recovery_history)): + profile_fixture = {**recovery_history, profile_path: b"server.port: 9000\n"} + (root / profile_path).parent.mkdir() + (root / profile_path).write_bytes(profile_fixture[profile_path]) + if current_snapshot(root) != profile_fixture or not all(map(relevant_path, profile_fixture)): raise AssertionError("isolated recovery history is not selected for both snapshots") # Exercise the actual composed convention wiring and exclude test-only dependencies. diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java index d46ec9c6a1..bcf748a8e5 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java @@ -9,6 +9,7 @@ public final class RecoveryControlDatabaseHostEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final String HOST_PROPERTY = "FIREMUD_RECOVERY_CONTROL_DB_HOST"; + static final String PORT_PROPERTY = "FIREMUD_RECOVERY_CONTROL_DB_PORT"; @Override public void postProcessEnvironment( @@ -21,6 +22,12 @@ public void postProcessEnvironment( throw new IllegalStateException( HOST_PROPERTY + " must name the isolated recovery database using exactly one host"); } + String port = environment.getProperty(PORT_PROPERTY, "5432"); + int portNumber = port.matches("[0-9]{1,5}") ? Integer.parseInt(port) : 0; + if (portNumber < 1 || portNumber > 65535) { + throw new IllegalStateException( + PORT_PROPERTY + " must be a decimal port from 1 through 65535"); + } } @Override diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 57e07c53c5..275db0b05c 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -13,6 +13,9 @@ import tools.jackson.core.json.JsonWriteFeature; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.cfg.CoercionAction; +import tools.jackson.databind.cfg.CoercionInputShape; +import tools.jackson.databind.type.LogicalType; /** Stable JSON and digest encoding for the operation-owned immutable tuples. */ @Component @@ -26,6 +29,9 @@ public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { .rebuild() .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) .disable(tools.jackson.databind.DeserializationFeature.ACCEPT_FLOAT_AS_INT) + .withCoercionConfig( + LogicalType.Integer, + config -> config.setCoercion(CoercionInputShape.String, CoercionAction.Fail)) .build(); this.digestMapper = this.objectMapper.writer().with(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } diff --git a/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql index 472833ec1d..493a9d2bdc 100644 --- a/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql +++ b/services/recovery-controller-service/src/main/resources/db/recovery-control-migration/V2__retain_initial_gameplay_release_attempt_closure.sql @@ -1,6 +1,7 @@ -- Source-only upgrade. Fence and drain all V1 writers before migration and rollout. -- V1 could overwrite prior closure evidence; never synthesize missing history. -- [jooq ignore start] +SET LOCAL lock_timeout = '5s'; LOCK TABLE recovery_control.initial_gameplay_release_outbox IN ACCESS EXCLUSIVE MODE; DO $$ diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 8f1086ae5b..1524dda084 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.recovery.RecoveryControllerServiceApplication; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseConflictException; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal; import net.firedevops.firemud.recovery.journal.InitialGameplayReleaseJournal.RetrySource; @@ -59,6 +60,9 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.LoggerFactory; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.core.env.StandardEnvironment; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -305,6 +309,69 @@ void clearJournal() { + "recovery_control.initial_gameplay_release_operation"); } + @Test + void packagedApplicationMigratesAndPersistsThroughTheInjectedJournal() throws Exception { + String database = "firemud_recovery_control"; + String fixtureUrl = POSTGRES.getJdbcUrl(); + String packagedUrl = fixtureUrl.substring(0, fixtureUrl.lastIndexOf('/') + 1) + database; + var environment = new StandardEnvironment(); + // Keep ambient datasource overrides out of the context before Flyway migrates. + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + + dsl.execute("CREATE DATABASE " + database); + try (var application = + new SpringApplicationBuilder(RecoveryControllerServiceApplication.class) + .environment(environment) + .web(WebApplicationType.NONE) + .run( + "--spring.config.location=classpath:/application.yml", + "--FIREMUD_RECOVERY_CONTROL_DB_HOST=" + POSTGRES.getHost(), + "--FIREMUD_RECOVERY_CONTROL_DB_PORT=" + POSTGRES.getMappedPort(5432), + "--FIREMUD_RECOVERY_CONTROL_DB_USER=" + POSTGRES.getUsername(), + "--FIREMUD_RECOVERY_CONTROL_DB_PASSWORD=" + POSTGRES.getPassword(), + "--spring.grpc.server.enabled=false", + "--firemud.auth.jwt-secret=" + UUID.randomUUID() + UUID.randomUUID(), + "--spring.ssl.bundle.pem.firemud-grpc.keystore.certificate=classpath:certs/dev-cert.pem", + "--spring.ssl.bundle.pem.firemud-grpc.keystore.private-key=classpath:certs/dev-key.pem", + "--spring.ssl.bundle.pem.firemud-grpc.truststore.certificate=classpath:certs/dev-ca.pem"); + Connection packagedConnection = + DriverManager.getConnection( + packagedUrl, POSTGRES.getUsername(), POSTGRES.getPassword())) { + DSLContext packagedDsl = DSL.using(packagedConnection, SQLDialect.POSTGRES); + assertThat( + packagedDsl + .fetch( + "SELECT script FROM recovery_control.flyway_schema_history_recovery_control WHERE version IS NOT NULL AND success") + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + "V1__initial_gameplay_release_journal.sql", + "V2__retain_initial_gameplay_release_attempt_closure.sql"); + + InitialGameplayReleaseJournal injected = + application.getBean(InitialGameplayReleaseJournal.class); + Scope requested = scope(); + UUID lockIdentity = UUID.randomUUID(); + Operation created = injected.create(requested, lockIdentity); + + assertThat(created.phase()).isEqualTo(Phase.COLLECTING); + assertThat(injected.find(requested.operationId())).contains(created); + assertThat( + packagedDsl + .fetchSingle( + "SELECT maintenance_lock_identity FROM recovery_control.initial_gameplay_release_operation WHERE operation_id=?", + requested.operationId()) + .get(0, UUID.class)) + .isEqualTo(lockIdentity); + } finally { + dsl.execute("DROP DATABASE " + database); + } + } + @Test void journalDoesNotLogControllerLockIdentityAtDebug() { Logger logger = (Logger) LoggerFactory.getLogger(LoggerListener.class); @@ -937,12 +1004,22 @@ void dispatchFloorUsesStoredMicrosecondsWithoutRoundingFutureOrLosingReceiptPrec EffectReadbackState.PROVEN_NO_EFFECT, "same-instant", dispatchInstant); - Operation recorded = journal.recordEffectReadback(dispatched, closure, base.plusSeconds(5)); + Operation recorded = journal.recordEffectReadback(dispatched, closure, dispatchInstant); String retained = storedOutbox(operationId, effectId); assertThat(retained).contains(tupleCodec.digest(closure)); assertThat(journal.recordEffectReadback(dispatched, closure, base.plusSeconds(6))) .isEqualTo(recorded); assertThat(storedOutbox(operationId, effectId)).isEqualTo(retained); + UUID replacementAttempt = UUID.randomUUID(); + assertThat( + journal + .claimEffect(operationId, effectId, replacementAttempt, base.plusSeconds(7)) + .lastAttemptId()) + .isEqualTo(replacementAttempt); + String replacement = storedOutbox(operationId, effectId); + assertThat(journal.recordEffectReadback(dispatched, closure, base.plusSeconds(8))) + .isEqualTo(recorded); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(replacement); } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java index 74cc2ceaee..682bdf9581 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.SpringApplication; import org.springframework.mock.env.MockEnvironment; @@ -64,4 +66,30 @@ void acceptsAnExplicitSingleRecoveryDatabaseHostname() { new SpringApplication())) .doesNotThrowAnyException(); } + + @ParameterizedTest + @ValueSource(strings = {"", "invalid", "0", "65536", "5432/other", "5432,5433"}) + void rejectsInvalidRecoveryDatabasePorts(String port) { + var environment = + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, "localhost") + .withProperty(RecoveryControlDatabaseHostEnvironmentPostProcessor.PORT_PROPERTY, port); + assertThatThrownBy( + () -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("FIREMUD_RECOVERY_CONTROL_DB_PORT"); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "5544", "65535"}) + void acceptsAnExplicitRecoveryDatabasePort(String port) { + var environment = + new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, "localhost") + .withProperty(RecoveryControlDatabaseHostEnvironmentPostProcessor.PORT_PROPERTY, port); + assertThatCode(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .doesNotThrowAnyException(); + } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index a310c2c895..9611ef0ab8 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -277,8 +277,8 @@ void readinessRejectsMissingPartitionAcknowledgementAndWriterFence() { @Test void tenantAndUuidCoverageFenceSurviveCodecAndBindTheScopeDigest() { - InitialGameplayReleaseTupleCodec codec = - new InitialGameplayReleaseTupleCodec(JsonMapper.builder().findAndAddModules().build()); + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); Scope original = scope(UUID.randomUUID()); Scope otherTenant = new Scope( @@ -295,26 +295,18 @@ void tenantAndUuidCoverageFenceSurviveCodecAndBindTheScopeDigest() { assertThat(codec.readEvidence(codec.toJson(proof)).issuerLayout().coverageFence()) .isEqualTo(proof.issuerLayout().coverageFence()); - String legacyScopeJson = - codec - .toJson(original) - .replace("\"canonicalTenantId\":\"" + original.canonicalTenantId() + "\",", ""); + ObjectNode legacyScope = (ObjectNode) mapper.readTree(codec.toJson(original)); + legacyScope.remove("canonicalTenantId"); + String legacyScopeJson = mapper.writeValueAsString(legacyScope); assertThatThrownBy(() -> codec.readScope(legacyScopeJson)).isInstanceOf(RuntimeException.class); - String nilTenantScopeJson = - codec - .toJson(original) - .replace( - "\"canonicalTenantId\":\"" + original.canonicalTenantId() + "\"", - "\"canonicalTenantId\":\"" + NIL_UUID + "\""); + legacyScope.put("canonicalTenantId", NIL_UUID.toString()); + String nilTenantScopeJson = mapper.writeValueAsString(legacyScope); assertThatThrownBy(() -> codec.readScope(nilTenantScopeJson)) .isInstanceOf(RuntimeException.class); - String legacyNumericFenceJson = - codec - .toJson(proof) - .replace( - "\"coverageFence\":\"" + proof.issuerLayout().coverageFence() + "\"", - "\"coverageFence\":34"); + ObjectNode legacyEvidence = (ObjectNode) mapper.readTree(codec.toJson(proof)); + ((ObjectNode) legacyEvidence.get("issuerLayout")).put("coverageFence", 34); + String legacyNumericFenceJson = mapper.writeValueAsString(legacyEvidence); assertThatThrownBy(() -> codec.readEvidence(legacyNumericFenceJson)) .isInstanceOf(RuntimeException.class); } @@ -502,7 +494,7 @@ void persistedPartitionAcknowledgementRequiresExplicitNonNullPartitionId() { } @Test - void persistedEvidenceRejectsFractionalOperationFence() { + void persistedEvidenceRequiresAnIntegerOperationFence() { JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); var original = evidence(scope(UUID.randomUUID())); @@ -511,9 +503,13 @@ void persistedEvidenceRejectsFractionalOperationFence() { ObjectNode altered = (ObjectNode) mapper.readTree(json); ((ObjectNode) altered.get("issuerLayout")).put("operationFence", 21.9); String fractionalJson = mapper.writeValueAsString(altered); + ((ObjectNode) altered.get("issuerLayout")).put("operationFence", "21"); + String stringJson = mapper.writeValueAsString(altered); assertThatThrownBy(() -> codec.readEvidence(fractionalJson)) .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> codec.readEvidence(stringJson)) + .isInstanceOf(IllegalStateException.class); } @Test From 6aaa4f4e8151992ddaca6a9c0999f45a479f535d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:54:48 +1300 Subject: [PATCH 103/199] Verify preview retry ownership and recovery proof --- .github/actionlint.yaml | 3 + .github/scripts/admit-pr-runtime-refresh.cjs | 27 +- .../workflows/admit-pr-runtime-refresh.yml | 3 +- .github/workflows/ci.yml | 2 +- .github/workflows/hosted-identity-request.yml | 4 +- .github/workflows/smoke.yml | 64 ++- .../infrastructure/deployment-environments.md | 2 +- .../architecture/system-architecture-cicd.md | 4 +- design/developer-workflows/pr-lifecycle.md | 2 +- .../preview/reconcile-preview-deploys.sh | 245 ++++++--- .../hosted/shared/wait-for-runtime-images.sh | 13 + .../tests/ci-lightweight-scope-contract.sh | 1 + ...d-identity-controller-workflow-contract.sh | 29 ++ .../pr-required-gate-context-contract.sh | 148 ++++-- .../tests/pr-retarget-workflow-contract.sh | 21 +- .../pr-runtime-image-publication-contract.sh | 49 +- .../tests/preview-merge-image-tag-contract.sh | 55 +- dev-tools/tests/preview-priority-contract.sh | 471 ++++++++++++++++-- .../preview-runner-isolation-contract.sh | 19 + .../tests/preview-runtime-refresh.test.cjs | 101 +++- .../tests/static-analysis-summary-contract.sh | 64 ++- dev-tools/validation/check-flyway-versions.py | 22 +- k8s/helm/firemud/templates/apps.yaml | 5 +- ...lDatabaseHostEnvironmentPostProcessor.java | 85 +++- .../InitialGameplayReleaseJournal.java | 7 + .../InitialGameplayReleaseTupleCodec.java | 8 +- .../JooqInitialGameplayReleaseJournal.java | 76 ++- ...ReleaseJournalPostgresIntegrationTest.java | 139 +++++- ...abaseHostEnvironmentPostProcessorTest.java | 153 ++++++ .../InitialGameplayReleaseTupleCodecTest.java | 54 ++ .../InitialGameplayReleaseModelTest.java | 30 ++ 31 files changed, 1648 insertions(+), 258 deletions(-) create mode 100644 services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodecTest.java diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 38448fa6ca..833522d4ce 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -6,6 +6,9 @@ self-hosted-runner: # actionlint release does not parse it, so suppress only that known parser lag # only in workflows explicitly using this documented queue option. paths: + .github/workflows/admit-pr-runtime-refresh.yml: + ignore: + - 'unexpected key "queue" for "concurrency" section' .github/workflows/static-analysis-summary.yml: ignore: - 'unexpected key "queue" for "concurrency" section' diff --git a/.github/scripts/admit-pr-runtime-refresh.cjs b/.github/scripts/admit-pr-runtime-refresh.cjs index 997ac1809b..e86e224dac 100644 --- a/.github/scripts/admit-pr-runtime-refresh.cjs +++ b/.github/scripts/admit-pr-runtime-refresh.cjs @@ -236,30 +236,41 @@ module.exports = async function admitPrRuntimeRefresh({ core.warning('Runtime active-run inventory was incomplete or ambiguous; preserving the required refresh fallback.'); } - let activeProducerVerified = false; - if (inventoryComplete && newestExact && isExactActiveRun(newestExact)) { + const selectedProducerIsActive = async () => { try { const latest = dataOf(await github.rest.actions.getWorkflowRun({ ...contextRepo, run_id: newestExact.id, })); - activeProducerVerified = isExactActiveRun(latest) && latest.id === newestExact.id && + return isExactActiveRun(latest) && latest.id === newestExact.id && latest.run_attempt === newestExact.run_attempt && latest.event === newestExact.event && latest.head_sha === newestExact.head_sha && Date.parse(latest.created_at) === Date.parse(newestExact.created_at); } catch { core.warning('The exact active runtime producer could not be reread; preserving the required refresh fallback.'); + return false; } - } + }; + const activeProducerVerified = inventoryComplete && newestExact && isExactActiveRun(newestExact) && + await selectedProducerIsActive(); if (!await currentIdentity()) { core.info('Runtime refresh tuple changed during admission; no dispatch.'); return 'obsolete'; } if (activeProducerVerified) { - core.info('The unique newest exact runtime producer is already active; no dispatch.'); - return 'already-active'; + // Tuple resolution can wait for merge computation. Do not suppress a repair + // using producer evidence from before that final live comparison lookup. + if (await selectedProducerIsActive()) { + core.info('The unique newest exact runtime producer is already active; no dispatch.'); + return 'already-active'; + } + if (!await currentIdentity()) { + core.info('Runtime refresh tuple changed during the final producer lookup; no dispatch.'); + return 'obsolete'; + } } const dispatchCreatedSince = secondsUtc(Date.now()); + const nextDispatchSecond = Date.parse(dispatchCreatedSince) + 1000; await github.rest.repos.createDispatchEvent({ ...contextRepo, event_type: 'pr-runtime-base-refresh', @@ -285,7 +296,9 @@ module.exports = async function admitPrRuntimeRefresh({ }); if (Array.isArray(inventory?.workflow_runs) && inventory.workflow_runs.some(run => isExactActiveRun(run) && - run.event === 'repository_dispatch' && Date.parse(run.created_at) >= Date.parse(dispatchCreatedSince) && + // Unseen activity in the dispatch second may predate this request. + // Second-resolution chronology cannot confirm its attribution. + run.event === 'repository_dispatch' && Date.parse(run.created_at) >= nextDispatchSecond && !observedRunIds.has(`${run.event}:${run.id}:${run.run_attempt}`))) { core.info('The dispatched runtime refresh is visible as an exact active producer.'); return 'dispatched-observed'; diff --git a/.github/workflows/admit-pr-runtime-refresh.yml b/.github/workflows/admit-pr-runtime-refresh.yml index f364cd807e..04fe77c025 100644 --- a/.github/workflows/admit-pr-runtime-refresh.yml +++ b/.github/workflows/admit-pr-runtime-refresh.yml @@ -10,10 +10,11 @@ jobs: dispatch: name: Admit Exact Runtime Tuple if: ${{ github.event.action == 'pr-runtime-base-refresh-request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - # Both trusted callbacks reserve the same tuple before observing or dispatching. + # Keep ordinary and preview-only intent in one non-replacing tuple queue. concurrency: group: admit-pr-runtime-refresh-${{ github.event.client_payload.pr_number }}-${{ github.event.client_payload.base_sha }}-${{ github.event.client_payload.head_sha }}-${{ github.event.client_payload.merge_sha }} cancel-in-progress: false + queue: max runs-on: ubuntu-latest timeout-minutes: 4 permissions: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 90b7378458..853bcbcb6e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,7 +132,7 @@ jobs: const entries = await github.paginate(github.rest.pulls.listFiles, { ...context.repo, pull_number: context.payload.pull_request.number, per_page: 100, }, response => response.data); - const knownDoc = path => path === "README.md" || path === "mkdocs.yml" || (typeof path === "string" && + const knownDoc = path => path === "README.md" || path === "AGENTS.md" || path === "mkdocs.yml" || (typeof path === "string" && /^(?:design\/|docs\/)[A-Za-z0-9_./-]+\.md$/.test(path) && !path.split("/").includes("..")); const knownDesignDoc = path => knownDoc(path) && path.startsWith("design/"); diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index d829140d12..dd7fcf4576 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -143,7 +143,9 @@ jobs: length == 1 and .[0].head.sha == $head) ' <<<"$workflow_run_json" >/dev/null || emit_no_action "Ignoring qualified source path without a matching pull request and head." - else + elif [[ "$SOURCE_EVENT" != repository_dispatch || -z "${DEFAULT_BRANCH:-}" || + ( "$source_path" != ".github/workflows/preview.yml@$DEFAULT_BRANCH" && + "$source_path" != ".github/workflows/preview.yml@refs/heads/$DEFAULT_BRANCH" ) ]]; then require_source_field path '.github/workflows/preview.yml' "$source_path" fi require_source_field conclusion success "$(jq -r '.conclusion // empty' <<<"$workflow_run_json")" diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5f91695242..8526a8c366 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -536,6 +536,14 @@ jobs: ].includes(code))); } + function canResumeAfterOptionalGitHubError(error, primary) { + // Missing optional refresh evidence permits only fresh selection of a + // retained pending native producer, never acceptance of missing proof. + const status = error?.status ?? error?.response?.status; + return isTransientOptionalGitHubError(error) || + (status === 404 && primary?.event === "pull_request" && primary.status !== "completed"); + } + async function withTransientGitHubRetry(label, operation) { const maxAttempts = 4; let retryDelayMs = 1000; @@ -1021,7 +1029,8 @@ jobs: newestPreExecutionCancellation ??= run; continue; } - if (run.status !== "completed" && !isRetryPrimary(selection, run)) { + if (run.status !== "completed" && selection.allowCompletedFallback !== false && + !isRetryPrimary(selection, run)) { let checkedSuccesses = 0; for (const {run: older} of matchingRuns.slice(index + 1)) { if (older.status !== "completed") continue; @@ -1260,7 +1269,7 @@ jobs: "repository_dispatch", expectedDisplayTitle, currentIdentity ); } catch (error) { - if (!isTransientOptionalGitHubError(error)) throw error; + if (!canResumeAfterOptionalGitHubError(error, matching)) throw error; core.warning("Trusted refresh inventory is unavailable; retain the native wait."); } try { @@ -1378,7 +1387,7 @@ jobs: } catch (error) { // Re-read the pending comparison on the next bounded poll. No // partial evidence from this alternative carries into that poll. - if (isTransientOptionalGitHubError(error) && await retryExactSelection( + if (canResumeAfterOptionalGitHubError(error, selection.pendingPrimary) && await retryExactSelection( `Runtime alternative ${matching.id} jobs are temporarily unavailable; retry exact primary selection.` )) continue smokeGatePolling; throw error; @@ -1536,7 +1545,7 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) )); } catch (error) { - if (isTransientOptionalGitHubError(error) && await retryExactSelection( + if (canResumeAfterOptionalGitHubError(error, selection.pendingPrimary) && await retryExactSelection( `Runtime run ${matching.id} final attempt is temporarily unavailable; retry exact selection.`, { requirePendingPrimary: false } )) continue smokeGatePolling; @@ -1567,7 +1576,7 @@ jobs: () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) )); } catch (error) { - if (isTransientOptionalGitHubError(error) && await retryExactSelection( + if (canResumeAfterOptionalGitHubError(error, selection.pendingPrimary) && await retryExactSelection( `Runtime run ${matching.id} final current-base attempt is temporarily unavailable; retry exact selection.`, { requirePendingPrimary: false } )) continue smokeGatePolling; @@ -1589,6 +1598,51 @@ jobs: core.info("Current-base identity changed after the final runtime attempt lookup; resume exact selection."); continue smokeGatePolling; } + // A rerun can start during that last live tuple lookup. This final + // attempt fence does not make the separate GitHub reads atomic. + let confirmedAttempt; + try { + ({ data: confirmedAttempt } = await withTransientGitHubRetry( + "current-base runtime attempt lookup after final live tuple validation", + () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: matching.id }) + )); + } catch (error) { + if (canResumeAfterOptionalGitHubError(error, selection.pendingPrimary) && await retryExactSelection( + `Runtime run ${matching.id} confirmed current-base attempt is temporarily unavailable; retry exact selection.`, + { requirePendingPrimary: false } + )) continue smokeGatePolling; + throw error; + } + if (confirmedAttempt.id !== matching.id || confirmedAttempt.run_attempt !== matching.run_attempt || + confirmedAttempt.status !== "completed" || confirmedAttempt.conclusion !== "success") { + core.info("Runtime attempt changed during final live tuple validation; resume exact selection."); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + } + if (selection.pendingPrimary) { + // One fresh ordering read fences the older-success fallback. A + // terminal or replaced primary must qualify through its own proof. + let freshPrimary; + try { + freshPrimary = await findMatchingRuntimeImagesRun( + selection.pendingPrimary.event, expectedDisplayTitle, currentIdentity, + { allowCompletedFallback: false } + ); + } catch (error) { + if (canResumeAfterOptionalGitHubError(error, selection.pendingPrimary) && await retryExactSelection( + "Runtime candidate ordering is unavailable; retry exact primary selection." + )) continue smokeGatePolling; + throw error; + } + if (freshPrimary?.id !== selection.pendingPrimary.id || + freshPrimary.run_attempt !== selection.pendingPrimary.run_attempt || + freshPrimary.status === "completed") { + if (await retryExactSelection( + "Runtime candidate ordering changed before accepting older success; retry exact primary selection." + )) continue smokeGatePolling; + break smokeGatePolling; + } } return; } diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 7e76cfe31c..960bf0aa3a 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -328,7 +328,7 @@ The internal preview CA is not installed while a legacy preview credential can r The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all fourteen labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and nine distinct workload projections (the eight serving-workload leaves and the independent `firemud-grpc-spring-cloud-gateway` outbound client leaf). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all fourteen labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. -Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A Namespace-backed counter permits at most three proof-retry dispatches for one exact base/head/merge/image tuple and resets when that tuple changes; the counter and tuple are read and updated with the Namespace `resourceVersion`, and malformed evidence fails closed. These controls bound retry dispatches without claiming live proof. +Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A retained Namespace retry record permits at most three proof retries for one exact base/head/merge/image tuple. Its counter resets for a changed tuple. A resource-version update binds each reservation to the Namespace UID, tuple, and a unique reservation ID. If the update response is lost, bounded readback must prove that same reservation before dispatch. Explicit dispatch rejection may return only the exact reservation to the previous counter state. An ambiguous dispatch stays charged. These controls require the retry record to survive Namespace recreation to preserve the budget across that boundary. #### Preview exposure modes and proof boundaries diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 652bc5845e..da2fbae9e0 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -104,7 +104,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Invokes a dedicated `generate-erd` job that runs [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) to build ERD diagrams from service migrations and upload them as artifacts. - Caches Buf modules, Node dependencies, Trivy database, and Gradle artifacts to speed up repeat workflow runs. - Runs markdownlint, blocking internal link checks, structural design contracts, and a MkDocs site build in pull-request CI. Push CI also checks external links; `docs.yml` verifies internal links again before publishing to GitHub Pages. -- Posts a summary comment on pull requests with test status and coverage, while Codecov publishes patch-coverage status separately. Native Validation, Security and Smoke comment jobs run only for uncancelled same-repository PR events whose actor is not `dependabot[bot]`; fork and Dependabot PRs retain check logs and artifacts. Failed dependencies still produce summaries. Publishers verify the current open PR head and base tuple before touching comments. Required gates retain their independent always-running conditions and fail-closed prerequisite evaluation. +- Posts a summary comment on pull requests with test status and coverage, while Codecov publishes patch-coverage status separately. Native Validation, Security and Smoke comment jobs run only for uncancelled same-repository PR events whose actor is not `dependabot[bot]`; fork and Dependabot PRs retain check logs and artifacts. Failed dependencies still produce summaries. Publishers verify the current open PR head and base tuple before touching comments. Substantive PR runs, including a base retarget, retain independent required-gate evaluation. A title or body edit preserves the earlier canonical result for the same comparison. Both paths fail closed when their required proof is missing. Source-built MinIO helper changes require the same runtime-image smoke tracking and preview image selection as their Dockerfiles. Trusted runtime publication accepts the conventional source workflow API name while separately requiring the exact identity-bearing run title and source provenance. @@ -230,7 +230,7 @@ FireMUD's preview workflow is reserved for real reviewer-accessible PR environme - Reset the preview namespace on each deploy, then seed the minimum bootstrap state needed for reviewer proof so the hosted environment remains reproducible across preview updates. - Tear the preview down when the pull request closes or merges, is explicitly released, or its visible bounded renewable lease expires. Eligible same-repository pull requests allocate automatically; ordinary requests remain first-come at the serialized allocation boundary rather than relying on GitHub's raw job-scheduling order. A currently `preview:priority`-labelled request may reclaim the oldest ordinary allocation when the pool is full, but never another priority-labelled allocation; both labels are re-read at the destructive boundary, and the full allocation/deploy/proof/cleanup lifecycle uses one durable bounded non-cancelling queue. The displaced pull request retains ordinary CI and its historical hosted result while reporting no current preview. -For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and submits the typed runtime-image refresh request to the shared admission workflow. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata and requires both the immutable event tuple and the eligible deployment plan’s resolved tuple. It binds them to the native run head and unique PR association, independently verifies the recorded and current merge parents, and uses the branch ref for current base authority. A failed render can still trigger repair after a successful eligible plan. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle; PR close is handled directly by the trusted close event. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. +For both `standalone` and explicit `hosted-controller` preview modes, automatic preview rendering uses `pull_request` with read-only permissions rather than `pull_request_target`. Typed `repository_dispatch` retains its default-branch-owned manual deploy/destroy route. The configured render checkout loads tools and local actions from the default branch, while the separate exact PR merge checkout supplies Helm chart data. A pull-request-owned workflow definition can change its own checkout steps, so that configured checkout is not itself a privilege boundary. Only the default-branch-owned privileged dispatch and lifecycle may exercise trusted authority; they never execute candidate scripts or actions. The write-capable runtime refresh in the source workflow is dispatch-only. A separate default-branch `preview-runtime-refresh.yml` observer handles automatic PR base refresh through `workflow_run`: it reads GitHub-owned source-run/PR metadata and current exact merge parents, checks out only the default branch to reuse its canonical image-selection policy, never checks out candidate code or downloads artifacts, and submits the typed runtime-image refresh request to the shared admission workflow. The PR preview producer preserves its existing run and job names, recording the event PR/base/head/merge tuple in a successful native step name. The refresh observer reads bounded exact-attempt job metadata and requires both the immutable event tuple and the eligible deployment plan’s resolved tuple. It binds them to the native run head and unique PR association, independently verifies the recorded and current merge parents, and uses the branch ref for current base authority. A failed render can still trigger repair after a successful eligible plan. Step metadata is not privilege authority: the PR-authored workflow can affect it, and every requested refresh still requires independent current-PR eligibility and exact current merge verification. Missing or malformed legacy tuple metadata explicitly requires a fresh render from the updated producer rather than inferring historical proof; the observer still downloads no artifacts. Unrelated native PR associations are tolerated only when exactly one association matches the selected target; duplicate matching associations fail closed. PR-controlled build and render work must have no cluster, registry-write, or hosted-identity requester credentials. This is a required credential-scope boundary, not proof supplied by a default-branch tools checkout; repository-level legacy credential removal remains a separate verified rollout prerequisite. The trusted default-branch lifecycle consumes its sanitized render artifact only after validating source-run provenance (including the GitHub-owned PR association and source head for `pull_request`), current head/base/merge binding, checksum, closed schema, exact image tags, and allowlisted Secret consumers. In `standalone` mode, the trusted lifecycle restores only the canonical cert-manager ingress issuer annotation after artifact validation; the PR render cannot choose it. A manual release publishes an unprivileged destroy intent for the trusted lifecycle. Once close cleanup is separately activated, the trusted close event handles PR close. Privileged preview maintenance and dev-demo operations run only from default-branch schedule, push, workflow-run, pull-request-target, or typed repository-dispatch events, never a branch-selectable privileged manual dispatch. Every secret-consuming hosted job selects the separately protected `trusted-hosted-cluster` GitHub Environment, whose deployment branch policy must allow only `develop`; the legacy GitHub Environments named `pr-preview` and `dev-demo-cluster` must not hold requester credentials. Before live activation, repository-scoped runtime, GHCR, and any remaining hosted-identity credentials must be migrated to the protected Environment or removed and rotated as appropriate. Cluster kubeconfigs are written only to job-temporary files and removed at job end; operators must clear any historical runner-home copy and rotate exposed credentials as needed. This separation does not activate hosted deployment or cleanup workflows and does not change repository event-policy settings. The temporary path-specific `preview.yml` exception permits only `pull_request_target` and `repository_dispatch`, so it blocks the new `pull_request` event. At rollout, separately authorize and coordinate the additive path-specific policy update: retain `pull_request_target` and `repository_dispatch` and add `pull_request`. Verify fresh natural PR and manual-dispatch events against the merged code; the documentation change itself neither grants authorization nor changes that policy. Do not rename the workflow to evade that policy. Disabled close cleanup still uses its existing trusted `pull_request_target` route and requires a separate policy/activation decision before enabling it. A read-only token is not a secret-free execution guarantee; privileged consumers must keep treating every PR artifact as hostile data rather than executable configuration. diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 324572e04a..bcadd4ba7b 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -81,7 +81,7 @@ Merge authority: - Stacked PRs are fine when the base dependency is explicit. After a parent merges, retarget the child to `develop` before rebasing or pushing it. - When active work moves to another worktree, report its absolute path and branch. - CI coverage for stacked bases, required gate names, and preview restrictions are owned by [CI/CD](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain). -- Verify the committed candidate and live head/base, effective parent, provider-observed diff base, ancestry, and unique patch before relying on review evidence; refresh after a change. Preserve the owned patch, findings, review evidence, and configured controls during reconciliation. The applicable substantive workflows must actually run on that comparison; Validation alone is not Smoke proof. A base-ref retarget requires replacement validation, while metadata edits isolate checks under non-required names; see [Required Gates on Metadata Edits](../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits). +- Verify the committed candidate and live head/base, effective parent, provider-observed diff base, ancestry, and unique patch before relying on review evidence. Refresh the evidence when the reviewed diff changes. Preserve the owned patch, findings, evidence, and configured controls during reconciliation. Evaluate each workflow result under its owning [CI proof contract](../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), including the Smoke event-comparison rules. A base-ref retarget requires replacement validation. Metadata edits isolate checks under non-required names under the [metadata-edit contract](../architecture/system-architecture-cicd.md#required-gates-on-metadata-edits). - Use `dev-tools/validation/report-worktree-pr-topology.sh` for branch, worktree, and PR inventory (`--pr ` for one stack, `--json` for machine output, `--include-renovate` to include Renovate PRs). - After a merge, remove the defunct local worktree and merged branches only after confirming nothing open depends on them. Keep unmerged branches. - Pass PR-body Markdown through a file or stdin, not literal `\n` strings. diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh index 94dc8ad4d6..579bb26d70 100644 --- a/dev-tools/hosted/preview/reconcile-preview-deploys.sh +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -54,7 +54,9 @@ parse_namespace_tuple() { metadata_field(.metadata; "resourceVersion") ] | if ( - (.[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") + (($annotations | has("firemud.dev/proof-retry-count") | not) + and ($annotations | has("firemud.dev/proof-retry-reservation-id") | not) + and .[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") or ( (.[13] | test("^[1-3]$")) and (.[14] | test("^[0-9a-f]{40}$")) @@ -63,14 +65,44 @@ parse_namespace_tuple() { and (.[17] | test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) ) ) then . else error("namespace proof-retry evidence is malformed") end + | if (($annotations | has("firemud.dev/proof-retry-reservation-id") | not) + or ($annotations["firemud.dev/proof-retry-reservation-id"] + | type == "string" and test("^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"))) + then . else error("namespace proof-retry reservation ID is malformed") end | join("|") end ' <<<"$1" } +validated_proof_retry_reservation_version() { + local snapshot="$1" namespace="$2" uid="$3" deployed_tuple="$4" + local retry_tuple="$5" count="$6" reservation_id="$7" previous_version="$8" + parse_namespace_tuple "$snapshot" >/dev/null || return 1 + jq -ers --arg namespace "$namespace" --arg uid "$uid" --arg deployed "$deployed_tuple" \ + --arg retry "$retry_tuple" --arg count "$count" --arg id "$reservation_id" \ + --arg previous_version "$previous_version" ' + select(length == 1) | .[0] + | .metadata as $metadata | ($metadata.annotations // {}) as $annotations + | select($uid != "" and $id != "" and $metadata.name == $namespace and $metadata.uid == $uid + and ($metadata.resourceVersion | type == "string" and length > 0 and . != $previous_version) + and $annotations["firemud.dev/proof-retry-reservation-id"] == $id + and $annotations["firemud.dev/proof-retry-count"] == $count + and ([$annotations["firemud.dev/last-preview-base-sha"] // "", + $annotations["firemud.dev/last-preview-head-sha"] // "", + $annotations["firemud.dev/last-preview-merge-sha"] // "", + $annotations["firemud.dev/last-preview-image-tag"] // ""] | join("|")) == $deployed + and ([$annotations["firemud.dev/proof-retry-base-sha"], + $annotations["firemud.dev/proof-retry-head-sha"], + $annotations["firemud.dev/proof-retry-merge-sha"], + $annotations["firemud.dev/proof-retry-image-tag"]] | join("|")) == $retry) + | $metadata.resourceVersion + ' <<<"$snapshot" +} + readonly repair_success=0 readonly repair_skip=10 readonly repair_dispatch=11 +readonly repair_missing_proof=12 readonly repair_abort=20 repair_requested_tuple() { @@ -84,6 +116,7 @@ repair_requested_tuple() { local requested_head_sha="$8" local requested_merge_sha="$9" local requested_image_tag="${10}" + local expected_namespace_uid="${11}" local fresh_namespace_json local fresh_namespace_tuple local fresh_last_base_sha @@ -122,6 +155,10 @@ repair_requested_tuple() { fresh_proof_namespace_uid _ _ _ _ _ \ fresh_namespace_uid \ fresh_namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "${fresh_namespace_uid}" != "${expected_namespace_uid}" ]]; then + echo "Skipping preview repair for PR #${pr_number}: namespace UID changed during annotation repair check." + return "$repair_skip" + fi if [[ "${fresh_last_base_sha}" != "${base_sha}" || "${fresh_last_head_sha}" != "${head_sha}" || "${fresh_last_merge_sha}" != "${merge_sha}" || @@ -136,7 +173,7 @@ repair_requested_tuple() { -z "${fresh_namespace_uid}" || "${fresh_proof_namespace_uid}" != "${fresh_namespace_uid}" ]]; then echo "Preview ${namespace} deployed tuple is missing proof for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}; dispatching retry." - return "$repair_dispatch" + return "$repair_missing_proof" fi if [[ "${fresh_requested_base_sha}" == "${base_sha}" && "${fresh_requested_head_sha}" == "${head_sha}" && @@ -213,10 +250,19 @@ prepare_preview_dispatch() { local namespace_uid local namespace_resource_version local next_retry_count + local previous_reservation_id + local reservation_id + local reservation_resource_version local reservation_namespace_json + local annotation_failed=false + local recheck_namespace_name + local recheck_namespace_uid + local recheck_namespace_resource_version local exact_retry_tuple=false proof_retry_reservation_count="" + proof_retry_reservation_id="" + proof_retry_previous_reservation_id="" proof_retry_previous_count="" proof_retry_previous_base_sha="" proof_retry_previous_head_sha="" @@ -310,7 +356,17 @@ prepare_preview_dispatch() { echo "Skipping PR #${pr_number}: Namespace retry custody is unavailable." >&2 return 1 fi + previous_reservation_id="$(jq -r '.metadata.annotations["firemud.dev/proof-retry-reservation-id"] // ""' <<<"${fresh_namespace_json}")" + # uuid4 uses the OS cryptographic random source. The ID is custody for this + # invocation only, not a durable retry ledger across Namespace deletion. + if ! reservation_id="$(python3 -c 'import uuid; print(uuid.uuid4())')" || + [[ ! "$reservation_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]]; then + echo "Unable to generate proof-retry reservation ID for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ + "firemud.dev/proof-retry-reservation-id=${reservation_id}" \ "firemud.dev/proof-retry-count=${next_retry_count}" \ "firemud.dev/proof-retry-base-sha=${base_sha}" \ "firemud.dev/proof-retry-head-sha=${head_sha}" \ @@ -318,10 +374,59 @@ prepare_preview_dispatch() { "firemud.dev/proof-retry-image-tag=${image_tag}" \ --overwrite \ --resource-version "${namespace_resource_version}" -o json)"; then - echo "Skipping PR #${pr_number}: Namespace ${namespace} changed before proof retry evidence could be recorded." >&2 + annotation_failed=true + # A failed kubectl response proves neither a CAS conflict nor that the + # reservation was not committed. Bound classification to one API reread; + # never retry the write or compensate a reservation we cannot attribute. + if ! reservation_namespace_json="$(kubectl get namespace "${namespace}" \ + --ignore-not-found -o json --request-timeout=10s)"; then + echo "Unable to recheck Namespace ${namespace} after proof-retry annotation failure; refusing dispatch with reservation outcome unknown." >&2 + dispatch_outcome_failed=true + return 1 + fi + if [[ -z "${reservation_namespace_json}" ]]; then + echo "Skipping PR #${pr_number}: Namespace ${namespace} disappeared after proof-retry annotation failure; retry on a later cycle." >&2 + return 1 + fi + fi + # The successful CAS response and a lost-response reread need the same full + # positive evidence; tuple/count alone must never attribute another writer. + if ! reservation_resource_version="$(validated_proof_retry_reservation_version \ + "$reservation_namespace_json" "$namespace" "$namespace_uid" \ + "${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" \ + "${base_sha}|${head_sha}|${merge_sha}|${image_tag}" "$next_retry_count" \ + "$reservation_id" "$namespace_resource_version")"; then + if [[ "$annotation_failed" == false ]]; then + echo "Unable to prove proof-retry reservation custody for PR #${pr_number} from the annotation response; leaving its budget charged without dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + if ! fresh_namespace_tuple="$(parse_namespace_tuple "${reservation_namespace_json}")" || + ! recheck_namespace_name="$(jq -er '.metadata.name | select(type == "string" and length > 0 and (test("[|\\r\\n]") | not))' \ + <<<"${reservation_namespace_json}")"; then + echo "Unable to verify Namespace ${namespace} after proof-retry annotation failure; refusing dispatch with reservation outcome unknown." >&2 + dispatch_outcome_failed=true + return 1 + fi + IFS='|' read -r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \ + recheck_namespace_uid recheck_namespace_resource_version <<<"${fresh_namespace_tuple}" + if [[ "${recheck_namespace_name}" != "${namespace}" || + ( -n "${recheck_namespace_uid}" && "${recheck_namespace_uid}" != "${namespace_uid}" ) ]]; then + echo "Skipping PR #${pr_number}: Namespace identity changed after proof-retry annotation failure; retry on a later cycle." >&2 + return 1 + fi + if [[ -z "${recheck_namespace_uid}" || -z "${recheck_namespace_resource_version}" || + "${recheck_namespace_resource_version}" == "${namespace_resource_version}" ]]; then + echo "Unable to prove a Namespace change after proof-retry annotation failure for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + echo "Skipping PR #${pr_number}: competing Namespace resource version observed after proof-retry annotation failure; retry on a later cycle." >&2 return 1 fi proof_retry_reservation_count="${next_retry_count}" + proof_retry_reservation_id="${reservation_id}" + proof_retry_previous_reservation_id="${previous_reservation_id}" proof_retry_previous_count="${retry_count}" proof_retry_previous_base_sha="${retry_base_sha}" proof_retry_previous_head_sha="${retry_head_sha}" @@ -329,9 +434,7 @@ prepare_preview_dispatch() { proof_retry_previous_image_tag="${retry_image_tag}" proof_retry_reservation_namespace_uid="${namespace_uid}" proof_retry_reservation_deployed_tuple="${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" - proof_retry_reservation_resource_version="$(jq -er --arg uid "${namespace_uid}" \ - '.metadata | select(.uid == $uid) | .resourceVersion | select(type == "string" and length > 0)' \ - <<<"${reservation_namespace_json}" 2>/dev/null || true)" + proof_retry_reservation_resource_version="${reservation_resource_version}" proof_retry_reservation_base_sha="${base_sha}" proof_retry_reservation_head_sha="${head_sha}" proof_retry_reservation_merge_sha="${merge_sha}" @@ -344,17 +447,6 @@ compensate_rejected_proof_retry() { local namespace="$1" local pr_number="$2" local fresh_namespace_json - local fresh_namespace_tuple - local current_base_sha - local current_head_sha - local current_merge_sha - local current_image_tag - local retry_count - local retry_base_sha - local retry_head_sha - local retry_merge_sha - local retry_image_tag - local namespace_uid local namespace_resource_version local -a annotations=() @@ -365,27 +457,23 @@ compensate_rejected_proof_retry() { echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 return 1 fi - if [[ -z "${fresh_namespace_json}" ]] || - ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then - echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 - return 1 - fi - IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ - _ _ _ _ _ _ _ _ _ retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ - namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "${namespace_uid}" != "${proof_retry_reservation_namespace_uid}" || - -z "${proof_retry_reservation_resource_version}" || - "${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" != "${proof_retry_reservation_deployed_tuple}" || - "${retry_count}" != "${proof_retry_reservation_count}" || - "${retry_base_sha}" != "${proof_retry_reservation_base_sha}" || - "${retry_head_sha}" != "${proof_retry_reservation_head_sha}" || - "${retry_merge_sha}" != "${proof_retry_reservation_merge_sha}" || - "${retry_image_tag}" != "${proof_retry_reservation_image_tag}" || - -z "${namespace_resource_version}" ]]; then + # An unrelated RV advance is safe only while the exact reservation ID and + # every custody field still match; the compensating CAS uses this fresh RV. + if [[ -z "${proof_retry_reservation_resource_version}" ]] || + ! namespace_resource_version="$(validated_proof_retry_reservation_version \ + "$fresh_namespace_json" "$namespace" "$proof_retry_reservation_namespace_uid" \ + "$proof_retry_reservation_deployed_tuple" \ + "${proof_retry_reservation_base_sha}|${proof_retry_reservation_head_sha}|${proof_retry_reservation_merge_sha}|${proof_retry_reservation_image_tag}" \ + "$proof_retry_reservation_count" "$proof_retry_reservation_id" "")"; then echo "Proof-retry reservation for PR #${pr_number} changed before confirmed-rejection compensation; leaving its budget charged." >&2 return 1 fi + if [[ -n "${proof_retry_previous_reservation_id}" ]]; then + annotations+=("firemud.dev/proof-retry-reservation-id=${proof_retry_previous_reservation_id}") + else + annotations+=(firemud.dev/proof-retry-reservation-id-) + fi if [[ -n "${proof_retry_previous_count}" ]]; then annotations+=( "firemud.dev/proof-retry-count=${proof_retry_previous_count}" @@ -435,11 +523,28 @@ preview_source_skipped_render() { ' } +preview_source_uploaded_render() { + local run_id="$1" attempt="$2" head="$3" + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' + .jobs as $jobs + | ([$jobs[] | select(.name == "Render Sanitized Preview Artifact")] | length) == 1 + and any($jobs[]; .name == "Render Sanitized Preview Artifact" and .run_id == $id + and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) + and .head_sha == $head and .status == "completed" and .conclusion == "success" + and (.steps | type == "array") + and all(.steps[]; type == "object" and (.name | type == "string") + and (.status | type == "string") and (.conclusion | type == "string")) + and ([.steps[] | select(.name == "Upload sanitized render artifact")] | length) == 1 + and any(.steps[]; .name == "Upload sanitized render artifact" + and .status == "completed" and .conclusion == "success")) + ' +} + automatic_preview_has_tuple() { local run_id="$1" attempt="$2" head="$3" tuple="$4" pr="$5" event="$6" jobs latest jobs_available=true local dispatch_tuple="${tuple#Preview resolved tuple }" local dispatch_title="Preview dispatch ${dispatch_tuple// /-}" - # 0: exact active tuple, 1: proven nonmatch, 2: unavailable/unfinished proof. + # 0: exact active tuple, 1: proven nonmatch, 2: unavailable proof, 3: completed upload. jobs="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${attempt}/jobs?per_page=100")" || jobs_available=false latest="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")" || return 2 jq -e ' @@ -507,21 +612,7 @@ automatic_preview_has_tuple() { # A completed, successful, explicitly explained no-op cannot still hand off a render. return 1 fi - if ! jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg head "$head" ' - .jobs as $jobs - | ([$jobs[] | select(.name == "Render Sanitized Preview Artifact")] | length) == 1 - and any($jobs[]; .name == "Render Sanitized Preview Artifact" and .run_id == $id - and ((has("run_attempt") | not) or (.run_attempt | type == "number" and . == $attempt)) - and .head_sha == $head and .status == "completed" and .conclusion == "success" - and (.steps | type == "array") - and all(.steps[]; type == "object" and (.name | type == "string") - and (.status | type == "string") and (.conclusion | type == "string")) - and ([.steps[] | select(.name == "Upload sanitized render artifact")] | length) == 1 - and any(.steps[]; .name == "Upload sanitized render artifact" - and .status == "completed" and .conclusion == "success")) - ' <<<"$jobs" >/dev/null; then - return 2 - fi + preview_source_uploaded_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" return 3 @@ -583,6 +674,7 @@ automatic_preview_has_tuple() { any(.jobs[] | select(.name == "Preview Plan") | .steps[]; .name == $tuple) ' <<<"$jobs" >/dev/null || return 1 if jq -e '.status == "completed" and .conclusion == "success"' <<<"$latest" >/dev/null; then + preview_source_uploaded_render "$run_id" "$attempt" "$head" <<<"$jobs" >/dev/null || return 2 completed_preview_source_updated_at="$(jq -r '.updated_at // empty' <<<"$latest")" # The trusted consumer may be queued after the active-run inventory. # Defer one cycle after an exact successful source completion. @@ -1020,7 +1112,7 @@ dispatch_candidates() { repair_status="$repair_success" if repair_requested_tuple \ "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ - "$requested_base_sha" "$requested_head_sha" "$requested_merge_sha" "$requested_image_tag"; then + "$requested_base_sha" "$requested_head_sha" "$requested_merge_sha" "$requested_image_tag" "$namespace_uid"; then repair_status="$repair_success" else repair_status=$? @@ -1032,6 +1124,9 @@ dispatch_candidates() { "$repair_dispatch") namespace_exists=false ;; + "$repair_missing_proof") + # The exact same Namespace remains live and must keep its UID and budget fence. + ;; "$repair_abort") exit 1 ;; @@ -1226,6 +1321,8 @@ dispatch_candidates() { fi # A consumer may finish deployment and proof during the active-run lookup. local proof_retry_reservation_count="" + local proof_retry_reservation_id="" + local proof_retry_previous_reservation_id="" local proof_retry_previous_count="" local proof_retry_previous_base_sha="" local proof_retry_previous_head_sha="" @@ -1314,17 +1411,31 @@ candidate_rows="$( | sort -t $'\t' -k1,1n -k2,2n )" if [[ -n "$candidate_rows" ]]; then + if ! preview_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/preview.yml" | jq -er --arg name "$preview_workflow_name" ' + select(.name == $name and .path == ".github/workflows/preview.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 + exit 1 + fi + if ! consumer_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/hosted-identity-request.yml" | jq -er ' + select(.name == "Trusted Hosted Identity Request" and .path == ".github/workflows/hosted-identity-request.yml") + | .id | select(type == "number" and . > 0 and . == floor) + ')"; then + echo "Unable to establish canonical trusted preview consumer identity; refusing preview reconcile." >&2 + exit 1 + fi active_preview_run_sets=() for active_status in requested queued in_progress waiting pending; do for active_run_scope in branch pull_request pull_request_target workflow_run; do if [[ "$active_run_scope" == branch ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" + active_run_query="repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" active_run_branch_filtered=true elif [[ "$active_run_scope" == pull_request || "$active_run_scope" == pull_request_target ]]; then - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100" + active_run_query="repos/${GITHUB_REPOSITORY}/actions/workflows/${preview_workflow_id}/runs?event=${active_run_scope}&status=${active_status}&per_page=100" active_run_branch_filtered=false else - active_run_query="repos/${GITHUB_REPOSITORY}/actions/runs?event=workflow_run&status=${active_status}&per_page=100" + active_run_query="repos/${GITHUB_REPOSITORY}/actions/workflows/${consumer_workflow_id}/runs?event=workflow_run&status=${active_status}&per_page=100" active_run_branch_filtered=false fi if ! active_preview_run_pages_json="$(gh api --paginate --slurp "$active_run_query")"; then @@ -1334,9 +1445,17 @@ if [[ -n "$candidate_rows" ]]; then if ! active_preview_runs_for_query="$( jq -c \ --argjson branch_filtered "$active_run_branch_filtered" ' - if type != "array" then - error("workflow run pages are not an array") + if type != "array" or length == 0 then + error("workflow run pages are unavailable") else + .[0].total_count as $count + | if ($count | type) != "number" or $count < 0 or $count != ($count | floor) or $count >= 1000 + or any(.[]; type != "object" or (.workflow_runs | type) != "array" or .total_count != $count) + or ([.[].workflow_runs[]] | length) != $count + or ([.[].workflow_runs[].id] | unique | length) != $count then + error("active workflow run inventory is incomplete or saturated") + else . end + | [ .[] as $page | if ($page | type) != "object" or ($page.workflow_runs | type) != "array" then @@ -1389,20 +1508,6 @@ if [[ -n "$candidate_rows" ]]; then echo "Unable to merge active preview workflow runs; refusing preview reconcile." >&2 exit 1 fi - if ! preview_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/preview.yml" | jq -er --arg name "$preview_workflow_name" ' - select(.name == $name and .path == ".github/workflows/preview.yml") - | .id | select(type == "number" and . > 0 and . == floor) - ')"; then - echo "Unable to establish canonical Preview workflow identity; refusing preview reconcile." >&2 - exit 1 - fi - if ! consumer_workflow_id="$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/hosted-identity-request.yml" | jq -er ' - select(.name == "Trusted Hosted Identity Request" and .path == ".github/workflows/hosted-identity-request.yml") - | .id | select(type == "number" and . > 0 and . == floor) - ')"; then - echo "Unable to establish canonical trusted preview consumer identity; refusing preview reconcile." >&2 - exit 1 - fi dispatch_candidates <<<"$candidate_rows" fi if [[ "$dispatch_outcome_failed" == true ]]; then diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 4e979991c0..241f6ea9f5 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -645,6 +645,19 @@ while (( SECONDS < deadline )); do if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then if [[ "${wait_mode}" == "branch" ]] && ! verify_branch_publication "$run_id" "$run_state"; then printf 'Trusted branch runtime-image run %s has no verified promotion for %s yet.\n' "$run_id" "$image_tag" >&2 + # A successful no-op can never provide promotion proof for an obsolete + # target. Only a positive trusted ref read can end this wait early. + if current_branch_ref="$(fetch_alternate_run_metadata "$deadline" "repos/${GITHUB_REPOSITORY}/git/ref/heads/${branch_name}")" && + current_branch_sha="$(jq -ser --arg ref "refs/heads/${branch_name}" ' + select(length == 1) | .[0] | select(.ref == $ref) | .object.sha + | select(type == "string" and length == 40 and test("^[0-9a-fA-F]{40}$")) + | ascii_downcase + ' <<<"$current_branch_ref")" && + [[ "$current_branch_sha" =~ ^[0-9a-f]{40}$ && "$current_branch_sha" != "${head_sha,,}" ]]; then + printf 'Branch runtime-image target %s@%s is obsolete: current head is %s; refusing deployment without verified promotion.\n' \ + "$branch_name" "$head_sha" "$current_branch_sha" >&2 + exit 1 + fi sleep "${sleep_seconds}" continue fi diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index ffef54fc56..3d12de0b8e 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -46,6 +46,7 @@ const execute = new AsyncFunction("require", "github", "context", "core", comput for (const [entries, count, expected, drift, expectsPython = false, expectsDesignDocs = false] of [ [[{filename: "design/README.md"}], 1, true, undefined, false, true], [[{filename: "README.md"}], 1, true], + [[{filename: "AGENTS.md"}], 1, true], [[{filename: "README.md", status: "renamed", previous_filename: "design/guide.md"}], 1, true, undefined, false, true], [[{filename: "dev-tools/validation/check-flyway-versions.py"}], 1, true, undefined, true], [[{filename: "dev-tools/validation/gradle-run-supervisor.py"}], 1, false], diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 596e5eb0b2..90a1e5ae7f 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -6551,6 +6551,7 @@ if [[ "$1" == run && "$2" == download ]]; then previous="$argument" done [[ -n "$artifact_name" && -n "$artifact_directory" ]] + printf '%s\n' "$*" >>"${SOURCE_GH_LOG:?}" mkdir -p "$artifact_directory" case "${FAKE_ARTIFACT_FILES:-valid}" in valid|extra|missing-metadata) @@ -6646,6 +6647,7 @@ case "$resource" in printf '%s' '{"sha":"dddddddddddddddddddddddddddddddddddddddd","parents":[{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},{"sha":"cccccccccccccccccccccccccccccccccccccccc"}]}' ;; repos/example/FireMUD/actions/runs/42/artifacts\?per_page=100) + printf '%s\n' "$*" >>"${SOURCE_GH_LOG:?}" if [[ -n "${FAKE_ARTIFACTS_JSON:-}" ]]; then printf '%s' "$FAKE_ARTIFACTS_JSON" else @@ -6801,6 +6803,18 @@ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$qualified_source_run_json" \ run_deploy_target_fixture qualified-source-deploy 0 'action=deploy' grep -Fxq 'action=deploy' "$TEMP_DIR/deploy-target-qualified-source-deploy.output" grep -Fxq "artifact_name=${canonical_artifact_name}" "$TEMP_DIR/deploy-target-qualified-source-deploy.output" +for reference in develop refs/heads/develop; do + dispatch_run="$(jq -c --arg reference "$reference" ' + .event = "repository_dispatch" | .head_branch = "develop" | .path += ("@" + $reference) + | del(.pull_requests)' <<<"$valid_workflow_run_json")" + FAKE_FIXTURE_WORKFLOW_RUN_JSON="$dispatch_run" FAKE_METADATA_EVENT=repository_dispatch \ + FAKE_METADATA_ACTION=deploy run_deploy_target_fixture "dispatch-${reference##*/}-${#reference}" 0 'action=deploy' +done +foreign_dispatch_run="$(jq -c ' + .event = "repository_dispatch" | .head_branch = "develop" | .path += "@refs/heads/not-develop" + | del(.pull_requests)' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$foreign_dispatch_run" \ + run_deploy_target_fixture foreign-dispatch-path 1 'Unexpected source run path' cross_pr_qualified_source_run_json="$(jq -c ' .path += "@refs/pull/901/merge" | .pull_requests += [{number:901,head:{sha:.head_sha}}] ' <<<"$valid_workflow_run_json")" @@ -6884,6 +6898,21 @@ FAKE_FIXTURE_WORKFLOW_RUN_JSON="$association_head_only_json" \ run_deploy_target_fixture association-head-only 0 'Ignoring source run without a bound pull request association.' grep -Fxq "action=none" "$TEMP_DIR/deploy-target-association-head-only.output" +# Reach the final artifact binding guard: PR 901/D satisfies the initial run +# association check, but the bare-path run/callback head D cannot authorize PR 900/C. +final_run_head_mismatch_json="$(jq -c --arg sha "$distinct_source_sha" ' + .head_sha = $sha | .pull_requests = [{number:901,head:{sha:$sha}}] + .pull_requests +' <<<"$valid_workflow_run_json")" +FAKE_FIXTURE_WORKFLOW_RUN_JSON="$final_run_head_mismatch_json" \ +FAKE_FIXTURE_WORKFLOW_RUN_HEAD_SHA="$distinct_source_sha" \ + run_deploy_target_fixture final-run-head-mismatch 0 'Ignoring artifact not bound to the source run pull request and head.' +test "$(cat "$TEMP_DIR/deploy-target-final-run-head-mismatch.output")" = $'action=none\nretire_identity=false\ncleanup_state=none' +grep -Fxq 'api repos/example/FireMUD/actions/runs/42' \ + "$TEMP_DIR/deploy-target-final-run-head-mismatch.gh.log" +grep -Fxq 'api --paginate --slurp repos/example/FireMUD/actions/runs/42/artifacts?per_page=100' \ + "$TEMP_DIR/deploy-target-final-run-head-mismatch.gh.log" +grep -Fxq "run download 42 --repo example/FireMUD --name $canonical_artifact_name --dir $TEMP_DIR/deploy-target-final-run-head-mismatch-artifact" \ + "$TEMP_DIR/deploy-target-final-run-head-mismatch.gh.log" # Unrelated native associations do not erase the uniquely selected artifact target. for association_order in before after; do diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 95cf1272e2..04ba15909a 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -171,16 +171,16 @@ def effective_group(group, action, base_ref, workflow_name="Required Gate", *, p return re.sub(r"\$\{\{(.*?)\}\}", render, group) -def cross_workflow_group_collisions(rendered_groups): +def concurrency_group_collisions(rendered_groups): owners = {} collisions = [] - for workflow, action, group in rendered_groups: + for workflow, owner, group in rendered_groups: key = group.casefold() prior = owners.get(key) - if prior is not None and prior[0] != workflow: - collisions.append((prior, (workflow, action, group))) + if prior is not None and prior[:2] != (workflow, owner): + collisions.append((prior, (workflow, owner, group))) else: - owners[key] = (workflow, action, group) + owners[key] = (workflow, owner, group) return collisions @@ -403,36 +403,39 @@ for workflow, (workflow_name, *_rest) in gates.items(): prior_pr = pr_group_owners.setdefault(rendered.casefold(), pr_number) if prior_pr != pr_number: raise SystemExit(f"{workflow} PRs {prior_pr} and {pr_number} share concurrency group {rendered!r}") - rendered_substantive_groups.append((workflow, action, rendered)) + rendered_substantive_groups.append((workflow, ("pr", pr_number), rendered)) -collisions = cross_workflow_group_collisions(rendered_substantive_groups) -if collisions: - first, second = collisions[0] - raise SystemExit( - f"required workflows {first[0]} and {second[0]} share a substantive concurrency group " - f"for the same PR (case-insensitive): {first[2]!r} / {second[2]!r}" - ) for branch in ("main", "develop"): - push_groups = [] for workflow, data in workflow_data.items(): if "push" not in data["on"]: continue branches = (data["on"]["push"] or {}).get("branches") if branches is not None and branch not in branches: continue - push_groups.append(( + rendered_substantive_groups.append(( workflow, - "push", + ("push", branch), effective_group(data["concurrency"]["group"], None, None, data["name"], push_branch=branch), )) - collisions = cross_workflow_group_collisions(push_groups) - if collisions: - first, second = collisions[0] - raise SystemExit(f"{first[0]} and {second[0]} share a push concurrency group on {branch}: {first[2]!r}") -assert cross_workflow_group_collisions([ - ("validation.yml", "opened", "required-pr-42"), - ("smoke.yml", "edited", "REQUIRED-PR-42"), +collisions = concurrency_group_collisions(rendered_substantive_groups) +if collisions: + first, second = collisions[0] + raise SystemExit( + f"{first[0]} {first[1]} and {second[0]} {second[1]} share a substantive " + f"concurrency group (case-insensitive): {first[2]!r} / {second[2]!r}" + ) +assert concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("smoke.yml", ("pr", 42), "REQUIRED-PR-42"), ]), "the collision detector must model GitHub's case-insensitive group comparison" +assert concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("ci.yml", ("push", "develop"), "required-pr-42"), +]), "a push and PR in the same workflow cannot replace each other" +assert not concurrency_group_collisions([ + ("ci.yml", ("pr", 42), "required-pr-42"), + ("ci.yml", ("pr", 42), "REQUIRED-PR-42"), +]), "substantive events of the same PR may share its concurrency group" PY # shellcheck disable=SC2016 # Match the checked-in arithmetic assignment literally. @@ -787,11 +790,14 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal const finalAttemptError = kind.startsWith("optional-final-read-attempt-"); const duplicatePrimary = kind === "optional-final-read-duplicate"; const newerFailure = kind === "duplicate-after-newer-failure"; + const newerSuccessDuringAcceptance = kind.startsWith("duplicate-succeeds-during-acceptance"); const disappearingSnapshot = kind === "optional-final-read-incomplete-snapshot"; const badStatus = kind.endsWith("-forbidden") ? 403 : kind.endsWith("-missing") ? 404 : 503; - const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && badStatus === 503; + const primaryDisappears = kind === "optional-final-read-primary-disappears-missing"; + const primaryCanRecover = h0 && !cancelledPrimary && !cancelledWithReplacement && !primaryDisappears && + [404, 503].includes(badStatus); const primaryReady = () => (primaryCanRecover || newerFailure) && primaryInventoryReads > 1; - let alternativeJobsReads = 0, primaryInventoryReads = 0, lookupFailure; + let alternativeJobsReads = 0, primaryInventoryReads = 0, completedPrimaryJobReads = 0, lookupFailure; let pullRequestLookups = 0, acceptanceLookupArmed = false, acceptanceLookupAttempts = 0; const nextBase = "e".repeat(40), nextMerge = "f".repeat(40); const baseAdvanceRead = { @@ -799,8 +805,8 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal "trusted-current-base-advances-during-acceptance-attempt": 3, }[kind] ?? Infinity; const tupleAdvanced = () => currentRunReads >= baseAdvanceRead; - let rerunStartedDuringLatestIdentityRead = false; - const failures = [], refs = [], info = []; + let rerunStartedDuringLatestIdentityRead = false, rerunStartedDuringFinalTupleRead = false; + const failures = [], refs = [], info = [], warnings = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: liveFallback ? null : merge, payload: { repository: {default_branch: "develop"}, pull_request: {number: 42, head: {sha: head, repo: {full_name: repository}}, @@ -830,6 +836,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal if (kind === "pending-native-refresh-skipped") job.steps.push({name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}); 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.startsWith("sole-final-")) job.steps.push({name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}); const sourceMutations = { "wrong-repository": {repository: {full_name: "other/repo"}}, "wrong-workflow": {workflow_id: 8}, "wrong-path": {path: ".github/workflows/fake.yml"}, @@ -849,6 +856,9 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal if (kind === "trusted-current-base-attempt-advances" && currentRunReads >= 2) { rerunStartedDuringLatestIdentityRead = true; } + if (kind === "trusted-current-base-attempt-advances-during-final-tuple" && currentRunReads >= 3) { + rerunStartedDuringFinalTupleRead = true; + } return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: tupleAdvanced() ? nextBase : base}, merge_commit_sha: tupleAdvanced() ? nextMerge : merge}}; }}, git: {getRef: async () => ({data: {object: {sha: tupleAdvanced() ? nextBase : base}}})}, @@ -867,6 +877,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), getWorkflowRun: async ({run_id: runId}) => { if (runId === 43 && primaryReady()) return {data: exactPrimary}; + if (runId === 43 && newerSuccessDuringAcceptance) return {data: exactPrimary}; if (runId === 44 && cancelledWithReplacement) return {data: dispatchPrimary}; if (kind === "optional-final-acceptance-transient" && runId === 44) { return {data: {...source, id: 44, event: "repository_dispatch", head_sha: defaultSha, @@ -878,6 +889,9 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal throw Object.assign(new Error("final current-base workflow-run lookup unavailable"), {status: 503}); } currentRunReads += 1; + if (kind === "sole-final-attempt-missing") { + throw Object.assign(new Error("sole final attempt missing"), {status: 404}); + } if (finalAttemptError && currentRunReads >= 2) { throw Object.assign(new Error("alternative final workflow-run unavailable"), kind.endsWith("-network") ? {cause: {code: "ECONNRESET"}} : {status: badStatus}); @@ -886,7 +900,8 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal snapshotRerunVisible = kind === "incomplete-snapshot-superseded"; return {data: {...source, run_attempt: snapshotRerunVisible ? 2 : 1}}; } - const superseded = kind === "newer-attempt" || rerunStartedDuringLatestIdentityRead || (kind === "rerun-after-proof" && currentRunReads > 1); + const superseded = kind === "newer-attempt" || rerunStartedDuringLatestIdentityRead || + rerunStartedDuringFinalTupleRead || (kind === "rerun-after-proof" && currentRunReads > 1); return {data: {...source, run_attempt: superseded ? 2 : 1, status: superseded ? "in_progress" : "completed"}}; }, }, @@ -914,6 +929,13 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal }, paginate: async (method, input) => { 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"); + if (input.run_id === 43 && newerSuccessDuringAcceptance) { + completedPrimaryJobReads += 1; + assert.equal(input.attempt_number, exactPrimary.run_attempt); + return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, + {name: "Run credential-free full-stack smoke", status: "completed", + conclusion: kind.endsWith("-without-proof") ? "skipped" : "success"}]}]; + } if (input.run_id === 43 && primaryReady()) { assert.equal(input.attempt_number, exactPrimary.run_attempt); return [{...job, run_id: 43, head_sha: head, steps: [...job.steps, @@ -930,6 +952,9 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal {name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; } assert.equal(input.run_id, 42); + if (kind === "sole-final-jobs-missing") { + throw Object.assign(new Error("sole final jobs missing"), {status: 404}); + } if (h0 && ++alternativeJobsReads > (cancelledPrimary ? 0 : 2) && !finalAttemptError) { assert.equal(input.attempt_number, source.run_attempt); if (kind.endsWith("-malformed")) return null; @@ -974,6 +999,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal } if ((h0 || newerFailure) && input.event === "pull_request") { primaryInventoryReads += 1; + if (primaryDisappears && primaryInventoryReads > 1) { yield {data: []}; return; } const primary = {...exactPrimary, status: cancelledPrimary || cancelledWithReplacement || primaryReady() ? "completed" : "queued", conclusion: cancelledPrimary || cancelledWithReplacement ? "cancelled" : primaryReady() ? "success" : null}; if (newerFailure) { @@ -998,24 +1024,31 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal refreshInventoryReads += 1; const forbidden = kind.endsWith("-forbidden"); throw Object.assign(new Error(forbidden ? "optional inventory forbidden" : "optional inventory unavailable"), - {status: forbidden ? 403 : 503}); + {status: forbidden ? 403 : kind.endsWith("-missing") ? 404 : 503}); + } + if (kind === "duplicate-fails-during-acceptance" || newerSuccessDuringAcceptance) { + primaryInventoryReads += 1; + yield {data: [{...exactPrimary, status: primaryInventoryReads === 1 ? "queued" : "completed", + conclusion: primaryInventoryReads === 1 ? null : newerSuccessDuringAcceptance ? "success" : "failure"}, source]}; + return; } if (incompleteSnapshot) { yield {data: [{...source, run_attempt: snapshotRerunVisible ? 2 : 1}]}; return; } + if (kind === "duplicate-preceding-green") primaryInventoryReads += 1; yield {data: kind.startsWith("duplicate-") && !["duplicate-jobs", "duplicate-attempt-jobs"].includes(kind) ? [{...source, id: 43, created_at: "2026-09-01T00:00:01Z", status: "in_progress", conclusion: null}, source] : [source]}; }; const clock = {now: () => now, parse: Date.parse}; try { - await execute(github, context, {info: message => info.push(message), warning: () => {}, setFailed: message => failures.push(message)}, + await execute(github, context, {info: message => info.push(message), warning: message => warnings.push(message), setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); } catch (error) { if (!captureLookupFailure) throw error; lookupFailure = error; } - return {failures, refs, snapshots, info, refreshInventoryReads, alternativeJobsReads, primaryInventoryReads, - acceptanceLookupAttempts, lookupFailure}; + return {failures, refs, snapshots, info, warnings, refreshInventoryReads, alternativeJobsReads, primaryInventoryReads, + completedPrimaryJobReads, acceptanceLookupAttempts, rerunStartedDuringFinalTupleRead, lookupFailure}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -1033,14 +1066,15 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(!result.info.some(line => line.startsWith("Found runtime-images run 42 with status=")), `${kind} must not select the refresh`); } - for (const [kind, event, selectionMessage] of [ - ["optional-final-read-refresh", "repository_dispatch", "supersedes the pending native wait"], - ["optional-final-read-jobs-network", "repository_dispatch", "supersedes the pending native wait"], - ["optional-final-read-duplicate", "pull_request", "precedes the pending duplicate"], + for (const [kind, event, selectionMessage, expectedReads] of [ + ["optional-final-read-refresh", "repository_dispatch", "supersedes the pending native wait", 6], + ["optional-final-read-jobs-network", "repository_dispatch", "supersedes the pending native wait", 6], + ["optional-final-read-duplicate", "pull_request", "precedes the pending duplicate", 6], + ["optional-final-read-missing", "repository_dispatch", "supersedes the pending native wait", 3], ]) { const result = await scenario(kind, event); assert(result.info.some(line => line.includes(selectionMessage)), kind); - assert.equal(result.alternativeJobsReads, 6, kind); + assert.equal(result.alternativeJobsReads, expectedReads, kind); assert.equal(result.primaryInventoryReads, 2, kind); assert(result.info.some(line => line.includes("Found runtime-images run 43 with status=completed")), kind); assert.deepEqual(result.failures, [], kind); @@ -1048,7 +1082,6 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal for (const [kind, expectedReads, status] of [ ["optional-final-read-cancelled-primary", 4, 503], ["optional-final-read-forbidden", 3, 403], - ["optional-final-read-missing", 3, 404], ["optional-final-read-malformed", 3, undefined], ]) { const result = await scenario(kind, "repository_dispatch", true); @@ -1062,6 +1095,7 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(cancelledReplacement.info.some(line => line.includes("Found runtime-images run 44 with status=completed"))); assert.deepEqual(cancelledReplacement.failures, []); for (const kind of ["optional-final-read-attempt-transient", "optional-final-read-attempt-network", + "optional-final-read-attempt-missing", "optional-final-read-incomplete-snapshot"]) { const result = await scenario(kind, "repository_dispatch"); assert.equal(result.primaryInventoryReads, 2, `${kind} resumes the native producer`); @@ -1077,16 +1111,29 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(finalCurrentBaseRetry.info.some(line => line.includes("Found runtime-images run 44 with status=completed"))); assert.deepEqual(finalCurrentBaseRetry.failures, [], "the pending exact producer may pass after the final transient read recovers"); - for (const [kind, code] of [["optional-final-read-attempt-forbidden", 403], ["optional-final-read-attempt-missing", 404]]) { + for (const [kind, code] of [["optional-final-read-attempt-forbidden", 403]]) { const result = await scenario(kind, "repository_dispatch", true); assert.equal(result.lookupFailure?.status ?? result.lookupFailure?.cause?.status, code, kind); assert.equal(result.primaryInventoryReads, 1, kind); } + for (const kind of ["sole-final-jobs-missing", "sole-final-attempt-missing"]) { + const result = await scenario(kind, "pull_request", true); + assert.equal(result.lookupFailure?.status, 404, `${kind} cannot recover without a retained native primary`); + assert.equal(result.primaryInventoryReads, 0, kind); + } + const missingPrimary = await scenario("optional-final-read-primary-disappears-missing", "repository_dispatch"); + assert.equal(missingPrimary.alternativeJobsReads, 3, "optional 404 resumes selection without accepting missing evidence"); + assert.match(missingPrimary.failures[0], /Timed out waiting for the exact/, + "a disappearing native primary cannot turn a missing optional refresh into proof"); const unavailable = await scenario("pending-native-inventory-unavailable", "repository_dispatch"); assert(unavailable.refreshInventoryReads >= 4, "temporary inventory errors exhaust the normal retries"); assert(unavailable.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), "temporary inventory outage must leave the native run selected"); assert.equal(unavailable.failures.length, 1, "a native run that never finishes still fails the gate"); + const missingInventory = await scenario("pending-native-inventory-missing", "repository_dispatch"); + assert(missingInventory.info.some(line => line.startsWith("Found runtime-images run 43 with status=queued")), + "missing optional refresh inventory must retain the native wait"); + assert.equal(missingInventory.failures.length, 1, "missing optional inventory never supplies proof"); await assert.rejects(() => scenario("pending-native-inventory-forbidden", "repository_dispatch"), /inventory forbidden/); for (const kind of ["duplicate-missing-step", "duplicate-nonterminal-step"]) { assert.deepEqual((await scenario(kind)).failures, [], `${kind} preserves canonical fallback`); @@ -1095,6 +1142,21 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(precedingGreen.info.some(line => line.includes("verified completed exact runtime producer precedes the pending duplicate")), "a verified green as the latest completed attempt may satisfy a pending duplicate"); assert.deepEqual(precedingGreen.failures, []); + assert.equal(precedingGreen.primaryInventoryReads, 2, + "a genuinely pending duplicate permits older proof after exactly one fresh acceptance ordering read"); + const failedDuringAcceptance = await scenario("duplicate-fails-during-acceptance"); + assert.equal(failedDuringAcceptance.primaryInventoryReads, 3, + "one acceptance ordering read must force fresh selection after the newer candidate becomes terminal"); + assert(failedDuringAcceptance.warnings.some(line => line.includes("candidate ordering changed before accepting older success"))); + assert.match(failedDuringAcceptance.failures[0], /Runtime images run 43 did not complete successfully: run=failure/, + "an older green cannot bypass a newer exact failure that appeared during acceptance"); + for (const kind of ["duplicate-succeeds-during-acceptance", "duplicate-succeeds-during-acceptance-without-proof"]) { + const result = await scenario(kind); + assert.equal(result.primaryInventoryReads, 3, `${kind} requires fresh selection of the now-terminal primary`); + assert.equal(result.completedPrimaryJobReads, 1, `${kind} must inspect the newer producer's own exact jobs`); + assert.equal(result.failures.length, kind.endsWith("-without-proof") ? 1 : 0, + `${kind} cannot inherit the older producer's successful smoke evidence`); + } const newerFailure = await scenario("duplicate-after-newer-failure"); assert(newerFailure.info.some(line => line.includes("Found runtime-images run 43 with status=queued")), "the older green must not bypass the newer completed failure"); @@ -1122,6 +1184,14 @@ async function scenario(kind, event = "pull_request", captureLookupFailure = fal assert(rerunningFallback.info.some(line => line.includes("attempt changed after current-base identity validation")), "rerunning the producer during the live tuple lookup cannot accept the old attempt"); assert.equal(rerunningFallback.failures.length, 1, "no exact proof for the new attempt must not pass"); + const rerunningDuringFinalTuple = await scenario( + "trusted-current-base-attempt-advances-during-final-tuple", "repository_dispatch" + ); + assert.equal(rerunningDuringFinalTuple.rerunStartedDuringFinalTupleRead, true, + "the fixture must start the rerun during the last live tuple lookup, not an earlier fence"); + assert(rerunningDuringFinalTuple.info.some(line => line.includes("attempt changed during final live tuple validation"))); + assert.equal(rerunningDuringFinalTuple.failures.length, 1, + "the final tuple lookup cannot leave the previously successful attempt authoritative after a rerun"); const advancedFallback = await scenario("trusted-current-base-advances", "repository_dispatch"); assert(advancedFallback.info.some(line => line.includes("identity changed after the final runtime attempt lookup")), "late base movement cannot accept the old trusted refresh"); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index d2e002ca94..b73f254a72 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1883,7 +1883,7 @@ for job in prepare-runtime deploy-runtime destroy-runtime retire-identity; do assert_job_contains hosted-identity-request.yml "$job" 'self-hosted' assert_job_contains hosted-identity-request.yml "$job" 'environment: trusted-hosted-cluster' done -require_contains "$preview_reconciler_script" 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' +require_contains "$preview_reconciler_script" 'actions/workflows/${preview_workflow_id}/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' require_contains "$preview_reconciler_script" 'gh api --paginate --slurp' require_contains "$preview_reconciler_script" '.display_title == $run_name' require_contains "$preview_reconciler_script" '"Preview dispatch pr-${pr_number}-base-${base_sha}-head-${head_sha}-merge-${merge_sha}"' @@ -2927,8 +2927,13 @@ if BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT= echo "A typed native publisher title without its source run ID must not be accepted" >&2 exit 1 fi -require_contains "$contract_fixture_dir/typed-native-old.error" \ - 'Timed out waiting for trusted PR image publisher' +if ! grep -Eq '^(Timed out waiting for trusted PR image publisher|No trusted PR image publisher appeared)' \ + "$contract_fixture_dir/typed-native-old.error"; then + cat "$contract_fixture_dir/typed-native-old.output" >&2 + cat "$contract_fixture_dir/typed-native-old.error" >&2 + echo "Expected a refusal because no publisher proved the typed source run" >&2 + exit 1 +fi BASH_ENV="$contract_fixture_dir/publisher-clock.sh" CONTRACT_DUPLICATE_EVENT=typed \ CONTRACT_DUPLICATE_DIR="$contract_fixture_dir" \ @@ -3542,8 +3547,14 @@ async function choose(runs, verifiedId, smokeConclusion = "success") { assert.deepEqual(await choose([pending, older(3)], 3, "skipped"), {id: 10, lookedUp: [3]}); assert.deepEqual(await choose([pending, {...older(3), display_title: "wrong tuple"}], 3), {id: 10, lookedUp: []}); - assert.deepEqual(await choose([pending, older(4), older(3), older(2), older(1)], 1), - {id: 10, lookedUp: [4, 3, 2]}); + // Shuffle completed rows and put the newest pending run last. Creation time + // outranks even the largest ID; equal-time candidates retain descending IDs. + const boundedCandidates = [older(2), {...older(99), created_at: "2026-07-24T00:00:00Z"}, + older(3), older(4), pending]; + assert.deepEqual(await choose(boundedCandidates, 2), {id: 2, lookedUp: [4, 3, 2]}, + "completed fallback must select verified proof at the third lookup in native chronology order"); + assert.deepEqual(await choose(boundedCandidates, 99), {id: 10, lookedUp: [4, 3, 2]}, + "completed fallback must retain pending when verified proof lies beyond the three-candidate cap"); })().catch(error => { console.error(error); process.exitCode = 1; }); NODE_DUPLICATE_SMOKE diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 976dbb46a6..cb0d6a1266 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -1326,8 +1326,14 @@ PY cat > "$fixture_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail -[[ "${1:-}" == api ]] || exit 2 -printf '%s\n' "$HEAD_SHA" +[[ "$*" == "api repos/benhook1013/FireMUD/git/ref/heads/develop --jq .object.sha" ]] || exit 2 +current_sha="$HEAD_SHA" +if [[ "$RUNTIME_HEAD_MODE" == advance && -s "$RUNTIME_HEAD_READ_LOG" ]]; then + current_sha='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + : > "$RUNTIME_HEAD_MOVED_MARKER" +fi +printf '%s\n' "$current_sha" >> "$RUNTIME_HEAD_READ_LOG" +printf '%s\n' "$current_sha" EOF chmod +x "$fixture_dir/gh" cat > "$fixture_dir/curl" <<'EOF' @@ -1373,7 +1379,12 @@ PY exit 0 fi if [[ "${1:-}" == buildx && "${2:-}" == imagetools && "${3:-}" == create ]]; then + [[ $# -eq 6 && "$4" == --tag ]] || exit 2 printf '%s\n' "$*" >> "$RUNTIME_REGISTRY_MARKER" + if [[ -f "$RUNTIME_HEAD_MOVED_MARKER" && ( "$5" == *:develop || "$5" == *:latest ) ]]; then + echo "runtime fixture refused a mutable alias write after observed branch movement" >&2 + exit 99 + fi exit 0 fi echo "unexpected runtime docker command: $*" >&2 @@ -1390,18 +1401,50 @@ runtime_common_env=( GHCR_USERNAME='test-user' GHCR_TOKEN='test-token' RUNTIME_REGISTRY_MARKER="$fixture_dir/runtime-registry-marker" + RUNTIME_HEAD_READ_LOG="$fixture_dir/runtime-head-reads" + RUNTIME_HEAD_MOVED_MARKER="$fixture_dir/runtime-head-moved" PATH="$fixture_dir:$PATH" ) run_runtime() { - env "${runtime_common_env[@]}" RUNTIME_TARGET_MODE="$1" bash "$runtime_script" + : > "$fixture_dir/runtime-head-reads" + rm -f "$fixture_dir/runtime-head-moved" + env "${runtime_common_env[@]}" RUNTIME_TARGET_MODE="$1" RUNTIME_HEAD_MODE="${2:-unchanged}" bash "$runtime_script" } +# Unchanged A remains eligible for immutable A, develop and latest publication. rm -f "$fixture_dir/runtime-registry-marker" run_runtime missing if [[ "$(wc -l < "$fixture_dir/runtime-registry-marker")" -ne 33 ]]; then echo "runtime publisher did not create every explicitly absent alias" >&2 exit 1 fi +if grep -Fvxq "$head_sha" "$fixture_dir/runtime-head-reads"; then + echo "unchanged-A publication observed an unexpected branch head" >&2 + exit 1 +fi + +# Admit A at the first promotion read, allow its immutable tag, then observe B +# at the fence immediately before develop/latest. The sink logs even refused +# alias attempts, so its safety guard cannot hide a missing production fence. +rm -f "$fixture_dir/runtime-registry-marker" +movement_status=0 +run_runtime missing advance >"$fixture_dir/runtime-head-movement.output" \ + 2>"$fixture_dir/runtime-head-movement.error" || movement_status=$? +if [[ "$movement_status" -ne 1 || ! -f "$fixture_dir/runtime-head-moved" ]]; then + echo "runtime publisher did not reject observed A-to-B branch movement at its publication fence" >&2 + exit 1 +fi +grep -Fq "Refusing canonical runtime publication: develop moved from ${head_sha} to ${base_sha}." \ + "$fixture_dir/runtime-head-movement.error" +if [[ "$(cat "$fixture_dir/runtime-head-reads")" != "${head_sha}"$'\n'"${base_sha}" ]]; then + echo "runtime branch movement fixture must expose A first and B before mutable alias promotion" >&2 + exit 1 +fi +if [[ ! -f "$fixture_dir/runtime-registry-marker" || \ + "$(cat "$fixture_dir/runtime-registry-marker")" != "buildx imagetools create --tag ghcr.io/benhook1013/account-service:${head_sha} ghcr.io/benhook1013/account-service:candidate" ]]; then + echo "runtime publisher must permit only the immutable A tag before rejecting movement, never develop/latest after it" >&2 + exit 1 +fi rm -f "$fixture_dir/runtime-registry-marker" run_runtime matching diff --git a/dev-tools/tests/preview-merge-image-tag-contract.sh b/dev-tools/tests/preview-merge-image-tag-contract.sh index af752e384f..61ac116540 100644 --- a/dev-tools/tests/preview-merge-image-tag-contract.sh +++ b/dev-tools/tests/preview-merge-image-tag-contract.sh @@ -32,7 +32,23 @@ if [[ "$*" == *"/pulls/7" ]]; then exit 0 fi if [[ "$*" == *"/git/ref/heads/"* ]]; then - printf '%s' '{"ref":"refs/heads/'"${GH_BASE_REF:-develop}"'","object":{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}' + case "${GH_FIXTURE:-}" in + branch_runs|branch_unpromoted_current) + printf '{"ref":"refs/heads/develop","object":{"sha":"%s"}}' "$head_sha" + ;; + branch_ref_unavailable) + exit 1 + ;; + branch_ref_malformed) + printf '%s' '{"ref":"refs/heads/develop","object":{"sha":"not-a-commit-sha"}}' + ;; + branch_ref_wrong_branch) + printf '{"ref":"refs/heads/main","object":{"sha":"%s"}}' "$base_sha" + ;; + *) + printf '%s' '{"ref":"refs/heads/'"${GH_BASE_REF:-develop}"'","object":{"sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}' + ;; + esac exit 0 fi if [[ "$*" == *"/commits/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* ]]; then @@ -65,7 +81,7 @@ case "${GH_FIXTURE:-}" in empty) printf '%s' '[[]]' ;; - branch_runs|branch_obsolete) + branch_runs|branch_obsolete|branch_unpromoted_current|branch_ref_unavailable|branch_ref_malformed|branch_ref_wrong_branch) source="$(printf '{"id":103,"run_attempt":2,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/103","display_title":"Build Runtime Images trusted-branch branch-develop sha-%s","created_at":"2026-09-21T00:02:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$head_sha")" case "$*" in *actions/runs/103) @@ -73,7 +89,7 @@ case "${GH_FIXTURE:-}" in ;; *actions/runs/103/attempts/2/jobs?per_page=100) conclusion=success - [[ "$GH_FIXTURE" != branch_obsolete ]] || conclusion=skipped + [[ "$GH_FIXTURE" == branch_runs ]] || conclusion=skipped printf '{"total_count":1,"jobs":[{"run_id":103,"run_attempt":2,"name":"Promote Smoke-Tested Runtime Images","status":"completed","conclusion":"%s","steps":[{"name":"Promote smoke-tested service digests","status":"completed","conclusion":"%s"}]}]}' "$conclusion" "$conclusion" ;; *actions/workflows/runtime-images.yml/runs?*) @@ -175,6 +191,10 @@ if [[ "${0##*/}" == wait-for-runtime-images.sh ]]; then unset SECONDS SECONDS=0 sleep() { + if [[ "${GH_FIXTURE:-}" == branch_obsolete ]]; then + echo "obsolete branch waiter must refuse before sleeping" >&2 + exit 99 + fi SECONDS=$((SECONDS + 1)) } fi @@ -206,7 +226,8 @@ GH_FIXTURE=branch_runs \ HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ - timeout 15s bash "$WAITER" "$head_sha" >/dev/null + timeout 15s bash "$WAITER" "$head_sha" >"$TEMP_DIR/branch-success.out" +grep -Fq "Matching runtime-images workflow 103 succeeded for ${head_sha} after" "$TEMP_DIR/branch-success.out" branch_obsolete_status=0 branch_obsolete_output="$( @@ -218,7 +239,31 @@ if [[ "$branch_obsolete_status" != 1 ]]; then exit 1 fi grep -Fq 'Trusted branch runtime-image run 103 has no verified promotion' <<<"$branch_obsolete_output" -grep -Fq "Timed out waiting for runtime-images workflow for ${head_sha} after" <<<"$branch_obsolete_output" +grep -Fq "Branch runtime-image target develop@${head_sha} is obsolete: current head is ${base_sha}; refusing deployment without verified promotion." <<<"$branch_obsolete_output" +if grep -Fq 'Timed out waiting' <<<"$branch_obsolete_output"; then + echo "obsolete branch waiter exhausted its deadline instead of refusing immediately" >&2 + exit 1 +fi + +# Current, unavailable, malformed, or wrong-ref metadata cannot replace promotion +# proof or positively establish that the requested develop target is obsolete. +for branch_fixture in branch_unpromoted_current branch_ref_unavailable branch_ref_malformed branch_ref_wrong_branch; do + branch_ref_status=0 + branch_ref_output="$( + GH_FIXTURE="$branch_fixture" HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 15s bash "$WAITER" "$head_sha" 2>&1 + )" || branch_ref_status=$? + if [[ "$branch_ref_status" != 1 ]]; then + printf 'unpromoted branch waiter must refuse with status 1 for %s, got %s\n' "$branch_fixture" "$branch_ref_status" >&2 + exit 1 + fi + grep -Fq 'Trusted branch runtime-image run 103 has no verified promotion' <<<"$branch_ref_output" + grep -Fq "Timed out waiting for runtime-images workflow for ${head_sha} after" <<<"$branch_ref_output" + if grep -Fq 'is obsolete:' <<<"$branch_ref_output"; then + printf 'branch waiter inferred obsolescence from %s without a verified different develop head\n' "$branch_fixture" >&2 + exit 1 + fi +done if branch_timeout_output="$( GH_FIXTURE=branch_wrong \ diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index c9359286cc..2cbd3141aa 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -148,12 +148,20 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && exit 0 fi if [[ -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" ]]; then - if [[ "${FAKE_ANNOTATE_CONFIRMATION_ERROR:-false}" == true ]]; then + if [[ "${FAKE_ANNOTATE_CONFIRMATION_ERROR:-false}" == true || + "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == recheck-error ]]; then exit 1 fi - if [[ "${FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE:-false}" == true ]]; then + if [[ "${FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE:-false}" == true || + "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == disappeared ]]; then exit 0 fi + if [[ "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == recheck-malformed ]]; then + printf '%s' '{not-json' + exit 0 + fi + # Only the post-annotation snapshot receives these failure scenarios. + snapshot_failure_case="${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" rm -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" fi canonical_head() { @@ -198,8 +206,9 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && jq -cn \ --arg count "$snapshot_retry_count" --arg base "$snapshot_retry_base" \ --arg head "$snapshot_retry_head" --arg merge "$snapshot_retry_merge" \ - --arg image "$snapshot_retry_image" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"}' \ + --arg image "$snapshot_retry_image" --arg id "${FAKE_PR_901_PROOF_RETRY_RESERVATION_ID:-}" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"} + | if $id != "" then .id = $id else . end' \ > "$FAKE_PROOF_RETRY_STATE_MARKER" fi snapshot_retry_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" @@ -207,6 +216,7 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_retry_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" + snapshot_retry_id="$(jq -r '.id // ""' "$FAKE_PROOF_RETRY_STATE_MARKER")" snapshot_resource_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" if [[ "${FAKE_UNRELATED_NAMESPACE_UPDATE:-false}" == true && "$snapshot_resource_version" == rv-902 ]]; then jq -c '.resourceVersion = "rv-903"' "$FAKE_PROOF_RETRY_STATE_MARKER" \ @@ -215,6 +225,9 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && snapshot_resource_version=rv-903 fi proof_complete="${FAKE_PR_901_PROOF_COMPLETE:-true}" + if [[ "$count" -gt 1 && "${FAKE_PR_901_PROOF_REMOVED_ON_RECHECK:-false}" == true ]]; then + proof_complete=false + fi if [[ "${FAKE_PR_901_PROOF_COMPLETE_AFTER_CONSUMER_COMPLETION:-false}" == true && -f "${FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER:-}" ]]; then proof_complete=true @@ -251,9 +264,23 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && --arg retry_head "$snapshot_retry_head" \ --arg retry_merge "$snapshot_retry_merge" \ --arg retry_image "$snapshot_retry_image" \ + --arg retry_id "$snapshot_retry_id" \ + --arg retry_count_present "${FAKE_PR_901_PROOF_RETRY_COUNT+x}" \ + --arg failure_case "${snapshot_failure_case:-}" \ --arg uid "$snapshot_uid" \ --arg resource_version "$snapshot_resource_version" \ - '{metadata:{name:"pr-901",uid:$uid,resourceVersion:$resource_version,annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head,"firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image,"firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head,"firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image,"firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head,"firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image,"firemud.dev/proof-preview-namespace-uid":$proof_uid,"firemud.dev/proof-retry-count":$retry_count,"firemud.dev/proof-retry-base-sha":$retry_base,"firemud.dev/proof-retry-head-sha":$retry_head,"firemud.dev/proof-retry-merge-sha":$retry_merge,"firemud.dev/proof-retry-image-tag":$retry_image}}}' + '{metadata:{name:"pr-901",uid:$uid,resourceVersion:$resource_version,annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head,"firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image,"firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head,"firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image,"firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head,"firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image,"firemud.dev/proof-preview-namespace-uid":$proof_uid,"firemud.dev/proof-retry-count":$retry_count,"firemud.dev/proof-retry-base-sha":$retry_base,"firemud.dev/proof-retry-head-sha":$retry_head,"firemud.dev/proof-retry-merge-sha":$retry_merge,"firemud.dev/proof-retry-image-tag":$retry_image}}} + | if $retry_count == "" and $retry_count_present != "x" then + del(.metadata.annotations["firemud.dev/proof-retry-count"]) + else . end + | if $retry_id != "" then .metadata.annotations["firemud.dev/proof-retry-reservation-id"] = $retry_id else . end + | if $failure_case == "recreated" then .metadata.uid = "uid-replacement" + elif $failure_case == "different-namespace" then .metadata.name = "pr-902" + elif $failure_case == "missing-uid" then del(.metadata.uid) + elif $failure_case == "missing-rv" then del(.metadata.resourceVersion) + elif $failure_case == "deployed-changed" then + .metadata.annotations["firemud.dev/last-preview-merge-sha"] = "dddddddddddddddddddddddddddddddddddddddd" + else . end' | tee "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" exit 0 fi if [[ "$1" == get && "$2" == namespace && @@ -364,6 +391,17 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then exit 1 fi if [[ "${3:-}" == pr-901 && ( "$*" == *"firemud.dev/proof-retry-count="* || "$*" == *"firemud.dev/proof-retry-count-"* ) ]]; then + case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in + forbidden|stable-error|recheck-error|recheck-malformed|disappeared|recreated|different-namespace|missing-uid|missing-rv) + : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" + if [[ "$FAKE_PROOF_RETRY_ANNOTATE_FAILURE" == forbidden ]]; then + echo 'Error from server (Forbidden): namespaces "pr-901" is forbidden' >&2 + else + echo 'Unable to receive annotation response' >&2 + fi + exit 1 + ;; + esac if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then jq -cn \ --arg count "${FAKE_PR_901_PROOF_RETRY_COUNT:-}" \ @@ -371,7 +409,9 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then --arg head "${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" \ --arg merge "${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" \ --arg image "${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"}' \ + --arg id "${FAKE_PR_901_PROOF_RETRY_RESERVATION_ID:-}" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"} + | if $id != "" then .id = $id else . end' \ > "$FAKE_PROOF_RETRY_STATE_MARKER" fi state_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" @@ -383,6 +423,16 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then break fi done + if [[ "$expected_version" != rv-901 ]]; then + case "${FAKE_PROOF_RETRY_COMPENSATION_CASE:-}" in + cas-conflict) + jq -c '.resourceVersion = "rv-903"' "$FAKE_PROOF_RETRY_STATE_MARKER" > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" + mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" + exit 1 + ;; + write-error) exit 1 ;; + esac + fi if [[ "$state_version" != "$expected_version" ]]; then exit 1 fi @@ -391,6 +441,7 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then local_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" local_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" local_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" + local_id="$(jq -r '.id // ""' "$FAKE_PROOF_RETRY_STATE_MARKER")" for annotation in "$@"; do case "$annotation" in firemud.dev/proof-retry-count=*) local_count="${annotation#*=}" ;; @@ -403,9 +454,27 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then firemud.dev/proof-retry-merge-sha-) local_merge="" ;; firemud.dev/proof-retry-image-tag=*) local_image="${annotation#*=}" ;; firemud.dev/proof-retry-image-tag-) local_image="" ;; + firemud.dev/proof-retry-reservation-id=*) local_id="${annotation#*=}" ;; + firemud.dev/proof-retry-reservation-id-) local_id="" ;; esac done + # A competing same-tuple writer has a different ID. The other changed-field + # cases retain this caller's ID to prove that the complete fence is needed. + case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in + competitor-version) + local_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" + ;; + competitor-count) local_count=3 ;; + competitor-tuple) local_merge=ffffffffffffffffffffffffffffffffffffffff ;; + competitor-exact) + if [[ "${local_id:0:1}" == 0 ]]; then local_id="1${local_id:1}"; else local_id="0${local_id:1}"; fi + ;; + competitor-missing-id) local_id="" ;; + esac state_resource_version=rv-902 + if [[ "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == lost-response-unchanged-rv ]]; then + state_resource_version=rv-901 + fi if [[ "$expected_version" == rv-902 ]]; then state_resource_version=rv-903 : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" @@ -414,16 +483,48 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" fi jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ - --arg merge "$local_merge" --arg image "$local_image" --arg rv "$state_resource_version" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:$rv}' \ + --arg merge "$local_merge" --arg image "$local_image" --arg rv "$state_resource_version" --arg id "$local_id" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:$rv} + | if $id != "" then .id = $id else . end' \ > "$FAKE_PROOF_RETRY_STATE_MARKER" + case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in + lost-response|lost-response-unchanged-rv|competitor-exact|competitor-missing-id|competitor-version|competitor-count|competitor-tuple|deployed-changed) + if [[ "$expected_version" == rv-901 ]]; then + : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" + if [[ "$FAKE_PROOF_RETRY_ANNOTATE_FAILURE" == lost-response* ]]; then + echo 'Reservation committed but its response was lost' >&2 + else + echo 'Error from server (Conflict): a competing writer changed the namespace' >&2 + fi + exit 1 + fi + ;; + esac if [[ "$expected_version" == rv-901 ]]; then jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ - --arg merge "$local_merge" --arg image "$local_image" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image}' \ + --arg merge "$local_merge" --arg image "$local_image" --arg id "$local_id" \ + '{count:$count,base:$base,head:$head,merge:$merge,image:$image,id:$id}' \ > "${FAKE_PROOF_RETRY_RESERVATION_MARKER:?}" if [[ "$*" == *"-o json"* ]]; then - printf '%s' '{"metadata":{"uid":"uid-pr-901","resourceVersion":"rv-902"}}' + jq -c --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ + --arg merge "$local_merge" --arg image "$local_image" --arg id "$local_id" \ + --arg variant "${FAKE_PROOF_RETRY_RESPONSE_CASE:-}" ' + .metadata.resourceVersion = "rv-902" + | .metadata.annotations += {"firemud.dev/proof-retry-count":$count, + "firemud.dev/proof-retry-base-sha":$base,"firemud.dev/proof-retry-head-sha":$head, + "firemud.dev/proof-retry-merge-sha":$merge,"firemud.dev/proof-retry-image-tag":$image, + "firemud.dev/proof-retry-reservation-id":$id} + | if $variant == "missing-id" then del(.metadata.annotations["firemud.dev/proof-retry-reservation-id"]) + elif $variant == "different-id" then + .metadata.annotations["firemud.dev/proof-retry-reservation-id"] |= (if startswith("0") then "1" else "0" end) + .[1:] + elif $variant == "unchanged-rv" then .metadata.resourceVersion = "rv-901" + elif $variant == "wrong-uid" then .metadata.uid = "uid-other" + elif $variant == "wrong-deployed" then .metadata.annotations["firemud.dev/last-preview-head-sha"] = "dddddddddddddddddddddddddddddddddddddddd" + elif $variant == "wrong-count" then .metadata.annotations["firemud.dev/proof-retry-count"] = "3" + elif $variant == "wrong-tuple" then .metadata.annotations["firemud.dev/proof-retry-merge-sha"] = "dddddddddddddddddddddddddddddddddddddddd" + elif $variant == "malformed" then .metadata.annotations = [] + else . end + ' "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" fi fi fi @@ -579,12 +680,23 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/173 for arg in "$@"; do [[ "$arg" != created=* ]] || range="${arg#created=}" done + probe=false + if [[ "$*" == *"per_page=1 "* || "$*" == *"per_page=1" ]]; then + probe=true + if [[ -z "$range" || "$*" == *"--paginate"* || "$*" == *"--slurp"* ]]; then + echo "invalid completed partition probe: $*" >&2 + exit 1 + fi + elif [[ "$*" != *"per_page=100"* || "$*" != *"--paginate"* || "$*" != *"--slurp"* ]]; then + echo "completed partition inventory must paginate and slurp full pages: $*" >&2 + exit 1 + fi if [[ -z "$range" ]]; then printf '%s\n' '[{"total_count":1001,"workflow_runs":[]}]' exit 0 fi jq -c --arg after "${range%..*}" --arg before "${range#*..}" \ - --argjson probe "$( [[ "$*" == *"per_page=1 "* || "$*" == *"per_page=1" ]] && echo true || echo false )" \ + --argjson probe "$probe" \ --arg broken "${FAKE_BROKEN_COMPLETED_PARTITION:-false}" ' map(select(.created_at >= $after and .created_at <= $before)) as $rows | ($rows|length) as $count @@ -634,14 +746,14 @@ if [[ "$1" == api && "$resource" == 'repos/example/FireMUD/actions/workflows/357 fi exit 0 fi -if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == */actions/runs\?event=pull_request\&status=* || "$resource" == */actions/runs\?event=pull_request_target\&status=* || "$resource" == */actions/runs\?event=workflow_run\&status=*) ]]; then +if [[ "$1" == api && ("$resource" == */actions/workflows/173511323/runs\?branch=* || "$resource" == */actions/workflows/173511323/runs\?event=pull_request\&status=* || "$resource" == */actions/workflows/173511323/runs\?event=pull_request_target\&status=* || "$resource" == */actions/workflows/357129350/runs\?event=workflow_run\&status=*) ]]; then active_query_status="${resource##*&status=}" active_query_status="${active_query_status%%&*}" - if [[ "$resource" == */actions/runs\?branch=* ]]; then + if [[ "$resource" == */actions/workflows/173511323/runs\?branch=* ]]; then active_query_scope=branch - elif [[ "$resource" == */actions/runs\?event=pull_request\&status=* ]]; then + elif [[ "$resource" == */actions/workflows/173511323/runs\?event=pull_request\&status=* ]]; then active_query_scope=pull_request - elif [[ "$resource" == */actions/runs\?event=pull_request_target\&status=* ]]; then + elif [[ "$resource" == */actions/workflows/173511323/runs\?event=pull_request_target\&status=* ]]; then active_query_scope=pull_request_target else active_query_scope=workflow_run @@ -650,12 +762,14 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == exit 1 fi if [[ "${FAKE_ACTIVE_PREVIEW_RUNS_API_MALFORMED:-false}" == true ]]; then - printf '%s' '[{"workflow_runs":[{"id":"not-a-number"}]}]' + printf '%s' '[{"total_count":1,"workflow_runs":[{"id":"not-a-number"}]}]' + elif [[ -n "${FAKE_ACTIVE_INVENTORY_TOTAL:-}" ]]; then + printf '[{"total_count":%s,"workflow_runs":[]}]' "$FAKE_ACTIVE_INVENTORY_TOTAL" elif [[ -v FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON ]]; then jq -c \ --arg requested_status "$active_query_status" \ --arg requested_scope "$active_query_scope" \ - '[.[] | .workflow_runs = [.workflow_runs[] | select(.status == $requested_status) | select((.event // $requested_scope) == $requested_scope or ($requested_scope == "branch" and .event == "repository_dispatch"))]]' \ + '[.[] | .workflow_runs = [.workflow_runs[] | select(.status == $requested_status) | select((.event // $requested_scope) == $requested_scope or ($requested_scope == "branch" and .event == "repository_dispatch"))]] | (map(.workflow_runs | length) | add) as $count | map(.total_count = $count)' \ <<<"$FAKE_ACTIVE_PREVIEW_RUN_PAGES_JSON" else jq -cn \ @@ -667,7 +781,7 @@ if [[ "$1" == api && ("$resource" == */actions/runs\?branch=* || "$resource" == path:".github/workflows/preview.yml",name:.displayTitle,head_branch:"develop", head_sha:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", repository:{full_name:"example/FireMUD"},head_repository:{full_name:"example/FireMUD"}, - display_title:.displayTitle,status:.status}]}]' + display_title:.displayTitle,status:.status}]}] | map(.total_count = (.workflow_runs | length))' fi exit 0 fi @@ -711,6 +825,18 @@ if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9 fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then printf '%s\n' "$*" >> "$FAKE_DISPATCH_LOG" + if [[ -f "$FAKE_PROOF_RETRY_STATE_MARKER" ]]; then + case "${FAKE_PROOF_RETRY_COMPENSATION_CASE:-}" in + different-id|missing-id) + jq -c --arg variant "$FAKE_PROOF_RETRY_COMPENSATION_CASE" ' + .resourceVersion = "rv-903" + | if $variant == "missing-id" then del(.id) + else .id |= (if startswith("0") then "1" else "0" end) + .[1:] end + ' "$FAKE_PROOF_RETRY_STATE_MARKER" > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" + mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" + ;; + esac + fi if [[ "${FAKE_DISPATCH_MISSING_STATUS:-false}" == true ]]; then exit "${FAKE_DISPATCH_GH_EXIT_CODE:-1}" fi @@ -1247,6 +1373,7 @@ adversarial_labels_base64="$(printf '%s' '[{"name":"custom:label"},{"name":"quot invalid_json_labels_base64="$(printf '%s' '{invalid-json' | base64 | tr -d '\n')" reset_case() { + rm -f "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" "$FAKE_PROOF_RETRY_STATE_MARKER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_SLEEP_LOG" "$FAKE_NAMESPACE_LIST_CALLS" "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" export GITHUB_OUTPUT="$TEMP_DIR/output" export FAKE_TARGET_PRIORITY=true @@ -1304,6 +1431,8 @@ reset_case() { export FAKE_NAMESPACE_SNAPSHOT_PARSE_FAIL=false export FAKE_NAMESPACE_SNAPSHOT_RECHECK_PARSE_FAIL=false export FAKE_ANNOTATE_ERROR=false + unset FAKE_PROOF_RETRY_ANNOTATE_FAILURE FAKE_PROOF_RETRY_RESPONSE_CASE \ + FAKE_PROOF_RETRY_COMPENSATION_CASE FAKE_PR_901_PROOF_RETRY_RESERVATION_ID export FAKE_ANNOTATE_CONFIRMATION_ERROR=false export FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE=false export FAKE_DELETE_FAIL=false @@ -2744,6 +2873,7 @@ for repair_status_assignment in \ 'readonly repair_success=0' \ 'readonly repair_skip=10' \ 'readonly repair_dispatch=11' \ + 'readonly repair_missing_proof=12' \ 'readonly repair_abort=20'; do grep -Fq "$repair_status_assignment" "$RECONCILER_RUN" done @@ -2751,13 +2881,13 @@ done grep -Fq 'case "$repair_status" in' "$RECONCILER_RUN" grep -Fq -- 'gh api --paginate --slurp' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal workflow source expressions. -grep -Fq -- 'actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' "$RECONCILER_RUN" +grep -Fq -- 'actions/workflows/${preview_workflow_id}/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Event scopes include automatic renders and direct closed cleanup. grep -Fq -- 'for active_run_scope in branch pull_request pull_request_target workflow_run' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert literal workflow query variables. -grep -Fq -- 'actions/runs?event=${active_run_scope}&status=${active_status}&per_page=100' "$RECONCILER_RUN" +grep -Fq -- 'actions/workflows/${preview_workflow_id}/runs?event=${active_run_scope}&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert workflow_run consumers are included without a branch filter. -grep -Fq -- 'actions/runs?event=workflow_run&status=${active_status}&per_page=100' "$RECONCILER_RUN" +grep -Fq -- 'actions/workflows/${consumer_workflow_id}/runs?event=workflow_run&status=${active_status}&per_page=100' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert each supported active status is queried independently. grep -Fq -- 'for active_status in requested queued in_progress waiting pending; do' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the active-run lookup is fenced to the candidate dispatch title. @@ -2876,7 +3006,7 @@ grep -Fqx \ test -s "$FAKE_DISPATCH_LOG" # An automatic run must prove exactly this tuple in its current native attempt. -for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_success_old_tuple completed_noop completed_old_noop active_noop; do +for tuple_case in current qualified target old_merge missing ambiguous stale_attempt wrong_list_path wrong_latest_path wrong_list_id wrong_latest_repo jobs_unavailable latest_unavailable old_event_current_plan event_only latest_missing_head latest_missing_path jobs_incomplete jobs_malformed stale_attempt_old_tuple job_attempt_missing job_attempt_mismatch job_attempt_null completed_failed_plan completed_success completed_plan_only completed_missing_upload completed_success_old_tuple completed_noop completed_old_noop active_noop; do reset_case reconciler_pull_request_output="$TEMP_DIR/reconciler-pull-request-$tuple_case.out" tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" @@ -2895,7 +3025,12 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att elif $variant == "completed_noop" or $variant == "active_noop" then [step($tuple | sub("resolved"; "event")),step("Explain preview skip")] elif $variant == "completed_old_noop" then [step($old | sub("resolved"; "event")),step("Explain preview skip")] elif $variant == "old_event_current_plan" then [step($old | sub("resolved"; "event")),step($tuple)] - else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] | + else [step($tuple),step($tuple | sub("resolved"; "event"))] end)}] + + (if $variant == "completed_success" or $variant == "completed_missing_upload" then + [{name:"Render Sanitized Preview Artifact",run_id:5254,run_attempt:2,head_sha:$head, + status:"completed",conclusion:"success", + steps:(if $variant == "completed_success" then [step("Upload sanitized render artifact")] else [] end)}] + else [] end) | if $variant == "job_attempt_missing" then map(del(.run_attempt)) else . end | if $variant == "missing" then {jobs:[],total_count:0} elif $variant == "jobs_incomplete" then {jobs:.,total_count:2} @@ -2907,7 +3042,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att | if $variant == "latest_missing_head" then del(.head_sha) elif $variant == "latest_missing_path" then del(.path) elif $variant == "completed_failed_plan" then .status = "completed" | .conclusion = "failure" - elif $variant == "completed_success" or $variant == "completed_success_old_tuple" or $variant == "completed_noop" or $variant == "completed_old_noop" then .status = "completed" | .conclusion = "success" + elif $variant == "completed_success" or $variant == "completed_plan_only" or $variant == "completed_missing_upload" or $variant == "completed_success_old_tuple" or $variant == "completed_noop" or $variant == "completed_old_noop" then .status = "completed" | .conclusion = "success" else . end')" ( cd "$ROOT_DIR" @@ -2929,7 +3064,7 @@ for tuple_case in current qualified target old_merge missing ambiguous stale_att "$reconciler_pull_request_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" - elif [[ "$tuple_case" == target || "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null || "$tuple_case" == active_noop ]]; then + elif [[ "$tuple_case" == target || "$tuple_case" == missing || "$tuple_case" == ambiguous || "$tuple_case" == jobs_unavailable || "$tuple_case" == latest_unavailable || "$tuple_case" == event_only || "$tuple_case" == stale_attempt || "$tuple_case" == latest_missing_head || "$tuple_case" == latest_missing_path || "$tuple_case" == jobs_incomplete || "$tuple_case" == jobs_malformed || "$tuple_case" == stale_attempt_old_tuple || "$tuple_case" == job_attempt_mismatch || "$tuple_case" == job_attempt_null || "$tuple_case" == active_noop || "$tuple_case" == completed_plan_only || "$tuple_case" == completed_missing_upload ]]; then grep -Fqx \ "Skipping proof retry for PR #901: active preview tuple lookup unavailable; retry budget unchanged." \ "$reconciler_pull_request_output" @@ -2953,8 +3088,11 @@ make_recent_source_evidence() { local updated_at="$1" local tuple_name="Preview resolved tuple pr-901 base-${preview_base_sha} head-${preview_head_sha} merge-${preview_merge_sha}" FAKE_PREVIEW_PLAN_JOBS_JSON="$(jq -cn --arg tuple "$tuple_name" --arg head "$preview_head_sha" ' - {total_count:1,jobs:[{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head, - status:"completed",conclusion:"success",steps:[{name:$tuple,status:"completed",conclusion:"success"}]}]}')" + {total_count:2,jobs:[{name:"Preview Plan",run_id:5254,run_attempt:2,head_sha:$head, + status:"completed",conclusion:"success",steps:[{name:$tuple,status:"completed",conclusion:"success"}]}, + {name:"Render Sanitized Preview Artifact",run_id:5254,run_attempt:2,head_sha:$head, + status:"completed",conclusion:"success",steps:[{name:"Upload sanitized render artifact", + status:"completed",conclusion:"success"}]}]}')" export FAKE_PREVIEW_PLAN_JOBS_JSON FAKE_PREVIEW_SOURCE_LATEST_JSON="$(jq -cn --arg head "$preview_head_sha" --arg updated_at "$updated_at" ' {id:5254,run_attempt:2,head_sha:$head,event:"pull_request",workflow_id:173511323, @@ -3402,8 +3540,10 @@ grep -Fqx \ grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 +jq -e '.id | test("^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")' \ + "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null -for compensation_case in existing-tuple version-moved different-tuple; do +for compensation_case in existing-tuple version-moved different-tuple prior-id lost-response; do reset_case reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry-${compensation_case}.out" namespace_update=false @@ -3413,6 +3553,11 @@ previous_base="$preview_base_sha" previous_head="$preview_head_sha" previous_merge="$preview_merge_sha" previous_image="$preview_image_tag" +previous_id="" +reservation_failure="" +if [[ "$compensation_case" == lost-response ]]; then + reservation_failure=lost-response +fi expected_reservation_count=3 if [[ "$compensation_case" == version-moved ]]; then namespace_update=true @@ -3424,6 +3569,9 @@ elif [[ "$compensation_case" == different-tuple ]]; then previous_image=pr-merge-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee expected_reservation_count=1 fi +if [[ "$compensation_case" == prior-id || "$compensation_case" == different-tuple ]]; then + previous_id=11111111-1111-4111-8111-111111111111 +fi if ( cd "$ROOT_DIR" FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ @@ -3435,6 +3583,8 @@ if ( FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$previous_head" \ FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$previous_merge" \ FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$previous_image" \ + FAKE_PR_901_PROOF_RETRY_RESERVATION_ID="$previous_id" \ + FAKE_PROOF_RETRY_ANNOTATE_FAILURE="$reservation_failure" \ FAKE_DISPATCH_HTTP_STATUS=422 \ FAKE_UNRELATED_NAMESPACE_UPDATE="$namespace_update" \ PREVIEW_MAX_ACTIVE=2 \ @@ -3451,15 +3601,77 @@ grep -Fq -- "firemud.dev/proof-retry-count=${expected_reservation_count}" "$FAKE grep -Fq -- 'firemud.dev/proof-retry-count=2' "$FAKE_ANNOTATE_LOG" grep -Fq -- "--resource-version ${expected_resource_version}" "$FAKE_ANNOTATE_LOG" test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" -jq -e --arg expected_count "$expected_reservation_count" --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ - '.count == $expected_count and .base == $base and .head == $head and .merge == $merge and .image == $image' \ - "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null +if [[ "$compensation_case" == lost-response ]]; then + test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 4 + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 2 +else + jq -e --arg expected_count "$expected_reservation_count" --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == $expected_count and .base == $base and .head == $head and .merge == $merge and .image == $image' \ + "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null +fi jq -e --arg base "$previous_base" --arg head "$previous_head" --arg rv "$result_resource_version" \ - --arg merge "$previous_merge" --arg image "$previous_image" \ + --arg merge "$previous_merge" --arg image "$previous_image" --arg id "$previous_id" \ '.count == "2" and .base == $base and .head == $head and .merge == $merge - and .image == $image and .resourceVersion == $rv' \ + and .image == $image and .resourceVersion == $rv and (.id // "") == $id' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null +if [[ -n "$previous_id" ]]; then + grep -Fq -- "firemud.dev/proof-retry-reservation-id=${previous_id}" "$FAKE_ANNOTATE_LOG" +else + grep -Fq -- 'firemud.dev/proof-retry-reservation-id-' "$FAKE_ANNOTATE_LOG" +fi +done + +reset_case +no_prior_reservation_output="$TEMP_DIR/reconciler-rejected-first-reservation.out" +if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false FAKE_DISPATCH_HTTP_STATUS=422 \ + PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" +) > "$no_prior_reservation_output" 2>&1; then + echo "confirmed first-reservation rejection left the reconcile job successful" >&2 + exit 1 +fi +grep -Fq 'Released proof-retry reservation for PR #901' "$no_prior_reservation_output" +test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 +test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 2 +jq -e '.count == "" and .base == "" and .head == "" and .merge == "" and .image == "" and (has("id") | not)' \ "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null + +for compensation_failure in different-id missing-id cas-conflict write-error; do + reset_case + compensation_failure_output="$TEMP_DIR/reconciler-compensation-${compensation_failure}.out" + if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=1 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_PROOF_RETRY_COMPENSATION_CASE="$compensation_failure" \ + FAKE_DISPATCH_HTTP_STATUS=422 PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" + ) > "$compensation_failure_output" 2>&1; then + echo "failed compensation ${compensation_failure} left the reconcile job successful" >&2 + exit 1 + fi + grep -Fq 'The rejected dispatch could not be safely compensated; its proof-retry budget remains charged.' "$compensation_failure_output" + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" + expected_annotates=1 + if [[ "$compensation_failure" == cas-conflict || "$compensation_failure" == write-error ]]; then + expected_annotates=2 + fi + test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq "$expected_annotates" + jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ + '.count == "2" and .base == $base and .head == $head and .merge == $merge and .image == $image' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null done reset_case @@ -3492,6 +3704,8 @@ jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ and .image == $image and .resourceVersion == "rv-902"' \ "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" +jq -es '.[0].id != null and .[0].id == .[1].id' \ + "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null if grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG"; then echo "ambiguous dispatch outcome released a proof-retry reservation" >&2 exit 1 @@ -3611,6 +3825,7 @@ grep -Fq -- "firemud.dev/proof-retry-count=1" "$FAKE_ANNOTATE_LOG" grep -Fq -- "firemud.dev/proof-retry-base-sha=${preview_base_sha}" "$FAKE_ANNOTATE_LOG" grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" +for malformed_retry_count in 3 '' ' '; do reset_case reconciler_malformed_proof_retry_output="$TEMP_DIR/reconciler-malformed-proof-retry.out" ( @@ -3619,30 +3834,149 @@ reconciler_malformed_proof_retry_output="$TEMP_DIR/reconciler-malformed-proof-re FAKE_PR_901_HEAD=head-901 \ FAKE_PR_901_REQUESTED_HEAD=head-901 \ FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=3 \ + FAKE_PR_901_PROOF_RETRY_COUNT="$malformed_retry_count" \ PREVIEW_MAX_ACTIVE=2 \ bash "$RECONCILER_RUN" ) > "$reconciler_malformed_proof_retry_output" 2>&1 grep -Fq 'unable to parse namespace pr-901 snapshot' "$reconciler_malformed_proof_retry_output" test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" +test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 1 +done -reset_case -reconciler_resource_version_failure_output="$TEMP_DIR/reconciler-resource-version-failure.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_ANNOTATE_ERROR=true \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_resource_version_failure_output" 2>&1 -grep -Fq \ - 'Namespace pr-901 changed before proof retry evidence could be recorded' \ - "$reconciler_resource_version_failure_output" -test ! -e "$FAKE_DISPATCH_LOG" +# Every failed annotation gets one bounded reread and never another reservation +# CAS. Only a lost success with this caller's ID and the full fence may POST once. +for reservation_failure in forbidden stable-error recheck-error recheck-malformed \ + disappeared recreated different-namespace missing-uid missing-rv \ + competitor-version competitor-count competitor-tuple deployed-changed \ + lost-response lost-response-unchanged-rv competitor-exact competitor-missing-id; do + reset_case + reservation_failure_output="$TEMP_DIR/reconciler-reservation-${reservation_failure}.out" + expected_status=1 + expected_count=1 + expected_rv=rv-901 + expected_merge="$preview_merge_sha" + expected_dispatches=0 + expected_diagnostic='Unable to prove a Namespace change after proof-retry annotation failure' + case "$reservation_failure" in + recheck-error) + expected_diagnostic='Unable to recheck Namespace pr-901 after proof-retry annotation failure' + ;; + recheck-malformed) + expected_diagnostic='Unable to verify Namespace pr-901 after proof-retry annotation failure' + ;; + disappeared) + expected_status=0 + expected_diagnostic='Namespace pr-901 disappeared after proof-retry annotation failure' + ;; + recreated|different-namespace) + expected_status=0 + expected_diagnostic='Namespace identity changed after proof-retry annotation failure' + ;; + competitor-version|competitor-count|competitor-tuple|deployed-changed|competitor-exact|competitor-missing-id) + expected_status=0 + expected_rv=rv-902 + expected_count=2 + expected_diagnostic='competing Namespace resource version observed after proof-retry annotation failure' + case "$reservation_failure" in + competitor-version) expected_count=1 ;; + competitor-count) expected_count=3 ;; + competitor-tuple) expected_merge=ffffffffffffffffffffffffffffffffffffffff ;; + esac + ;; + lost-response) + expected_status=0 + expected_count=2 + expected_rv=rv-902 + expected_dispatches=1 + expected_diagnostic='Recorded proof retry 2/3 for PR #901' + ;; + lost-response-unchanged-rv) + expected_count=2 + ;; + esac + actual_status=0 + ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 \ + FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PR_901_PROOF_RETRY_COUNT=1 \ + FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ + FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ + FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ + FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ + FAKE_PROOF_RETRY_ANNOTATE_FAILURE="$reservation_failure" \ + FAKE_DISPATCH_HTTP_STATUS=204 \ + PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" + ) > "$reservation_failure_output" 2>&1 || actual_status=$? + if [[ "$actual_status" -ne "$expected_status" ]]; then + echo "reservation failure ${reservation_failure} returned ${actual_status}, expected ${expected_status}" >&2 + cat "$reservation_failure_output" >&2 + exit 1 + fi + grep -Fq "$expected_diagnostic" "$reservation_failure_output" + if [[ "$reservation_failure" == forbidden ]]; then + grep -Fq 'Error from server (Forbidden)' "$reservation_failure_output" + fi + if [[ "$expected_status" -eq 1 ]]; then + grep -Fq 'One or more preview inventory, capacity, or dispatch checks failed.' "$reservation_failure_output" + fi + test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 3 + test "$(grep -Fc -- '--request-timeout=10s' "$FAKE_NAMESPACE_SNAPSHOT_LOG")" -eq 1 + test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 1 + grep -Fq -- '--resource-version rv-901' "$FAKE_ANNOTATE_LOG" + if [[ "$expected_dispatches" -eq 1 ]]; then + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + else + test ! -e "$FAKE_DISPATCH_LOG" + fi + test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" + test ! -e "$FAKE_PROOF_RETRY_RESERVATION_MARKER" + attempted_id="$(grep -oE 'firemud[.]dev/proof-retry-reservation-id=[0-9a-f-]+' "$FAKE_ANNOTATE_LOG")" + attempted_id="${attempted_id#*=}" + [[ "$attempted_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]] + case "$reservation_failure" in + competitor-exact) + jq -e --arg id "$attempted_id" '.id != $id' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null + ;; + lost-response|lost-response-unchanged-rv|competitor-version|competitor-count|competitor-tuple|deployed-changed) + jq -e --arg id "$attempted_id" '.id == $id' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null + ;; + *) jq -e 'has("id") | not' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null ;; + esac + jq -e --arg count "$expected_count" --arg rv "$expected_rv" \ + --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ + --arg merge "$expected_merge" --arg image "$preview_image_tag" \ + '.count == $count and .resourceVersion == $rv and .base == $base + and .head == $head and .merge == $merge and .image == $image' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null +done + +for unsafe_response in missing-id different-id unchanged-rv wrong-uid wrong-deployed wrong-count wrong-tuple malformed; do + reset_case + unsafe_response_output="$TEMP_DIR/reconciler-reservation-response-${unsafe_response}.out" + if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false \ + FAKE_PROOF_RETRY_RESPONSE_CASE="$unsafe_response" \ + PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" + ) > "$unsafe_response_output" 2>&1; then + echo "unsafe reservation success response ${unsafe_response} was accepted" >&2 + exit 1 + fi + grep -Fq 'Unable to prove proof-retry reservation custody for PR #901 from the annotation response' "$unsafe_response_output" + test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 + test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 1 + test ! -e "$FAKE_DISPATCH_LOG" + test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" + jq -e '.count == "1" and .resourceVersion == "rv-902" and (.id | length) == 36' \ + "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null +done reset_case reconciler_paginated_active_output="$TEMP_DIR/reconciler-paginated-active.out" @@ -3700,6 +4034,23 @@ grep -Fqx \ "$reconciler_active_api_malformed_output" test ! -e "$FAKE_DISPATCH_LOG" +for active_inventory_total in 1 1000; do + reset_case + inventory_output="$TEMP_DIR/reconciler-active-inventory-$active_inventory_total.out" + if ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_NAMESPACE_ABSENT=true \ + FAKE_ACTIVE_INVENTORY_TOTAL="$active_inventory_total" \ + PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" + ) > "$inventory_output" 2>&1; then + echo "reconciler accepted an incomplete or saturated active inventory" >&2 + exit 1 + fi + grep -Fq 'active workflow run inventory is incomplete or saturated' "$inventory_output" + test ! -e "$FAKE_DISPATCH_LOG" +done + reset_case reconciler_stacked_output="$TEMP_DIR/reconciler-stacked.out" ( @@ -4053,6 +4404,20 @@ test ! -e "$FAKE_ANNOTATE_LOG" test ! -e "$FAKE_DISPATCH_LOG" test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 +reset_case +reconciler_recreated_output="$TEMP_DIR/reconciler-recreated-during-repair.out" +( + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD='' \ + FAKE_PR_901_NAMESPACE_UID=uid-observed FAKE_PR_901_RECHECK_NAMESPACE_UID=uid-recreated \ + FAKE_PR_901_PROOF_REMOVED_ON_RECHECK=true PREVIEW_MAX_ACTIVE=2 \ + bash "$RECONCILER_RUN" +) > "$reconciler_recreated_output" +grep -Fqx 'Skipping preview repair for PR #901: namespace UID changed during annotation repair check.' \ + "$reconciler_recreated_output" +test ! -e "$FAKE_ANNOTATE_LOG" +test ! -e "$FAKE_DISPATCH_LOG" + reset_case malformed_labels_base64="$(printf '%s' '{}' | base64 | tr -d '\n')" reconciler_malformed_output="$TEMP_DIR/reconciler-malformed.out" @@ -4584,7 +4949,7 @@ function_end = run.index("\n}\n\ncandidate_rows=", function_start) function_body = run[function_start:function_end] assert "gh api --paginate --slurp" not in function_body assert run.count( - "actions/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" + "actions/workflows/${preview_workflow_id}/runs?branch=${DEFAULT_BRANCH}&status=${active_status}&per_page=100" ) == 1 candidate_rows_start = run.index("candidate_rows=") active_runs_start = run.index("active_preview_run_sets=()", candidate_rows_start) diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index bf81c5d7d3..43d4ab57f1 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -508,8 +508,27 @@ def check_candidate_checkout(step: dict[str, Any]) -> None: raise AssertionError("preview candidate must check out the current repository") if options.get("ref") != "refs/pull/${{ needs.preview-plan.outputs.pr_number }}/merge" or options.get("path") != "candidate": raise AssertionError("preview render must isolate the exact PR merge ref under candidate/") + depth = options.get("fetch-depth") + if not re.fullmatch(r"0|[1-9][0-9]*", str(depth)) or int(depth) == 1: + raise AssertionError("preview candidate checkout must fetch depth 0 or an explicit integer at least 2 to verify ordered merge parents") check_candidate_checkout(render_checkouts[1]) +for depth in (0, 2, 3, "2"): + check_candidate_checkout({ + **render_checkouts[1], + "with": {**render_checkouts[1]["with"], "fetch-depth": depth}, + }) +for options in ( + {key: value for key, value in render_checkouts[1]["with"].items() if key != "fetch-depth"}, + {**render_checkouts[1]["with"], "fetch-depth": 1}, +): + try: + check_candidate_checkout({**render_checkouts[1], "with": options}) + except AssertionError as error: + if str(error) != "preview candidate checkout must fetch depth 0 or an explicit integer at least 2 to verify ordered merge parents": + raise + else: + raise AssertionError(f"shallow candidate checkout escaped ordered-parent checking: {options}") try: check_candidate_checkout({ **render_checkouts[1], diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index c9083133ce..8d8d3edd6f 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -54,14 +54,15 @@ function admissionFixture() { const run = runs.find(run => run.id === run_id); return {data: state.refreshProducer ? state.refreshProducer(run) : run}; }, - listWorkflowRuns: async ({workflow_id, status, event, page, created}) => { + listWorkflowRuns: async ({workflow_id, status, event, per_page, page, created}) => { assert.equal(workflow_id, 42); - assert.ok(page <= 3); - state.lookups.push({status, event, page, created}); + assert.equal(per_page, 100); + assert.ok(Number.isSafeInteger(page) && page > 0 && page <= 3); + state.lookups.push({status, event, per_page, page, created}); state.afterInventory?.(); const matching = runs.filter(run => (!status || run.status === status) && run.event === event && (!created || Date.parse(run.created_at) >= Date.parse(created.split('..')[0]))); - return {data: {workflow_runs: matching.slice((page - 1) * 100, page * 100), + return {data: {workflow_runs: matching.slice((page - 1) * per_page, page * per_page), total_count: matching.length}}; }, }, @@ -78,7 +79,9 @@ function admissionFixture() { }, createDispatchEvent: async payload => { sent.push(payload); - state.newRun = makeRun({id: state.nextId++}); + // Registration becomes visible after the fixture's first two-second wait. + state.newRun = makeRun({id: state.nextId++, created_at: state.dispatchCreatedAt ?? + new Date(Date.now() + 2000).toISOString()}); }, }, }}; @@ -216,40 +219,64 @@ test('admission suppresses only when the selected active producer still proves t f.runs.push(f.makeRun()); f.state.refreshProducer = run => ({...run, status: 'in_progress'}); assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); - assert.deepEqual(f.state.producerReads, [300]); + assert.deepEqual(f.state.producerReads, [300, 300]); assert.deepEqual(f.sent, []); }); test('a stale or unavailable selected producer leaves an exact refresh eligible', async () => { - for (const refreshProducer of [ + const invalidProducers = [ () => { throw Object.assign(new Error('missing run'), {status: 404}); }, () => null, run => ({...run, id: run.id + 1}), run => ({...run, run_attempt: run.run_attempt + 1}), + ...[undefined, null, 0, -1, '1'].map(run_attempt => run => ({...run, run_attempt})), run => ({...run, event: 'pull_request'}), run => ({...run, display_title: run.display_title.replace(A, E)}), + run => ({...run, head_sha: E}), + run => ({...run, created_at: new Date(Date.parse(run.created_at) + 1000).toISOString()}), run => ({...run, status: 'completed', conclusion: 'success'}), run => ({...run, status: 'completed', conclusion: 'failure'}), - ]) { - const f = admissionFixture(); - f.runs.push(f.makeRun()); - f.state.refreshProducer = refreshProducer; - assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); - assert.deepEqual(f.state.producerReads, [300]); - assert.equal(f.sent.length, 1); + run => ({...run, status: 'completed', conclusion: 'cancelled'}), + ]; + for (const afterFinalTuple of [false, true]) { + for (const refreshProducer of invalidProducers) { + const f = admissionFixture(); + f.runs.push(f.makeRun()); + f.state.refreshProducer = run => !afterFinalTuple || f.state.commitRefs.length >= 2 ? + refreshProducer(run) : run; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.deepEqual(f.state.producerReads, afterFinalTuple ? [300, 300] : [300]); + assert.deepEqual(f.state.commitRefs, afterFinalTuple ? [A, A, A] : [A, A]); + assert.equal(f.sent.length, 1); + } } }); -test('admission rereads the pinned comparison after the producer lookup before fallback', async () => { +test('a producer that completes while the final live tuple is pending cannot suppress repair', async () => { const f = admissionFixture(); f.runs.push(f.makeRun()); - f.state.refreshProducer = run => { - f.state.base = D; - return {...run, status: 'completed', conclusion: 'failure'}; - }; - assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); - assert.deepEqual(f.state.producerReads, [300]); - assert.deepEqual(f.sent, []); + f.state.pullObservations = [{}, {mergeable: null, merge_commit_sha: null}]; + f.state.afterWait = () => { f.runs[0] = {...f.runs[0], status: 'completed', conclusion: 'failure'}; }; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.deepEqual(f.state.producerReads, [300, 300]); + assert.deepEqual(f.state.commitRefs, [A, A, A]); + assert.deepEqual(f.state.waits, [2000, 2000]); + assert.equal(f.sent.length, 1); +}); + +test('admission rereads the pinned comparison after the producer lookup before fallback', async () => { + for (const afterFinalTuple of [false, true]) { + const f = admissionFixture(); + f.runs.push(f.makeRun()); + f.state.refreshProducer = run => { + if (afterFinalTuple && f.state.commitRefs.length < 2) return run; + f.state.base = D; + return {...run, status: 'completed', conclusion: 'failure'}; + }; + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); + assert.deepEqual(f.state.producerReads, afterFinalTuple ? [300, 300] : [300]); + assert.deepEqual(f.sent, []); + } }); test('an active run from a different repository cannot suppress the repair', async () => { @@ -267,7 +294,30 @@ test('indeterminate dispatch visibility does not silently consume a repair or ca assert.ok(f.warnings.length > 0); }); -test('both wake inputs are serialized by one exact tuple group on the default branch', () => { +test('unseen same-second activity is ambiguous dispatch attribution and never triggers a retry', async t => { + t.mock.method(Date, 'now', () => Date.parse('2026-11-22T12:00:00.750Z')); + for (const milliseconds of ['000', '749', '750', '999']) { + const f = admissionFixture(); + f.state.keepHidden = true; + const unseen = f.makeRun({created_at: `2026-11-22T12:00:00.${milliseconds}Z`}); + f.state.afterWait = () => { if (!f.runs.includes(unseen)) f.runs.push(unseen); }; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + assert.equal(f.sent.length, 1); + assert.equal(f.state.waits.length, 7); + assert.ok(f.warnings.some(warning => warning.includes('remained unconfirmed'))); + } +}); + +test('unseen exact activity in the next second can confirm bounded dispatch observation', async t => { + t.mock.method(Date, 'now', () => Date.parse('2026-11-22T12:00:00.750Z')); + const f = admissionFixture(); + f.state.dispatchCreatedAt = '2026-11-22T12:00:01Z'; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); + assert.equal(f.sent.length, 1); + assert.deepEqual(f.state.waits, [2000]); +}); + +test('both wake inputs retain intent in one non-replacing exact tuple queue on the default branch', () => { const admissionWorkflow = JSON.parse(execFileSync('python3', ['-c', 'import yaml,json,sys; print(json.dumps(yaml.load(open(sys.argv[1]), Loader=yaml.BaseLoader)))', path.join(root, '.github/workflows/admit-pr-runtime-refresh.yml')], {encoding: 'utf8'})); @@ -277,6 +327,7 @@ test('both wake inputs are serialized by one exact tuple group on the default br assert.deepEqual(job.concurrency, { group: 'admit-pr-runtime-refresh-${{ github.event.client_payload.pr_number }}-${{ github.event.client_payload.base_sha }}-${{ github.event.client_payload.head_sha }}-${{ github.event.client_payload.merge_sha }}', 'cancel-in-progress': 'false', + queue: 'max', }); assert.deepEqual(job.permissions, {actions: 'read', contents: 'write', 'pull-requests': 'read'}); assert.deepEqual(job.steps.find(step => step.uses.startsWith('actions/checkout@')).with, @@ -460,8 +511,12 @@ test('unexpected canonical image selection fails closed', async () => { test('qualified canonical workflow path remains eligible', async () => { const f = fixture(); f.run.path += '@refs/pull/7/merge'; assert.equal((await execute(f)).length, 1); +}); +test('a malformed qualified workflow path is refused before any commit lookup', async () => { + const f = fixture(); f.run.path = '.github/workflows/preview.yml@'; assert.deepEqual(await execute(f), []); + assert.deepEqual(f.mergeReads ?? [], []); }); test('observer callbacks cannot replace a different source run or attempt', () => { const group = workflow.jobs.refresh.concurrency.group; diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 659ab1b895..91eab5b7ca 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -733,6 +733,63 @@ async function assertSkippedRequiredGates() { github.paginate = originalPaginate; } } +async function assertDuplicateDeletionRecovery() { + const originalPaginate = github.paginate; + const originalIssues = github.rest.issues; + const comments = [ + {id: 2, user: {login: "github-actions[bot]"}, body: "### Static Analysis Summary\nold"}, + {id: 3, user: {login: "github-actions[bot]"}, body: "### Static Analysis Summary\nduplicate"}, + ]; + const writes = {updated: [], created: [], deleted: []}; + const deletionFailure = {status: 500}; + let failDeletion = true; + github.paginate = async (method, input) => method === commentsList + ? comments.map(comment => ({...comment})) : originalPaginate(method, input); + github.rest.issues = { + ...originalIssues, + updateComment: async input => { + writes.updated.push(input); + const comment = comments.find(({id}) => id === input.comment_id); + if (!comment) throw new Error("recovery must update the stored canonical comment"); + comment.body = input.body; + }, + createComment: async input => { + writes.created.push(input); + comments.push({id: 4, user: {login: "github-actions[bot]"}, body: input.body}); + }, + deleteComment: async ({comment_id}) => { + writes.deleted.push(comment_id); + if (failDeletion) throw deletionFailure; + const index = comments.findIndex(({id}) => id === comment_id); + if (index === -1) throw new Error("recovery must delete the stored duplicate"); + comments.splice(index, 1); + }, + }; + try { + let failed = false; + try { await run(github, context, core); } catch (error) { + if (error !== deletionFailure) throw error; + failed = true; + } + if (!failed || writes.updated.length !== 1 || writes.updated[0].comment_id !== 2 || + writes.created.length || writes.deleted.length !== 1 || writes.deleted[0] !== 3 || + comments.length !== 2 || comments[0].body !== writes.updated[0].body || + !comments[0].body.includes("checks failed")) { + throw new Error("duplicate deletion failure must propagate after persisting the canonical update"); + } + const publishedBody = comments[0].body; + failDeletion = false; + await run(github, context, core); + if (writes.updated.length !== 1 || writes.created.length || + writes.deleted.length !== 2 || writes.deleted[1] !== 3 || + comments.length !== 1 || comments[0].id !== 2 || comments[0].body !== publishedBody) { + throw new Error("later callback must finish duplicate deletion without republishing the canonical summary"); + } + } finally { + github.paginate = originalPaginate; + github.rest.issues = originalIssues; + } +} async function assertInterruptedRecovery() { const originalPaginate = github.paginate; const reset = () => { @@ -848,9 +905,10 @@ run(github, context, core).then(async () => { return run(github, context, core).then( () => { throw new Error("non-404 duplicate deletion errors must propagate"); }, async (error) => { - if (error?.status !== 500) throw error; - deleteStatus = null; - await assertCompletionOrders(); + if (error?.status !== 500) throw error; + deleteStatus = null; + await assertDuplicateDeletionRecovery(); + await assertCompletionOrders(); await assertProducerSelectionRace(); await assertExactBaseRef(); await assertSkippedRequiredGates(); diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 75fc7b43a0..937535872f 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -16,6 +16,7 @@ VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/(?:migration|recovery-control-migration)/") RECOVERY_MIGRATION_DIR = "/db/recovery-control-migration/" +PACKAGED_CONFIG_RE = re.compile(r"/src/main/resources/(?:config/)?application[^/]*\.(?:ya?ml|properties)$") RUNTIME_DEPENDENCY_RE = re.compile( r'(?:implementation|api|runtimeOnly)\s*\(\s*project\(\s*":([^\"]+)"' r'|dependencies\.add\(\s*"(?:implementation|api|runtimeOnly)"\s*,\s*project\.project\(\s*":([^\"]+)"' @@ -47,7 +48,7 @@ def relevant_path(path: str) -> bool: return bool(MIGRATION_PATH_RE.match(path)) or ( path.startswith("services/") and (path.endswith("/build.gradle.kts") - or re.search(r"/src/main/resources/(?:config/)?application[^/]*\.ya?ml$", path)) + or PACKAGED_CONFIG_RE.search(path)) ) or (path.startswith("buildSrc/") and path.endswith((".kt", ".kts"))) @@ -55,6 +56,8 @@ def current_snapshot(repo_root: Path) -> Snapshot: paths = [*repo_root.glob("services/*/build.gradle.kts"), *repo_root.glob("services/*/src/main/resources/application*.y*ml"), *repo_root.glob("services/*/src/main/resources/config/application*.y*ml"), + *repo_root.glob("services/*/src/main/resources/application*.properties"), + *repo_root.glob("services/*/src/main/resources/config/application*.properties"), *repo_root.glob("services/*/src/main/resources/db/migration/**/*"), *repo_root.glob("services/*/src/main/java/db/migration/**/*"), *repo_root.glob("services/*/src/main/resources/db/recovery-control-migration/**/*"), @@ -175,6 +178,11 @@ def flatten_properties( flatten_properties(child, (*prefix, *parts), properties, ambiguous) resource_root = f"services/{project}/src/main/resources" + # Properties and imported files can override the packaged YAML. This static + # check qualifies only the configuration sources it can evaluate completely. + properties_pattern = re.compile(rf"{re.escape(resource_root)}/(?:config/)?application(?:-[^/]+)?\.properties") + if any(properties_pattern.fullmatch(path) for path in snapshot): + return False # Config in the packaged config/ directory takes precedence over the root. # Within a location Spring Boot gives .yml precedence over .yaml. base_paths = [f"{directory}/application.{extension}" @@ -197,6 +205,10 @@ def flatten_properties( properties: dict[str, object] = {} ambiguous: set[str] = set() flatten_properties(document, (), properties, ambiguous) + if any(path == "spring.config.import" or + path.startswith(("spring.config.import.", "spring.config.import[")) + for path in properties): + return False enabled_path = "spring.flyway.enabled" locations_path = "spring.flyway.locations" guard_paths = { @@ -362,6 +374,14 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str recovery_settings = b"spring:\n flyway:\n locations: classpath:db/recovery-control-migration\n" recovery_history = {recovery + "V1__journal.sql": b"-- journal", recovery_config: recovery_settings} check("unchanged isolated recovery history", recovery_history, recovery_history, None) + check("packaged property override cannot qualify recovery history", { + **recovery_history, + recovery_config.removesuffix(".yml") + ".properties": b"spring.flyway.enabled=false\n", + }, recovery_history, "historical effective migration no longer applied") + check("unchecked packaged import cannot qualify recovery history", { + **recovery_history, + recovery_config: recovery_settings + b"spring.config.import: classpath:recovery-overrides.yml\n", + }, recovery_history, "historical effective migration no longer applied") yaml_config = recovery_config.removesuffix(".yml") + ".yaml" renamed_recovery_config = {recovery + "V1__journal.sql": b"-- journal", yaml_config: recovery_settings} check("equivalent application.yaml recovery history", renamed_recovery_config, recovery_history, None) diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index e575b41e13..61f94904ad 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -196,11 +196,12 @@ spec: - name: SERVICE_SCHEMA value: {{ default (replace "-" "_" $service.name) $service.schema | quote }} {{- with $.Values.previewStack.jvm }} + {{- if ne (empty .javaToolOptions) (empty .mallocArenaMax) }} + {{- fail "previewStack.jvm.javaToolOptions and mallocArenaMax must both be set or both be empty" }} + {{- end }} {{- if .javaToolOptions }} - name: JAVA_TOOL_OPTIONS value: {{ .javaToolOptions | quote }} - {{- end }} - {{- if .mallocArenaMax }} - name: MALLOC_ARENA_MAX value: {{ .mallocArenaMax | quote }} {{- end }} diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java index bcf748a8e5..36c6c6c853 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java @@ -1,11 +1,18 @@ package net.firedevops.firemud.recovery.config; +import java.net.URI; +import java.util.Map; +import java.util.Objects; import org.springframework.boot.EnvironmentPostProcessor; import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; -/** Rejects an implicit or multi-host recovery-control database endpoint before datasource setup. */ +/** + * Rejects implicit, malformed, or divergent recovery database endpoints before datasource setup. + */ public final class RecoveryControlDatabaseHostEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { public static final String HOST_PROPERTY = "FIREMUD_RECOVERY_CONTROL_DB_HOST"; @@ -15,10 +22,7 @@ public final class RecoveryControlDatabaseHostEnvironmentPostProcessor public void postProcessEnvironment( ConfigurableEnvironment environment, SpringApplication application) { String host = environment.getProperty(HOST_PROPERTY); - if (host == null - || host.isBlank() - || host.indexOf(',') >= 0 - || host.chars().anyMatch(Character::isWhitespace)) { + if (!isSingleHost(host)) { throw new IllegalStateException( HOST_PROPERTY + " must name the isolated recovery database using exactly one host"); } @@ -28,6 +32,77 @@ public void postProcessEnvironment( throw new IllegalStateException( PORT_PROPERTY + " must be a decimal port from 1 through 65535"); } + // Use Boot's relaxed binding, including environment-variable and command-line overrides. + // Validate rather than silently overriding an endpoint that would escape journal isolation. + try { + Binder binder = Binder.get(environment); + String url = "jdbc:postgresql://" + host + ":" + port + "/firemud_recovery_control"; + requireMatchingOverride(binder, "spring.datasource.url", url); + requireMatchingOverride(binder, "spring.datasource.hikari.jdbc-url", url); + String user = environment.getProperty("FIREMUD_RECOVERY_CONTROL_DB_USER"); + String password = environment.getProperty("FIREMUD_RECOVERY_CONTROL_DB_PASSWORD"); + requireMatchingOverride(binder, "spring.datasource.username", user); + requireMatchingOverride(binder, "spring.datasource.password", password); + requireMatchingOverride(binder, "spring.datasource.hikari.username", user); + requireMatchingOverride(binder, "spring.datasource.hikari.password", password); + requireMatchingOverride( + binder, "spring.datasource.type", "com.zaxxer.hikari.HikariDataSource"); + requireAbsent(binder, "spring.datasource.jndi-name"); + requireAbsent(binder, "spring.datasource.hikari.data-source-class-name"); + requireAbsent(binder, "spring.datasource.hikari.data-source-j-n-d-i"); + Map dataSourceProperties = + binder + .bind( + "spring.datasource.hikari.data-source-properties", + Bindable.mapOf(String.class, String.class)) + .orElse(Map.of()); + if (!dataSourceProperties.isEmpty()) { + throw new IllegalStateException("Recovery datasource driver overrides are unsupported"); + } + // Flyway must use the very same datasource, not create an independent connection endpoint. + requireAbsent(binder, "spring.flyway.url"); + requireAbsent(binder, "spring.flyway.user"); + requireAbsent(binder, "spring.flyway.password"); + } catch (RuntimeException invalidOverride) { + // Binding exceptions can carry URLs and passwords in both their message and cause. + throw new IllegalStateException( + "Recovery database overrides must retain the dedicated datasource and shared Flyway connection"); + } + } + + private static void requireMatchingOverride(Binder binder, String property, String expected) { + var value = binder.bind(property, String.class); + if (value.isBound() && !Objects.equals(value.get(), expected)) { + throw new IllegalStateException("Recovery datasource override differs"); + } + } + + private static void requireAbsent(Binder binder, String property) { + if (binder.bind(property, String.class).isBound()) { + throw new IllegalStateException("Separate recovery database endpoint is unsupported"); + } + } + + private static boolean isSingleHost(String host) { + if (host == null || host.isEmpty()) return false; + // JDBC interpolation requires brackets around IPv6. URI parsing validates the literal without + // performing DNS resolution; scoped/escaped addresses and URL components are not supported. + if (host.matches("\\[[0-9a-fA-F:.]+\\]")) { + try { + return URI.create("http://" + host).getHost() != null; + } catch (IllegalArgumentException invalidLiteral) { + return false; + } + } + if (host.matches("[0-9]+(?:\\.[0-9]+){3}")) { + for (String octet : host.split("\\.")) { + if (octet.length() > 3 || Integer.parseInt(octet) > 255) return false; + } + return true; + } + return host.length() <= 253 + && host.matches( + "[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\\.?"); } @Override diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java index 1d0fb4d2c2..3a06da648b 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseJournal.java @@ -30,6 +30,13 @@ Operation bindVerifiedEvidence( Optional findNextEffect(UUID operationId); + /** + * Uses a fresh attempt identity for each invocation, including retries after an uncertain claim + * outcome. An existing dispatched or ambiguous result is for exact owner readback, not permission + * to send again. Reuse is intentional only after a proven local NOT_DISPATCHED outcome; it + * creates a new dispatch ordinal. A durable owner rejection or closure permanently retires that + * identity. + */ OutboxEntry claimEffect(UUID operationId, UUID effectId, UUID attemptId, Instant now); /** False only for an exact dispatch superseded after definitive owner rejection or closure. */ diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java index 275db0b05c..f42b44a7e9 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodec.java @@ -15,6 +15,7 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.cfg.CoercionAction; import tools.jackson.databind.cfg.CoercionInputShape; +import tools.jackson.databind.cfg.EnumFeature; import tools.jackson.databind.type.LogicalType; /** Stable JSON and digest encoding for the operation-owned immutable tuples. */ @@ -28,6 +29,7 @@ public InitialGameplayReleaseTupleCodec(ObjectMapper objectMapper) { Objects.requireNonNull(objectMapper, "objectMapper must not be null") .rebuild() .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .enable(EnumFeature.FAIL_ON_NUMBERS_FOR_ENUMS) .disable(tools.jackson.databind.DeserializationFeature.ACCEPT_FLOAT_AS_INT) .withCoercionConfig( LogicalType.Integer, @@ -157,7 +159,11 @@ private boolean hasCanonicalJsonShape(JsonNode persisted, Object value) { InitialGameplayReleaseModel.EffectReadback readEffectReadback(String json) { try { - return objectMapper.readValue(json, InitialGameplayReleaseModel.EffectReadback.class); + var readback = objectMapper.readValue(json, InitialGameplayReleaseModel.EffectReadback.class); + if (readback == null) { + throw new IllegalStateException("Persisted initial gameplay release readback is null"); + } + return readback; } catch (JacksonException exception) { throw new IllegalStateException( "Unable to read persisted initial gameplay release effect readback", exception); diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java index 4990d7f34a..2126465014 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/journal/JooqInitialGameplayReleaseJournal.java @@ -27,7 +27,9 @@ import org.jooq.JSONB; import org.jooq.Record; import org.jooq.conf.Settings; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import org.springframework.dao.DuplicateKeyException; /** * PostgreSQL compare-and-set journal and transactional outbox for initial gameplay release only. @@ -58,31 +60,42 @@ public Operation create(Scope scope, UUID controllerIssuedLockIdentity) { JSONB scopePayload = JSONB.valueOf(tupleCodec.toJson(scope)); JSONB bindingPayload = JSONB.valueOf(tupleCodec.toJson(scope.peerStorageBinding())); Instant now = Instant.now(); - return dsl.transactionResult(configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute( - """ - INSERT INTO recovery_control.initial_gameplay_release_operation ( - operation_id, operation_kind, target_namespace, playable_state_namespace_id, - peer_storage_binding, scope_payload, evidence_ref, scope_digest, - maintenance_lock_identity, phase, revision, created_at, updated_at - ) VALUES (?, 'initial_gameplay_release', ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, 'collecting', 1, CAST(? AS timestamptz), CAST(? AS timestamptz)) - ON CONFLICT (operation_id) DO NOTHING - """, - scope.operationId(), - scope.targetNamespace(), - scope.playableStateNamespaceId(), - bindingPayload, - scopePayload, - scope.evidenceRef(), - scopeDigest, - controllerIssuedLockIdentity, - toOffsetDateTime(now), - toOffsetDateTime(now)); - Operation operation = selectOperation(tx, scope.operationId(), true); - requireSameScope(operation.scope(), scope, scopeDigest); - return operation; - }); + try { + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute( + """ + INSERT INTO recovery_control.initial_gameplay_release_operation ( + operation_id, operation_kind, target_namespace, playable_state_namespace_id, + peer_storage_binding, scope_payload, evidence_ref, scope_digest, + maintenance_lock_identity, phase, revision, created_at, updated_at + ) VALUES (?, 'initial_gameplay_release', ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, 'collecting', 1, CAST(? AS timestamptz), CAST(? AS timestamptz)) + ON CONFLICT (operation_id) DO NOTHING + """, + scope.operationId(), + scope.targetNamespace(), + scope.playableStateNamespaceId(), + bindingPayload, + scopePayload, + scope.evidenceRef(), + scopeDigest, + controllerIssuedLockIdentity, + toOffsetDateTime(now), + toOffsetDateTime(now)); + Operation operation = selectOperation(tx, scope.operationId(), true); + requireSameScope(operation.scope(), scope, scopeDigest); + return operation; + }); + } catch (DuplicateKeyException failure) { + // Auto-configured jOOQ may translate the same violation at the Spring boundary. + throw conflict("maintenance-lock identity is already bound"); + } catch (DataAccessException failure) { + if ("23505".equals(failure.sqlState())) { + // PostgreSQL's unique-key detail contains the credential. Never retain its cause. + throw conflict("maintenance-lock identity is already bound"); + } + throw failure; + } } @Override @@ -450,12 +463,14 @@ public Operation recordEffectReadback( if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT && readbackDigest.equals(storedDigest)) { requireValidExactStoredReadback(readback, stored, storedDigest, current); + requireRetainedClosureMatchesStoredReadback(tx, current, stored, storedDigest); requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } if (readback.state() == EffectReadbackState.PROVEN_NO_EFFECT && stored != null && sameRetainedOutcome(readback, stored, storedDigest)) { + requireRetainedClosureMatchesStoredReadback(tx, current, stored, storedDigest); requireTerminalReplayWithinAttempt(readback, stored, now); return operation; } @@ -925,6 +940,17 @@ private void requireValidExactStoredReadback( saved, current, current.effect().operationId(), current.effect().effectId()); } + private void requireRetainedClosureMatchesStoredReadback( + DSLContext tx, OutboxEntry current, Record stored, String storedDigest) { + EffectReadback retained = + findRetainedClosure(tx, current, current.lastAttemptId(), current.attemptCount()); + if (retained == null) { + throw conflict("durable owner closure has no retained attempt identity"); + } + // Compare the first durable receipt, not a replay's possibly newer observation time. + requireValidExactStoredReadback(retained, stored, storedDigest, current); + } + private void requireNonRegressingReadback( EffectReadback readback, Record stored, OutboxEntry current) { JSONB payload = stored.get("readback_payload", JSONB.class); diff --git a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java index 1524dda084..0fd7ec831d 100644 --- a/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java +++ b/services/recovery-controller-service/src/test/java/integration/net/firedevops/firemud/recovery/InitialGameplayReleaseJournalPostgresIntegrationTest.java @@ -279,7 +279,7 @@ static void setUp() throws Exception { .load(); assertThat(flyway.info().all()) .extracting(info -> info.getScript()) - .containsExactlyInAnyOrder( + .contains( "V1__initial_gameplay_release_journal.sql", "V2__retain_initial_gameplay_release_attempt_closure.sql"); flyway.migrate(); @@ -348,7 +348,7 @@ void packagedApplicationMigratesAndPersistsThroughTheInjectedJournal() throws Ex .fetch( "SELECT script FROM recovery_control.flyway_schema_history_recovery_control WHERE version IS NOT NULL AND success") .getValues(0, String.class)) - .containsExactlyInAnyOrder( + .contains( "V1__initial_gameplay_release_journal.sql", "V2__retain_initial_gameplay_release_attempt_closure.sql"); @@ -360,6 +360,13 @@ void packagedApplicationMigratesAndPersistsThroughTheInjectedJournal() throws Ex assertThat(created.phase()).isEqualTo(Phase.COLLECTING); assertThat(injected.find(requested.operationId())).contains(created); + Scope duplicateCredentialScope = scope(); + assertThatThrownBy(() -> injected.create(duplicateCredentialScope, lockIdentity)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessage("IDEMPOTENCY_CONFLICT: maintenance-lock identity is already bound") + .hasNoCause(); + assertThat(injected.find(duplicateCredentialScope.operationId())).isEmpty(); + assertThat(injected.create(requested, UUID.randomUUID())).isEqualTo(created); assertThat( packagedDsl .fetchSingle( @@ -408,6 +415,25 @@ void journalDoesNotLogControllerLockIdentityAtDebug() { } } + @Test + void duplicateMaintenanceCredentialRefusesWithoutExposingDatabaseDetailOrCause() { + Scope original = scope(); + UUID lockIdentity = UUID.randomUUID(); + Operation created = journal.create(original, lockIdentity); + Scope conflicting = scope(); + + assertThatThrownBy(() -> journal.create(conflicting, lockIdentity)) + .isInstanceOf(InitialGameplayReleaseConflictException.class) + .hasMessage("IDEMPOTENCY_CONFLICT: maintenance-lock identity is already bound") + .hasNoCause() + .hasNoSuppressedExceptions() + .satisfies( + failure -> assertThat(failure.toString()).doesNotContain(lockIdentity.toString())); + assertThat(journal.find(conflicting.operationId())).isEmpty(); + assertThat(journal.find(original.operationId())).contains(created); + assertThat(journal.create(original, UUID.randomUUID())).isEqualTo(created); + } + @Test void journalPersistsExactScopeEvidenceTransitionsAndOwnerReadbackGatedHandoff() { Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); @@ -762,6 +788,7 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { assertThat(journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(6))) .isEqualTo(authorized); String retained = storedOutbox(scope.operationId(), effectId); + String retainedClosure = storedClosure(dispatched); assertThat(journal.recordEffectReadback(dispatched, terminal, base.plusSeconds(7))) .isEqualTo(authorized); @@ -770,6 +797,7 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { dispatched, "LATE_TIMEOUT", base.plusSeconds(7))) .isTrue(); assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); + assertThat(storedClosure(dispatched)).isEqualTo(retainedClosure); assertThatThrownBy(() -> journal.recordAmbiguousEffectForDispatch( withAttempt(dispatched, UUID.randomUUID()), "WRONG_ATTEMPT", base.plusSeconds(7))) @@ -783,6 +811,8 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { base.plusSeconds(6)); assertThat(journal.recordEffectReadback(dispatched, observedAgain, base.plusSeconds(7))) .isEqualTo(authorized); + assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(retained); + assertThat(storedClosure(dispatched)).isEqualTo(retainedClosure); for (Instant invalid : List.of(base.plusSeconds(3), base.plusSeconds(8))) { EffectReadback invalidObservation = readbackFor( @@ -831,6 +861,106 @@ void definitiveAttemptClosureIsReplayableAndCannotBeOverwritten() { assertThat(storedOutbox(scope.operationId(), effectId)).isEqualTo(replacement); } + @Test + void noEffectReplayRequiresExactOriginalClosureHistory() { + for (String variant : + List.of( + "missing", + "ordinal", + "digest", + "attempt", + "receipt", + "observation", + "dispatch", + "outbox-observation")) { + clearJournal(); + Instant base = Instant.parse("2026-09-01T00:00:00Z"); + OutboxEntry dispatch = authorizedDispatch(base); + UUID operationId = dispatch.effect().operationId(); + UUID effectId = dispatch.effect().effectId(); + EffectReadback original = + readbackFor( + dispatch, + dispatch.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + "original-closure", + base.plusSeconds(5)); + Operation operation = journal.recordEffectReadback(dispatch, original, base.plusSeconds(7)); + if (variant.equals("missing")) { + dsl.execute( + "DELETE FROM recovery_control.initial_gameplay_release_attempt_closure WHERE outbox_id=?", + dispatch.outboxId()); + } else if (variant.equals("ordinal")) { + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_attempt_closure SET attempt_ordinal=2 WHERE outbox_id=?", + dispatch.outboxId()); + } else if (variant.equals("digest")) { + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_attempt_closure SET readback_digest=? WHERE outbox_id=?", + "c".repeat(64), + dispatch.outboxId()); + } else if (variant.equals("dispatch")) { + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_attempt_closure SET dispatched_at=CAST(? AS timestamptz) WHERE outbox_id=?", + base.plusSeconds(6).atOffset(ZoneOffset.UTC), + dispatch.outboxId()); + } else if (variant.equals("outbox-observation")) { + EffectReadback altered = + readbackFor( + dispatch, + dispatch.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + original.readbackIdentity(), + base.plusSeconds(6)); + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_outbox SET readback_payload=CAST(? AS jsonb), readback_digest=? WHERE outbox_id=?", + tupleCodec.toJson(altered), + tupleCodec.digest(altered), + dispatch.outboxId()); + } else { + EffectReadback altered = + readbackFor( + dispatch, + variant.equals("attempt") ? UUID.randomUUID() : dispatch.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + variant.equals("receipt") ? "conflicting-closure" : "original-closure", + variant.equals("observation") ? base.plusSeconds(6) : original.observedAt()); + dsl.execute( + "UPDATE recovery_control.initial_gameplay_release_attempt_closure SET readback_payload=CAST(? AS jsonb), readback_digest=? WHERE outbox_id=?", + tupleCodec.toJson(altered), + tupleCodec.digest(altered), + dispatch.outboxId()); + } + String outboxBefore = storedOutbox(operationId, effectId); + String closureBefore = variant.equals("missing") ? null : storedClosure(dispatch); + for (Instant observation : List.of(original.observedAt(), base.plusSeconds(6))) { + EffectReadback replay = + readbackFor( + dispatch, + dispatch.lastAttemptId(), + EffectReadbackState.PROVEN_NO_EFFECT, + original.readbackIdentity(), + observation); + assertThatThrownBy( + () -> journal.recordEffectReadback(dispatch, replay, base.plusSeconds(8))) + .as(variant + " closure history must refuse both exact and later-observation replay") + .isInstanceOf(InitialGameplayReleaseConflictException.class); + assertThat(storedOutbox(operationId, effectId)).isEqualTo(outboxBefore); + assertThat(journal.find(operationId)).contains(operation); + assertThat(journal.findEffect(operationId, EffectKind.COMMIT_OWNER_AUTHORIZED_HANDOFF)) + .isEmpty(); + if (closureBefore != null) { + assertThat(storedClosure(dispatch)).isEqualTo(closureBefore); + } else { + assertThat( + dsl.fetchCount( + DSL.table("recovery_control.initial_gameplay_release_attempt_closure"))) + .isZero(); + } + } + } + } + @Test void firstDurableClosureAfterDefinitiveRejectionIsRetainedAndFenced() { Instant base = Instant.now().truncatedTo(ChronoUnit.SECONDS).plusSeconds(60); @@ -1620,6 +1750,7 @@ void migrationPreservesPendingLegacyOutboxAndRefusesClaimedRows(boolean claimed) .table("flyway_schema_history_recovery_control") .placeholders(Map.of("serviceSchema", SCHEMA)) .locations("classpath:db/recovery-control-migration") + .target("2") .load(); if (claimed) { assertThatThrownBy(() -> upgrade.migrate()) @@ -1865,7 +1996,7 @@ private static OutboxEntry authorizedDispatch(EffectKind effectKind, Instant bas private static String storedClosure(OutboxEntry dispatch) { return java.util.Objects.requireNonNull( dsl.fetchOne( - "SELECT row_to_json(c)::text AS row_json" + "SELECT row_to_json(c)::text || ':' || c.xmin::text AS row_json" + " FROM recovery_control.initial_gameplay_release_attempt_closure c" + " WHERE outbox_id = ? AND attempt_id = ?", dispatch.outboxId(), @@ -1877,7 +2008,7 @@ private static String storedClosure(OutboxEntry dispatch) { private static String storedOutbox(UUID operationId, UUID effectId) { return java.util.Objects.requireNonNull( dsl.fetchOne( - "SELECT row_to_json(o)::text AS row_json FROM recovery_control.initial_gameplay_release_outbox o" + "SELECT row_to_json(o)::text || ':' || o.xmin::text AS row_json FROM recovery_control.initial_gameplay_release_outbox o" + " WHERE operation_id = ? AND effect_id = ?", operationId, effectId), diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java index 682bdf9581..a95dfb4dae 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessorTest.java @@ -3,10 +3,12 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.SpringApplication; +import org.springframework.core.env.SystemEnvironmentPropertySource; import org.springframework.mock.env.MockEnvironment; class RecoveryControlDatabaseHostEnvironmentPostProcessorTest { @@ -92,4 +94,155 @@ void acceptsAnExplicitRecoveryDatabasePort(String port) { assertThatCode(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) .doesNotThrowAnyException(); } + + @ParameterizedTest + @ValueSource( + strings = { + "localhost", + "127.0.0.1", + "10.2.3.4", + "[::1]", + "[2001:db8::1]", + "recovery-control", + "recovery-control.invalid." + }) + void acceptsOnlySupportedSingleHostForms(String host) { + var environment = + new MockEnvironment() + .withProperty(RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, host); + assertThatCode(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "host:5432", + "host/database", + "host?user=secret", + "host#fragment", + "user@host", + "host%2fother", + "jdbc:postgresql://host", + "//host", + "host\\other", + "host,other", + "host other", + "host\n", + "::1", + "[::1]:5432", + "[::gg]", + "[1:2:3]", + "[fe80::1%25eth0]", + "256.1.2.3", + "-host", + "host..invalid" + }) + void rejectsUrlComponentsAndMalformedHostLiterals(String host) { + var environment = + new MockEnvironment() + .withProperty(RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, host); + assertThatThrownBy( + () -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exactly one host") + .hasNoCause(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "spring.datasource.url", + "spring.datasource.hikari.jdbc-url", + "spring.datasource.username", + "spring.datasource.password", + "spring.datasource.hikari.username", + "spring.datasource.hikari.password", + "spring.datasource.jndi-name", + "spring.datasource.type", + "spring.datasource.hikari.data-source-class-name", + "spring.datasource.hikari.data-source-jndi", + "spring.datasource.hikari.data-source-properties.serverName", + "spring.flyway.url", + "spring.flyway.user", + "spring.flyway.password" + }) + void refusesDivergentDatasourceOrSeparateFlywayOverridesWithoutExposingValues(String property) { + var environment = fixtureEnvironment().withProperty(property, "override-secret"); + assertThatThrownBy( + () -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Recovery database overrides must retain the dedicated datasource and shared Flyway connection") + .hasNoCause(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "SPRING_DATASOURCE_URL", + "SPRING_DATASOURCE_HIKARI_JDBCURL", + "SPRING_DATASOURCE_PASSWORD", + "SPRING_DATASOURCE_HIKARI_DATASOURCECLASSNAME", + "SPRING_DATASOURCE_HIKARI_DATASOURCEPROPERTIES_SERVERNAME", + "SPRING_FLYWAY_URL", + "SPRING_FLYWAY_USER", + "SPRING_FLYWAY_PASSWORD" + }) + void refusesRelaxedEnvironmentOverridesBeforeDatasourceOrMigrationSetup(String property) { + var environment = fixtureEnvironment(); + environment + .getPropertySources() + .addFirst( + new SystemEnvironmentPropertySource( + "test-systemEnvironment", Map.of(property, "override-secret"))); + assertThatThrownBy( + () -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Recovery database overrides must retain the dedicated datasource and shared Flyway connection") + .hasNoCause(); + } + + @Test + void acceptsMatchingDatasourceOverridesAndKeepsLocalFixtureSettings() { + String url = "jdbc:postgresql://localhost:5544/firemud_recovery_control"; + var environment = + fixtureEnvironment() + .withProperty("FIREMUD_RECOVERY_CONTROL_DB_PORT", "5544") + .withProperty("spring.datasource.url", url) + .withProperty("spring.datasource.hikari.jdbc-url", url) + .withProperty("spring.datasource.username", "fixture-user") + .withProperty("spring.datasource.password", "fixture-password") + .withProperty("spring.datasource.hikari.username", "fixture-user") + .withProperty("spring.datasource.hikari.password", "fixture-password") + .withProperty("spring.datasource.type", "com.zaxxer.hikari.HikariDataSource") + .withProperty("spring.flyway.schemas", "recovery_control") + .withProperty("spring.flyway.default-schema", "recovery_control") + .withProperty("spring.flyway.table", "flyway_schema_history_recovery_control") + .withProperty("spring.flyway.locations", "classpath:db/recovery-control-migration"); + assertThatCode(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .doesNotThrowAnyException(); + } + + @Test + void refusesEvenAnIdenticalExplicitFlywayEndpoint() { + var environment = + fixtureEnvironment() + .withProperty( + "spring.flyway.url", "jdbc:postgresql://localhost:5432/firemud_recovery_control"); + assertThatThrownBy( + () -> postProcessor.postProcessEnvironment(environment, new SpringApplication())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("shared Flyway connection") + .hasNoCause(); + } + + private static MockEnvironment fixtureEnvironment() { + return new MockEnvironment() + .withProperty( + RecoveryControlDatabaseHostEnvironmentPostProcessor.HOST_PROPERTY, "localhost") + .withProperty("FIREMUD_RECOVERY_CONTROL_DB_USER", "fixture-user") + .withProperty("FIREMUD_RECOVERY_CONTROL_DB_PASSWORD", "fixture-password"); + } } diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodecTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodecTest.java new file mode 100644 index 0000000000..7744da987c --- /dev/null +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/journal/InitialGameplayReleaseTupleCodecTest.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.recovery.journal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectKind; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadback; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackAuthority; +import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.EffectReadbackState; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class InitialGameplayReleaseTupleCodecTest { + @ParameterizedTest + @ValueSource(strings = {"0", "0.0", "\"0\"", "true"}) + void persistedReadbackEnumsRequireTextualNames(String replacement) { + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); + for (EffectKind kind : EffectKind.values()) { + for (EffectReadbackState state : EffectReadbackState.values()) { + var original = + new EffectReadback( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 1, + kind, + "a".repeat(64), + "b".repeat(64), + state, + state == EffectReadbackState.PROVEN_NO_EFFECT + ? EffectReadbackAuthority.GAME_SESSION_DURABLE_CLOSED_ATTEMPT + : EffectReadbackAuthority.GAME_SESSION_DURABLE_CURRENT_STATE, + "owner-receipt", + Instant.EPOCH); + String json = codec.toJson(original); + assertThat(codec.readEffectReadback(json)).isEqualTo(original); + for (String field : List.of("effectKind", "state", "authority")) { + ObjectNode altered = (ObjectNode) mapper.readTree(json); + altered.set(field, mapper.readTree(replacement)); + String alteredJson = mapper.writeValueAsString(altered); + assertThatThrownBy(() -> codec.readEffectReadback(alteredJson)) + .as(field + " must retain its textual enum name") + .isInstanceOf(IllegalStateException.class); + } + } + } + } +} diff --git a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java index 9611ef0ab8..92b85dd2c7 100644 --- a/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java +++ b/services/recovery-controller-service/src/test/java/unit/net/firedevops/firemud/recovery/model/InitialGameplayReleaseModelTest.java @@ -24,6 +24,8 @@ import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterFenceProof; import net.firedevops.firemud.recovery.model.InitialGameplayReleaseModel.WriterInventory; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import tools.jackson.databind.json.JsonMapper; import tools.jackson.databind.node.ObjectNode; @@ -512,6 +514,34 @@ void persistedEvidenceRequiresAnIntegerOperationFence() { .isInstanceOf(IllegalStateException.class); } + @ParameterizedTest + @ValueSource(strings = {"0", "0.0", "\"0\"", "true"}) + void persistedEvidenceEnumsRequireNamesRatherThanOrdinals(String replacement) { + JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); + InitialGameplayReleaseTupleCodec codec = new InitialGameplayReleaseTupleCodec(mapper); + var original = evidence(scope(UUID.randomUUID())); + String json = codec.toJson(original); + assertThat(codec.readEvidence(json)).isEqualTo(original); + for (String pointer : + List.of( + "/migration/disposition", + "/writerFencing/legacyWriterDisposition", + "/writerFencing/writerAcknowledgements/0/disposition", + "/worldInitialization/ownerService", + "/worldInitialization/disposition", + "/entityInitialization/ownerService", + "/entityInitialization/disposition")) { + ObjectNode altered = (ObjectNode) mapper.readTree(json); + int fieldStart = pointer.lastIndexOf('/'); + ((ObjectNode) altered.at(pointer.substring(0, fieldStart))) + .set(pointer.substring(fieldStart + 1), mapper.readTree(replacement)); + String alteredJson = mapper.writeValueAsString(altered); + assertThatThrownBy(() -> codec.readEvidence(alteredJson)) + .as(pointer + " must retain its textual enum name") + .isInstanceOf(IllegalStateException.class); + } + } + @Test void persistedEvidenceRejectsNoncanonicalAndDuplicateNormalizedCapacityKeys() { JsonMapper mapper = JsonMapper.builder().findAndAddModules().build(); From 47e093b2fcd2423bf39d21e942dda55e79cb0415 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:55:35 +1300 Subject: [PATCH 104/199] Keep License permission proof aligned with native gates --- dev-tools/tests/test_license_workflow_enforcement.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/dev-tools/tests/test_license_workflow_enforcement.py b/dev-tools/tests/test_license_workflow_enforcement.py index b591f588c2..a719f74248 100644 --- a/dev-tools/tests/test_license_workflow_enforcement.py +++ b/dev-tools/tests/test_license_workflow_enforcement.py @@ -47,9 +47,7 @@ def test_candidate_jobs_cannot_write_to_pull_requests(self) -> None: self.assertEqual("read", permissions.get("pull-requests")) self.assertNotIn("write", permissions.values()) - reporting_permissions = self.jobs["license-gate"]["permissions"] - self.assertEqual("read", reporting_permissions.get("pull-requests")) - self.assertEqual("write", reporting_permissions.get("statuses")) + self.assertEqual({}, self.jobs["license-gate"]["permissions"]) def test_both_scans_use_the_actions_supported_violation_gate(self) -> None: for job_name in ("ort-gradle", "ort-npm"): From 2aedf1de510a336a48845d091016f9c362a3014f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:39:12 +1300 Subject: [PATCH 105/199] Require exact native image publication and promotion proof --- .../hosted/shared/wait-for-runtime-images.sh | 52 ++++++-- .../tests/preview-merge-image-tag-contract.sh | 125 +++++++++++++++++- 2 files changed, 160 insertions(+), 17 deletions(-) diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 241f6ea9f5..f2c4e8fbe3 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -90,14 +90,9 @@ if any(not isinstance(run, dict) for run in workflow_runs): def is_matching_run(run): if wait_mode == "branch": - display_title = run.get("display_title", "") - tokens = display_title.split() return ( run.get("event") == "workflow_run" - and display_title.startswith("Build Runtime Images trusted-branch ") - and "branch-develop" in tokens - and f"sha-{head_sha}" in tokens - and len(tokens) == 6 + and run.get("display_title") == f"Build Runtime Images trusted-branch branch-develop sha-{head_sha}" ) # A base refresh is dispatched as the typed pr-runtime-base-refresh event; @@ -412,6 +407,7 @@ use_completed_duplicate_publication() { ($jobs | length) == 1 and ($jobs[0] | .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and .status == "completed" and .conclusion == "success" and + (.steps | type == "array") and ([.steps[] | select(.name == "Publish fixed PR image tags")] as $steps | ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) ' <<<"$jobs" >/dev/null || continue @@ -463,19 +459,27 @@ branch_publication_attempt() { verify_branch_publication() { local run_id="$1" selected_state="$2" endpoint run attempt jobs latest + local promotion_conclusion="${3:-success}" endpoint="repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}" run="$(fetch_alternate_run_metadata "$deadline" "$endpoint")" || return 1 [[ "$(jq -c '{workflow_runs:[.]}' <<<"$run" | read_run_state)" == "$selected_state" ]] || return 1 attempt="$(branch_publication_attempt "$run_id" <<<"$run")" || return 1 jobs="$(fetch_alternate_run_metadata "$deadline" "${endpoint}/attempts/${attempt}/jobs?per_page=100")" || return 1 - jq -e --argjson id "$run_id" --argjson attempt "$attempt" ' + jq -e --argjson id "$run_id" --argjson attempt "$attempt" --arg conclusion "$promotion_conclusion" ' (.jobs | type == "array") and (.total_count == (.jobs | length)) and ([.jobs[] | select(.name == "Promote Smoke-Tested Runtime Images")] as $jobs | ($jobs | length) == 1 and ($jobs[0] | .run_id == $id and ((has("run_attempt") | not) or .run_attempt == $attempt) and - .status == "completed" and .conclusion == "success" and - ([.steps[] | select(.name == "Promote smoke-tested service digests")] as $steps | - ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success"))) + .status == "completed" and .conclusion == $conclusion and + (if $conclusion == "skipped" then + # A wholly skipped native promotion job is positive no-op evidence, + # not a missing, failed, or partially executed promotion step. + (.steps == null or .steps == []) + else + (.steps | type == "array") and + ([.steps[] | select(.name == "Promote smoke-tested service digests")] as $steps | + ($steps | length) == 1 and $steps[0].status == "completed" and $steps[0].conclusion == "success") + end))) ' <<<"$jobs" >/dev/null || return 1 latest="$(fetch_alternate_run_metadata "$deadline" "$endpoint")" || return 1 [[ "$(branch_publication_attempt "$run_id" <<<"$latest")" == "$attempt" && @@ -483,6 +487,28 @@ verify_branch_publication() { (( SECONDS < deadline )) } +find_earlier_branch_publication() { + local selected_id="$1" selected_state="$2" inventory="$3" + local candidates candidate state candidate_id status conclusion + # Only an authoritatively skipped exact current attempt may be bypassed. + # Keep failures and unavailable or ambiguous proof as barriers to fallback. + verify_branch_publication "$selected_id" "$selected_state" skipped || return 1 + candidates="$(read_run_state "" alternates <<<"$inventory")" || return 1 + while IFS= read -r candidate; do + (( SECONDS < deadline )) || break + IFS=$'\t' read -r state candidate_id status conclusion _ <<<"$candidate" + [[ "$candidate_id" != "$selected_id" ]] || continue + [[ "$state" == "found" && "$status" == "completed" && "$conclusion" == "success" ]] || return 1 + if verify_branch_publication "$candidate_id" "$candidate"; then + printf 'Earlier trusted branch runtime-image run %s has verified promotion for %s after a newer skipped promotion.\n' \ + "$candidate_id" "$image_tag" + return 0 + fi + verify_branch_publication "$candidate_id" "$candidate" skipped || return 1 + done <<<"$candidates" + return 1 +} + wait_for_pr_publisher() { local source_state="$1" local alternate_sources="$2" @@ -644,9 +670,13 @@ while (( SECONDS < deadline )); do if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then if [[ "${wait_mode}" == "branch" ]] && ! verify_branch_publication "$run_id" "$run_state"; then + if find_earlier_branch_publication "$run_id" "$run_state" "$workflow_payload"; then + exit 0 + fi printf 'Trusted branch runtime-image run %s has no verified promotion for %s yet.\n' "$run_id" "$image_tag" >&2 # A successful no-op can never provide promotion proof for an obsolete - # target. Only a positive trusted ref read can end this wait early. + # target. Without promotion proof, only a positive trusted ref read can + # end this wait early. if current_branch_ref="$(fetch_alternate_run_metadata "$deadline" "repos/${GITHUB_REPOSITORY}/git/ref/heads/${branch_name}")" && current_branch_sha="$(jq -ser --arg ref "refs/heads/${branch_name}" ' select(length == 1) | .[0] | select(.ref == $ref) | .object.sha diff --git a/dev-tools/tests/preview-merge-image-tag-contract.sh b/dev-tools/tests/preview-merge-image-tag-contract.sh index 61ac116540..828d84b8f7 100644 --- a/dev-tools/tests/preview-merge-image-tag-contract.sh +++ b/dev-tools/tests/preview-merge-image-tag-contract.sh @@ -33,7 +33,7 @@ if [[ "$*" == *"/pulls/7" ]]; then fi if [[ "$*" == *"/git/ref/heads/"* ]]; then case "${GH_FIXTURE:-}" in - branch_runs|branch_unpromoted_current) + branch_runs|branch_unpromoted_current|branch_newer_noop|branch_newer_failed|branch_newer_ambiguous|branch_older_mismatch|branch_older_unproved) printf '{"ref":"refs/heads/develop","object":{"sha":"%s"}}' "$head_sha" ;; branch_ref_unavailable) @@ -102,16 +102,61 @@ case "${GH_FIXTURE:-}" in esac ;; branch_wrong) - printf '[{"workflow_runs":[{"id":104,"status":"completed","conclusion":"success","event":"workflow_run","head_sha":"dddddddddddddddddddddddddddddddddddddd","html_url":"https://example.test/runtime/104","display_title":"Build Runtime Images trusted-branch branch-main sha-%s","created_at":"2026-09-21T00:02:00Z"}]}]' "$head_sha" + printf '[{"workflow_runs":[{"id":104,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/104","display_title":"Build Runtime Images trusted-branch branch-main sha-%s","created_at":"2026-09-21T00:02:00Z"},{"id":105,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/105","display_title":"Build Runtime Images trusted-branch sha-%s branch-develop","created_at":"2026-09-21T00:03:00Z"}]}]' "$head_sha" "$head_sha" ;; - success_runs|wrong_runs) + branch_newer_noop|branch_newer_failed|branch_newer_ambiguous|branch_older_mismatch|branch_older_unproved) + source="$(printf '{"id":103,"run_attempt":2,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/103","display_title":"Build Runtime Images trusted-branch branch-develop sha-%s","created_at":"2026-09-21T00:02:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$head_sha")" + older_sha="$head_sha" + [[ "$GH_FIXTURE" != branch_older_mismatch ]] || older_sha="$base_sha" + older="$(printf '{"id":102,"run_attempt":1,"status":"completed","conclusion":"success","event":"workflow_run","html_url":"https://example.test/runtime/102","display_title":"Build Runtime Images trusted-branch branch-develop sha-%s","created_at":"2026-09-21T00:01:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$older_sha")" + case "$*" in + *actions/runs/103) + printf '%s' "$source" + ;; + *actions/runs/102) + printf '%s' "$older" + ;; + *actions/runs/103/attempts/2/jobs?per_page=100) + case "$GH_FIXTURE" in + branch_newer_failed) + printf '%s' '{"total_count":1,"jobs":[{"run_id":103,"run_attempt":2,"name":"Promote Smoke-Tested Runtime Images","status":"completed","conclusion":"failure","steps":[]}]}' + ;; + branch_newer_ambiguous) + # An absent promotion job is not affirmative skipped-work proof. + printf '%s' '{"total_count":0,"jobs":[]}' + ;; + *) + printf '%s' '{"total_count":1,"jobs":[{"run_id":103,"run_attempt":2,"name":"Promote Smoke-Tested Runtime Images","status":"completed","conclusion":"skipped","steps":[]}]}' + ;; + esac + ;; + *actions/runs/102/attempts/1/jobs?per_page=100) + conclusion=success + [[ "$GH_FIXTURE" != branch_older_unproved ]] || conclusion=failure + printf '{"total_count":1,"jobs":[{"run_id":102,"run_attempt":1,"name":"Promote Smoke-Tested Runtime Images","status":"completed","conclusion":"%s","steps":[{"name":"Promote smoke-tested service digests","status":"completed","conclusion":"%s"}]}]}' "$conclusion" "$conclusion" + ;; + *actions/workflows/runtime-images.yml/runs?*) + printf '[{"workflow_runs":[%s,%s]}]' "$source" "$older" + ;; + *) + echo "Unexpected branch fallback API request in $GH_FIXTURE fixture" >&2 + exit 2 + ;; + esac + ;; + success_runs|wrong_runs|publisher_steps_absent|publisher_duplicate_steps|typed_publisher_success|typed_publisher_step_absent) source_title="Build Runtime Images secure-pr-artifact pr-7 base-${base_sha} head-${head_sha} merge-${merge_sha} mode-required" + source_event=pull_request publisher_merge="$merge_sha" if [[ "$GH_FIXTURE" == wrong_runs ]]; then publisher_merge=dddddddddddddddddddddddddddddddddddddddd fi publisher_title="Publish PR Runtime Images Build Runtime Images secure-pr-artifact pr-7 base-${base_sha} head-${head_sha} merge-${publisher_merge} mode-required" - source="$(printf '{"id":101,"run_attempt":1,"status":"completed","conclusion":"success","event":"pull_request","head_sha":"%s","html_url":"https://example.test/runtime/101","display_title":"%s","created_at":"2026-09-21T00:00:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$head_sha" "$source_title")" + if [[ "$GH_FIXTURE" == typed_publisher_* ]]; then + source_event=repository_dispatch + publisher_title+=" source-run-101" + fi + source="$(printf '{"id":101,"run_attempt":1,"status":"completed","conclusion":"success","event":"%s","head_sha":"%s","html_url":"https://example.test/runtime/101","display_title":"%s","created_at":"2026-09-21T00:00:00Z","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$source_event" "$head_sha" "$source_title")" publisher="$(printf '{"id":102,"run_attempt":2,"status":"completed","conclusion":"success","event":"workflow_run","display_title":"%s","created_at":"2026-09-21T00:01:00Z","path":".github/workflows/publish-pr-runtime-images.yml","head_branch":"develop","repository":{"full_name":"example/firemud"},"head_repository":{"full_name":"example/firemud"}}' "$publisher_title")" case "$*" in "api repos/example/firemud") @@ -124,7 +169,27 @@ case "${GH_FIXTURE:-}" in printf '%s' "$publisher" ;; *actions/runs/102/attempts/2/jobs?per_page=100) - printf '%s' '{"total_count":1,"jobs":[{"run_id":102,"run_attempt":2,"name":"Publish Fixed PR Merge Image Tags","status":"completed","conclusion":"success","steps":[{"name":"Publish fixed PR image tags","status":"completed","conclusion":"success"}]}]}' + publication_step='{"name":"Publish fixed PR image tags","status":"completed","conclusion":"success"}' + unrelated_step='{"name":"Load fixed-tag images","status":"completed","conclusion":"success"}' + case "$GH_FIXTURE" in + publisher_steps_absent) + steps=null + ;; + typed_publisher_step_absent) + steps="[$unrelated_step]" + ;; + publisher_duplicate_steps) + steps="[$publication_step,$publication_step]" + ;; + *) + steps="[$publication_step]" + ;; + esac + jq -cn --argjson steps "$steps" ' + {run_id:102,run_attempt:2,name:"Publish Fixed PR Merge Image Tags",status:"completed",conclusion:"success"} + + (if $steps == null then {} else {steps:$steps} end) + | {total_count:1,jobs:[.]} + ' ;; *actions/workflows/publish-pr-runtime-images.yml/runs?*event=workflow_run*) printf '{"total_count":1,"workflow_runs":[%s]}' "$publisher" @@ -208,6 +273,30 @@ GH_FIXTURE=success_runs \ timeout 15s bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" >"$TEMP_DIR/publisher-success.out" grep -Fq 'Trusted PR image publisher 102 succeeded' "$TEMP_DIR/publisher-success.out" +# A typed native callback binds the exact source run in its title, and both +# producer events still require one positive publication step for the attempt. +GH_FIXTURE=typed_publisher_success \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ + HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ + timeout 15s bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" >"$TEMP_DIR/typed-publisher-success.out" +grep -Fq 'Trusted PR image publisher 102 succeeded' "$TEMP_DIR/typed-publisher-success.out" + +for publisher_fixture in publisher_steps_absent publisher_duplicate_steps typed_publisher_step_absent; do + publisher_status=0 + publisher_output="$( + GH_FIXTURE="$publisher_fixture" HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ + HOSTED_IMAGE_PUBLISHER_WAIT_TIMEOUT_SECONDS=1 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ + timeout 15s bash "$WAITER" "$merge_sha" "$base_sha" "$head_sha" 2>&1 + )" || publisher_status=$? + if [[ "$publisher_status" != 1 ]]; then + printf 'publisher proof must refuse with status 1 for %s, got %s\n' "$publisher_fixture" "$publisher_status" >&2 + exit 1 + fi + grep -Fq 'publisher 102 completed successfully, but its exact current-attempt fixed-tag publication proof is unavailable' <<<"$publisher_output" +done + # A publisher with a mismatched merge token must not satisfy the PR wait. if wrong_merge_output="$( GH_FIXTURE=wrong_runs \ @@ -229,6 +318,30 @@ GH_FIXTURE=branch_runs \ timeout 15s bash "$WAITER" "$head_sha" >"$TEMP_DIR/branch-success.out" grep -Fq "Matching runtime-images workflow 103 succeeded for ${head_sha} after" "$TEMP_DIR/branch-success.out" +# A later successful callback with a wholly skipped promotion cannot hide exact +# immutable-commit promotion proof from an earlier callback. +GH_FIXTURE=branch_newer_noop \ + HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 \ + HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 15s bash "$WAITER" "$head_sha" >"$TEMP_DIR/branch-earlier-success.out" +grep -Fq "Earlier trusted branch runtime-image run 102 has verified promotion for ${head_sha} after a newer skipped promotion." "$TEMP_DIR/branch-earlier-success.out" + +# No fallback for a failed/unknown newer promotion, a different immutable commit, +# or an older callback lacking the existing positive promotion-step evidence. +for branch_fixture in branch_newer_failed branch_newer_ambiguous branch_older_mismatch branch_older_unproved; do + branch_fallback_status=0 + branch_fallback_output="$( + GH_FIXTURE="$branch_fixture" HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ + timeout 15s bash "$WAITER" "$head_sha" 2>&1 + )" || branch_fallback_status=$? + if [[ "$branch_fallback_status" != 1 ]]; then + printf 'branch fallback must refuse with status 1 for %s, got %s\n' "$branch_fixture" "$branch_fallback_status" >&2 + exit 1 + fi + grep -Fq 'Trusted branch runtime-image run 103 has no verified promotion' <<<"$branch_fallback_output" + grep -Fq "Timed out waiting for runtime-images workflow for ${head_sha} after" <<<"$branch_fallback_output" +done + branch_obsolete_status=0 branch_obsolete_output="$( GH_FIXTURE=branch_obsolete HOSTED_IMAGE_WAIT_TIMEOUT_SECONDS=2 HOSTED_IMAGE_WAIT_SLEEP_SECONDS=0 \ @@ -272,7 +385,7 @@ if branch_timeout_output="$( HOSTED_IMAGE_WAIT_MISSING_WORKFLOW_TIMEOUT_SECONDS=0 \ timeout 15s bash "$WAITER" "$head_sha" 2>&1 )"; then - echo "branch waiter accepted a non-develop runtime image run" >&2 + echo "branch waiter accepted a runtime image run without the exact develop title" >&2 exit 1 fi grep -Fq "No trusted branch runtime-image publication appeared for branch develop and exact head SHA ${head_sha} after" <<<"$branch_timeout_output" From b4ab4678336bb6f0029d63720982851ffa1a1610 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:11:35 +1300 Subject: [PATCH 106/199] Keep exact preview retry budgets across namespace recreation --- .github/workflows/hosted-identity-request.yml | 86 +- .github/workflows/preview-janitor.yml | 6 +- .../infrastructure/deployment-environments.md | 2 +- .../architecture/system-architecture-cicd.md | 2 +- dev-tools/hosted/README.md | 2 +- .../preview/annotate-preview-namespace.sh | 43 +- .../preview/preview-proof-retry-record.shlib | 139 +++ .../preview/prune-stale-preview-namespaces.sh | 20 +- .../preview/reconcile-preview-deploys.sh | 407 ++----- .../hosted/shared/delete-hosted-namespace.sh | 23 +- .../provision-scoped-kubeconfigs.py | 5 + ...d-identity-controller-workflow-contract.sh | 153 +-- dev-tools/tests/preview-priority-contract.sh | 995 +++++------------- .../trust-bootstrap-provision-contract.sh | 14 +- .../tests/trust-bootstrap-rbac-contract.sh | 25 + k8s/trust-bootstrap/README.md | 8 +- k8s/trust-bootstrap/deployment-rbac.yaml | 34 + 17 files changed, 675 insertions(+), 1289 deletions(-) create mode 100644 dev-tools/hosted/preview/preview-proof-retry-record.shlib diff --git a/.github/workflows/hosted-identity-request.yml b/.github/workflows/hosted-identity-request.yml index dd7fcf4576..dd097f85a9 100644 --- a/.github/workflows/hosted-identity-request.yml +++ b/.github/workflows/hosted-identity-request.yml @@ -753,85 +753,6 @@ jobs: "$PR_NUMBER" "$EXPECTED_HEAD_SHA" "$EXPECTED_BASE_SHA" "$EXPECTED_MERGE_SHA" \ "before clean runtime redeploy" - - name: Capture exact proof-retry record before namespace recreation - id: capture-proof-retry - if: ${{ steps.allocate-capacity.outputs.allocation_status == 'allocated' }} - env: - KUBECONFIG: ${{ runner.temp }}/preview-namespace-manager.kubeconfig - RUNTIME_NAMESPACE: ${{ needs.validate-target.outputs.namespace }} - PR_NUMBER: ${{ needs.validate-target.outputs.pr_number }} - EXPECTED_BASE_SHA: ${{ needs.validate-target.outputs.base_sha }} - EXPECTED_HEAD_SHA: ${{ needs.validate-target.outputs.head_sha }} - EXPECTED_MERGE_SHA: ${{ needs.validate-target.outputs.merge_sha }} - EXPECTED_IMAGE_TAG: ${{ needs.validate-target.outputs.image_tag }} - run: | - set -euo pipefail - namespace_json="$(kubectl get namespace "$RUNTIME_NAMESPACE" --ignore-not-found -o json)" - [[ -n "$namespace_json" ]] || exit 0 - retry_snapshot="$(jq -er ' - (.metadata.annotations // {}) as $annotations - | [ - "firemud.dev/proof-retry-count", - "firemud.dev/proof-retry-base-sha", - "firemud.dev/proof-retry-head-sha", - "firemud.dev/proof-retry-merge-sha", - "firemud.dev/proof-retry-image-tag" - ] as $keys - | { - present: ([$keys[] | . as $key | select($annotations | has($key))] | length), - values: [ - $keys[] - | . as $key - | if ($annotations | has($key)) then - ($annotations[$key] | if type == "string" then . else "__invalid:type__" end) - else "" - end - ] - } - | [.present, .values[]] - | @tsv - ' <<<"$namespace_json")" || { - echo "::error title=Malformed proof-retry annotations::Unable to inspect the existing runtime Namespace retry record." >&2 - exit 1 - } - IFS=$'\t' read -r present_count retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag <<<"$retry_snapshot" - if [[ "$present_count" == 0 ]]; then - exit 0 - fi - if [[ "$present_count" != 5 || "$retry_count" == "__invalid:type__" || \ - "$retry_base_sha" == "__invalid:type__" || "$retry_head_sha" == "__invalid:type__" || \ - "$retry_merge_sha" == "__invalid:type__" || "$retry_image_tag" == "__invalid:type__" ]]; then - echo "::error title=Malformed proof-retry annotations::Retry annotations must be a complete string record before namespace recreation." >&2 - exit 1 - fi - [[ "$retry_count" =~ ^[1-3]$ ]] || { - echo "::error title=Invalid proof-retry count::Expected a retry count from 1 through 3." >&2 - exit 1 - } - [[ "$retry_base_sha" =~ ^[0-9a-f]{40}$ && "$retry_head_sha" =~ ^[0-9a-f]{40}$ && \ - "$retry_merge_sha" =~ ^[0-9a-f]{40}$ ]] || { - echo "::error title=Invalid proof-retry tuple::Retry tuple SHAs must be exactly 40 lowercase hexadecimal characters." >&2 - exit 1 - } - [[ "$retry_image_tag" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]] || { - echo "::error title=Invalid proof-retry image tag::Expected a canonical immutable image tag." >&2 - exit 1 - } - if [[ "$retry_base_sha" != "$EXPECTED_BASE_SHA" || \ - "$retry_head_sha" != "$EXPECTED_HEAD_SHA" || \ - "$retry_merge_sha" != "$EXPECTED_MERGE_SHA" || \ - "$retry_image_tag" != "$EXPECTED_IMAGE_TAG" ]]; then - echo "Existing proof-retry record belongs to another tuple; resetting its budget." >&2 - exit 0 - fi - { - echo "proof_retry_count=$retry_count" - echo "proof_retry_base_sha=$retry_base_sha" - echo "proof_retry_head_sha=$retry_head_sha" - echo "proof_retry_merge_sha=$retry_merge_sha" - echo "proof_retry_image_tag=$retry_image_tag" - } >> "$GITHUB_OUTPUT" - - name: Delete exact preview runtime namespace before recreate if: ${{ steps.allocate-capacity.outputs.allocation_status == 'allocated' }} env: @@ -875,12 +796,7 @@ jobs: kubectl create namespace "$RUNTIME_NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - bash ./dev-tools/hosted/preview/annotate-preview-namespace.sh \ "$RUNTIME_NAMESPACE" "$PR_NUMBER" "$BASE_SHA" "$HEAD_SHA" "$MERGE_SHA" "$IMAGE_TAG" \ - "$EXPOSURE_MODE" "$TELNET_PORT" "$ALLOCATION_TIMESTAMP" \ - "${{ steps.capture-proof-retry.outputs.proof_retry_count }}" \ - "${{ steps.capture-proof-retry.outputs.proof_retry_base_sha }}" \ - "${{ steps.capture-proof-retry.outputs.proof_retry_head_sha }}" \ - "${{ steps.capture-proof-retry.outputs.proof_retry_merge_sha }}" \ - "${{ steps.capture-proof-retry.outputs.proof_retry_image_tag }}" + "$EXPOSURE_MODE" "$TELNET_PORT" "$ALLOCATION_TIMESTAMP" - name: Bind scoped runtime and certificate roles if: ${{ steps.allocate-capacity.outputs.allocation_status == 'allocated' }} diff --git a/.github/workflows/preview-janitor.yml b/.github/workflows/preview-janitor.yml index d355fa51f8..8dfd842ed0 100644 --- a/.github/workflows/preview-janitor.yml +++ b/.github/workflows/preview-janitor.yml @@ -95,13 +95,13 @@ jobs: hosted-controller) if [[ "$HOSTED_IDENTITY_REQUESTER_CREDENTIALS_AVAILABLE" == true ]]; then bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh \ - --apply --retire-terminal-identities + --apply --retire-terminal-identities --retire-proof-retries else - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply + bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply --retire-proof-retries fi ;; standalone) - bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply + bash ./dev-tools/hosted/preview/prune-stale-preview-namespaces.sh --apply --retire-proof-retries ;; *) echo "unsupported certificate identity mode: ${HOSTED_IDENTITY_MODE}" >&2 diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 960bf0aa3a..68cf981dbc 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -328,7 +328,7 @@ The internal preview CA is not installed while a legacy preview credential can r The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all fourteen labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and nine distinct workload projections (the eight serving-workload leaves and the independent `firemud-grpc-spring-cloud-gateway` outbound client leaf). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all fourteen labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. -Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A retained Namespace retry record permits at most three proof retries for one exact base/head/merge/image tuple. Its counter resets for a changed tuple. A resource-version update binds each reservation to the Namespace UID, tuple, and a unique reservation ID. If the update response is lost, bounded readback must prove that same reservation before dispatch. Explicit dispatch rejection may return only the exact reservation to the previous counter state. An ambiguous dispatch stays charged. These controls require the retry record to survive Namespace recreation to preserve the budget across that boundary. +Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. The independently installed `firemud-system/firemud-preview-proof-retries` ConfigMap retains one record per PR, with at most three proof retries for the exact repository, PR, and base/head/merge/image tuple. A changed tuple starts a fresh budget. The namespace manager can get and patch only this named ConfigMap. Each reservation uses the holder's UID and resource version, records the observed runtime Namespace UID or confirmed absence, and binds the counter to a unique reservation ID. A bounded readback after a lost write response must prove that exact reservation before dispatch. The reconciler rechecks the runtime Namespace fence before sending. A confirmed rejection can restore only the exact reservation's preceding record. An ambiguous dispatch stays charged. Clean runtime Namespace recreation leaves the retained budget intact. During cutover, a complete legacy Namespace record is copied before UID- and resource-version-fenced deletion when the independent holder has no entry. The protected janitor may remove an entry only after positive same-repository merge evidence and confirmed runtime Namespace absence. Close, reclaim, or lease expiry alone preserves the entry. #### Preview exposure modes and proof boundaries diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index da2fbae9e0..d179aeb3b9 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -240,7 +240,7 @@ Hosted verification waits for the complete readiness tuple defined by the owning Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. -Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. A successful exact source completion during lookup defers one retry cycle while its trusted consumer may enter the queue. When GitHub caps the completed-source inventory, the reconciler checks disjoint creation ranges across the history. It still evaluates handoff freshness from completion evidence, including later attempts of older runs, and preserves the retry budget if any range cannot be verified. A confirmed GitHub dispatch rejection releases only the matching Namespace retry reservation, fenced by the returned resource version. An uncertain dispatch outcome leaves the reservation charged. +Before spending a preview proof retry, the reconciler checks for active work for that exact comparison. The trusted consumer records the validated PR/base/head/merge tuple in a successful step of its native validation job. The reconciler requires the default-branch consumer workflow identity and the current attempt's successful step before treating that consumer as an exact match. An inherited source run title can identify a candidate for lookup but cannot establish a match. When the lookup budget leaves candidates unexamined, the reconciler preserves the retry budget. It rechecks the live Namespace proof after candidate lookup so a consumer that finished during the lookup does not cause another render. A successful exact source completion during lookup defers one retry cycle while its trusted consumer may enter the queue. When GitHub caps the completed-source inventory, the reconciler checks disjoint creation ranges across the history. It still evaluates handoff freshness from completion evidence, including later attempts of older runs, and preserves the retry budget if any range cannot be verified. The [hosted identity lifecycle](./infrastructure/deployment-environments.md#hosted-identity-lifecycle) owns durable retry custody across Namespace recreation and the dispatch rejection boundary. The initial Telnet-first hosted milestone is complete. Continuing preview acceptance follows [ADR 0178](decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md): one shared semantic authenticated, admitted, `LOOK` assertion set is exercised through both the public Telnet path and the deployed first-party browser path. Telnet proves TCP Proxy and bridge/framing behavior. The bounded browser journey proves frontend delivery, HTTPS bootstrap and discovery, connect-token cookie and `/ws/game/**` admission, one reconnect, logout, and non-reuse. Direct backend WebSocket smoke remains CI or diagnostic evidence rather than a substitute or third required hosted path. Dedicated frontend delivery and the browser journey remain implementation gaps, so current TCP/Telnet preview proof is not yet transport-complete. diff --git a/dev-tools/hosted/README.md b/dev-tools/hosted/README.md index fa0d4d44a2..5a2357ef36 100644 --- a/dev-tools/hosted/README.md +++ b/dev-tools/hosted/README.md @@ -12,7 +12,7 @@ This directory contains tooling for FireMUD's hosted Kubernetes environments. - `preview/` - PR-preview-only helpers - capacity allocation and bounded priority reclaim, PR-head freshness checks, preview namespace pruning, preview NodePort allocation, and preview-specific value rendering/summary output - - the reconciler suppresses duplicate proof repair while the exact source or trusted consumer run is active and caps Namespace-backed proof-retry dispatches at three per exact deployed tuple + - the reconciler suppresses duplicate proof repair while the exact source or trusted consumer run is active and caps proof-retry dispatches at three per exact tuple using the [durable holder](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) - [Preview eligibility](preview/preview-eligibility.py) requires valid GitHub label metadata for deploy and retain operations; destroy remains eligible for cleanup when metadata is malformed. Same-repository pull requests targeting `main` or `develop` remain ordinarily eligible, while another same-repository base requires the maintainer-controlled `preview:priority` label in addition to current mergeability and exact source-tuple validation - priority reclaim applies only when the preview pool is full, selects the oldest ordinary allocation after rechecking both target and victim labels at the deletion boundary, and never reclaims another currently priority-labelled allocation diff --git a/dev-tools/hosted/preview/annotate-preview-namespace.sh b/dev-tools/hosted/preview/annotate-preview-namespace.sh index b336cb89ac..83acacb9e8 100644 --- a/dev-tools/hosted/preview/annotate-preview-namespace.sh +++ b/dev-tools/hosted/preview/annotate-preview-namespace.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -if [[ $# -ne 9 && $# -ne 14 ]]; then - echo "usage: $0 [proof_retry_count proof_retry_base_sha proof_retry_head_sha proof_retry_merge_sha proof_retry_image_tag]" >&2 +if [[ $# -ne 9 ]]; then + echo "usage: $0 " >&2 exit 1 fi @@ -15,11 +15,6 @@ image_tag="$6" exposure_mode="$7" telnet_port="$8" allocation_timestamp="$9" -proof_retry_count="${10:-}" -proof_retry_base_sha="${11:-}" -proof_retry_head_sha="${12:-}" -proof_retry_merge_sha="${13:-}" -proof_retry_image_tag="${14:-}" if ! [[ "$pr_number" =~ ^[1-9][0-9]{0,50}$ ]]; then echo "pr_number must match [1-9][0-9]{0,50}" >&2 @@ -57,31 +52,6 @@ if ! [[ "$allocation_timestamp" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2} echo "allocation_timestamp must be a valid UTC timestamp in YYYY-MM-DDTHH:MM:SSZ format" >&2 exit 1 fi -if [[ -n "$proof_retry_count$proof_retry_base_sha$proof_retry_head_sha$proof_retry_merge_sha$proof_retry_image_tag" ]]; then - if [[ -z "$proof_retry_count" || -z "$proof_retry_base_sha" || -z "$proof_retry_head_sha" || - -z "$proof_retry_merge_sha" || -z "$proof_retry_image_tag" ]]; then - echo "proof retry record must provide all five fields or none" >&2 - exit 1 - fi - if ! [[ "$proof_retry_count" =~ ^[1-3]$ ]]; then - echo "proof_retry_count must be an integer from 1 through 3" >&2 - exit 1 - fi - for retry_sha_name in proof_retry_base_sha proof_retry_head_sha proof_retry_merge_sha; do - retry_sha_value="${!retry_sha_name}" - if ! [[ "$retry_sha_value" =~ ^[0-9a-f]{40}$ ]]; then - echo "${retry_sha_name} must be exactly 40 lowercase hexadecimal characters" >&2 - exit 1 - fi - done - if [[ "$proof_retry_base_sha" != "$base_sha" || - "$proof_retry_head_sha" != "$head_sha" || - "$proof_retry_merge_sha" != "$merge_sha" || - "$proof_retry_image_tag" != "$image_tag" ]]; then - echo "proof retry record tuple must match the requested preview tuple" >&2 - exit 1 - fi -fi sync_timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" @@ -98,15 +68,6 @@ if [[ "$exposure_mode" == public ]]; then else annotations+=("firemud.dev/last-preview-telnet-port-") fi -if [[ -n "$proof_retry_count" ]]; then - annotations+=( - "firemud.dev/proof-retry-count=${proof_retry_count}" \ - "firemud.dev/proof-retry-base-sha=${proof_retry_base_sha}" \ - "firemud.dev/proof-retry-head-sha=${proof_retry_head_sha}" \ - "firemud.dev/proof-retry-merge-sha=${proof_retry_merge_sha}" \ - "firemud.dev/proof-retry-image-tag=${proof_retry_image_tag}" - ) -fi kubectl annotate namespace "$namespace" \ "${annotations[@]}" \ diff --git a/dev-tools/hosted/preview/preview-proof-retry-record.shlib b/dev-tools/hosted/preview/preview-proof-retry-record.shlib new file mode 100644 index 0000000000..3a054d4387 --- /dev/null +++ b/dev-tools/hosted/preview/preview-proof-retry-record.shlib @@ -0,0 +1,139 @@ +# shellcheck shell=bash +# The installed holder survives a clean preview Namespace recreation. +readonly preview_retry_holder_namespace=firemud-system +readonly preview_retry_holder_name=firemud-preview-proof-retries + +validate_preview_retry_holder() { + jq -ces --arg namespace "$preview_retry_holder_namespace" --arg name "$preview_retry_holder_name" ' + select(length == 1) | .[0] + | select(.apiVersion == "v1" and .kind == "ConfigMap" + and .metadata.namespace == $namespace and .metadata.name == $name + and (.metadata.uid | type == "string" and length > 0) + and (.metadata.resourceVersion | type == "string" and length > 0) + and .metadata.deletionTimestamp == null and ((.metadata.ownerReferences // []) == []) + and (.data | type == "object" and .schemaVersion == "1" + and all(keys[]; . == "schemaVersion" or test("^pr-[1-9][0-9]{0,50}$")))) + ' <<<"$1" +} + +read_preview_retry_holder() { + local snapshot + snapshot="$(kubectl -n "$preview_retry_holder_namespace" get configmap "$preview_retry_holder_name" \ + -o json --request-timeout=10s)" || return 1 + validate_preview_retry_holder "$snapshot" +} + +preview_retry_entry() { + local snapshot="$1" namespace="$2" + jq -c --arg namespace "$namespace" --arg repo "$GITHUB_REPOSITORY" ' + if (.data | has($namespace) | not) then null + else .data[$namespace] | fromjson + | if ( + keys == ["base","count","head","image","merge","namespace","namespaceUid","nonce","repository"] + and .repository == $repo and .namespace == $namespace + and (.count | type == "number" and . == floor and . >= 1 and . <= 3) + and all(.base,.head,.merge; type == "string" and test("^[a-f0-9]{40}$")) + and (.image | type == "string" and test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) + and (.namespaceUid | type == "string" and test("^([A-Za-z0-9][A-Za-z0-9._:-]{0,127})?$")) + and (.nonce | type == "string" and test("^([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})?$")) + ) then . else error("invalid preview proof-retry record") end + end + ' <<<"$snapshot" +} + +write_preview_retry_entry() { + local snapshot="$1" namespace="$2" replacement="$3" + local patch response entry uid version + [[ "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]] || return 1 + uid="$(jq -er '.metadata.uid' <<<"$snapshot")" || return 1 + version="$(jq -er '.metadata.resourceVersion' <<<"$snapshot")" || return 1 + patch="$(jq -c --arg key "/data/$namespace" --argjson replacement "$replacement" ' + [ + {op:"test",path:"/metadata/uid",value:.metadata.uid}, + {op:"test",path:"/metadata/resourceVersion",value:.metadata.resourceVersion}, + (if $replacement == null then {op:"remove",path:$key} + else {op:"add",path:$key,value:($replacement | tojson)} end) + ] + ' <<<"$snapshot")" || return 1 + if response="$(kubectl -n "$preview_retry_holder_namespace" patch configmap "$preview_retry_holder_name" \ + --type=json --patch "$patch" -o json --request-timeout=10s)"; then + response="$(validate_preview_retry_holder "$response")" || return 1 + else + # A response can be lost after the server commits. Prove the exact row + # and holder identity with one bounded reread before authorizing a send. + response="$(read_preview_retry_holder)" || return 1 + fi + jq -e --arg uid "$uid" --arg version "$version" ' + .metadata.uid == $uid and .metadata.resourceVersion != $version + ' <<<"$response" >/dev/null || return 1 + entry="$(preview_retry_entry "$response" "$namespace")" || return 1 + jq -en --argjson actual "$entry" --argjson expected "$replacement" '$actual == $expected' >/dev/null || return 1 + printf '%s\n' "$response" +} + +legacy_preview_retry_entry() { + local snapshot="$1" namespace="$2" + jq -c --arg repo "${GITHUB_REPOSITORY:-}" --arg namespace "$namespace" ' + (.metadata.annotations // {}) as $annotations + | (["count","base-sha","head-sha","merge-sha","image-tag","reservation-id"] + | map("firemud.dev/proof-retry-" + .)) as $keys + | if any($keys[]; . as $key | $annotations | has($key)) then + .metadata.uid as $uid + | if ( + ($repo | test("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")) + and .metadata.name == $namespace + and .metadata.labels["firemud.dev/preview"] == "true" + and .metadata.labels["firemud.dev/pr-number"] == ($namespace | ltrimstr("pr-")) + and ($uid | type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")) + and ($annotations[$keys[0]] | type == "string" and test("^[1-3]$")) + and all($keys[1:4][]; $annotations[.] | type == "string" and test("^[a-f0-9]{40}$")) + and ($annotations[$keys[4]] | type == "string" and test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) + and (if $annotations | has($keys[5]) then + $annotations[$keys[5]] | type == "string" + and test("^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$") + else true end) + ) then {repository:$repo,namespace:$namespace,namespaceUid:$uid, + count:($annotations[$keys[0]] | tonumber),base:$annotations[$keys[1]], + head:$annotations[$keys[2]],merge:$annotations[$keys[3]],image:$annotations[$keys[4]], + nonce:($annotations[$keys[5]] // "")} + else error("malformed legacy preview proof-retry annotations") end + else null end + ' <<<"$snapshot" +} + +preserve_legacy_preview_retry_entry() { + local legacy="$1" namespace="$2" stored holder + holder="$(read_preview_retry_holder)" || return 1 + stored="$(preview_retry_entry "$holder" "$namespace")" || return 1 + # Once present, the durable holder owns the counter; old Namespace + # annotations are a one-time import source only. + [[ "$stored" == null ]] || return 0 + write_preview_retry_entry "$holder" "$namespace" "$legacy" >/dev/null +} + +retire_merged_preview_retry_entries() { + local holder holder_uid entries namespace pr_number pr runtime row + holder="$(read_preview_retry_holder)" || return 1 + holder_uid="$(jq -er '.metadata.uid' <<<"$holder")" || return 1 + entries="$(jq -r '.data | keys[] | select(. != "schemaVersion")' <<<"$holder")" || return 1 + while IFS= read -r namespace; do + [[ -n "$namespace" ]] || continue + pr_number="${namespace#pr-}" + # A closed, unmerged pull request can reopen with the same tuple. Only + # positive, same-repository merge evidence permits automatic retirement. + pr="$(timeout 10s gh api "repos/${GITHUB_REPOSITORY}/pulls/$pr_number")" || continue + jq -es --arg number "$pr_number" --arg repo "$GITHUB_REPOSITORY" ' + select(length == 1) | .[0] + | (.number | tostring) == $number and .state == "closed" and .merged == true + and .head.repo.full_name == $repo and .base.repo.full_name == $repo + ' <<<"$pr" >/dev/null || continue + runtime="$(kubectl get namespace "$namespace" --ignore-not-found -o json --request-timeout=10s)" || continue + [[ -z "$runtime" ]] || continue + holder="$(read_preview_retry_holder)" || return 1 + jq -e --arg uid "$holder_uid" '.metadata.uid == $uid' <<<"$holder" >/dev/null || return 1 + row="$(preview_retry_entry "$holder" "$namespace")" || return 1 + [[ "$row" != null ]] || continue + write_preview_retry_entry "$holder" "$namespace" null >/dev/null || return 1 + echo "Retired the proof-retry record for merged PR #$pr_number." + done <<<"$entries" +} diff --git a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh index b4b949ed09..1293c1936a 100644 --- a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh +++ b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh @@ -38,6 +38,7 @@ fi apply=false retire_terminal_identities=false +retire_proof_retries=false for arg in "$@"; do case "$arg" in --apply) @@ -46,13 +47,21 @@ for arg in "$@"; do --retire-terminal-identities) retire_terminal_identities=true ;; + --retire-proof-retries) + retire_proof_retries=true + ;; *) - echo "usage: $0 [--apply] [--retire-terminal-identities]" >&2 + echo "usage: $0 [--apply] [--retire-terminal-identities] [--retire-proof-retries]" >&2 exit 1 ;; esac done +if [[ "$retire_proof_retries" == true && "$apply" != true ]]; then + echo "--retire-proof-retries requires --apply" >&2 + exit 2 +fi + if [[ "$retire_terminal_identities" == true ]]; then if [[ "$apply" != true ]]; then echo "--retire-terminal-identities requires --apply" >&2 @@ -425,3 +434,12 @@ if (( runtime_deletion_failures > 0 || retirement_failures > 0 )); then echo "${runtime_deletion_failures} hosted runtime deletion(s) and ${retirement_failures} hosted identity retirement(s) failed; stale cleanup is incomplete." >&2 exit 1 fi + +if [[ "$retire_proof_retries" == true ]]; then + # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib + source "$script_dir/preview-proof-retry-record.shlib" + if ! retire_merged_preview_retry_entries; then + echo "Unable to retire verified merged preview proof-retry records." >&2 + exit 1 + fi +fi diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh index 579bb26d70..d63514493d 100644 --- a/dev-tools/hosted/preview/reconcile-preview-deploys.sh +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -4,6 +4,8 @@ preview_workflow_name="PR Preview Environment" eligibility_script="./dev-tools/hosted/preview/preview-eligibility.py" max_active="${PREVIEW_MAX_ACTIVE:-2}" preview_handoff_window_seconds=600 +# shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib +source ./dev-tools/hosted/preview/preview-proof-retry-record.shlib parse_namespace_tuple() { jq -er ' @@ -45,60 +47,13 @@ parse_namespace_tuple() { annotation($annotations; "firemud.dev/proof-preview-merge-sha"), annotation($annotations; "firemud.dev/proof-preview-image-tag"), annotation($annotations; "firemud.dev/proof-preview-namespace-uid"), - annotation($annotations; "firemud.dev/proof-retry-count"), - annotation($annotations; "firemud.dev/proof-retry-base-sha"), - annotation($annotations; "firemud.dev/proof-retry-head-sha"), - annotation($annotations; "firemud.dev/proof-retry-merge-sha"), - annotation($annotations; "firemud.dev/proof-retry-image-tag"), metadata_field(.metadata; "uid"), metadata_field(.metadata; "resourceVersion") - ] - | if ( - (($annotations | has("firemud.dev/proof-retry-count") | not) - and ($annotations | has("firemud.dev/proof-retry-reservation-id") | not) - and .[13] == "" and .[14] == "" and .[15] == "" and .[16] == "" and .[17] == "") - or ( - (.[13] | test("^[1-3]$")) - and (.[14] | test("^[0-9a-f]{40}$")) - and (.[15] | test("^[0-9a-f]{40}$")) - and (.[16] | test("^[0-9a-f]{40}$")) - and (.[17] | test("^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")) - ) - ) then . else error("namespace proof-retry evidence is malformed") end - | if (($annotations | has("firemud.dev/proof-retry-reservation-id") | not) - or ($annotations["firemud.dev/proof-retry-reservation-id"] - | type == "string" and test("^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"))) - then . else error("namespace proof-retry reservation ID is malformed") end - | join("|") + ] | join("|") end ' <<<"$1" } -validated_proof_retry_reservation_version() { - local snapshot="$1" namespace="$2" uid="$3" deployed_tuple="$4" - local retry_tuple="$5" count="$6" reservation_id="$7" previous_version="$8" - parse_namespace_tuple "$snapshot" >/dev/null || return 1 - jq -ers --arg namespace "$namespace" --arg uid "$uid" --arg deployed "$deployed_tuple" \ - --arg retry "$retry_tuple" --arg count "$count" --arg id "$reservation_id" \ - --arg previous_version "$previous_version" ' - select(length == 1) | .[0] - | .metadata as $metadata | ($metadata.annotations // {}) as $annotations - | select($uid != "" and $id != "" and $metadata.name == $namespace and $metadata.uid == $uid - and ($metadata.resourceVersion | type == "string" and length > 0 and . != $previous_version) - and $annotations["firemud.dev/proof-retry-reservation-id"] == $id - and $annotations["firemud.dev/proof-retry-count"] == $count - and ([$annotations["firemud.dev/last-preview-base-sha"] // "", - $annotations["firemud.dev/last-preview-head-sha"] // "", - $annotations["firemud.dev/last-preview-merge-sha"] // "", - $annotations["firemud.dev/last-preview-image-tag"] // ""] | join("|")) == $deployed - and ([$annotations["firemud.dev/proof-retry-base-sha"], - $annotations["firemud.dev/proof-retry-head-sha"], - $annotations["firemud.dev/proof-retry-merge-sha"], - $annotations["firemud.dev/proof-retry-image-tag"]] | join("|")) == $retry) - | $metadata.resourceVersion - ' <<<"$snapshot" -} - readonly repair_success=0 readonly repair_skip=10 readonly repair_dispatch=11 @@ -152,7 +107,7 @@ repair_requested_tuple() { IFS='|' read -r fresh_last_base_sha fresh_last_head_sha fresh_last_merge_sha fresh_last_image_tag \ fresh_requested_base_sha fresh_requested_head_sha fresh_requested_merge_sha fresh_requested_image_tag \ fresh_proof_base_sha fresh_proof_head_sha fresh_proof_merge_sha fresh_proof_image_tag \ - fresh_proof_namespace_uid _ _ _ _ _ \ + fresh_proof_namespace_uid \ fresh_namespace_uid \ fresh_namespace_resource_version <<<"${fresh_namespace_tuple}" if [[ "${fresh_namespace_uid}" != "${expected_namespace_uid}" ]]; then @@ -218,73 +173,24 @@ repair_requested_tuple() { } prepare_preview_dispatch() { - local namespace="$1" - local pr_number="$2" - local base_sha="$3" - local head_sha="$4" - local merge_sha="$5" - local image_tag="$6" - local require_deployed_tuple="$7" - local priority="$8" - local expected_namespace_uid="$9" - local fresh_namespace_json - local fresh_namespace_tuple - local current_base_sha - local current_head_sha - local current_merge_sha - local current_image_tag - local requested_base_sha - local requested_head_sha - local requested_merge_sha - local requested_image_tag - local proof_base_sha - local proof_head_sha - local proof_merge_sha - local proof_image_tag - local proof_namespace_uid - local retry_count - local retry_base_sha - local retry_head_sha - local retry_merge_sha - local retry_image_tag - local namespace_uid - local namespace_resource_version - local next_retry_count - local previous_reservation_id - local reservation_id - local reservation_resource_version - local reservation_namespace_json - local annotation_failed=false - local recheck_namespace_name - local recheck_namespace_uid - local recheck_namespace_resource_version - local exact_retry_tuple=false + local namespace="$1" pr_number="$2" base_sha="$3" head_sha="$4" merge_sha="$5" image_tag="$6" + local require_deployed_tuple="$7" priority="$8" expected_namespace_uid="$9" + local snapshot="" tuple="" namespace_uid="" namespace_resource_version="" + local deployed_base deployed_head deployed_merge deployed_image deployed_exact=false + local proof_base proof_head proof_merge proof_image proof_uid + local holder prior legacy reservation next_count=1 nonce fresh_snapshot + proof_retry_record="" + proof_retry_prior_record="" + proof_retry_holder_uid="" - proof_retry_reservation_count="" - proof_retry_reservation_id="" - proof_retry_previous_reservation_id="" - proof_retry_previous_count="" - proof_retry_previous_base_sha="" - proof_retry_previous_head_sha="" - proof_retry_previous_merge_sha="" - proof_retry_previous_image_tag="" - proof_retry_reservation_namespace_uid="" - proof_retry_reservation_resource_version="" - proof_retry_reservation_deployed_tuple="" - proof_retry_reservation_base_sha="" - proof_retry_reservation_head_sha="" - proof_retry_reservation_merge_sha="" - proof_retry_reservation_image_tag="" - - if ! fresh_namespace_json="$( - kubectl get namespace "${namespace}" --ignore-not-found -o json - )"; then - echo "Unable to recheck namespace ${namespace} before preview dispatch." >&2 + if ! snapshot="$(kubectl get namespace "$namespace" --ignore-not-found -o json)"; then + echo "Unable to recheck namespace $namespace before preview dispatch." >&2 + dispatch_outcome_failed=true return 1 fi - if [[ -z "${fresh_namespace_json}" ]]; then + if [[ -z "$snapshot" ]]; then if [[ "$require_deployed_tuple" == true ]]; then - echo "Skipping PR #${pr_number}: namespace ${namespace} disappeared before proof retry dispatch." >&2 + echo "Skipping PR #${pr_number}: namespace $namespace disappeared before proof retry dispatch." >&2 return 1 fi if [[ "$priority" != true && "$available_slots" -le 0 ]]; then @@ -298,205 +204,123 @@ prepare_preview_dispatch() { return 1 fi fi - return 0 - fi - if ! fresh_namespace_tuple="$(parse_namespace_tuple "${fresh_namespace_json}")"; then - echo "Skipping PR #${pr_number}: malformed namespace proof-retry evidence; refusing dispatch." >&2 - return 1 + else + if ! tuple="$(parse_namespace_tuple "$snapshot")"; then + echo "Skipping PR #${pr_number}: malformed namespace evidence; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + IFS='|' read -r deployed_base deployed_head deployed_merge deployed_image _ _ _ _ \ + proof_base proof_head proof_merge proof_image proof_uid namespace_uid namespace_resource_version <<<"$tuple" + if [[ "$require_deployed_tuple" == true && + ( -z "$expected_namespace_uid" || "$namespace_uid" != "$expected_namespace_uid" ) ]]; then + echo "Skipping PR #${pr_number}: namespace $namespace was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 + return 1 + fi + if [[ "$deployed_base|$deployed_head|$deployed_merge|$deployed_image" == "$base_sha|$head_sha|$merge_sha|$image_tag" ]]; then + deployed_exact=true + elif [[ "$require_deployed_tuple" == true ]]; then + echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 + return 1 + fi + if [[ "$proof_base|$proof_head|$proof_merge|$proof_image" == "$base_sha|$head_sha|$merge_sha|$image_tag" && + -n "$namespace_uid" && "$proof_uid" == "$namespace_uid" ]]; then + echo "Skipping PR #${pr_number}: proof completed before retry dispatch." >&2 + return 2 + fi fi - IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ - requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ - proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ - retry_count retry_base_sha retry_head_sha retry_merge_sha retry_image_tag \ - namespace_uid namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "$require_deployed_tuple" == true && - ( -z "$expected_namespace_uid" || "$namespace_uid" != "$expected_namespace_uid" ) ]]; then - echo "Skipping PR #${pr_number}: namespace ${namespace} was recreated before proof retry dispatch; refusing to charge its retry budget." >&2 + + if ! holder="$(read_preview_retry_holder)" || + ! prior="$(preview_retry_entry "$holder" "$namespace")"; then + echo "Unable to verify the proof-retry holder for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true return 1 fi - if [[ "${retry_base_sha}" == "${base_sha}" && - "${retry_head_sha}" == "${head_sha}" && - "${retry_merge_sha}" == "${merge_sha}" && - "${retry_image_tag}" == "${image_tag}" ]]; then - exact_retry_tuple=true - fi - if [[ "${current_base_sha}" != "${base_sha}" || - "${current_head_sha}" != "${head_sha}" || - "${current_merge_sha}" != "${merge_sha}" || - "${current_image_tag}" != "${image_tag}" ]]; then - if [[ "$require_deployed_tuple" == true ]]; then - echo "Skipping PR #${pr_number}: deployed preview tuple changed before proof retry dispatch." >&2 + if [[ "$prior" == null && -n "$snapshot" ]]; then + if ! legacy="$(legacy_preview_retry_entry "$snapshot" "$namespace")"; then + echo "Skipping PR #${pr_number}: malformed legacy proof-retry evidence; refusing dispatch." >&2 + dispatch_outcome_failed=true return 1 fi - # A failed namespace recreation can retain the exact retry record before - # the new workload has written its deployed tuple. - if [[ "$exact_retry_tuple" == false ]]; then - return 0 + if [[ "$legacy" != null ]]; then + if ! holder="$(write_preview_retry_entry "$holder" "$namespace" "$legacy")"; then + echo "Unable to retain the legacy proof-retry record for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 + fi + prior="$legacy" fi fi - if [[ "${proof_base_sha}" == "${base_sha}" && - "${proof_head_sha}" == "${head_sha}" && - "${proof_merge_sha}" == "${merge_sha}" && - "${proof_image_tag}" == "${image_tag}" && - -n "${namespace_uid}" && - "${proof_namespace_uid}" == "${namespace_uid}" ]]; then - echo "Skipping PR #${pr_number}: proof completed before retry dispatch." >&2 - return 2 - fi - if [[ "$exact_retry_tuple" == true ]]; then - next_retry_count=$((10#${retry_count} + 1)) - else - next_retry_count=1 + if jq -e --arg base "$base_sha" --arg head "$head_sha" --arg merge "$merge_sha" --arg image "$image_tag" ' + . != null and .base == $base and .head == $head and .merge == $merge and .image == $image + ' <<<"$prior" >/dev/null; then + next_count="$(( $(jq -r '.count' <<<"$prior") + 1 ))" + elif [[ "$deployed_exact" == false ]]; then + return 0 fi - if (( next_retry_count > 3 )); then - echo "Skipping PR #${pr_number}: proof retry budget exhausted for ${base_sha}/${head_sha}/${merge_sha}/${image_tag}." >&2 + if (( next_count > 3 )); then + echo "Skipping PR #${pr_number}: proof retry budget exhausted for $base_sha/$head_sha/$merge_sha/$image_tag." >&2 return 3 fi - if [[ -z "$namespace_uid" || -z "$namespace_resource_version" ]]; then + if [[ -n "$snapshot" && ( -z "$namespace_uid" || -z "$namespace_resource_version" ) ]]; then echo "Skipping PR #${pr_number}: Namespace retry custody is unavailable." >&2 + dispatch_outcome_failed=true return 1 fi - previous_reservation_id="$(jq -r '.metadata.annotations["firemud.dev/proof-retry-reservation-id"] // ""' <<<"${fresh_namespace_json}")" - # uuid4 uses the OS cryptographic random source. The ID is custody for this - # invocation only, not a durable retry ledger across Namespace deletion. - if ! reservation_id="$(python3 -c 'import uuid; print(uuid.uuid4())')" || - [[ ! "$reservation_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]]; then + if ! nonce="$(python3 -c 'import uuid; print(uuid.uuid4())')" || + [[ ! "$nonce" =~ ^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$ ]]; then echo "Unable to generate proof-retry reservation ID for PR #${pr_number}; refusing dispatch." >&2 dispatch_outcome_failed=true return 1 fi - if ! reservation_namespace_json="$(kubectl annotate namespace "${namespace}" \ - "firemud.dev/proof-retry-reservation-id=${reservation_id}" \ - "firemud.dev/proof-retry-count=${next_retry_count}" \ - "firemud.dev/proof-retry-base-sha=${base_sha}" \ - "firemud.dev/proof-retry-head-sha=${head_sha}" \ - "firemud.dev/proof-retry-merge-sha=${merge_sha}" \ - "firemud.dev/proof-retry-image-tag=${image_tag}" \ - --overwrite \ - --resource-version "${namespace_resource_version}" -o json)"; then - annotation_failed=true - # A failed kubectl response proves neither a CAS conflict nor that the - # reservation was not committed. Bound classification to one API reread; - # never retry the write or compensate a reservation we cannot attribute. - if ! reservation_namespace_json="$(kubectl get namespace "${namespace}" \ - --ignore-not-found -o json --request-timeout=10s)"; then - echo "Unable to recheck Namespace ${namespace} after proof-retry annotation failure; refusing dispatch with reservation outcome unknown." >&2 - dispatch_outcome_failed=true - return 1 - fi - if [[ -z "${reservation_namespace_json}" ]]; then - echo "Skipping PR #${pr_number}: Namespace ${namespace} disappeared after proof-retry annotation failure; retry on a later cycle." >&2 - return 1 - fi + reservation="$(jq -cn --arg repo "$GITHUB_REPOSITORY" --arg namespace "$namespace" \ + --arg uid "$namespace_uid" --arg nonce "$nonce" --argjson count "$next_count" \ + --arg base "$base_sha" --arg head "$head_sha" --arg merge "$merge_sha" --arg image "$image_tag" ' + {repository:$repo,namespace:$namespace,namespaceUid:$uid,nonce:$nonce,count:$count, + base:$base,head:$head,merge:$merge,image:$image} + ')" || return 1 + if ! holder="$(write_preview_retry_entry "$holder" "$namespace" "$reservation")"; then + echo "Unable to prove proof-retry reservation custody for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + return 1 fi - # The successful CAS response and a lost-response reread need the same full - # positive evidence; tuple/count alone must never attribute another writer. - if ! reservation_resource_version="$(validated_proof_retry_reservation_version \ - "$reservation_namespace_json" "$namespace" "$namespace_uid" \ - "${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" \ - "${base_sha}|${head_sha}|${merge_sha}|${image_tag}" "$next_retry_count" \ - "$reservation_id" "$namespace_resource_version")"; then - if [[ "$annotation_failed" == false ]]; then - echo "Unable to prove proof-retry reservation custody for PR #${pr_number} from the annotation response; leaving its budget charged without dispatch." >&2 - dispatch_outcome_failed=true - return 1 - fi - if ! fresh_namespace_tuple="$(parse_namespace_tuple "${reservation_namespace_json}")" || - ! recheck_namespace_name="$(jq -er '.metadata.name | select(type == "string" and length > 0 and (test("[|\\r\\n]") | not))' \ - <<<"${reservation_namespace_json}")"; then - echo "Unable to verify Namespace ${namespace} after proof-retry annotation failure; refusing dispatch with reservation outcome unknown." >&2 - dispatch_outcome_failed=true - return 1 - fi - IFS='|' read -r _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \ - recheck_namespace_uid recheck_namespace_resource_version <<<"${fresh_namespace_tuple}" - if [[ "${recheck_namespace_name}" != "${namespace}" || - ( -n "${recheck_namespace_uid}" && "${recheck_namespace_uid}" != "${namespace_uid}" ) ]]; then - echo "Skipping PR #${pr_number}: Namespace identity changed after proof-retry annotation failure; retry on a later cycle." >&2 - return 1 - fi - if [[ -z "${recheck_namespace_uid}" || -z "${recheck_namespace_resource_version}" || - "${recheck_namespace_resource_version}" == "${namespace_resource_version}" ]]; then - echo "Unable to prove a Namespace change after proof-retry annotation failure for PR #${pr_number}; refusing dispatch." >&2 + proof_retry_record="$reservation" + proof_retry_prior_record="$prior" + proof_retry_holder_uid="$(jq -r '.metadata.uid' <<<"$holder")" + if ! fresh_snapshot="$(kubectl get namespace "$namespace" --ignore-not-found -o json --request-timeout=10s)"; then + echo "Unable to verify the Namespace fence for PR #${pr_number}; refusing dispatch." >&2 + dispatch_outcome_failed=true + compensate_rejected_proof_retry "$namespace" "$pr_number" "before dispatch" || true + return 1 + fi + if [[ -z "$snapshot" && -n "$fresh_snapshot" ]] || + { [[ -n "$snapshot" ]] && ! jq -e --arg namespace "$namespace" --arg uid "$namespace_uid" \ + --arg rv "$namespace_resource_version" ' + .metadata.name == $namespace and .metadata.uid == $uid and .metadata.resourceVersion == $rv + ' <<<"$fresh_snapshot" >/dev/null; }; then + echo "Skipping PR #${pr_number}: Namespace fence changed before proof retry dispatch." >&2 + if ! compensate_rejected_proof_retry "$namespace" "$pr_number" "before dispatch"; then dispatch_outcome_failed=true - return 1 fi - echo "Skipping PR #${pr_number}: competing Namespace resource version observed after proof-retry annotation failure; retry on a later cycle." >&2 return 1 fi - proof_retry_reservation_count="${next_retry_count}" - proof_retry_reservation_id="${reservation_id}" - proof_retry_previous_reservation_id="${previous_reservation_id}" - proof_retry_previous_count="${retry_count}" - proof_retry_previous_base_sha="${retry_base_sha}" - proof_retry_previous_head_sha="${retry_head_sha}" - proof_retry_previous_merge_sha="${retry_merge_sha}" - proof_retry_previous_image_tag="${retry_image_tag}" - proof_retry_reservation_namespace_uid="${namespace_uid}" - proof_retry_reservation_deployed_tuple="${current_base_sha}|${current_head_sha}|${current_merge_sha}|${current_image_tag}" - proof_retry_reservation_resource_version="${reservation_resource_version}" - proof_retry_reservation_base_sha="${base_sha}" - proof_retry_reservation_head_sha="${head_sha}" - proof_retry_reservation_merge_sha="${merge_sha}" - proof_retry_reservation_image_tag="${image_tag}" - echo "Recorded proof retry ${next_retry_count}/3 for PR #${pr_number} (${base_sha}/${head_sha}/${merge_sha}/${image_tag})." + echo "Recorded proof retry $next_count/3 for PR #${pr_number} ($base_sha/$head_sha/$merge_sha/$image_tag)." return 0 } compensate_rejected_proof_retry() { - local namespace="$1" - local pr_number="$2" - local fresh_namespace_json - local namespace_resource_version - local -a annotations=() - - if [[ -z "${proof_retry_reservation_count}" ]]; then - return 0 - fi - if ! fresh_namespace_json="$(kubectl get namespace "${namespace}" --ignore-not-found -o json)"; then - echo "Unable to verify proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 - return 1 - fi - # An unrelated RV advance is safe only while the exact reservation ID and - # every custody field still match; the compensating CAS uses this fresh RV. - if [[ -z "${proof_retry_reservation_resource_version}" ]] || - ! namespace_resource_version="$(validated_proof_retry_reservation_version \ - "$fresh_namespace_json" "$namespace" "$proof_retry_reservation_namespace_uid" \ - "$proof_retry_reservation_deployed_tuple" \ - "${proof_retry_reservation_base_sha}|${proof_retry_reservation_head_sha}|${proof_retry_reservation_merge_sha}|${proof_retry_reservation_image_tag}" \ - "$proof_retry_reservation_count" "$proof_retry_reservation_id" "")"; then - echo "Proof-retry reservation for PR #${pr_number} changed before confirmed-rejection compensation; leaving its budget charged." >&2 - return 1 - fi - - if [[ -n "${proof_retry_previous_reservation_id}" ]]; then - annotations+=("firemud.dev/proof-retry-reservation-id=${proof_retry_previous_reservation_id}") - else - annotations+=(firemud.dev/proof-retry-reservation-id-) - fi - if [[ -n "${proof_retry_previous_count}" ]]; then - annotations+=( - "firemud.dev/proof-retry-count=${proof_retry_previous_count}" - "firemud.dev/proof-retry-base-sha=${proof_retry_previous_base_sha}" - "firemud.dev/proof-retry-head-sha=${proof_retry_previous_head_sha}" - "firemud.dev/proof-retry-merge-sha=${proof_retry_previous_merge_sha}" - "firemud.dev/proof-retry-image-tag=${proof_retry_previous_image_tag}" - ) - else - annotations+=( - firemud.dev/proof-retry-count- - firemud.dev/proof-retry-base-sha- - firemud.dev/proof-retry-head-sha- - firemud.dev/proof-retry-merge-sha- - firemud.dev/proof-retry-image-tag- - ) - fi - if ! kubectl annotate namespace "${namespace}" "${annotations[@]}" \ - --overwrite --resource-version "${namespace_resource_version}" >/dev/null; then - echo "Unable to release rejected proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 + local namespace="$1" pr_number="$2" reason="${3:-after GitHub confirmed dispatch rejection}" + local holder current + [[ -n "$proof_retry_record" ]] || return 0 + if ! holder="$(read_preview_retry_holder)" || + ! current="$(preview_retry_entry "$holder" "$namespace")" || + ! jq -e --arg uid "$proof_retry_holder_uid" '.metadata.uid == $uid' <<<"$holder" >/dev/null || + ! jq -en --argjson current "$current" --argjson reserved "$proof_retry_record" '$current == $reserved' >/dev/null || + ! write_preview_retry_entry "$holder" "$namespace" "$proof_retry_prior_record" >/dev/null; then + echo "Unable to release proof-retry reservation for PR #${pr_number}; leaving its budget charged." >&2 return 1 fi - echo "Released proof-retry reservation for PR #${pr_number} after GitHub confirmed dispatch rejection." + echo "Released proof-retry reservation for PR #${pr_number} $reason." } active_count="$(kubectl get namespaces -l firemud.dev/preview=true -o name | sed '/^$/d' | wc -l)" @@ -1049,7 +873,6 @@ dispatch_candidates() { IFS='|' read -r current_base_sha current_head_sha current_merge_sha current_image_tag \ requested_base_sha requested_head_sha requested_merge_sha requested_image_tag \ proof_base_sha proof_head_sha proof_merge_sha proof_image_tag proof_namespace_uid \ - _ _ _ _ _ \ namespace_uid _ <<<"${namespace_tuple}" elif [[ "$priority" != "true" && "$available_slots" -le 0 ]]; then if ! refresh_available_slots; then @@ -1320,21 +1143,7 @@ dispatch_candidates() { require_deployed_tuple=true fi # A consumer may finish deployment and proof during the active-run lookup. - local proof_retry_reservation_count="" - local proof_retry_reservation_id="" - local proof_retry_previous_reservation_id="" - local proof_retry_previous_count="" - local proof_retry_previous_base_sha="" - local proof_retry_previous_head_sha="" - local proof_retry_previous_merge_sha="" - local proof_retry_previous_image_tag="" - local proof_retry_reservation_namespace_uid="" - local proof_retry_reservation_resource_version="" - local proof_retry_reservation_deployed_tuple="" - local proof_retry_reservation_base_sha="" - local proof_retry_reservation_head_sha="" - local proof_retry_reservation_merge_sha="" - local proof_retry_reservation_image_tag="" + local proof_retry_record="" proof_retry_prior_record="" proof_retry_holder_uid="" prepare_preview_dispatch "$namespace" "$pr_number" "$base_sha" "$head_sha" "$merge_sha" "$image_tag" \ "$require_deployed_tuple" "$priority" "$namespace_uid" || continue diff --git a/dev-tools/hosted/shared/delete-hosted-namespace.sh b/dev-tools/hosted/shared/delete-hosted-namespace.sh index c987179d06..d01c17dea4 100644 --- a/dev-tools/hosted/shared/delete-hosted-namespace.sh +++ b/dev-tools/hosted/shared/delete-hosted-namespace.sh @@ -84,11 +84,32 @@ if [[ -n "$expected_namespace_uid" && "$namespace_uid" != "$expected_namespace_u exit 1 fi delete_uid="${expected_namespace_uid:-$namespace_uid}" +delete_resource_version="" + +if [[ -n "$expected_pr_number" ]]; then + script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib + source "$script_dir/../preview/preview-proof-retry-record.shlib" + if ! legacy_retry="$(legacy_preview_retry_entry "$namespace_json" "$namespace")"; then + echo "unable to read legacy proof-retry evidence for $namespace; refusing deletion" >&2 + exit 1 + fi + if [[ "$legacy_retry" != null ]]; then + if ! delete_resource_version="$(jq -er '.metadata.resourceVersion | select(type == "string" and length > 0)' <<<"$namespace_json")" || + ! preserve_legacy_preview_retry_entry "$legacy_retry" "$namespace"; then + echo "unable to retain the proof-retry budget for $namespace; refusing deletion" >&2 + exit 1 + fi + fi +fi delete_options="$( jq -cn \ --arg uid "$delete_uid" \ - '{apiVersion:"v1",kind:"DeleteOptions",preconditions:{uid:$uid}}' + --arg resource_version "$delete_resource_version" ' + {apiVersion:"v1",kind:"DeleteOptions",preconditions:{uid:$uid}} + | if $resource_version != "" then .preconditions.resourceVersion = $resource_version else . end + ' )" delete_status=0 printf '%s\n' "$delete_options" | diff --git a/dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py b/dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py index aeaf3008f2..04b6648f91 100644 --- a/dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py +++ b/dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py @@ -77,6 +77,11 @@ class Credential: ("get", "namespaces", None, "yes"), ("delete", "namespaces", None, "yes"), ("get", "secrets", "proof", "no"), + ("get", "configmaps/firemud-preview-proof-retries", "control", "yes"), + ("patch", "configmaps/firemud-preview-proof-retries", "control", "yes"), + ("create", "configmaps", "control", "no"), + ("list", "configmaps", "control", "no"), + ("patch", "configmaps/firemud-unrelated", "control", "no"), ), ), Credential( diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 90a1e5ae7f..8ea52ef230 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -1936,11 +1936,6 @@ clean_revalidate_step_index = next( for index, step in enumerate(deploy_steps) if step.get("name") == "Revalidate exact PR target before clean runtime redeploy" ) -capture_retry_step_index = next( - index - for index, step in enumerate(deploy_steps) - if step.get("name") == "Capture exact proof-retry record before namespace recreation" -) allocate_port_step_index = next( index for index, step in enumerate(deploy_steps) @@ -1959,7 +1954,6 @@ deployed_step_index = next( assert ( allocate_port_step_index < clean_revalidate_step_index - < capture_retry_step_index < clean_delete_step_index < requested_step_index < apply_step_index @@ -1994,30 +1988,6 @@ assert ( 'bash ./dev-tools/hosted/shared/delete-hosted-namespace.sh \\\n' ' "$RUNTIME_NAMESPACE" "$RUNTIME_NAMESPACE"' ) in clean_delete["run"] -capture_retry = deploy_by_name[ - "Capture exact proof-retry record before namespace recreation" -] -assert capture_retry["env"] == { - "KUBECONFIG": "${{ runner.temp }}/preview-namespace-manager.kubeconfig", - "RUNTIME_NAMESPACE": "${{ needs.validate-target.outputs.namespace }}", - "PR_NUMBER": "${{ needs.validate-target.outputs.pr_number }}", - "EXPECTED_BASE_SHA": "${{ needs.validate-target.outputs.base_sha }}", - "EXPECTED_HEAD_SHA": "${{ needs.validate-target.outputs.head_sha }}", - "EXPECTED_MERGE_SHA": "${{ needs.validate-target.outputs.merge_sha }}", - "EXPECTED_IMAGE_TAG": "${{ needs.validate-target.outputs.image_tag }}", -} -for required in ( - 'kubectl get namespace "$RUNTIME_NAMESPACE" --ignore-not-found -o json', - 'firemud.dev/proof-retry-count', - 'firemud.dev/proof-retry-base-sha', - 'firemud.dev/proof-retry-head-sha', - 'firemud.dev/proof-retry-merge-sha', - 'firemud.dev/proof-retry-image-tag', - 'Retry annotations must be a complete string record before namespace recreation.', - 'Existing proof-retry record belongs to another tuple; resetting its budget.', - 'proof_retry_count=$retry_count', -): - assert required in capture_retry["run"], required create_step = deploy_by_name["Create and annotate exact preview runtime namespace"] assert create_step["env"]["ALLOCATED_TELNET_PORT"] == ( "${{ steps.allocate-telnet-port.outputs.port }}" @@ -2025,14 +1995,8 @@ assert create_step["env"]["ALLOCATED_TELNET_PORT"] == ( assert create_step["env"]["ALLOCATION_TIMESTAMP"] == ( "${{ steps.allocate-capacity.outputs.allocation_timestamp }}" ) -for output_name in ( - "proof_retry_count", - "proof_retry_base_sha", - "proof_retry_head_sha", - "proof_retry_merge_sha", - "proof_retry_image_tag", -): - assert f"steps.capture-proof-retry.outputs.{output_name}" in create_step["run"] +assert "proof_retry_" not in create_step["run"] +assert "Capture exact proof-retry record before namespace recreation" not in deploy_by_name standalone_grpc_shared = deploy_by_name["Prepare standalone shared gRPC TLS secret"] standalone_grpc_certificates = deploy_by_name["Prepare standalone gRPC certificates"] standalone_grpc = deploy_by_name["Prepare standalone gRPC TLS secret"] @@ -3302,117 +3266,16 @@ mapfile -t preview_annotator_calls <"$preview_annotator_log" [[ "${preview_annotator_calls[1]}" == \ "label namespace pr-42 firemud.dev/preview=true firemud.dev/pr-number=42 firemud.dev/preview-exposure-mode=private --overwrite" ]] +# Retry custody belongs to the independent management holder. The runtime +# writer must reject additional retry arguments instead of restoring them. : >"$preview_annotator_log" -run_preview_annotator \ +if run_preview_annotator \ pr-42 42 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa cccccccccccccccccccccccccccccccccccccccc aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - private 0 2026-09-13T01:02:03Z \ - 2 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - cccccccccccccccccccccccccccccccccccccccc aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -mapfile -t preview_annotator_calls <"$preview_annotator_log" -[[ "${#preview_annotator_calls[@]}" -eq 2 ]] -[[ "${preview_annotator_calls[0]}" == *"firemud.dev/proof-retry-count=2"* ]] -[[ "${preview_annotator_calls[0]}" == *"firemud.dev/proof-retry-base-sha=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"* ]] -[[ "${preview_annotator_calls[0]}" == *"firemud.dev/proof-retry-head-sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* ]] -[[ "${preview_annotator_calls[0]}" == *"firemud.dev/proof-retry-merge-sha=cccccccccccccccccccccccccccccccccccccccc"* ]] -[[ "${preview_annotator_calls[0]}" == *"firemud.dev/proof-retry-image-tag=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"* ]] - -for partial_retry_args in \ - "2" \ - "2 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; do - : >"$preview_annotator_log" - read -r -a partial_retry_values <<<"$partial_retry_args" - if run_preview_annotator \ - pr-42 42 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa cccccccccccccccccccccccccccccccccccccccc aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - private 0 2026-09-13T01:02:03Z "${partial_retry_values[@]}" \ - >"$TEMP_DIR/invalid-preview-retry.output" \ - 2>"$TEMP_DIR/invalid-preview-retry.error"; then - echo "preview namespace annotator accepted a partial proof-retry record: $partial_retry_args" >&2 - exit 1 - fi - [[ ! -s "$preview_annotator_log" ]] -done - -capture_retry_step="$TEMP_DIR/capture-proof-retry.sh" -python3 - "$trusted" "$capture_retry_step" <<'PY' -import sys -from pathlib import Path - -import yaml - -workflow = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) -steps = workflow["jobs"]["deploy-runtime"]["steps"] -step = next( - step - for step in steps - if step.get("name") == "Capture exact proof-retry record before namespace recreation" -) -Path(sys.argv[2]).write_text(step["run"], encoding="utf-8") -PY -chmod +x "$capture_retry_step" -capture_retry_stub_dir="$TEMP_DIR/capture-retry-stubs" -capture_retry_namespace_json="$TEMP_DIR/capture-retry-namespace.json" -capture_retry_output="$TEMP_DIR/capture-retry-output" -capture_retry_partial_stdout="$TEMP_DIR/capture-retry-partial.stdout" -capture_retry_partial_stderr="$TEMP_DIR/capture-retry-partial.stderr" -mkdir -p "$capture_retry_stub_dir" -cat >"$capture_retry_stub_dir/kubectl" <<'SH' -#!/usr/bin/env bash -set -euo pipefail -if [[ "$1" == get && "$2" == namespace ]]; then - cat "${CAPTURE_RETRY_NAMESPACE_JSON:?}" - exit 0 -fi -printf 'unexpected capture-retry kubectl invocation: %s\n' "$*" >&2 -exit 2 -SH -chmod +x "$capture_retry_stub_dir/kubectl" -run_capture_retry() { - env \ - PATH="$capture_retry_stub_dir:$PATH" \ - KUBECONFIG=fake \ - RUNTIME_NAMESPACE=pr-42 \ - PR_NUMBER=42 \ - EXPECTED_BASE_SHA=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb \ - EXPECTED_HEAD_SHA=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - EXPECTED_MERGE_SHA=cccccccccccccccccccccccccccccccccccccccc \ - EXPECTED_IMAGE_TAG=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - GITHUB_OUTPUT="$capture_retry_output" \ - CAPTURE_RETRY_NAMESPACE_JSON="$capture_retry_namespace_json" \ - bash "$capture_retry_step" -} -jq -nc \ - '{metadata:{annotations:{ - "firemud.dev/proof-retry-count":"2", - "firemud.dev/proof-retry-base-sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "firemud.dev/proof-retry-head-sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "firemud.dev/proof-retry-merge-sha":"cccccccccccccccccccccccccccccccccccccccc", - "firemud.dev/proof-retry-image-tag":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }}}' >"$capture_retry_namespace_json" -: >"$capture_retry_output" -run_capture_retry -grep -Fqx 'proof_retry_count=2' "$capture_retry_output" -grep -Fqx 'proof_retry_base_sha=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' "$capture_retry_output" -grep -Fqx 'proof_retry_head_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' "$capture_retry_output" -grep -Fqx 'proof_retry_merge_sha=cccccccccccccccccccccccccccccccccccccccc' "$capture_retry_output" -grep -Fqx 'proof_retry_image_tag=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' "$capture_retry_output" - -jq -nc \ - '{metadata:{annotations:{ - "firemud.dev/proof-retry-count":"2", - "firemud.dev/proof-retry-base-sha":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" - }}}' >"$capture_retry_namespace_json" -: >"$capture_retry_output" -if run_capture_retry >"$capture_retry_partial_stdout" 2>"$capture_retry_partial_stderr"; then - echo "capture accepted a partial proof-retry annotation record" >&2 + private 0 2026-09-13T01:02:03Z 2 >/dev/null 2>&1; then + echo "preview namespace annotator accepted obsolete retry arguments" >&2 exit 1 fi -[[ ! -s "$capture_retry_output" ]] -grep -Fqx '::error title=Malformed proof-retry annotations::Retry annotations must be a complete string record before namespace recreation.' \ - "$capture_retry_partial_stderr" || { - echo "capture rejected a partial proof-retry record without the expected error; observed stderr:" >&2 - cat "$capture_retry_partial_stderr" >&2 - exit 1 - } +[[ ! -s "$preview_annotator_log" ]] invalid_preview_annotator_cases=( "pr-042|042|public|32000|2026-09-13T01:02:03Z" diff --git a/dev-tools/tests/preview-priority-contract.sh b/dev-tools/tests/preview-priority-contract.sh index 2cbd3141aa..137a18e06a 100644 --- a/dev-tools/tests/preview-priority-contract.sh +++ b/dev-tools/tests/preview-priority-contract.sh @@ -100,6 +100,49 @@ mkdir -p "$TEMP_DIR/bin" cat > "$TEMP_DIR/bin/kubectl" <<'EOF' #!/usr/bin/env bash set -euo pipefail +if [[ "$*" == "-n firemud-system get configmap firemud-preview-proof-retries -o json --request-timeout=10s" ]]; then + if [[ "${FAKE_RETRY_HOLDER_MISSING:-false}" == true ]]; then exit 1; fi + if [[ -f "$FAKE_RETRY_HOLDER" ]]; then + cat "$FAKE_RETRY_HOLDER" + else + printf '%s\n' '{"apiVersion":"v1","kind":"ConfigMap","metadata":{"namespace":"firemud-system","name":"firemud-preview-proof-retries","uid":"uid-holder","resourceVersion":"1"},"data":{"schemaVersion":"1"}}' + fi + exit 0 +fi +if [[ "${1:-}" == -n && "${2:-}" == firemud-system && "${3:-}" == patch && + "${4:-}" == configmap && "${5:-}" == firemud-preview-proof-retries && "${6:-}" == --type=json && + "${7:-}" == --patch && "${9:-}" == -o && "${10:-}" == json && "${11:-}" == --request-timeout=10s ]]; then + printf '%s\n' "$8" >> "$FAKE_RETRY_PATCH_LOG" + case "${FAKE_RETRY_PATCH_CASE:-}" in + denied) echo 'Error from server (Forbidden): holder patch denied' >&2; exit 1 ;; + esac + state="$(kubectl -n firemud-system get configmap firemud-preview-proof-retries -o json --request-timeout=10s)" + next="$(jq -ec --argjson patch "$8" ' + select(($patch | length) == 3 + and $patch[0] == {op:"test",path:"/metadata/uid",value:.metadata.uid} + and $patch[1] == {op:"test",path:"/metadata/resourceVersion",value:.metadata.resourceVersion} + and ($patch[2].path | test("^/data/pr-[1-9][0-9]*$"))) + | ($patch[2].path | ltrimstr("/data/")) as $key + | if $patch[2].op == "remove" then del(.data[$key]) + elif $patch[2].op == "add" then .data[$key] = $patch[2].value + else error("unexpected operation") end + | .metadata.resourceVersion |= (tonumber + 1 | tostring) + ' <<<"$state")" || exit 1 + if [[ "${FAKE_RETRY_PATCH_CASE:-}" == different-nonce ]]; then + next="$(jq -c '.data["pr-901"] |= (fromjson | .nonce = "12345678-1234-4234-8234-123456789abc" | tojson)' <<<"$next")" + fi + printf '%s\n' "$next" > "$FAKE_RETRY_HOLDER" + if [[ "${FAKE_RETRY_PATCH_CASE:-}" == lost-response || "${FAKE_RETRY_PATCH_CASE:-}" == different-nonce ]]; then + exit 1 + fi + case "${FAKE_RETRY_PATCH_CASE:-}" in + wrong-holder) jq -c '.metadata.uid = "replacement-holder"' <<<"$next" ;; + unchanged-version) jq -c --argjson old "$state" '.metadata.resourceVersion = $old.metadata.resourceVersion' <<<"$next" ;; + wrong-row) jq -c '.data["pr-901"] |= (fromjson | .count = 3 | tojson)' <<<"$next" ;; + *) printf '%s\n' "$next" ;; + esac + exit 0 +fi if [[ "$*" == *"get namespaces"* ]]; then if [[ "${FAKE_NAMESPACE_LIST_ERROR:-false}" == true ]]; then exit 1 @@ -148,22 +191,18 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && exit 0 fi if [[ -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" ]]; then - if [[ "${FAKE_ANNOTATE_CONFIRMATION_ERROR:-false}" == true || - "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == recheck-error ]]; then + if [[ "${FAKE_ANNOTATE_CONFIRMATION_ERROR:-false}" == true ]]; then exit 1 fi - if [[ "${FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE:-false}" == true || - "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == disappeared ]]; then - exit 0 - fi - if [[ "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == recheck-malformed ]]; then - printf '%s' '{not-json' + if [[ "${FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE:-false}" == true ]]; then exit 0 fi - # Only the post-annotation snapshot receives these failure scenarios. - snapshot_failure_case="${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" rm -f "${FAKE_ANNOTATE_FAILURE_MARKER:?}" fi + if [[ "${FAKE_RETRY_RUNTIME_DELETED_AFTER_REQUEST:-false}" == true && + -f "$FAKE_RUNTIME_DELETE_UID_LOG" ]]; then + exit 0 + fi canonical_head() { case "${1:-}" in head-901) printf '%s' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;; @@ -196,33 +235,9 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && if [[ "$count" -gt 1 && -v FAKE_PR_901_RECHECK_NAMESPACE_UID ]]; then snapshot_uid="$FAKE_PR_901_RECHECK_NAMESPACE_UID" fi - snapshot_retry_count="${FAKE_PR_901_PROOF_RETRY_COUNT:-}" - snapshot_retry_base="${FAKE_PR_901_PROOF_RETRY_BASE_SHA:-}" - snapshot_retry_head="${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" - snapshot_retry_merge="${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" - snapshot_retry_image="${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" snapshot_resource_version=rv-901 - if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then - jq -cn \ - --arg count "$snapshot_retry_count" --arg base "$snapshot_retry_base" \ - --arg head "$snapshot_retry_head" --arg merge "$snapshot_retry_merge" \ - --arg image "$snapshot_retry_image" --arg id "${FAKE_PR_901_PROOF_RETRY_RESERVATION_ID:-}" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"} - | if $id != "" then .id = $id else . end' \ - > "$FAKE_PROOF_RETRY_STATE_MARKER" - fi - snapshot_retry_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_retry_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_retry_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_retry_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_retry_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_retry_id="$(jq -r '.id // ""' "$FAKE_PROOF_RETRY_STATE_MARKER")" - snapshot_resource_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" - if [[ "${FAKE_UNRELATED_NAMESPACE_UPDATE:-false}" == true && "$snapshot_resource_version" == rv-902 ]]; then - jq -c '.resourceVersion = "rv-903"' "$FAKE_PROOF_RETRY_STATE_MARKER" \ - > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" - mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" - snapshot_resource_version=rv-903 + if [[ "${FAKE_RETRY_RUNTIME_CHANGE_BEFORE_SEND:-false}" == true && "$count" -gt 2 ]]; then + snapshot_resource_version=rv-drift fi proof_complete="${FAKE_PR_901_PROOF_COMPLETE:-true}" if [[ "$count" -gt 1 && "${FAKE_PR_901_PROOF_REMOVED_ON_RECHECK:-false}" == true ]]; then @@ -259,28 +274,19 @@ if [[ "$1" == get && "$2" == namespace && "$3" == pr-901 && --arg proof_merge "$snapshot_proof_merge" \ --arg proof_image "$snapshot_proof_image" \ --arg proof_uid "$snapshot_proof_uid" \ - --arg retry_count "$snapshot_retry_count" \ - --arg retry_base "$snapshot_retry_base" \ - --arg retry_head "$snapshot_retry_head" \ - --arg retry_merge "$snapshot_retry_merge" \ - --arg retry_image "$snapshot_retry_image" \ - --arg retry_id "$snapshot_retry_id" \ - --arg retry_count_present "${FAKE_PR_901_PROOF_RETRY_COUNT+x}" \ - --arg failure_case "${snapshot_failure_case:-}" \ + --arg legacy_retry "${FAKE_LEGACY_RETRY_JSON:-null}" \ --arg uid "$snapshot_uid" \ --arg resource_version "$snapshot_resource_version" \ - '{metadata:{name:"pr-901",uid:$uid,resourceVersion:$resource_version,annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head,"firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image,"firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head,"firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image,"firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head,"firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image,"firemud.dev/proof-preview-namespace-uid":$proof_uid,"firemud.dev/proof-retry-count":$retry_count,"firemud.dev/proof-retry-base-sha":$retry_base,"firemud.dev/proof-retry-head-sha":$retry_head,"firemud.dev/proof-retry-merge-sha":$retry_merge,"firemud.dev/proof-retry-image-tag":$retry_image}}} - | if $retry_count == "" and $retry_count_present != "x" then - del(.metadata.annotations["firemud.dev/proof-retry-count"]) - else . end - | if $retry_id != "" then .metadata.annotations["firemud.dev/proof-retry-reservation-id"] = $retry_id else . end - | if $failure_case == "recreated" then .metadata.uid = "uid-replacement" - elif $failure_case == "different-namespace" then .metadata.name = "pr-902" - elif $failure_case == "missing-uid" then del(.metadata.uid) - elif $failure_case == "missing-rv" then del(.metadata.resourceVersion) - elif $failure_case == "deployed-changed" then - .metadata.annotations["firemud.dev/last-preview-merge-sha"] = "dddddddddddddddddddddddddddddddddddddddd" - else . end' | tee "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" + '{metadata:{name:"pr-901",uid:$uid,resourceVersion:$resource_version, + labels:{"firemud.dev/preview":"true","firemud.dev/pr-number":"901"}, + annotations:{"firemud.dev/last-preview-base-sha":$base,"firemud.dev/last-preview-head-sha":$head, + "firemud.dev/last-preview-merge-sha":$merge,"firemud.dev/last-preview-image-tag":$image, + "firemud.dev/requested-preview-base-sha":$requested_base,"firemud.dev/requested-preview-head-sha":$requested_head, + "firemud.dev/requested-preview-merge-sha":$requested_merge,"firemud.dev/requested-preview-image-tag":$requested_image, + "firemud.dev/proof-preview-base-sha":$proof_base,"firemud.dev/proof-preview-head-sha":$proof_head, + "firemud.dev/proof-preview-merge-sha":$proof_merge,"firemud.dev/proof-preview-image-tag":$proof_image, + "firemud.dev/proof-preview-namespace-uid":$proof_uid}}} + | if $legacy_retry != "null" then .metadata.annotations += ($legacy_retry | fromjson) else . end' exit 0 fi if [[ "$1" == get && "$2" == namespace && @@ -390,144 +396,6 @@ if [[ "$1" == annotate && "$2" == namespace ]]; then : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" exit 1 fi - if [[ "${3:-}" == pr-901 && ( "$*" == *"firemud.dev/proof-retry-count="* || "$*" == *"firemud.dev/proof-retry-count-"* ) ]]; then - case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in - forbidden|stable-error|recheck-error|recheck-malformed|disappeared|recreated|different-namespace|missing-uid|missing-rv) - : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" - if [[ "$FAKE_PROOF_RETRY_ANNOTATE_FAILURE" == forbidden ]]; then - echo 'Error from server (Forbidden): namespaces "pr-901" is forbidden' >&2 - else - echo 'Unable to receive annotation response' >&2 - fi - exit 1 - ;; - esac - if [[ ! -f "${FAKE_PROOF_RETRY_STATE_MARKER:?}" ]]; then - jq -cn \ - --arg count "${FAKE_PR_901_PROOF_RETRY_COUNT:-}" \ - --arg base "${FAKE_PR_901_PROOF_RETRY_BASE_SHA:-}" \ - --arg head "${FAKE_PR_901_PROOF_RETRY_HEAD_SHA:-}" \ - --arg merge "${FAKE_PR_901_PROOF_RETRY_MERGE_SHA:-}" \ - --arg image "${FAKE_PR_901_PROOF_RETRY_IMAGE_TAG:-}" \ - --arg id "${FAKE_PR_901_PROOF_RETRY_RESERVATION_ID:-}" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:"rv-901"} - | if $id != "" then .id = $id else . end' \ - > "$FAKE_PROOF_RETRY_STATE_MARKER" - fi - state_version="$(jq -r '.resourceVersion' "$FAKE_PROOF_RETRY_STATE_MARKER")" - expected_version="" - annotate_args=("$@") - for ((i = 0; i + 1 < ${#annotate_args[@]}; i++)); do - if [[ "${annotate_args[i]}" == --resource-version ]]; then - expected_version="${annotate_args[i + 1]}" - break - fi - done - if [[ "$expected_version" != rv-901 ]]; then - case "${FAKE_PROOF_RETRY_COMPENSATION_CASE:-}" in - cas-conflict) - jq -c '.resourceVersion = "rv-903"' "$FAKE_PROOF_RETRY_STATE_MARKER" > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" - mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" - exit 1 - ;; - write-error) exit 1 ;; - esac - fi - if [[ "$state_version" != "$expected_version" ]]; then - exit 1 - fi - local_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" - local_base="$(jq -r '.base' "$FAKE_PROOF_RETRY_STATE_MARKER")" - local_head="$(jq -r '.head' "$FAKE_PROOF_RETRY_STATE_MARKER")" - local_merge="$(jq -r '.merge' "$FAKE_PROOF_RETRY_STATE_MARKER")" - local_image="$(jq -r '.image' "$FAKE_PROOF_RETRY_STATE_MARKER")" - local_id="$(jq -r '.id // ""' "$FAKE_PROOF_RETRY_STATE_MARKER")" - for annotation in "$@"; do - case "$annotation" in - firemud.dev/proof-retry-count=*) local_count="${annotation#*=}" ;; - firemud.dev/proof-retry-count-) local_count="" ;; - firemud.dev/proof-retry-base-sha=*) local_base="${annotation#*=}" ;; - firemud.dev/proof-retry-base-sha-) local_base="" ;; - firemud.dev/proof-retry-head-sha=*) local_head="${annotation#*=}" ;; - firemud.dev/proof-retry-head-sha-) local_head="" ;; - firemud.dev/proof-retry-merge-sha=*) local_merge="${annotation#*=}" ;; - firemud.dev/proof-retry-merge-sha-) local_merge="" ;; - firemud.dev/proof-retry-image-tag=*) local_image="${annotation#*=}" ;; - firemud.dev/proof-retry-image-tag-) local_image="" ;; - firemud.dev/proof-retry-reservation-id=*) local_id="${annotation#*=}" ;; - firemud.dev/proof-retry-reservation-id-) local_id="" ;; - esac - done - # A competing same-tuple writer has a different ID. The other changed-field - # cases retain this caller's ID to prove that the complete fence is needed. - case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in - competitor-version) - local_count="$(jq -r '.count' "$FAKE_PROOF_RETRY_STATE_MARKER")" - ;; - competitor-count) local_count=3 ;; - competitor-tuple) local_merge=ffffffffffffffffffffffffffffffffffffffff ;; - competitor-exact) - if [[ "${local_id:0:1}" == 0 ]]; then local_id="1${local_id:1}"; else local_id="0${local_id:1}"; fi - ;; - competitor-missing-id) local_id="" ;; - esac - state_resource_version=rv-902 - if [[ "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" == lost-response-unchanged-rv ]]; then - state_resource_version=rv-901 - fi - if [[ "$expected_version" == rv-902 ]]; then - state_resource_version=rv-903 - : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" - elif [[ "$expected_version" == rv-903 && "${FAKE_UNRELATED_NAMESPACE_UPDATE:-false}" == true ]]; then - state_resource_version=rv-904 - : > "${FAKE_PROOF_RETRY_COMPENSATED_MARKER:?}" - fi - jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ - --arg merge "$local_merge" --arg image "$local_image" --arg rv "$state_resource_version" --arg id "$local_id" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,resourceVersion:$rv} - | if $id != "" then .id = $id else . end' \ - > "$FAKE_PROOF_RETRY_STATE_MARKER" - case "${FAKE_PROOF_RETRY_ANNOTATE_FAILURE:-}" in - lost-response|lost-response-unchanged-rv|competitor-exact|competitor-missing-id|competitor-version|competitor-count|competitor-tuple|deployed-changed) - if [[ "$expected_version" == rv-901 ]]; then - : > "${FAKE_ANNOTATE_FAILURE_MARKER:?}" - if [[ "$FAKE_PROOF_RETRY_ANNOTATE_FAILURE" == lost-response* ]]; then - echo 'Reservation committed but its response was lost' >&2 - else - echo 'Error from server (Conflict): a competing writer changed the namespace' >&2 - fi - exit 1 - fi - ;; - esac - if [[ "$expected_version" == rv-901 ]]; then - jq -cn --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ - --arg merge "$local_merge" --arg image "$local_image" --arg id "$local_id" \ - '{count:$count,base:$base,head:$head,merge:$merge,image:$image,id:$id}' \ - > "${FAKE_PROOF_RETRY_RESERVATION_MARKER:?}" - if [[ "$*" == *"-o json"* ]]; then - jq -c --arg count "$local_count" --arg base "$local_base" --arg head "$local_head" \ - --arg merge "$local_merge" --arg image "$local_image" --arg id "$local_id" \ - --arg variant "${FAKE_PROOF_RETRY_RESPONSE_CASE:-}" ' - .metadata.resourceVersion = "rv-902" - | .metadata.annotations += {"firemud.dev/proof-retry-count":$count, - "firemud.dev/proof-retry-base-sha":$base,"firemud.dev/proof-retry-head-sha":$head, - "firemud.dev/proof-retry-merge-sha":$merge,"firemud.dev/proof-retry-image-tag":$image, - "firemud.dev/proof-retry-reservation-id":$id} - | if $variant == "missing-id" then del(.metadata.annotations["firemud.dev/proof-retry-reservation-id"]) - elif $variant == "different-id" then - .metadata.annotations["firemud.dev/proof-retry-reservation-id"] |= (if startswith("0") then "1" else "0" end) + .[1:] - elif $variant == "unchanged-rv" then .metadata.resourceVersion = "rv-901" - elif $variant == "wrong-uid" then .metadata.uid = "uid-other" - elif $variant == "wrong-deployed" then .metadata.annotations["firemud.dev/last-preview-head-sha"] = "dddddddddddddddddddddddddddddddddddddddd" - elif $variant == "wrong-count" then .metadata.annotations["firemud.dev/proof-retry-count"] = "3" - elif $variant == "wrong-tuple" then .metadata.annotations["firemud.dev/proof-retry-merge-sha"] = "dddddddddddddddddddddddddddddddddddddddd" - elif $variant == "malformed" then .metadata.annotations = [] - else . end - ' "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" - fi - fi - fi exit 0 fi if [[ "$*" == "-n firemud-system get hostedenvironmentidentities.platform.firemud.dev -o json" ]]; then @@ -825,17 +693,16 @@ if [[ "$1" == api && "$resource" =~ ^repos/example/FireMUD/actions/runs/(525[6-9 fi if [[ "$*" == *"repos/example/FireMUD/dispatches"* ]]; then printf '%s\n' "$*" >> "$FAKE_DISPATCH_LOG" - if [[ -f "$FAKE_PROOF_RETRY_STATE_MARKER" ]]; then - case "${FAKE_PROOF_RETRY_COMPENSATION_CASE:-}" in - different-id|missing-id) - jq -c --arg variant "$FAKE_PROOF_RETRY_COMPENSATION_CASE" ' - .resourceVersion = "rv-903" - | if $variant == "missing-id" then del(.id) - else .id |= (if startswith("0") then "1" else "0" end) + .[1:] end - ' "$FAKE_PROOF_RETRY_STATE_MARKER" > "${FAKE_PROOF_RETRY_STATE_MARKER}.next" - mv "${FAKE_PROOF_RETRY_STATE_MARKER}.next" "$FAKE_PROOF_RETRY_STATE_MARKER" - ;; - esac + if [[ "${FAKE_RETRY_CUSTODY_CHANGED_AT_POST:-false}" != false ]]; then + jq -c --arg change "$FAKE_RETRY_CUSTODY_CHANGED_AT_POST" ' + .metadata.resourceVersion |= (tonumber + 1 | tostring) + | if $change == "changed" then + .data["pr-901"] |= (fromjson | .nonce = "12345678-1234-4234-8234-123456789abc" | tojson) + else + .data["pr-902"] = (.data["pr-901"] | fromjson | .namespace = "pr-902" | tojson) + end + ' "$FAKE_RETRY_HOLDER" > "${FAKE_RETRY_HOLDER}.next" + mv "${FAKE_RETRY_HOLDER}.next" "$FAKE_RETRY_HOLDER" fi if [[ "${FAKE_DISPATCH_MISSING_STATUS:-false}" == true ]]; then exit "${FAKE_DISPATCH_GH_EXIT_CODE:-1}" @@ -1003,6 +870,13 @@ case "$resource" in printf '%s\t%s\t%s\n' "${FAKE_TARGET_STATE:-open}" "$FAKE_TARGET_HEAD" "$(fake_labels_json "$priority" "$labels_valid" | base64 | tr -d '\n')" ;; */pulls/901) + if [[ -n "${FAKE_RETRY_MERGE_STATE:-}" ]]; then + jq -cn --arg result "$FAKE_RETRY_MERGE_STATE" ' + {number:901,state:"closed",merged:($result != "unmerged"), + head:{repo:{full_name:"example/FireMUD"}}, + base:{repo:{full_name:(if $result == "wrong-owner" then "example/another" else "example/FireMUD" end)}}}' + exit 0 + fi live_head="${FAKE_PR_901_HEAD:-head-901}" case "$live_head" in head-901|stale-head) live_head=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ;; @@ -1329,9 +1203,8 @@ export FAKE_COMMENT_METHOD_LOG="$TEMP_DIR/comment-method.log" export FAKE_ANNOTATE_LOG="$TEMP_DIR/annotate.log" export FAKE_ANNOTATE_FAILURE_MARKER="$TEMP_DIR/annotate-failure.marker" export FAKE_DISPATCH_LOG="$TEMP_DIR/dispatch.log" -export FAKE_PROOF_RETRY_RESERVATION_MARKER="$TEMP_DIR/proof-retry-reservation.json" -export FAKE_PROOF_RETRY_COMPENSATED_MARKER="$TEMP_DIR/proof-retry-compensated.marker" -export FAKE_PROOF_RETRY_STATE_MARKER="$TEMP_DIR/proof-retry-state.json" +export FAKE_RETRY_HOLDER="$TEMP_DIR/proof-retry-holder.json" +export FAKE_RETRY_PATCH_LOG="$TEMP_DIR/proof-retry-patch.log" export FAKE_SLEEP_LOG="$TEMP_DIR/sleep.log" export FAKE_NAMESPACE_LIST_CALLS="$TEMP_DIR/namespace-list-calls" export FAKE_RECENT_HANDOFF_LOOKUP_LOG="$TEMP_DIR/recent-handoff-lookup.log" @@ -1373,8 +1246,7 @@ adversarial_labels_base64="$(printf '%s' '[{"name":"custom:label"},{"name":"quot invalid_json_labels_base64="$(printf '%s' '{invalid-json' | base64 | tr -d '\n')" reset_case() { - rm -f "${FAKE_PROOF_RETRY_STATE_MARKER}.snapshot" - rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" "$FAKE_PROOF_RETRY_STATE_MARKER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_SLEEP_LOG" "$FAKE_NAMESPACE_LIST_CALLS" "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" + rm -f "$FAKE_DELETE_LOG" "$FAKE_DELETE_TIMEOUT_LOG" "$FAKE_PUBLISH_LOG" "$FAKE_PUBLISHED_STATE" "$FAKE_PUBLISH_CALLS" "$FAKE_SOURCE_BINDING_CALLS" "$FAKE_COMMENT_METHOD_LOG" "$FAKE_COMMENT_TARGET_LOG" "$FAKE_PREVIOUS_COMMENT_ID_LOG" "$FAKE_ANNOTATE_LOG" "$FAKE_ANNOTATE_FAILURE_MARKER" "$FAKE_DISPATCH_LOG" "$FAKE_RETRY_PATCH_LOG" "$FAKE_RETRY_HOLDER" "$FAKE_TRUSTED_CONSUMER_COMPLETED_MARKER" "$FAKE_SLEEP_LOG" "$FAKE_NAMESPACE_LIST_CALLS" "$FAKE_RECENT_HANDOFF_LOOKUP_LOG" "$FAKE_TARGET_CALLS" "$FAKE_TARGET_METADATA_CALLS" "$FAKE_PR_101_CALLS" "$FAKE_PRUNE_QUERY_LOG" "$FAKE_PRIORITY_QUERY_LOG" "$FAKE_NAMESPACE_JSON_CALLS" "$FAKE_RECONCILER_RESOLUTION_LOG" "$FAKE_NAMESPACE_SNAPSHOT_LOG" "$FAKE_NAMESPACE_SNAPSHOT_CALLS" "$FAKE_RUNTIME_KUBECTL_LOG" "$FAKE_RUNTIME_DELETE_UID_LOG" "$FAKE_RUNTIME_NAMESPACE_DELETED_MARKER" "$FAKE_RUNTIME_WAIT_MARKER" "$FAKE_HELM_LOG" "$FAKE_IDENTITY_LOG" "$FAKE_IDENTITY_LIST_KUBECONFIG_LOG" "$FAKE_IDENTITY_REQUEST_LOG" "$FAKE_IDENTITY_WAIT_LOG" "$FAKE_OPERATION_SEQUENCE" "$TEMP_DIR/output" export GITHUB_OUTPUT="$TEMP_DIR/output" export FAKE_TARGET_PRIORITY=true export FAKE_TARGET_LABELS_VALID=valid @@ -1431,8 +1303,6 @@ reset_case() { export FAKE_NAMESPACE_SNAPSHOT_PARSE_FAIL=false export FAKE_NAMESPACE_SNAPSHOT_RECHECK_PARSE_FAIL=false export FAKE_ANNOTATE_ERROR=false - unset FAKE_PROOF_RETRY_ANNOTATE_FAILURE FAKE_PROOF_RETRY_RESPONSE_CASE \ - FAKE_PROOF_RETRY_COMPENSATION_CASE FAKE_PR_901_PROOF_RETRY_RESERVATION_ID export FAKE_ANNOTATE_CONFIRMATION_ERROR=false export FAKE_ANNOTATE_NAMESPACE_ABSENT_AFTER_FAILURE=false export FAKE_DELETE_FAIL=false @@ -1488,6 +1358,201 @@ reset_case() { unset PREVIEW_REVALIDATE_SOURCE_BINDING_SCRIPT } +run_proof_retry_contract() ( + local retry_reconciler="$ROOT_DIR/dev-tools/hosted/preview/reconcile-preview-deploys.sh" + local base=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + local head=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + local merge=cccccccccccccccccccccccccccccccccccccccc + local other_base=dddddddddddddddddddddddddddddddddddddddd + local nonce=01234567-0123-4123-8123-0123456789ab + local case_output="$TEMP_DIR/durable-proof-retry.out" + + seed_retry_holder() { + local count="$1" seed_base="${2:-$base}" repo="${3:-$GITHUB_REPOSITORY}" + jq -cn --argjson count "$count" --arg base "$seed_base" --arg head "$head" \ + --arg merge "$merge" --arg repo "$repo" --arg nonce "$nonce" ' + {apiVersion:"v1",kind:"ConfigMap", + metadata:{namespace:"firemud-system",name:"firemud-preview-proof-retries",uid:"uid-holder",resourceVersion:"1"}, + data:{schemaVersion:"1","pr-901":({repository:$repo,namespace:"pr-901",namespaceUid:"uid-pr-901", + nonce:$nonce,count:$count,base:$base,head:$head,merge:$merge,image:$base} | tojson)}}' > "$FAKE_RETRY_HOLDER" + } + + fixture_reconcile() ( + cd "$ROOT_DIR" + FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ + FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ + FAKE_PR_901_PROOF_COMPLETE=false DEFAULT_BRANCH=develop PREVIEW_MAX_ACTIVE=2 \ + bash "$retry_reconciler" + ) + + assert_retry_count() { + jq -e --argjson count "$1" '(.data["pr-901"] | fromjson).count == $count' "$FAKE_RETRY_HOLDER" >/dev/null + } + + reset_case + fixture_reconcile >"$case_output" + grep -Fq 'Recorded proof retry 1/3 for PR #901' "$case_output" + assert_retry_count 1 + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + test ! -e "$FAKE_ANNOTATE_LOG" + jq -se 'length == 1 and .[0][0].value == "uid-holder" and .[0][1].value == "1" + and ((.[0][2].value | length) < 512)' "$FAKE_RETRY_PATCH_LOG" >/dev/null + + reset_case + seed_retry_holder 2 + if FAKE_DISPATCH_HTTP_STATUS=500 fixture_reconcile >"$case_output" 2>&1; then + echo 'an unknown provider outcome must surface after charging the reservation' >&2 + exit 1 + fi + grep -Fq 'proof-retry budget remains charged' "$case_output" + assert_retry_count 3 + # A fresh callback after deletion, and then an unannotated replacement, + # recognize the same exhausted tuple without dispatching or patching it. + FAKE_PR_901_NAMESPACE_ABSENT=true fixture_reconcile >"$case_output" 2>&1 + grep -Fq 'proof retry budget exhausted' "$case_output" + FAKE_PR_901_SNAPSHOT_HEAD='' FAKE_PR_901_NAMESPACE_UID=replacement-uid fixture_reconcile >"$case_output" 2>&1 + grep -Fq 'proof retry budget exhausted' "$case_output" + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + test "$(wc -l < "$FAKE_RETRY_PATCH_LOG")" -eq 1 + + reset_case + seed_retry_holder 3 "$other_base" + FAKE_PR_901_NAMESPACE_ABSENT=true fixture_reconcile >"$case_output" + grep -Fq 'Dispatching preview render for PR #901' "$case_output" + assert_retry_count 3 + fixture_reconcile >"$case_output" + assert_retry_count 1 + jq -e --arg base "$base" '(.data["pr-901"] | fromjson).base == $base' "$FAKE_RETRY_HOLDER" >/dev/null + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 2 + + for patch_case in denied different-nonce wrong-holder unchanged-version wrong-row lost-response; do + reset_case + seed_retry_holder 1 + local status=0 + FAKE_RETRY_PATCH_CASE="$patch_case" fixture_reconcile >"$case_output" 2>&1 || status=$? + test "$(wc -l < "$FAKE_RETRY_PATCH_LOG")" -eq 1 + if [[ "$patch_case" == lost-response ]]; then + test "$status" -eq 0 + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + assert_retry_count 2 + else + test "$status" -ne 0 + grep -Fq 'Unable to prove proof-retry reservation custody' "$case_output" + test ! -e "$FAKE_DISPATCH_LOG" + fi + done + + reset_case + if FAKE_RETRY_HOLDER_MISSING=true fixture_reconcile >"$case_output" 2>&1; then + echo 'missing holder authorized dispatch' >&2 + exit 1 + fi + grep -Fq 'Unable to verify the proof-retry holder' "$case_output" + test ! -e "$FAKE_DISPATCH_LOG" + + reset_case + seed_retry_holder 2 "$base" example/another + if fixture_reconcile >"$case_output" 2>&1; then + echo 'record with the wrong repository authorized dispatch' >&2 + exit 1 + fi + test ! -e "$FAKE_RETRY_PATCH_LOG" + test ! -e "$FAKE_DISPATCH_LOG" + + reset_case + seed_retry_holder 1 + FAKE_RETRY_RUNTIME_CHANGE_BEFORE_SEND=true fixture_reconcile >"$case_output" 2>&1 + grep -Fq 'Namespace fence changed before proof retry dispatch' "$case_output" + assert_retry_count 1 + test "$(wc -l < "$FAKE_RETRY_PATCH_LOG")" -eq 2 + test ! -e "$FAKE_DISPATCH_LOG" + + for custody in exact updated changed; do + reset_case + seed_retry_holder 2 + local mutate="$custody" + [[ "$custody" != exact ]] || mutate=false + if FAKE_RETRY_CUSTODY_CHANGED_AT_POST="$mutate" FAKE_DISPATCH_HTTP_STATUS=422 fixture_reconcile >"$case_output" 2>&1; then + echo 'confirmed rejection was reported successful' >&2 + exit 1 + fi + test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 + if [[ "$custody" != changed ]]; then + assert_retry_count 2 + jq -e --arg nonce "$nonce" '(.data["pr-901"] | fromjson).nonce == $nonce' "$FAKE_RETRY_HOLDER" >/dev/null + test "$(wc -l < "$FAKE_RETRY_PATCH_LOG")" -eq 2 + if [[ "$custody" == updated ]]; then + jq -e '.data | has("pr-902")' "$FAKE_RETRY_HOLDER" >/dev/null + fi + else + assert_retry_count 3 + test "$(wc -l < "$FAKE_RETRY_PATCH_LOG")" -eq 1 + fi + done + + reset_case + if FAKE_DISPATCH_HTTP_STATUS=422 fixture_reconcile >"$case_output" 2>&1; then + echo 'confirmed initial rejection was reported successful' >&2 + exit 1 + fi + jq -e '.data == {schemaVersion:"1"}' "$FAKE_RETRY_HOLDER" >/dev/null + + reset_case + seed_retry_holder 2 + if FAKE_DISPATCH_HTTP_STATUS=429 FAKE_DISPATCH_RETRY_AFTER=30 fixture_reconcile >"$case_output" 2>&1; then + echo 'rate-limited rejection was reported successful' >&2 + exit 1 + fi + assert_retry_count 2 + test "$(<"$FAKE_SLEEP_LOG")" = 30 + + reset_case + local legacy + legacy="$(jq -cn --arg base "$base" --arg head "$head" --arg merge "$merge" ' + {"firemud.dev/proof-retry-count":"3","firemud.dev/proof-retry-base-sha":$base, + "firemud.dev/proof-retry-head-sha":$head,"firemud.dev/proof-retry-merge-sha":$merge, + "firemud.dev/proof-retry-image-tag":$base}')" + FAKE_LEGACY_RETRY_JSON="$legacy" FAKE_RETRY_RUNTIME_DELETED_AFTER_REQUEST=true \ + FAKE_RUNTIME_NAMESPACE_UID=uid-pr-901 bash "$DELETE_HOSTED_NAMESPACE" pr-901 pr-901 >"$case_output" + assert_retry_count 3 + test "$(<"$FAKE_RUNTIME_DELETE_UID_LOG")" = uid-pr-901 + # Stop between deletion and restore. There is no recreated Namespace or + # workflow output to recover, and the next callback still sees count three. + FAKE_PR_901_NAMESPACE_ABSENT=true fixture_reconcile >"$case_output" 2>&1 + grep -Fq 'proof retry budget exhausted' "$case_output" + test ! -e "$FAKE_DISPATCH_LOG" + + reset_case + if FAKE_LEGACY_RETRY_JSON='{"firemud.dev/proof-retry-count":""}' \ + bash "$DELETE_HOSTED_NAMESPACE" pr-901 pr-901 >"$case_output" 2>&1; then + echo 'malformed legacy record permitted deletion' >&2 + exit 1 + fi + test ! -e "$FAKE_RUNTIME_DELETE_UID_LOG" + + for terminal_case in unmerged wrong-owner runtime-live merged; do + reset_case + seed_retry_holder 3 + local namespace_absent=true + [[ "$terminal_case" != runtime-live ]] || namespace_absent=false + FAKE_NAMESPACE_ROWS='' FAKE_PR_901_NAMESPACE_ABSENT="$namespace_absent" \ + FAKE_RETRY_MERGE_STATE="$terminal_case" bash "$PRUNER" --apply --retire-proof-retries >"$case_output" + if [[ "$terminal_case" == merged ]]; then + jq -e '.data == {schemaVersion:"1"}' "$FAKE_RETRY_HOLDER" >/dev/null + grep -Fq 'Retired the proof-retry record for merged PR #901' "$case_output" + else + assert_retry_count 3 + test ! -e "$FAKE_RETRY_PATCH_LOG" + fi + done + echo 'Preview durable proof-retry contract passed.' +) + +run_proof_retry_contract +if [[ "${PREVIEW_RETRY_CONTRACT_ONLY:-false}" == true ]]; then + exit 0 +fi + run_allocator() { bash "$ALLOCATOR" "$1" "$2" "$3" "$4" \ "$FAKE_TARGET_BASE_SHA" "$FAKE_TARGET_MERGE_SHA" @@ -3235,7 +3300,7 @@ reconciler_completed_dispatch_skip_output="$TEMP_DIR/reconciler-completed-dispat grep -Fqx \ "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ "$reconciler_completed_dispatch_skip_output" -test -s "$FAKE_ANNOTATE_LOG" +test -s "$FAKE_RETRY_PATCH_LOG" test -s "$FAKE_DISPATCH_LOG" reset_case @@ -3437,7 +3502,7 @@ elif [[ "$observation_case" == consumer-finished-without-proof ]]; then grep -Fqx \ "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ "$reconciler_active_status_advance_output" - test -s "$FAKE_ANNOTATE_LOG" + test -s "$FAKE_RETRY_PATCH_LOG" test -s "$FAKE_DISPATCH_LOG" else grep -Fqx \ @@ -3448,24 +3513,6 @@ fi done -reset_case -reconciler_first_proof_retry_output="$TEMP_DIR/reconciler-first-proof-retry.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_first_proof_retry_output" -grep -Fqx \ - "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ - "$reconciler_first_proof_retry_output" -grep -Fq -- 'firemud.dev/proof-retry-count=1' "$FAKE_ANNOTATE_LOG" -grep -Fq -- '--resource-version rv-901' "$FAKE_ANNOTATE_LOG" -grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" - for namespace_count_sequence in 2,1 2,2; do reset_case reconciler_capacity_refresh_output="$TEMP_DIR/reconciler-capacity-refresh-${namespace_count_sequence//,/-}.out" @@ -3517,467 +3564,8 @@ for namespace_count_sequence in 2,1 2,2; do fi done -reset_case -reconciler_preserved_proof_retry_output="$TEMP_DIR/reconciler-preserved-proof-retry.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_DISPATCH_HTTP_STATUS=204 \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_preserved_proof_retry_output" -grep -Fqx \ - "Recorded proof retry 3/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ - "$reconciler_preserved_proof_retry_output" -grep -Fq -- 'firemud.dev/proof-retry-count=3' "$FAKE_ANNOTATE_LOG" -grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" -test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 -jq -e '.id | test("^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")' \ - "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null - -for compensation_case in existing-tuple version-moved different-tuple prior-id lost-response; do -reset_case -reconciler_rejected_proof_retry_output="$TEMP_DIR/reconciler-rejected-proof-retry-${compensation_case}.out" -namespace_update=false -expected_resource_version=rv-902 -result_resource_version=rv-903 -previous_base="$preview_base_sha" -previous_head="$preview_head_sha" -previous_merge="$preview_merge_sha" -previous_image="$preview_image_tag" -previous_id="" -reservation_failure="" -if [[ "$compensation_case" == lost-response ]]; then - reservation_failure=lost-response -fi -expected_reservation_count=3 -if [[ "$compensation_case" == version-moved ]]; then - namespace_update=true - expected_resource_version=rv-903 - result_resource_version=rv-904 -elif [[ "$compensation_case" == different-tuple ]]; then - previous_head=dddddddddddddddddddddddddddddddddddddddd - previous_merge=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - previous_image=pr-merge-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - expected_reservation_count=1 -fi -if [[ "$compensation_case" == prior-id || "$compensation_case" == different-tuple ]]; then - previous_id=11111111-1111-4111-8111-111111111111 -fi -if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$previous_base" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$previous_head" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$previous_merge" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$previous_image" \ - FAKE_PR_901_PROOF_RETRY_RESERVATION_ID="$previous_id" \ - FAKE_PROOF_RETRY_ANNOTATE_FAILURE="$reservation_failure" \ - FAKE_DISPATCH_HTTP_STATUS=422 \ - FAKE_UNRELATED_NAMESPACE_UPDATE="$namespace_update" \ - PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_rejected_proof_retry_output" 2>&1; then - echo "confirmed dispatch rejection left the reconcile job successful" >&2 - exit 1 -fi -grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 422).' \ - "$reconciler_rejected_proof_retry_output" -grep -Fq 'Released proof-retry reservation for PR #901 after GitHub confirmed dispatch rejection.' \ - "$reconciler_rejected_proof_retry_output" -grep -Fq -- "firemud.dev/proof-retry-count=${expected_reservation_count}" "$FAKE_ANNOTATE_LOG" -grep -Fq -- 'firemud.dev/proof-retry-count=2' "$FAKE_ANNOTATE_LOG" -grep -Fq -- "--resource-version ${expected_resource_version}" "$FAKE_ANNOTATE_LOG" -test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" -if [[ "$compensation_case" == lost-response ]]; then - test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 4 - test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 - test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 2 -else - jq -e --arg expected_count "$expected_reservation_count" --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ - '.count == $expected_count and .base == $base and .head == $head and .merge == $merge and .image == $image' \ - "$FAKE_PROOF_RETRY_RESERVATION_MARKER" >/dev/null -fi -jq -e --arg base "$previous_base" --arg head "$previous_head" --arg rv "$result_resource_version" \ - --arg merge "$previous_merge" --arg image "$previous_image" --arg id "$previous_id" \ - '.count == "2" and .base == $base and .head == $head and .merge == $merge - and .image == $image and .resourceVersion == $rv and (.id // "") == $id' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -if [[ -n "$previous_id" ]]; then - grep -Fq -- "firemud.dev/proof-retry-reservation-id=${previous_id}" "$FAKE_ANNOTATE_LOG" -else - grep -Fq -- 'firemud.dev/proof-retry-reservation-id-' "$FAKE_ANNOTATE_LOG" -fi -done - -reset_case -no_prior_reservation_output="$TEMP_DIR/reconciler-rejected-first-reservation.out" -if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false FAKE_DISPATCH_HTTP_STATUS=422 \ - PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" -) > "$no_prior_reservation_output" 2>&1; then - echo "confirmed first-reservation rejection left the reconcile job successful" >&2 - exit 1 -fi -grep -Fq 'Released proof-retry reservation for PR #901' "$no_prior_reservation_output" -test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 -test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 2 -jq -e '.count == "" and .base == "" and .head == "" and .merge == "" and .image == "" and (has("id") | not)' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null - -for compensation_failure in different-id missing-id cas-conflict write-error; do - reset_case - compensation_failure_output="$TEMP_DIR/reconciler-compensation-${compensation_failure}.out" - if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=1 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_PROOF_RETRY_COMPENSATION_CASE="$compensation_failure" \ - FAKE_DISPATCH_HTTP_STATUS=422 PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" - ) > "$compensation_failure_output" 2>&1; then - echo "failed compensation ${compensation_failure} left the reconcile job successful" >&2 - exit 1 - fi - grep -Fq 'The rejected dispatch could not be safely compensated; its proof-retry budget remains charged.' "$compensation_failure_output" - test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 - test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" - expected_annotates=1 - if [[ "$compensation_failure" == cas-conflict || "$compensation_failure" == write-error ]]; then - expected_annotates=2 - fi - test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq "$expected_annotates" - jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ - '.count == "2" and .base == $base and .head == $head and .merge == $merge and .image == $image' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -done - -reset_case -reconciler_ambiguous_proof_retry_output="$TEMP_DIR/reconciler-ambiguous-proof-retry.out" -if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_DISPATCH_HTTP_STATUS=500 \ - PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_ambiguous_proof_retry_output" 2>&1; then - echo "ambiguous dispatch outcome left the reconcile job successful" >&2 - exit 1 -fi -grep -Fq 'outcome for PR #901 is ambiguous (gh=1, HTTP=500); proof-retry budget remains charged.' \ - "$reconciler_ambiguous_proof_retry_output" -test "$(jq -r '.count' "$FAKE_PROOF_RETRY_RESERVATION_MARKER")" = 3 -test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 -jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ - '.count == "3" and .base == $base and .head == $head and .merge == $merge - and .image == $image and .resourceVersion == "rv-902"' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" -jq -es '.[0].id != null and .[0].id == .[1].id' \ - "$FAKE_PROOF_RETRY_RESERVATION_MARKER" "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -if grep -Fq -- '--resource-version rv-902' "$FAKE_ANNOTATE_LOG"; then - echo "ambiguous dispatch outcome released a proof-retry reservation" >&2 - exit 1 -fi - -for rate_case in http-429 http-403-evidence; do - reset_case - rate_limit_output="$TEMP_DIR/reconciler-rate-limit-${rate_case}.out" - rate_status=429 - rate_after=90 - if [[ "$rate_case" == http-403-evidence ]]; then - rate_status=403 - rate_after=30 - fi - if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_DISPATCH_HTTP_STATUS="$rate_status" \ - FAKE_DISPATCH_RETRY_AFTER="$rate_after" \ - PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" - ) > "$rate_limit_output" 2>&1; then - echo "rate-limited dispatch left the reconcile job successful" >&2 - exit 1 - fi - grep -Fq "GitHub rate-limited preview dispatch; stopping this cycle and waiting" "$rate_limit_output" - grep -Fq 'the preview dispatch cycle already stopped after a request attempt' "$rate_limit_output" - test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 - test "$(<"$FAKE_SLEEP_LOG")" = "$rate_after" - test -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" - jq -e --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$preview_merge_sha" --arg image "$preview_image_tag" \ - '.count == "2" and .base == $base and .head == $head and .merge == $merge - and .image == $image and .resourceVersion == "rv-903"' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -done - -reset_case -reconciler_candidate_rejection_output="$TEMP_DIR/reconciler-candidate-rejection.out" -if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="0\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n1\t902\thead-902\thuman\tdevelop\topen\t${ordinary_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=2 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_DISPATCH_HTTP_STATUS=403 \ - PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_candidate_rejection_output" 2>&1; then - echo "definitive dispatch rejections left the reconcile job successful" >&2 - exit 1 -fi -grep -Fq 'GitHub confirmed preview dispatch rejection for PR #901 (HTTP 403).' "$reconciler_candidate_rejection_output" -if ! grep -Fq 'Dispatching preview render for PR #902' "$reconciler_candidate_rejection_output"; then - cat "$reconciler_candidate_rejection_output" >&2 - exit 1 -fi -test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 2 -test ! -e "$FAKE_SLEEP_LOG" - -for deployed_head in head-901 ""; do -reset_case -reconciler_exhausted_proof_retry_output="$TEMP_DIR/reconciler-exhausted-proof-retry.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_SNAPSHOT_HEAD="$deployed_head" \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=3 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_exhausted_proof_retry_output" 2>&1 -grep -Fq 'proof retry budget exhausted' "$reconciler_exhausted_proof_retry_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" -done - -reset_case -reconciler_changed_tuple_retry_output="$TEMP_DIR/reconciler-changed-tuple-retry.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=3 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA=dddddddddddddddddddddddddddddddddddddddd \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA=eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA=ffffffffffffffffffffffffffffffffffffffff \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG=old-image \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_changed_tuple_retry_output" -grep -Fqx \ - "Recorded proof retry 1/3 for PR #901 (${preview_base_sha}/${preview_head_sha}/${preview_merge_sha}/${preview_image_tag})." \ - "$reconciler_changed_tuple_retry_output" -grep -Fq -- "firemud.dev/proof-retry-count=1" "$FAKE_ANNOTATE_LOG" -grep -Fq -- "firemud.dev/proof-retry-base-sha=${preview_base_sha}" "$FAKE_ANNOTATE_LOG" -grep -Fq 'repos/example/FireMUD/dispatches -f event_type=preview-deploy' "$FAKE_DISPATCH_LOG" - -for malformed_retry_count in 3 '' ' '; do -reset_case -reconciler_malformed_proof_retry_output="$TEMP_DIR/reconciler-malformed-proof-retry.out" -( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT="$malformed_retry_count" \ -PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" -) > "$reconciler_malformed_proof_retry_output" 2>&1 -grep -Fq 'unable to parse namespace pr-901 snapshot' "$reconciler_malformed_proof_retry_output" -test ! -e "$FAKE_ANNOTATE_LOG" -test ! -e "$FAKE_DISPATCH_LOG" -test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 1 -done - -# Every failed annotation gets one bounded reread and never another reservation -# CAS. Only a lost success with this caller's ID and the full fence may POST once. -for reservation_failure in forbidden stable-error recheck-error recheck-malformed \ - disappeared recreated different-namespace missing-uid missing-rv \ - competitor-version competitor-count competitor-tuple deployed-changed \ - lost-response lost-response-unchanged-rv competitor-exact competitor-missing-id; do - reset_case - reservation_failure_output="$TEMP_DIR/reconciler-reservation-${reservation_failure}.out" - expected_status=1 - expected_count=1 - expected_rv=rv-901 - expected_merge="$preview_merge_sha" - expected_dispatches=0 - expected_diagnostic='Unable to prove a Namespace change after proof-retry annotation failure' - case "$reservation_failure" in - recheck-error) - expected_diagnostic='Unable to recheck Namespace pr-901 after proof-retry annotation failure' - ;; - recheck-malformed) - expected_diagnostic='Unable to verify Namespace pr-901 after proof-retry annotation failure' - ;; - disappeared) - expected_status=0 - expected_diagnostic='Namespace pr-901 disappeared after proof-retry annotation failure' - ;; - recreated|different-namespace) - expected_status=0 - expected_diagnostic='Namespace identity changed after proof-retry annotation failure' - ;; - competitor-version|competitor-count|competitor-tuple|deployed-changed|competitor-exact|competitor-missing-id) - expected_status=0 - expected_rv=rv-902 - expected_count=2 - expected_diagnostic='competing Namespace resource version observed after proof-retry annotation failure' - case "$reservation_failure" in - competitor-version) expected_count=1 ;; - competitor-count) expected_count=3 ;; - competitor-tuple) expected_merge=ffffffffffffffffffffffffffffffffffffffff ;; - esac - ;; - lost-response) - expected_status=0 - expected_count=2 - expected_rv=rv-902 - expected_dispatches=1 - expected_diagnostic='Recorded proof retry 2/3 for PR #901' - ;; - lost-response-unchanged-rv) - expected_count=2 - ;; - esac - actual_status=0 - ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 \ - FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PR_901_PROOF_RETRY_COUNT=1 \ - FAKE_PR_901_PROOF_RETRY_BASE_SHA="$preview_base_sha" \ - FAKE_PR_901_PROOF_RETRY_HEAD_SHA="$preview_head_sha" \ - FAKE_PR_901_PROOF_RETRY_MERGE_SHA="$preview_merge_sha" \ - FAKE_PR_901_PROOF_RETRY_IMAGE_TAG="$preview_image_tag" \ - FAKE_PROOF_RETRY_ANNOTATE_FAILURE="$reservation_failure" \ - FAKE_DISPATCH_HTTP_STATUS=204 \ - PREVIEW_MAX_ACTIVE=2 \ - bash "$RECONCILER_RUN" - ) > "$reservation_failure_output" 2>&1 || actual_status=$? - if [[ "$actual_status" -ne "$expected_status" ]]; then - echo "reservation failure ${reservation_failure} returned ${actual_status}, expected ${expected_status}" >&2 - cat "$reservation_failure_output" >&2 - exit 1 - fi - grep -Fq "$expected_diagnostic" "$reservation_failure_output" - if [[ "$reservation_failure" == forbidden ]]; then - grep -Fq 'Error from server (Forbidden)' "$reservation_failure_output" - fi - if [[ "$expected_status" -eq 1 ]]; then - grep -Fq 'One or more preview inventory, capacity, or dispatch checks failed.' "$reservation_failure_output" - fi - test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 3 - test "$(grep -Fc -- '--request-timeout=10s' "$FAKE_NAMESPACE_SNAPSHOT_LOG")" -eq 1 - test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 1 - grep -Fq -- '--resource-version rv-901' "$FAKE_ANNOTATE_LOG" - if [[ "$expected_dispatches" -eq 1 ]]; then - test "$(wc -l < "$FAKE_DISPATCH_LOG")" -eq 1 - else - test ! -e "$FAKE_DISPATCH_LOG" - fi - test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" - test ! -e "$FAKE_PROOF_RETRY_RESERVATION_MARKER" - attempted_id="$(grep -oE 'firemud[.]dev/proof-retry-reservation-id=[0-9a-f-]+' "$FAKE_ANNOTATE_LOG")" - attempted_id="${attempted_id#*=}" - [[ "$attempted_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]] - case "$reservation_failure" in - competitor-exact) - jq -e --arg id "$attempted_id" '.id != $id' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null - ;; - lost-response|lost-response-unchanged-rv|competitor-version|competitor-count|competitor-tuple|deployed-changed) - jq -e --arg id "$attempted_id" '.id == $id' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null - ;; - *) jq -e 'has("id") | not' "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null ;; - esac - jq -e --arg count "$expected_count" --arg rv "$expected_rv" \ - --arg base "$preview_base_sha" --arg head "$preview_head_sha" \ - --arg merge "$expected_merge" --arg image "$preview_image_tag" \ - '.count == $count and .resourceVersion == $rv and .base == $base - and .head == $head and .merge == $merge and .image == $image' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -done - -for unsafe_response in missing-id different-id unchanged-rv wrong-uid wrong-deployed wrong-count wrong-tuple malformed; do - reset_case - unsafe_response_output="$TEMP_DIR/reconciler-reservation-response-${unsafe_response}.out" - if ( - cd "$ROOT_DIR" - FAKE_OPEN_PRIORITY_ROWS="1\t901\thead-901\thuman\tdevelop\topen\t${adversarial_labels_base64}\n" \ - FAKE_PR_901_HEAD=head-901 FAKE_PR_901_REQUESTED_HEAD=head-901 \ - FAKE_PR_901_PROOF_COMPLETE=false \ - FAKE_PROOF_RETRY_RESPONSE_CASE="$unsafe_response" \ - PREVIEW_MAX_ACTIVE=2 bash "$RECONCILER_RUN" - ) > "$unsafe_response_output" 2>&1; then - echo "unsafe reservation success response ${unsafe_response} was accepted" >&2 - exit 1 - fi - grep -Fq 'Unable to prove proof-retry reservation custody for PR #901 from the annotation response' "$unsafe_response_output" - test "$(<"$FAKE_NAMESPACE_SNAPSHOT_CALLS")" -eq 2 - test "$(wc -l < "$FAKE_ANNOTATE_LOG")" -eq 1 - test ! -e "$FAKE_DISPATCH_LOG" - test ! -e "$FAKE_PROOF_RETRY_COMPENSATED_MARKER" - jq -e '.count == "1" and .resourceVersion == "rv-902" and (.id | length) == 36' \ - "$FAKE_PROOF_RETRY_STATE_MARKER" >/dev/null -done - +# Reservation-specific storage and interruption proof runs below with the +# durable holder, while capacity and provider inventory remain independent. reset_case reconciler_paginated_active_output="$TEMP_DIR/reconciler-paginated-active.out" ( @@ -4885,17 +4473,14 @@ PY grep -q -- '--retire-terminal-identities' "$ROOT_DIR/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh" grep -q 'Skipping ordinary PR #' "$RECONCILER_RUN" grep -q 'preview dispatch cycle already stopped after a request attempt' "$RECONCILER_RUN" -# Proof repair is bounded by the exact deployed tuple and must not duplicate an -# active source or trusted consumer run. -grep -Fq 'firemud.dev/proof-retry-count' "$RECONCILER_RUN" -grep -Fq 'firemud.dev/proof-retry-base-sha' "$RECONCILER_RUN" -grep -Fq 'firemud.dev/proof-retry-head-sha' "$RECONCILER_RUN" -grep -Fq 'firemud.dev/proof-retry-merge-sha' "$RECONCILER_RUN" -grep -Fq 'firemud.dev/proof-retry-image-tag' "$RECONCILER_RUN" -grep -Fq 'namespace proof-retry evidence is malformed' "$RECONCILER_RUN" +# Proof repair is bounded by the exact retained tuple and must not duplicate +# an active source or trusted consumer run. +retry_record_helper="$ROOT_DIR/dev-tools/hosted/preview/preview-proof-retry-record.shlib" +grep -Fq 'read_preview_retry_holder' "$RECONCILER_RUN" +grep -Fq 'write_preview_retry_entry' "$RECONCILER_RUN" grep -Fq 'proof retry budget exhausted' "$RECONCILER_RUN" -# shellcheck disable=SC2016 # Assert literal resource-version fencing. -grep -Fq -- '--resource-version "${namespace_resource_version}"' "$RECONCILER_RUN" +grep -Fq '{op:"test",path:"/metadata/uid",value:.metadata.uid}' "$retry_record_helper" +grep -Fq '{op:"test",path:"/metadata/resourceVersion",value:.metadata.resourceVersion}' "$retry_record_helper" # shellcheck disable=SC2016 # Assert canonical workflow lookup and native custody. grep -Fq -- 'actions/workflows/preview.yml" | jq' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the literal jq workflow and repository checks. @@ -4907,8 +4492,8 @@ grep -Fq "run-name: \${{ github.event_name == 'workflow_run' && github.event.wor # shellcheck disable=SC2016 # Assert one fail-closed JSON snapshot feeds each namespace decision. grep -Fq 'kubectl get namespace "${namespace}" --ignore-not-found -o json' \ "$RECONCILER_RUN" -# shellcheck disable=SC2016 # Assert the initial, repair, pre-dispatch, and compensation snapshots. -test "$(grep -Fc 'kubectl get namespace "${namespace}" --ignore-not-found -o json' "$RECONCILER_RUN")" -eq 5 +# shellcheck disable=SC2016 # Assert the final runtime fence is read independently of reservation custody. +grep -Fq 'kubectl get namespace "$namespace" --ignore-not-found -o json --request-timeout=10s' "$RECONCILER_RUN" # shellcheck disable=SC2016 # Assert the fresh namespace snapshot fences repair. grep -Fq 'requested preview tuple changed during annotation repair check' "$RECONCILER_RUN" # The janitor keeps explicit kubeconfig selection on the consuming kubectl steps; diff --git a/dev-tools/tests/trust-bootstrap-provision-contract.sh b/dev-tools/tests/trust-bootstrap-provision-contract.sh index 09a73747a8..0f6f1170ce 100755 --- a/dev-tools/tests/trust-bootstrap-provision-contract.sh +++ b/dev-tools/tests/trust-bootstrap-provision-contract.sh @@ -62,7 +62,7 @@ expected = { assert set(module._CREDENTIALS_BY_NAME) == set(expected) for name, credential in module._CREDENTIALS_BY_NAME.items(): assert (credential.environment, credential.github_secret) == expected[name] - expected_probe_count = 3 if name == "firemud-preview-namespace-manager" else 2 + expected_probe_count = 8 if name == "firemud-preview-namespace-manager" else 2 assert len(credential.rbac_probes) == expected_probe_count assert {probe[3] for probe in credential.rbac_probes} == {"yes", "no"} manager = module._CREDENTIALS_BY_NAME["firemud-preview-namespace-manager"] @@ -70,6 +70,11 @@ assert manager.rbac_probes == ( ("get", "namespaces", None, "yes"), ("delete", "namespaces", None, "yes"), ("get", "secrets", "proof", "no"), + ("get", "configmaps/firemud-preview-proof-retries", "control", "yes"), + ("patch", "configmaps/firemud-preview-proof-retries", "control", "yes"), + ("create", "configmaps", "control", "no"), + ("list", "configmaps", "control", "no"), + ("patch", "configmaps/firemud-unrelated", "control", "no"), ) assert module.REPOSITORY == "benhook1013/FireMUD" @@ -392,7 +397,7 @@ manager_identity_json = json.dumps({ }).encode("utf-8") with ( patch.object(module, "run_command", return_value=manager_identity_json), - patch.object(module, "run_auth_can_i", side_effect=["yes", "yes", "no"]) as probes, + patch.object(module, "run_auth_can_i", side_effect=[probe[3] for probe in manager.rbac_probes]) as probes, ): module.verify_generated_kubeconfig( module.build_kubeconfig( @@ -410,6 +415,11 @@ with ( ["get", "namespaces"], ["delete", "namespaces"], ["get", "secrets", "-n", "pr-42"], + ["get", "configmaps/firemud-preview-proof-retries", "-n", "firemud-system"], + ["patch", "configmaps/firemud-preview-proof-retries", "-n", "firemud-system"], + ["create", "configmaps", "-n", "firemud-system"], + ["list", "configmaps", "-n", "firemud-system"], + ["patch", "configmaps/firemud-unrelated", "-n", "firemud-system"], ] write_offset = source.index("file.write(kubeconfig)") diff --git a/dev-tools/tests/trust-bootstrap-rbac-contract.sh b/dev-tools/tests/trust-bootstrap-rbac-contract.sh index 56ea432548..9ec4dbd73a 100755 --- a/dev-tools/tests/trust-bootstrap-rbac-contract.sh +++ b/dev-tools/tests/trust-bootstrap-rbac-contract.sh @@ -150,6 +150,31 @@ assert subjects == [{ "namespace": "firemud-system", }] +holder_name = "firemud-preview-proof-retries" +holder = [item for item in deployment if item["kind"] == "ConfigMap"] +assert holder == [{ + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": {"name": holder_name, "namespace": "firemud-system"}, + "data": {"schemaVersion": "1"}, +}] +named_roles = [item for item in deployment if item["kind"] == "Role"] +assert len(named_roles) == 1 +assert named_roles[0]["metadata"] == holder[0]["metadata"] +assert named_roles[0]["rules"] == [{ + "apiGroups": [""], + "resources": ["configmaps"], + "resourceNames": [holder_name], + "verbs": ["get", "patch"], +}] +named_bindings = [item for item in deployment if item["kind"] == "RoleBinding"] +assert len(named_bindings) == 1 +assert named_bindings[0]["metadata"] == holder[0]["metadata"] +assert named_bindings[0]["roleRef"] == { + "apiGroup": "rbac.authorization.k8s.io", "kind": "Role", "name": holder_name, +} +assert named_bindings[0]["subjects"] == subjects + admission = documents(admission_path) policy_names = { "firemud-trust-runtime-namespace-boundary", diff --git a/k8s/trust-bootstrap/README.md b/k8s/trust-bootstrap/README.md index 9e896c9c8d..7fb6950a83 100644 --- a/k8s/trust-bootstrap/README.md +++ b/k8s/trust-bootstrap/README.md @@ -14,17 +14,17 @@ This is a prerequisite for the private Gateway–TCP Proxy bridge in #2713. It m ## Isolated namespace cleanup proof -This proof validates only the namespace-manager credential and one disposable runtime-namespace deletion. It does not complete the trust bootstrap, activate ordinary deployment workflows, retire `preview-deployer`, or authorize CA or issuer installation. The existing `deployment-rbac.yaml` and `deployment-admission.yaml` contain the 11-resource manager-stage subset; there is no separate Kustomize target. Keep the controller inactive and leave the remaining trust-bootstrap resources unapplied for this proof. +This proof validates only the namespace-manager credential and one disposable runtime-namespace deletion. It does not complete the trust bootstrap, activate ordinary deployment workflows, retire `preview-deployer`, or authorize CA or issuer installation. The existing `deployment-rbac.yaml` and `deployment-admission.yaml` contain the 14-resource manager-stage subset; there is no separate Kustomize target. Keep the controller inactive and leave the remaining trust-bootstrap resources unapplied for this proof. Before publishing the manager credential, disable the ordinary manager consumers using GitHub's reversible workflow controls: `preview-janitor.yml`, `preview-reconciler.yml`, `dev-demo-reconciler.yml`, `dev-demo.yml`, and `hosted-identity-request.yml`. Disabling prevents new triggers but does not stop executions already queued, pending, waiting for Environment approval, or running. Drain or cancel every nonterminal execution of all five workflows, then immediately before publication verify that none remains, including queued, pending, and Environment-waiting runs or jobs. Leave all five disabled after the proof until a separately approved activation. The isolated `preview-cleanup-proof.yml` workflow is the only manager consumer during this stage. Do not run the janitor or reconciler as a targeted proof; both process broader lifecycle state. -Under the explicit `system:masters` context, apply only `k8s/trust-bootstrap/deployment-rbac.yaml` and `k8s/trust-bootstrap/deployment-admission.yaml`. Select a real same-repository closed PR with an unused `pr-N` namespace. Create a fresh empty namespace named `pr-N` with `firemud.dev/preview: "true"`, `firemud.dev/pr-number: "N"`, and annotation `firemud.dev/cleanup-proof: "true"`. Capture its Namespace UID. Run `dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh pr-N` under that same operator context; the helper creates or validates only the exact runtime and standalone-certificate-writer RoleBindings. Do not add workloads or other namespace resources. +Under the explicit `system:masters` context, apply only `k8s/trust-bootstrap/deployment-rbac.yaml` and `k8s/trust-bootstrap/deployment-admission.yaml`. These manifests pre-create `firemud-system/firemud-preview-proof-retries` and bind only named get and patch access to the namespace manager. Keep the fixed ConfigMap in place across workflow upgrades and apply the manifests without replacing it. The installer owns its schema field and the reconciler owns the per-PR entries. Drain any already-running version that can still write Namespace-only retry counters before adopting the independent holder. Select a real same-repository closed PR with an unused `pr-N` namespace. Create a fresh empty namespace named `pr-N` with `firemud.dev/preview: "true"`, `firemud.dev/pr-number: "N"`, and annotation `firemud.dev/cleanup-proof: "true"`. Capture its Namespace UID. Run `dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh pr-N` under that same operator context; the helper creates or validates only the exact runtime and standalone-certificate-writer RoleBindings. Do not add workloads or other namespace resources. -Provision only the namespace-manager credential under the explicit operator context, using the proof namespace and an operator-verified runner-reachable TLS endpoint: `python3 dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py --context --apply --confirm --proof-namespace pr-N --runner-api-server https://host:port --credential firemud-preview-namespace-manager`. The endpoint is interpreted from the self-hosted preview runner's network and keeps the selected context's CA for normal TLS validation. The provisioner verifies the exact manager identity, `get namespaces=yes`, `delete namespaces=yes`, and `get secrets in pr-N=no`; it publishes only `TRUSTED_HOSTED_PREVIEW_NAMESPACE_MANAGER_KUBECONFIG` to `trusted-hosted-cluster`. GitHub's Environment branch restriction must admit only `develop`; the provisioner verifies that exact policy for the configured protected environments. The Kubernetes service-account-token Secret has no configured expiry, so it remains an active grant until it is rotated or explicitly revoked. +Provision only the namespace-manager credential under the explicit operator context, using the proof namespace and an operator-verified runner-reachable TLS endpoint: `python3 dev-tools/hosted/trust-bootstrap/provision-scoped-kubeconfigs.py --context --apply --confirm --proof-namespace pr-N --runner-api-server https://host:port --credential firemud-preview-namespace-manager`. The endpoint is interpreted from the self-hosted preview runner's network and keeps the selected context's CA for normal TLS validation. The provisioner verifies the exact manager identity, `get namespaces=yes`, `delete namespaces=yes`, and `get secrets in pr-N=no`; it also verifies named retry-record get and patch and rejects broader ConfigMap access. It publishes only `TRUSTED_HOSTED_PREVIEW_NAMESPACE_MANAGER_KUBECONFIG` to `trusted-hosted-cluster`. GitHub's Environment branch restriction must admit only `develop`; the provisioner verifies that exact policy for the configured protected environments. The Kubernetes service-account-token Secret has no configured expiry, so it remains an active grant until it is rotated or explicitly revoked. Dispatch `Preview Runtime Cleanup Proof` from `develop` with the closed PR number, its exact current head SHA, and the captured Namespace UID. The workflow uses the self-hosted preview runner, verifies the exact namespace-manager username, `get namespaces=yes`, `delete namespaces=yes`, and `get secrets in pr-N=no`, then rechecks that the PR is closed and both head and base belong to this repository. Immediately before deletion it requires the namespace name, UID, canonical preview labels, and cleanup-proof annotation to match the supplied inputs. It passes the captured UID through the existing `prune-stale-preview-namespaces.sh --delete-runtime` path; the shared deletion helper refuses a changed UID and uses the captured value as the Kubernetes DELETE precondition. It requires a subsequent Namespace `NotFound`. It does not retire hosted identity, read Secret data, touch `dev`, or delete another namespace. -The [runtime and retained identity lifecycle boundary](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) keeps garbage collection subject to the fixed caller, namespace, and object predicates. DELETE admission checks use `oldObject.metadata.name`: Kubernetes collection deletion supplies each stored object while omitting the request name. CEL type-checking and an accepted Namespace DELETE do not establish successful content garbage collection or Namespace `NotFound`; the isolated proof must observe that final result with the policies still installed. This also applies to the reserved CA Secret and dormant hosted identity admission policies; correcting their source does not authorize installing them during the 11-resource manager stage. +The [runtime and retained identity lifecycle boundary](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) keeps garbage collection subject to the fixed caller, namespace, and object predicates. DELETE admission checks use `oldObject.metadata.name`: Kubernetes collection deletion supplies each stored object while omitting the request name. CEL type-checking and an accepted Namespace DELETE do not establish successful content garbage collection or Namespace `NotFound`; the isolated proof must observe that final result with the policies still installed. This also applies to the reserved CA Secret and dormant hosted identity admission policies; correcting their source does not authorize installing them during the 14-resource manager stage. Afterward, keep ordinary manager consumers suspended. To abandon the stage, first revoke the manager Environment secret and its exact provisioner-owned token Secret; only then may an operator remove the staged policy and RBAC resources. If `gh secret set` may have accepted the value before reporting failure, retain the token and recover by rerunning only the manager credential with `--credential firemud-preview-namespace-manager --reuse-token-secret ` and the same proof namespace and endpoint. Do not mint a replacement or remove the admission boundary while a published token may still be active. Preserve the legacy credential throughout; this proof is not `--finalize` and does not establish permission to migrate or activate any ordinary workflow. diff --git a/k8s/trust-bootstrap/deployment-rbac.yaml b/k8s/trust-bootstrap/deployment-rbac.yaml index dff232f1d4..fc937c8bb1 100644 --- a/k8s/trust-bootstrap/deployment-rbac.yaml +++ b/k8s/trust-bootstrap/deployment-rbac.yaml @@ -172,3 +172,37 @@ subjects: - kind: ServiceAccount name: firemud-preview-namespace-manager namespace: firemud-system +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: firemud-preview-proof-retries + namespace: firemud-system +data: + # Installation owns only this field. The manager patches pr-N fields. + schemaVersion: "1" +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: firemud-preview-proof-retries + namespace: firemud-system +rules: + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["firemud-preview-proof-retries"] + verbs: ["get", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: firemud-preview-proof-retries + namespace: firemud-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: firemud-preview-proof-retries +subjects: + - kind: ServiceAccount + name: firemud-preview-namespace-manager + namespace: firemud-system From 3dbb7c2648578bb09682898fd09bf72f47cec99b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:11:33 +1300 Subject: [PATCH 107/199] Fix validation findings for preview retry and recovery isolation --- dev-tools/hosted/preview/prune-stale-preview-namespaces.sh | 2 +- dev-tools/hosted/preview/reconcile-preview-deploys.sh | 2 +- dev-tools/hosted/shared/delete-hosted-namespace.sh | 2 +- dev-tools/tests/pr-retarget-workflow-contract.sh | 4 +--- .../RecoveryControlDatabaseHostEnvironmentPostProcessor.java | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh index 1293c1936a..41f79ce3df 100644 --- a/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh +++ b/dev-tools/hosted/preview/prune-stale-preview-namespaces.sh @@ -436,7 +436,7 @@ if (( runtime_deletion_failures > 0 || retirement_failures > 0 )); then fi if [[ "$retire_proof_retries" == true ]]; then - # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib + # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib disable=SC1091 source "$script_dir/preview-proof-retry-record.shlib" if ! retire_merged_preview_retry_entries; then echo "Unable to retire verified merged preview proof-retry records." >&2 diff --git a/dev-tools/hosted/preview/reconcile-preview-deploys.sh b/dev-tools/hosted/preview/reconcile-preview-deploys.sh index d63514493d..1eeedfa769 100644 --- a/dev-tools/hosted/preview/reconcile-preview-deploys.sh +++ b/dev-tools/hosted/preview/reconcile-preview-deploys.sh @@ -4,7 +4,7 @@ preview_workflow_name="PR Preview Environment" eligibility_script="./dev-tools/hosted/preview/preview-eligibility.py" max_active="${PREVIEW_MAX_ACTIVE:-2}" preview_handoff_window_seconds=600 -# shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib +# shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib disable=SC1091 source ./dev-tools/hosted/preview/preview-proof-retry-record.shlib parse_namespace_tuple() { diff --git a/dev-tools/hosted/shared/delete-hosted-namespace.sh b/dev-tools/hosted/shared/delete-hosted-namespace.sh index d01c17dea4..0eff6bfd3d 100644 --- a/dev-tools/hosted/shared/delete-hosted-namespace.sh +++ b/dev-tools/hosted/shared/delete-hosted-namespace.sh @@ -88,7 +88,7 @@ delete_resource_version="" if [[ -n "$expected_pr_number" ]]; then script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib + # shellcheck source=dev-tools/hosted/preview/preview-proof-retry-record.shlib disable=SC1091 source "$script_dir/../preview/preview-proof-retry-record.shlib" if ! legacy_retry="$(legacy_preview_retry_entry "$namespace_json" "$namespace")"; then echo "unable to read legacy proof-retry evidence for $namespace; refusing deletion" >&2 diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index b73f254a72..3f26eb4241 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1676,9 +1676,7 @@ assert_job_contains runtime-images.yml pr-local-smoke 'BASE_SHA="${{ needs.image assert_job_contains runtime-images.yml pr-local-smoke 'MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}"' assert_job_contains runtime-images.yml pr-controller-smoke 'github.event_name == '\''repository_dispatch'\''' require_contains "$image_wait_path" 'display_title = run.get("display_title", "")' -require_contains "$image_wait_path" 'display_title.startswith("Build Runtime Images trusted-branch ")' -require_contains "$image_wait_path" 'and f"sha-{head_sha}" in tokens' -require_contains "$image_wait_path" 'and "branch-develop" in tokens' +require_contains "$image_wait_path" 'run.get("display_title") == f"Build Runtime Images trusted-branch branch-develop sha-{head_sha}"' require_contains "$image_wait_path" 'and f"base-{base_sha}" in tokens' require_contains "$image_wait_path" 'and f"merge-{merge_sha}" in tokens' require_contains "$image_wait_path" 'run.get("event") == "workflow_run"' diff --git a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java index 36c6c6c853..55cd9c123f 100644 --- a/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java +++ b/services/recovery-controller-service/src/main/java/net/firedevops/firemud/recovery/config/RecoveryControlDatabaseHostEnvironmentPostProcessor.java @@ -56,7 +56,7 @@ public void postProcessEnvironment( "spring.datasource.hikari.data-source-properties", Bindable.mapOf(String.class, String.class)) .orElse(Map.of()); - if (!dataSourceProperties.isEmpty()) { + if (dataSourceProperties == null || !dataSourceProperties.isEmpty()) { throw new IllegalStateException("Recovery datasource driver overrides are unsupported"); } // Flyway must use the very same datasource, not create an independent connection endpoint. From f6897087c9b1a092ae100da3093a97f03b3e3d26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:17:40 +1300 Subject: [PATCH 108/199] Retain exact PR runtime refresh dispatch claims --- .github/scripts/admit-pr-runtime-refresh.cjs | 241 ++++++++++++++++-- .github/workflows/runtime-images.yml | 39 +++ .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 2 +- .../pr-runtime-image-publication-contract.sh | 52 +++- .../tests/preview-runtime-refresh.test.cjs | 154 ++++++++++- 6 files changed, 456 insertions(+), 34 deletions(-) diff --git a/.github/scripts/admit-pr-runtime-refresh.cjs b/.github/scripts/admit-pr-runtime-refresh.cjs index e86e224dac..eea95452ad 100644 --- a/.github/scripts/admit-pr-runtime-refresh.cjs +++ b/.github/scripts/admit-pr-runtime-refresh.cjs @@ -1,4 +1,5 @@ const {execFileSync} = require('node:child_process'); +const {createHash, randomBytes} = require('node:crypto'); const {resolve} = require('node:path'); module.exports = async function admitPrRuntimeRefresh({ @@ -13,6 +14,9 @@ module.exports = async function admitPrRuntimeRefresh({ const shaPattern = /^[0-9a-f]{40}$/; const activeStatuses = new Set(['queued', 'waiting', 'requested', 'pending', 'in_progress']); const inventoryEvents = ['pull_request', 'repository_dispatch']; + const inventoryPages = 3; + const pageSize = 100; + const inventoryLimit = inventoryPages * pageSize; const fail = message => { throw new Error(message); }; const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value); @@ -171,17 +175,17 @@ module.exports = async function admitPrRuntimeRefresh({ let newestExact = null; const observedRunIds = new Set(); const exactRuns = []; - const collectInventory = async (event, status, createdSince) => { + const collectInventory = async (event, status, createdSince, runs = exactRuns, ids = observedRunIds) => { let total; let seen = 0; - for (let page = 1; page <= 3; page++) { + for (let page = 1; page <= inventoryPages; page++) { const {data: inventory} = await github.rest.actions.listWorkflowRuns({ - ...contextRepo, workflow_id: runtimeWorkflow.id, event, status, per_page: 100, page, + ...contextRepo, workflow_id: runtimeWorkflow.id, event, status, per_page: pageSize, page, ...(createdSince ? {created: `${createdSince}..*`} : {}), }); if (!Number.isSafeInteger(inventory?.total_count) || inventory.total_count < 0 || - inventory.total_count > 300 || !Array.isArray(inventory.workflow_runs) || - inventory.workflow_runs.length > 100 || (total !== undefined && inventory.total_count !== total)) { + inventory.total_count > inventoryLimit || !Array.isArray(inventory.workflow_runs) || + inventory.workflow_runs.length > pageSize || (total !== undefined && inventory.total_count !== total)) { throw new Error('Incomplete runtime run inventory.'); } total = inventory.total_count; @@ -197,17 +201,17 @@ module.exports = async function admitPrRuntimeRefresh({ throw new Error('Exact runtime run has invalid native chronology.'); } const identity = `${run.event}:${run.id}:${run.run_attempt}`; - if (observedRunIds.has(identity)) throw new Error('Duplicate exact runtime run identity.'); - observedRunIds.add(identity); + if (ids.has(identity)) throw new Error('Duplicate exact runtime run identity.'); + ids.add(identity); if (activeStatuses.has(run.status)) { if (run.conclusion != null) throw new Error('Active runtime run has a conclusion.'); } else if (run.status !== 'completed' || typeof run.conclusion !== 'string' || run.conclusion.length === 0) { throw new Error('Exact runtime run status is unclear.'); } - exactRuns.push(run); + runs.push(run); } if (seen === total) return; - if (seen > total || inventory.workflow_runs.length < 100) break; + if (seen > total || inventory.workflow_runs.length < pageSize) break; } throw new Error('Incomplete runtime run inventory.'); }; @@ -269,20 +273,211 @@ module.exports = async function admitPrRuntimeRefresh({ } } + const tuple = Object.fromEntries(requiredFields.map(field => [field, input[field]])); + const sha256 = value => createHash('sha256').update(value, 'utf8').digest('hex'); + const baseRefHash = sha256(input.base_ref); + const claimNamespace = `firemud-runtime-refresh-intent/v1/pr-${input.pr_number}/${input.merge_sha}/${baseRefHash}/`; + const refPrefix = `refs/tags/${claimNamespace}`; + const tagName = generation => `${claimNamespace}g${generation}`; + const claimMessage = (generation, witness_sha256) => + `${JSON.stringify({...tuple, generation: String(generation), witness_sha256})}\n`; + const tagger = {name: 'FireMUD Runtime Refresh', email: 'runtime-refresh@firemud.dev'}; + const isSha = value => typeof value === 'string' && value.length === 40 && shaPattern.test(value); + const isCanonicalDate = value => validChronology(value) && secondsUtc(Date.parse(value)) === value; + const parseGeneration = value => { + const generation = Number(value); + if (!isPositiveInteger(generation) || String(generation) !== value) fail('Invalid runtime claim generation.'); + return generation; + }; + const exactTag = (tag, generation, expectedWitnessDigest) => { + if (tag?.tag !== tagName(generation) || !isSha(tag.sha) || tag.object?.type !== 'commit' || + tag.object.sha !== input.merge_sha || typeof tag.message !== 'string' || + tag.tagger?.name !== tagger.name || tag.tagger.email !== tagger.email || + !isCanonicalDate(tag.tagger.date)) return false; + const annotation = JSON.parse(tag.message); + const digest = annotation?.witness_sha256; + return typeof digest === 'string' && digest.length === 64 && /^[0-9a-f]{64}$/.test(digest) && + (expectedWitnessDigest === undefined || digest === expectedWitnessDigest) && + tag.message === claimMessage(generation, digest); + }; + + const latestClaim = async () => { + // Matching refs returns an array, not a count-backed paginated inventory. + // Do not use a response that signals pagination or exceeds the inventory budget. + const response = await github.rest.git.listMatchingRefs({...contextRepo, ref: `tags/${claimNamespace}`}); + const refs = response?.data; + if (response?.status !== 200 || !isRecord(response.headers) || + Object.keys(response.headers).some(name => name.toLowerCase() === 'link') || + !Array.isArray(refs) || refs.length > inventoryLimit) fail('Incomplete runtime claim ref inventory.'); + + const claims = new Map(); + const tagShas = new Set(); + for (const ref of refs) { + if (typeof ref?.ref !== 'string' || !ref.ref.startsWith(`${refPrefix}g`) || + ref.object?.type !== 'tag' || !isSha(ref.object.sha)) fail('Invalid runtime claim ref.'); + const generation = parseGeneration(ref.ref.slice(refPrefix.length + 1)); + if (claims.has(generation) || tagShas.has(ref.object.sha)) fail('Duplicate runtime claim ref.'); + claims.set(generation, ref.object.sha); + tagShas.add(ref.object.sha); + } + for (let generation = 1; generation <= claims.size; generation++) { + if (!claims.has(generation)) fail('Gapped runtime claim ref inventory.'); + } + + if (claims.size === 0) return null; + const generation = claims.size; + const tag_sha = claims.get(generation); + const tag = dataOf(await github.rest.git.getTag({...contextRepo, tag_sha})); + if (!exactTag(tag, generation) || tag.sha !== tag_sha) fail('Invalid runtime claim annotation.'); + return {generation, date: tag.tagger.date, tag_sha}; + }; + + const receiverProvesClaim = async (run, claim) => { + if (!isSha(run.head_sha)) fail('Invalid terminal runtime receiver head.'); + let total; + const jobIds = new Set(); + let metadataJob; + for (let page = 1; page <= inventoryPages; page++) { + const jobs = dataOf(await github.rest.actions.listJobsForWorkflowRunAttempt({ + ...contextRepo, run_id: run.id, attempt_number: run.run_attempt, per_page: pageSize, page, + })); + if (!Number.isSafeInteger(jobs?.total_count) || jobs.total_count < 0 || jobs.total_count > inventoryLimit || + (total !== undefined && jobs.total_count !== total) || !Array.isArray(jobs.jobs) || + jobs.jobs.length !== Math.min(pageSize, jobs.total_count - jobIds.size)) { + fail('Incomplete runtime receiver job inventory.'); + } + total = jobs.total_count; + for (const job of jobs.jobs) { + if (!isPositiveInteger(job?.id) || jobIds.has(job.id) || job.run_id !== run.id || + job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || typeof job.name !== 'string') { + fail('Invalid runtime receiver job identity.'); + } + jobIds.add(job.id); + if (job.name !== 'Derive Runtime Image Metadata') continue; + if (metadataJob) fail('Duplicate runtime receiver metadata job.'); + metadataJob = job; + } + if (jobIds.size === total) break; + } + if (jobIds.size !== total) fail('Incomplete runtime receiver job inventory.'); + if (!metadataJob) return false; + const steps = metadataJob.steps; + if (!Array.isArray(steps) || steps.some(step => typeof step?.name !== 'string')) { + fail('Invalid runtime receiver step inventory.'); + } + const markerPrefix = 'Runtime refresh claim generation'; + const markers = steps.filter(step => step.name.startsWith(markerPrefix)); + if (markers.length === 0) return false; + if (markers.length !== 1) fail('Ambiguous runtime receiver claim marker.'); + const [marker] = markers; + const expected = `${markerPrefix} ${claim.generation} attempt ${run.run_attempt} tag ${claim.tag_sha}`; + if (marker.name === expected) { + if (metadataJob.status !== 'completed' || marker.status !== 'completed' || marker.conclusion !== 'success') { + fail('Unsuccessful runtime receiver claim marker.'); + } + return true; + } + + const suffix = marker.name.slice(markerPrefix.length); + if (marker.status === 'completed' && marker.conclusion === 'skipped' && + /^(?:[1-9][0-9]*|attempt\s+tag)?$/.test(suffix.trim())) return false; + + const identity = /^ ([1-9][0-9]*) attempt ([1-9][0-9]*) tag ([0-9a-f]{40})$/.exec(suffix); + if (identity?.[0] !== suffix) fail('Invalid runtime receiver claim marker.'); + const generation = parseGeneration(identity[1]); + const attempt = Number(identity[2]); + if (!isPositiveInteger(attempt) || attempt > run.run_attempt) fail('Invalid runtime receiver marker attempt.'); + // The title omits the base ref. Even an exact native run can carry another + // claim's tag, or retain a marker from a prior partial rerun attempt. + if (identity[3] !== claim.tag_sha) return false; + if (generation !== claim.generation) fail('Inconsistent runtime receiver marker generation.'); + return false; + }; + + const terminalReceiverProven = async claim => { + const runs = []; + await collectInventory('repository_dispatch', 'completed', claim.date, runs, new Set()); + if (new Set(runs.map(run => run.id)).size !== runs.length) fail('Duplicate terminal runtime receiver run.'); + let receiver; + for (const run of runs) { + if (!await receiverProvesClaim(run, claim)) continue; + if (receiver) fail('Multiple terminal runtime receivers for the same claim.'); + receiver = run; + } + if (!receiver) return false; + + const latest = dataOf(await github.rest.actions.getWorkflowRun({...contextRepo, run_id: receiver.id})); + return exactNativeTuple(latest) && latest.event === 'repository_dispatch' && latest.id === receiver.id && + latest.run_attempt === receiver.run_attempt && latest.head_sha === receiver.head_sha && + latest.created_at === receiver.created_at && latest.status === 'completed' && + latest.conclusion === receiver.conclusion; + }; + + let generation; + let witness; + try { + const prior = await latestClaim(); + if (prior && !await terminalReceiverProven(prior)) { + core.info('Runtime refresh claim has no proven terminal receiver; no dispatch.'); + return 'claim-held'; + } + generation = (prior?.generation ?? 0) + 1; + const date = secondsUtc(Date.now()); + if (!isPositiveInteger(generation) || (prior && date < prior.date)) fail('Invalid successor runtime claim.'); + const candidateWitness = randomBytes(32).toString('hex'); + const witnessDigest = sha256(candidateWitness); + const tag = await github.rest.git.createTag({ + ...contextRepo, tag: tagName(generation), message: claimMessage(generation, witnessDigest), + object: input.merge_sha, type: 'commit', tagger: {...tagger, date}, request: {retries: 0}, + }); + if (tag?.status !== 201 || !exactTag(tag.data, generation, witnessDigest) || tag.data.tagger.date !== date) { + fail('Runtime claim tag creation is unproven.'); + } + const ref = `refs/tags/${tagName(generation)}`; + const created = await github.rest.git.createRef({...contextRepo, ref, sha: tag.data.sha, request: {retries: 0}}); + if (created?.status !== 201 || created.data?.ref !== ref || + created.data.object?.type !== 'tag' || created.data.object.sha !== tag.data.sha) { + fail('Runtime claim ref creation is unproven.'); + } + witness = candidateWitness; + } catch { + // A lost response is not ownership. Never adopt, update, delete, or retry a claim ref. + core.warning('Runtime refresh claim ownership or predecessor evidence is unproven; no dispatch.'); + return 'claim-held'; + } + + try { + if (!await currentIdentity()) { + core.info('Runtime refresh tuple changed after claiming; no dispatch.'); + return 'obsolete'; + } + } catch { + core.warning('Runtime refresh tuple could not be rechecked after claiming; no dispatch.'); + return 'claim-held'; + } + const dispatchCreatedSince = secondsUtc(Date.now()); const nextDispatchSecond = Date.parse(dispatchCreatedSince) + 1000; - await github.rest.repos.createDispatchEvent({ - ...contextRepo, - event_type: 'pr-runtime-base-refresh', - client_payload: { - pr_number: input.pr_number, - base_ref: input.base_ref, - base_sha: input.base_sha, - head_sha: input.head_sha, - merge_sha: input.merge_sha, - image_tag: `pr-merge-${input.merge_sha}`, - }, - }); + try { + const dispatched = await github.rest.repos.createDispatchEvent({ + ...contextRepo, + event_type: 'pr-runtime-base-refresh', + client_payload: { + ...tuple, + image_tag: `pr-merge-${input.merge_sha}`, + runtime_refresh_claim: String(generation), + runtime_refresh_claim_witness: witness, + }, + request: {retries: 0}, + }); + if (dispatched?.status !== 204) fail('Unexpected runtime refresh dispatch status.'); + } catch { + core.warning('Runtime refresh dispatch acceptance is unproven; leaving the claim held without retry.'); + return 'claim-held'; + } finally { + witness = undefined; + } + core.info('Runtime refresh dispatch returned HTTP 204; terminal claim receipt is not established.'); for (let observation = 0; observation < 8; observation += 1) { try { @@ -300,7 +495,7 @@ module.exports = async function admitPrRuntimeRefresh({ // Second-resolution chronology cannot confirm its attribution. run.event === 'repository_dispatch' && Date.parse(run.created_at) >= nextDispatchSecond && !observedRunIds.has(`${run.event}:${run.id}:${run.run_attempt}`))) { - core.info('The dispatched runtime refresh is visible as an exact active producer.'); + core.info('An exact active runtime producer became visible after dispatch; this is not claim receipt.'); return 'dispatched-observed'; } } catch { @@ -309,6 +504,6 @@ module.exports = async function admitPrRuntimeRefresh({ if (observation < 7) await sleep(2000); } - core.warning('Runtime refresh was dispatched but remained unconfirmed after bounded polling.'); + core.warning('No exact active runtime producer became visible after dispatch within the bounded poll.'); return 'dispatched-unconfirmed'; }; diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index ab8d9a59da..666f560c9a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -112,6 +112,7 @@ jobs: 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_RUNTIME_REFRESH_CLAIM: ${{ github.event.client_payload.runtime_refresh_claim || '' }} EVENT_ACTION: ${{ github.event.action || '' }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} run: | @@ -121,6 +122,9 @@ jobs: BASE_REF="" BASE_SHA="" MERGE_SHA="" + RUNTIME_REFRESH_CLAIM="" + RUNTIME_REFRESH_CLAIM_TAG="" + RUNTIME_REFRESH_CLAIM_ATTEMPT="" CANONICAL_PLAY_TRANSITION=false if [ "$EVENT_NAME" = "pull_request" ]; then PR_NUMBER="$EVENT_PR_NUMBER" @@ -223,6 +227,34 @@ jobs: echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 exit 1 } + claim_witness="$(jq -er '.client_payload.runtime_refresh_claim_witness // "" | select(type == "string")' "$GITHUB_EVENT_PATH")" + if [[ -n "${EVENT_RUNTIME_REFRESH_CLAIM:-}" || -n "$claim_witness" ]]; then + if [[ ! "$EVENT_RUNTIME_REFRESH_CLAIM" =~ ^[1-9][0-9]{0,15}$ ]] || + (( EVENT_RUNTIME_REFRESH_CLAIM > 9007199254740991 )) || + [[ ! "$claim_witness" =~ ^[0-9a-f]{64}$ || ! "$GITHUB_RUN_ATTEMPT" =~ ^[1-9][0-9]*$ ]]; then + echo "Runtime PR refresh claim identity is invalid." >&2 + exit 1 + fi + base_ref_hash="$(printf '%s' "$BASE_REF" | sha256sum | cut -d' ' -f1)" + witness_hash="$(printf '%s' "$claim_witness" | sha256sum | cut -d' ' -f1)" + claim="firemud-runtime-refresh-intent/v1/pr-${PR_NUMBER}/${MERGE_SHA}/${base_ref_hash}/g${EVENT_RUNTIME_REFRESH_CLAIM}" + claim_ref="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/tags/${claim}")" + claim_sha="$(jq -er --arg claim "refs/tags/${claim}" 'select(.ref == $claim and .object.type == "tag") | .object.sha | select(type == "string" and test("^[0-9a-f]{40}$"))' <<<"$claim_ref")" + claim_tag="$(gh api "repos/${GITHUB_REPOSITORY}/git/tags/${claim_sha}")" + jq -e --arg sha "$claim_sha" --arg claim "$claim" --arg merge "$MERGE_SHA" \ + --arg pr "$PR_NUMBER" --arg base_ref "$BASE_REF" --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \ + --arg generation "$EVENT_RUNTIME_REFRESH_CLAIM" --arg witness_hash "$witness_hash" \ + '.sha == $sha and .tag == $claim and .object.type == "commit" and .object.sha == $merge and + ((.message | fromjson) == + {pr_number:$pr,base_ref:$base_ref,base_sha:$base,head_sha:$head,merge_sha:$merge,generation:$generation,witness_sha256:$witness_hash})' \ + <<<"$claim_tag" >/dev/null || { + echo "Runtime PR refresh claim does not bind the verified tuple and dispatch witness." >&2 + exit 1 + } + RUNTIME_REFRESH_CLAIM="$EVENT_RUNTIME_REFRESH_CLAIM" + RUNTIME_REFRESH_CLAIM_TAG="$claim_sha" + RUNTIME_REFRESH_CLAIM_ATTEMPT="$GITHUB_RUN_ATTEMPT" + fi # 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")' \ @@ -291,8 +323,15 @@ jobs: echo "candidate_tag=${CANDIDATE_TAG}" echo "base_image=${BASE_IMAGE}" echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + echo "runtime_refresh_claim=${RUNTIME_REFRESH_CLAIM}" + echo "runtime_refresh_claim_tag=${RUNTIME_REFRESH_CLAIM_TAG}" + echo "runtime_refresh_claim_attempt=${RUNTIME_REFRESH_CLAIM_ATTEMPT}" } >> "$GITHUB_OUTPUT" + - name: Runtime refresh claim generation ${{ steps.meta.outputs.runtime_refresh_claim }} attempt ${{ steps.meta.outputs.runtime_refresh_claim_attempt }} tag ${{ steps.meta.outputs.runtime_refresh_claim_tag }} + if: ${{ steps.meta.outputs.runtime_refresh_claim != '' }} + run: ':' + - name: Verify successful CI push for manual publication if: ${{ github.event_name == 'workflow_dispatch' && steps.meta.outputs.head_sha != '' }} env: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 8526a8c366..db9b498c88 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -580,7 +580,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "48de05024423cf754e5da10dcb9034558bf64807fb59b8ea02931044c3704617"; + const canonicalRuntimeWorkflowSha256 = "91c71f0decaafe48b1139c90f4bc6f97bad1b8e971d0f932792a66e5882d5d40"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index d179aeb3b9..badaee350b 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -66,7 +66,7 @@ The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | | [`hosted-identity-request.yml`](../../.github/workflows/hosted-identity-request.yml) (`Hosted Identity Request`) | Trusted default-branch workflow | Validate the exact source run, current PR base/head/merge, and artifact, wait for the matching merge-scoped images or proven base images, then deploy or retire the PR namespace and report preview access | Only the trusted job receives protected deployment credentials; it never executes PR-controlled code. | -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 its executed substantive Validation Gate enforcement 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. Runtime producers group by exact PR/base/head/merge tuple. An old-head rerun uses a separate group, and a duplicate request cannot cancel an already-running producer. With the default GitHub single-pending queue, a later matching request can still replace a pending producer. The two trusted observers submit an exact refresh request to one default-branch admission workflow. Admission serializes each PR/base/head/merge tuple, independently verifies the current comparison, and rechecks for a visible active producer before sending the existing runtime dispatch. After dispatch it holds the same tuple's reservation for a bounded visibility check. Completed, failed, or unverifiable attempts leave the tuple eligible for repair. 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. +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 its executed substantive Validation Gate enforcement 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. Runtime producers group by exact PR/base/head/merge tuple. An old-head rerun uses a separate group, and a duplicate request cannot cancel an already-running producer. With the default GitHub single-pending queue, a later matching request can still replace a pending producer. The two trusted observers submit an exact refresh request to one default-branch admission workflow. Admission serializes each PR/base/head/merge tuple, verifies the current comparison, and rechecks for a visible active producer. Before sending the trusted refresh, it creates an immutable annotated Git claim for the exact PR, base ref, merge, and send generation using the existing repository permissions. The annotation retains the digest of a one-time dispatch witness. The runtime receiver verifies the entire current tuple and that witness, then records the claim tag and execution attempt in the native metadata job. A retry can claim the next generation after the unique exact native terminal receiver proves the preceding claim in its current attempt. Carried evidence from an older attempt does not qualify. Missing or ambiguous receiver evidence holds the existing claim, including after an accepted dispatch whose response was lost. The claim persists across admission jobs and Actions run visibility delays. 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. diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index cb0d6a1266..c6ccfd5c36 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -597,6 +597,14 @@ case "${2:-}" in fi cat "$FIXTURE_DIR/base-ref.json" ;; + repos/benhook1013/FireMUD/git/ref/tags/firemud-runtime-refresh-intent/*) + [[ "$2" == "${EXPECTED_RUNTIME_CLAIM_REF:-}" ]] || exit 2 + cat "$FIXTURE_DIR/runtime-claim-ref.json" + ;; + repos/benhook1013/FireMUD/git/tags/*) + [[ "$2" == "${EXPECTED_RUNTIME_CLAIM_TAG:-}" ]] || exit 2 + cat "$FIXTURE_DIR/runtime-claim-tag.json" + ;; repos/benhook1013/FireMUD/commits/cccccccccccccccccccccccccccccccccccccccc) cat "$FIXTURE_DIR/merge-commit.json" ;; *) echo "unexpected endpoint: ${2:-}" >&2; exit 2 ;; esac @@ -612,6 +620,7 @@ chmod +x "$fake_bin/docker" # Execute the real credential-free metadata admission for a feature-base bot PR. # Preview admission is a separate privileged boundary; exact tuple checks remain. PATH="$fake_bin:$PATH" FIXTURE_DIR="$fixture_dir" python3 - "$RUNTIME_WORKFLOW" <<'PY' +import hashlib import json import os from pathlib import Path @@ -621,7 +630,7 @@ from urllib.parse import quote fixture = Path(os.environ["FIXTURE_DIR"]) workflow = Path(sys.argv[1]).read_text() -section = workflow.split(" - name: Derive image tags\n", 1)[1].split(" - name: Verify successful CI push for manual publication\n", 1)[0] +section = workflow.split(" - name: Derive image tags\n", 1)[1].split("\n - name:", 1)[0] script = section.split(" run: |\n", 1)[1] script = "\n".join(line[10:] if line.startswith(" ") else line for line in script.splitlines()) script_template = script @@ -656,6 +665,11 @@ def admit(current_request, current_merge, current_branch, overrides=None, event_ calls = fixture / "runtime-meta-ref-calls" calls.write_text("") current_env = {**env, **(overrides or {})} + event_path = fixture / "runtime-meta-event.json" + event_path.write_text(json.dumps({"client_payload": { + "runtime_refresh_claim_witness": current_env.get("TEST_RUNTIME_CLAIM_WITNESS", ""), + }})) + current_env["GITHUB_EVENT_PATH"] = str(event_path) current_env.update({ "BASE_REF_CALLS": str(calls), "EXPECTED_BASE_REF_ENDPOINT": "repos/benhook1013/FireMUD/git/ref/heads/" + quote(current_env["EVENT_BASE_REF"], safe="/"), @@ -672,6 +686,42 @@ try: assert f"image_tag=pr-merge-{merge['sha']}\n" in output assert f"base_image=ghcr.io/benhook1013/firemud-base:{merge['sha']}\n" in output assert "canonical_play_transition=false\n" in output + assert "runtime_refresh_claim=\n" in output + base_ref_hash = hashlib.sha256(request["base"]["ref"].encode()).hexdigest() + claim = f"firemud-runtime-refresh-intent/v1/pr-{request['number']}/{merge['sha']}/{base_ref_hash}/g1" + claim_sha = "d" * 40 + claim_witness = "f" * 64 + claim_ref = {"ref": f"refs/tags/{claim}", "object": {"type": "tag", "sha": claim_sha}} + claim_tag = {"sha": claim_sha, "tag": claim, "object": {"type": "commit", "sha": merge["sha"]}, + "message": json.dumps({"pr_number": str(request["number"]), "base_ref": request["base"]["ref"], + "base_sha": branch["object"]["sha"], "head_sha": request["head"]["sha"], + "merge_sha": merge["sha"], "generation": "1", + "witness_sha256": hashlib.sha256(claim_witness.encode()).hexdigest()}) + "\n"} + claim_tag_file = fixture / "runtime-claim-tag.json" + (fixture / "runtime-claim-ref.json").write_text(json.dumps(claim_ref)) + claim_tag_file.write_text(json.dumps(claim_tag)) + claim_request = { + "EVENT_RUNTIME_REFRESH_CLAIM": "1", + "TEST_RUNTIME_CLAIM_WITNESS": claim_witness, + "EXPECTED_RUNTIME_CLAIM_REF": f"repos/benhook1013/FireMUD/git/ref/tags/{claim}", + "EXPECTED_RUNTIME_CLAIM_TAG": f"repos/benhook1013/FireMUD/git/tags/{claim_sha}", + } + accepted_claim = admit(request, merge, branch, claim_request) + assert accepted_claim.returncode == 0, accepted_claim.stderr + output = Path(env["GITHUB_OUTPUT"]).read_text() + assert "runtime_refresh_claim=1\n" in output + assert "runtime_refresh_claim_attempt=1\n" in output + assert f"runtime_refresh_claim_tag={claim_sha}\n" in output + assert claim_witness not in output + assert admit(request, merge, branch, {**claim_request, "TEST_RUNTIME_CLAIM_WITNESS": "b" * 64}).returncode != 0 + assert admit(request, merge, branch, {**claim_request, "TEST_RUNTIME_CLAIM_WITNESS": ""}).returncode != 0 + assert admit(request, merge, branch, {**claim_request, "EVENT_RUNTIME_REFRESH_CLAIM": ""}).returncode != 0 + claim_tag_file.write_text(json.dumps({**claim_tag, "object": {"type": "commit", "sha": "e" * 40}})) + assert admit(request, merge, branch, claim_request).returncode != 0 + assert "runtime_refresh_claim=1\n" not in Path(env["GITHUB_OUTPUT"]).read_text() + assert admit(request, merge, branch, {**claim_request, "EVENT_RUNTIME_REFRESH_CLAIM": "9007199254740992"}).returncode != 0 + assert admit(request, merge, branch, claim_request, event_name="pull_request").returncode == 0 + assert "runtime_refresh_claim=\n" in Path(env["GITHUB_OUTPUT"]).read_text() labeled_request = json.loads(json.dumps(request)) labeled_request["labels"] = [{"name": "canonical-play-transition"}] assert admit(labeled_request, merge, branch).returncode == 0 diff --git a/dev-tools/tests/preview-runtime-refresh.test.cjs b/dev-tools/tests/preview-runtime-refresh.test.cjs index 8d8d3edd6f..0ec779149b 100644 --- a/dev-tools/tests/preview-runtime-refresh.test.cjs +++ b/dev-tools/tests/preview-runtime-refresh.test.cjs @@ -1,5 +1,6 @@ const assert = require('node:assert/strict'); const {execFileSync} = require('node:child_process'); +const {createHash} = require('node:crypto'); const {test} = require('node:test'); const path = require('node:path'); const root = path.resolve(__dirname, '../..'); @@ -17,7 +18,7 @@ function admissionFixture() { const repository = 'example/FireMUD'; const runtimePath = '.github/workflows/runtime-images.yml'; const makeRun = (overrides = {}) => ({ - id: 300, run_attempt: 1, workflow_id: 42, event: 'repository_dispatch', status: 'queued', + id: 300, run_attempt: 1, workflow_id: 42, event: 'repository_dispatch', status: 'queued', head_sha: D, conclusion: null, path: runtimePath, head_branch: 'develop', repository: {full_name: repository}, head_repository: {full_name: repository}, created_at: new Date().toISOString(), display_title: `Build Runtime Images secure-pr-artifact pr-7 base-${B} head-${C} merge-${A} mode-required`, @@ -26,6 +27,9 @@ function admissionFixture() { const sent = []; const warnings = []; const runs = []; + const claimRefs = new Map(); + const claimTags = new Map(); + const receiverJobs = new Map(); const state = {base: B, mergeParents: [B, C], keepHidden: false, afterInventory: null, labels: [{name: 'preview:priority'}], nextId: 301, lookups: [], pullObservations: [], baseReads: 0, commitRefs: [], missingExactCommitReads: 0, waits: [], producerReads: []}; @@ -38,7 +42,29 @@ function admissionFixture() { ...state.pullObservations.shift()}}; }}, git: { + listMatchingRefs: async ({ref}) => ({status: 200, headers: {}, data: [...claimRefs.values()] + .filter(entry => entry.ref.startsWith(`refs/${ref}`))}), + getTag: async ({tag_sha}) => ({data: claimTags.get(tag_sha)}), + createTag: async ({tag, message, object, type, tagger}) => { + const sha = String(claimTags.size + 1).padStart(40, '0'); + const record = {sha, tag, message, object: {type, sha: object}, tagger}; + claimTags.set(sha, record); + return {status: 201, data: record}; + }, + createRef: async ({ref, sha}) => { + assert.ok(claimTags.has(sha)); + if (claimRefs.has(ref)) throw Object.assign(new Error('ref already exists'), {status: 422}); + const record = {ref, object: {type: 'tag', sha}}; + claimRefs.set(ref, record); + state.afterClaim?.(); + if (state.loseClaimResponse) throw new Error('response lost after ref creation'); + return {status: 201, data: record}; + }, getRef: async ({ref}) => { + if (ref.startsWith('tags/')) { + if (!claimRefs.has(`refs/${ref}`)) throw Object.assign(new Error('ref not found'), {status: 404}); + return {data: claimRefs.get(`refs/${ref}`)}; + } assert.equal(ref, `heads/${input.base_ref}`); state.baseReads++; return {data: {ref: `refs/heads/${input.base_ref}`, object: {sha: state.base}}}; @@ -54,6 +80,10 @@ function admissionFixture() { const run = runs.find(run => run.id === run_id); return {data: state.refreshProducer ? state.refreshProducer(run) : run}; }, + listJobsForWorkflowRunAttempt: async ({run_id, attempt_number}) => { + const jobs = receiverJobs.get(`${run_id}:${attempt_number}`) || []; + return {data: {total_count: jobs.length, jobs}}; + }, listWorkflowRuns: async ({workflow_id, status, event, per_page, page, created}) => { assert.equal(workflow_id, 42); assert.equal(per_page, 100); @@ -82,6 +112,8 @@ function admissionFixture() { // Registration becomes visible after the fixture's first two-second wait. state.newRun = makeRun({id: state.nextId++, created_at: state.dispatchCreatedAt ?? new Date(Date.now() + 2000).toISOString()}); + if (state.loseDispatchResponse) throw new Error('response lost after dispatch acceptance'); + return {status: state.dispatchStatus ?? 204}; }, }, }}; @@ -92,15 +124,21 @@ function admissionFixture() { state.afterWait?.(); if (!state.keepHidden && state.newRun && !runs.includes(state.newRun)) runs.push(state.newRun); }}; - return {admission, makeRun, runs, sent, state, warnings}; + return {admission, makeRun, runs, sent, state, warnings, claimRefs, claimTags, receiverJobs}; } test('serialized admission waits for the first exact receiver before releasing the permit', async () => { const f = admissionFixture(); assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); assert.equal(await admitRuntimeRefresh(f.admission), 'already-active'); + const [tag] = f.claimTags.values(); + const {runtime_refresh_claim_witness: witness} = f.sent[0].client_payload; + assert.match(witness, /^[0-9a-f]{64}$/); + assert.equal(JSON.parse(tag.message).witness_sha256, createHash('sha256').update(witness).digest('hex')); assert.deepEqual(f.sent, [{owner: 'example', repo: 'FireMUD', event_type: 'pr-runtime-base-refresh', - client_payload: {...f.admission.input, image_tag: `pr-merge-${A}`}}]); + client_payload: {...f.admission.input, image_tag: `pr-merge-${A}`, runtime_refresh_claim: '1', + runtime_refresh_claim_witness: witness}, + request: {retries: 0}}]); }); test('completed producers still permit an exact repair', async () => { @@ -182,8 +220,8 @@ test('admission rereads PR and base through pending mergeability, a stale base p f.state.alternateCommit = {sha: E, parents: [{sha: D}, {sha: C}]}; f.state.missingExactCommitReads = 1; assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); - assert.deepEqual(f.state.commitRefs, [E, A, A, A]); - assert.equal(f.state.baseReads, 6); + assert.deepEqual(f.state.commitRefs, [E, A, A, A, A]); + assert.equal(f.state.baseReads, 7); assert.deepEqual(f.state.waits, [2000, 2000, 2000, 2000, 2000]); assert.equal(f.sent[0].client_payload.merge_sha, A); }); @@ -246,7 +284,7 @@ test('a stale or unavailable selected producer leaves an exact refresh eligible' refreshProducer(run) : run; assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); assert.deepEqual(f.state.producerReads, afterFinalTuple ? [300, 300] : [300]); - assert.deepEqual(f.state.commitRefs, afterFinalTuple ? [A, A, A] : [A, A]); + assert.deepEqual(f.state.commitRefs, afterFinalTuple ? [A, A, A, A] : [A, A, A]); assert.equal(f.sent.length, 1); } } @@ -259,7 +297,7 @@ test('a producer that completes while the final live tuple is pending cannot sup f.state.afterWait = () => { f.runs[0] = {...f.runs[0], status: 'completed', conclusion: 'failure'}; }; assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-observed'); assert.deepEqual(f.state.producerReads, [300, 300]); - assert.deepEqual(f.state.commitRefs, [A, A, A]); + assert.deepEqual(f.state.commitRefs, [A, A, A, A]); assert.deepEqual(f.state.waits, [2000, 2000]); assert.equal(f.sent.length, 1); }); @@ -292,6 +330,106 @@ test('indeterminate dispatch visibility does not silently consume a repair or ca assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); assert.equal(f.sent.length, 1); assert.ok(f.warnings.length > 0); + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); +}); + +test('a lost dispatch acknowledgement keeps the exact tuple held across callbacks', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + f.state.loseDispatchResponse = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); + f.state.loseDispatchResponse = false; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); + assert.equal(f.claimRefs.size, 1); +}); + +test('a lost atomic claim acknowledgement does not authorize either callback to send', async () => { + const f = admissionFixture(); + f.state.loseClaimResponse = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.claimRefs.size, 1); + f.state.loseClaimResponse = false; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.deepEqual(f.sent, []); +}); + +test('an unexpected dispatch response status cannot be described as accepted', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + f.state.dispatchStatus = 202; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); +}); + +test('a comparison moving during the claim is never dispatched', async () => { + const f = admissionFixture(); + f.state.afterClaim = () => { f.state.base = D; }; + assert.equal(await admitRuntimeRefresh(f.admission), 'obsolete'); + assert.equal(f.claimRefs.size, 1); + assert.deepEqual(f.sent, []); +}); + +test('advancing a generation requires one exact terminal receiver with a successful claim marker', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + const run = {...f.state.newRun, status: 'completed', conclusion: 'failure'}; + f.runs.push(run); + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); + const [tag] = f.claimTags.values(); + const jobs = [{id: 1, run_id: run.id, run_attempt: run.run_attempt, head_sha: run.head_sha, + name: 'Derive Runtime Image Metadata', status: 'completed', conclusion: 'success', + steps: [{name: `Runtime refresh claim generation 1 attempt 1 tag ${tag.sha}`, + status: 'completed', conclusion: 'success'}]}]; + const legacy = f.makeRun({id: 299, created_at: run.created_at, status: 'completed', conclusion: 'success'}); + f.runs.push(legacy); + f.receiverJobs.set(`${legacy.id}:${legacy.run_attempt}`, [{...jobs[0], id: 2, run_id: legacy.id, + steps: [{name: 'Runtime refresh claim generation attempt tag ', status: 'completed', conclusion: 'skipped'}]}]); + f.receiverJobs.set(`${run.id}:${run.run_attempt}`, jobs); + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + assert.deepEqual(f.sent.map(({client_payload}) => client_payload.runtime_refresh_claim), ['1', '2']); + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 2); +}); + +test('a successful marker carried from another attempt cannot advance the claim', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + const [tag] = f.claimTags.values(); + const run = {...f.state.newRun, status: 'completed', conclusion: 'failure', run_attempt: 2}; + f.runs.push(run); + f.receiverJobs.set(`${run.id}:2`, [{id: 1, run_id: run.id, run_attempt: 2, head_sha: run.head_sha, + name: 'Derive Runtime Image Metadata', status: 'completed', conclusion: 'success', + steps: [{name: `Runtime refresh claim generation 1 attempt 1 tag ${tag.sha}`, + status: 'completed', conclusion: 'success'}]}]); + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); +}); + +test('an equal commit on a different base ref gets an independent exact claim', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + f.admission.input.base_ref = 'feature/stack'; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + assert.equal(f.claimRefs.size, 2); + assert.deepEqual(f.sent.map(({client_payload}) => client_payload.runtime_refresh_claim), ['1', '1']); +}); + +test('an annotated claim which points at a different merge can never authorize dispatch', async () => { + const f = admissionFixture(); + f.state.keepHidden = true; + assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); + const [record] = f.claimTags.values(); + record.object.sha = D; + assert.equal(await admitRuntimeRefresh(f.admission), 'claim-held'); + assert.equal(f.sent.length, 1); }); test('unseen same-second activity is ambiguous dispatch attribution and never triggers a retry', async t => { @@ -304,7 +442,7 @@ test('unseen same-second activity is ambiguous dispatch attribution and never tr assert.equal(await admitRuntimeRefresh(f.admission), 'dispatched-unconfirmed'); assert.equal(f.sent.length, 1); assert.equal(f.state.waits.length, 7); - assert.ok(f.warnings.some(warning => warning.includes('remained unconfirmed'))); + assert.ok(f.warnings.some(warning => warning.includes('No exact active runtime producer became visible'))); } }); From b0118a3526934adaac11d17b208e54cd7417e8f9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:09:01 +1300 Subject: [PATCH 109/199] Keep JaCoCo recovery contract aligned with the Maven 429 delay --- dev-tools/tests/gradle-dependency-recovery-contract.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index b7f3e251d9..fbd54663c1 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1257,7 +1257,7 @@ esac' assert_call 1 ":common-saga:test -PfullCheck --dry-run --no-configuration-cache" assert_call 2 "--refresh-dependencies :common-saga:test -PfullCheck --dry-run --no-configuration-cache" [[ "$(grep -c '^--refresh-dependencies ' "$CASE_DIR/calls")" -eq 1 ]] || fail "JaCoCo repeated dependency refresh" - [[ "$(cat "$CASE_DIR/sleeps")" == 2 ]] || fail "JaCoCo did not use exactly one bounded recovery delay" + assert_rate_limit_delay cmp "$CASE_DIR/calls" "$CASE_DIR/locked-calls" || fail "JaCoCo bypassed the existing locked runner" done From 27594d6e40f4f5c3ed56e212a91e9ef6ec476e64 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:21:45 +1300 Subject: [PATCH 110/199] Make candidate runtime smoke caches read-only on GitHub --- .github/actionlint.yaml | 2 ++ .github/workflows/runtime-images.yml | 4 +++- design/architecture/system-architecture-cicd.md | 2 +- .../tests/hosted-identity-controller-workflow-contract.sh | 2 +- dev-tools/tests/pr-runtime-image-publication-contract.sh | 2 ++ 5 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 833522d4ce..d0b3bd164e 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -24,6 +24,8 @@ paths: .github/workflows/runtime-images.yml: ignore: - 'unexpected key "queue" for "concurrency" section' + # Provider-supported job cache permissions validated by the runtime image contract. + - 'unexpected key "cache-mode" for "job" section' .github/workflows/preview-cleanup-proof.yml: ignore: - 'unexpected key "queue" for "concurrency" section' diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 666f560c9a..6a3c02e266 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1597,6 +1597,8 @@ jobs: 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 + # A repository dispatch runs on the default branch but builds candidate code. + cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read @@ -1908,6 +1910,7 @@ jobs: 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 + cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read @@ -1952,7 +1955,6 @@ jobs: 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 diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index badaee350b..8a968c8640 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -143,7 +143,7 @@ Other workflows support additional automation: ## Building and Pushing Images -Trusted branch images retain commit-SHA tags. Pull-request images are built locally without registry credentials; only the successful artifact for an exact base/head/merge crosses into the trusted publisher, which pushes immutable `pr-merge-` tags to **GitHub Container Registry (GHCR)**. Trusted `develop` and `main` builds first publish unique candidate tags, run full-stack smoke against those candidates, then assign commit-SHA and branch aliases to the tested digests. Shared build-cache tags are not deployment evidence. +Trusted branch images retain commit-SHA tags. Pull-request images are built locally without registry credentials; only the successful artifact for an exact base/head/merge crosses into the trusted publisher, which pushes immutable `pr-merge-` tags to **GitHub Container Registry (GHCR)**. The candidate runtime and controller smoke jobs use GitHub-enforced read-only Actions cache tokens because a typed repository dispatch runs on the default branch while building candidate code. Trusted `develop` and `main` builds first publish unique candidate tags, run full-stack smoke against those candidates, then assign commit-SHA and branch aliases to the tested digests. Shared build-cache tags are not deployment evidence. The `hosted-environment-identity-controller` image is a trusted infrastructure artifact published only by its dedicated job during trusted-source `develop` and `main` runs. That job builds the controller service from the checked-out branch commit against the exact registry-returned `firemud-base` digest produced by its prerequisite job, smokes the exact local controller image, pushes that same image to the dedicated `ghcr.io/benhook1013/firemud-hosted-identity-controller` package, and records SLSA provenance for the registry-returned controller digest. A pre-existing tag is overwritten by the exact smoke-tested build rather than accepted as trusted. Pull-request runs may build and smoke a clearly local controller image without registry credentials, but they exclude it from the exported PR runtime-image artifact, and the trusted PR artifact publisher never publishes it. Runtime deployment accepts only a digest-pinned reference from the dedicated controller package whose GitHub attestation verifies the `runtime-images.yml` signer workflow and a `develop` or `main` source ref. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 8ea52ef230..42600ea9db 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -399,6 +399,7 @@ assert "needs.pr-local-smoke.outputs.publishable == 'true'" in ( controller_job = workflow["jobs"]["pr-controller-smoke"] assert controller_job["needs"] == ["image-meta"] +assert controller_job["cache-mode"] == "read" assert "needs.image-meta.outputs.controller_smoke_required == 'true'" in ( controller_job["if"] ) @@ -431,7 +432,6 @@ assert base_step["with"] == { "load": True, "tags": "${{ env.BASE_IMAGE }}", "cache-from": "type=gha,scope=pr-controller-smoke", - "cache-to": "type=gha,mode=max,scope=pr-controller-smoke", } assert "docker/login-action@" not in str(controller_job) assert "GITHUB_TOKEN" not in str(controller_job) diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index c6ccfd5c36..8e370c6d08 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -346,6 +346,8 @@ for job in ["pr-local-smoke", "pr-controller-smoke"]: section = re.split(r"\n [a-z][a-z-]*:", runtime_workflow.split(" " + job + ":\n", 1)[1], maxsplit=1)[0] if "contents: read" not in section or "contents: write" in section or "packages: write" in section: raise SystemExit("PR source jobs must remain read-only") + if not re.search(r"(?m)^ cache-mode: read$", section) or "cache-to:" in section: + raise SystemExit("PR source jobs must use provider-enforced read-only caches without exports") runtime_start = runtime_workflow.index("- name: Promote smoke-tested service digests") runtime_run = runtime_workflow.index(" run: |\n", runtime_start) + len(" run: |\n") runtime_script = runtime_workflow[runtime_run:] From e578f3cbd98f203d152b68cf0bb83e1e9d839ccc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:17:41 +1300 Subject: [PATCH 111/199] Rebind Smoke Gate to the verified runtime workflow --- .github/workflows/smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index db9b498c88..b0523ea892 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -580,7 +580,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "91c71f0decaafe48b1139c90f4bc6f97bad1b8e971d0f932792a66e5882d5d40"; + const canonicalRuntimeWorkflowSha256 = "004af984d2aa7ab023758cbc38c6c20f92976b8f07040c9a4965bda6616d5dd5"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", From 24be654789d2f0bf7a91f1bf92bdea1f154c3cba Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:12:27 +1300 Subject: [PATCH 112/199] Use shared runtime claims for stale-base preview refreshes --- .github/workflows/preview.yml | 8 ++--- .../preview-runner-isolation-contract.sh | 29 +++++++++++++++---- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index d2bce23cb2..b02f5f087d 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -496,23 +496,23 @@ jobs: !shaPattern.test(process.env.HEAD_SHA) || !shaPattern.test(process.env.MERGE_SHA) || process.env.IMAGE_TAG === process.env.BASE_SHA) { - core.setFailed("Runtime refresh dispatch has an invalid PR image tuple."); + core.setFailed("Runtime refresh request has an invalid PR image tuple."); return; } await github.rest.repos.createDispatchEvent({ ...context.repo, - event_type: "pr-runtime-base-refresh", + event_type: "pr-runtime-base-refresh-request", client_payload: { pr_number: process.env.PR_NUMBER, base_ref: baseRef, base_sha: process.env.BASE_SHA, head_sha: process.env.HEAD_SHA, merge_sha: process.env.MERGE_SHA, - image_tag: process.env.IMAGE_TAG, + preview_only: true, }, }); - core.info(`Dispatched current-base runtime refresh for PR #${process.env.PR_NUMBER}.`); + core.info(`Requested current-base runtime refresh admission for PR #${process.env.PR_NUMBER}; no runtime start is confirmed.`); preview-render: name: Render Sanitized Preview Artifact diff --git a/dev-tools/tests/preview-runner-isolation-contract.sh b/dev-tools/tests/preview-runner-isolation-contract.sh index 43d4ab57f1..abfcb57682 100644 --- a/dev-tools/tests/preview-runner-isolation-contract.sh +++ b/dev-tools/tests/preview-runner-isolation-contract.sh @@ -410,7 +410,12 @@ if refresh_needs != "preview-plan" and refresh_needs != ["preview-plan"]: if checkouts(refresh_job): raise AssertionError("preview runtime base refresh must not check out PR-controlled source") refresh_if = str(refresh_job.get("if", "")) -for required in ("base_refresh_required == 'true'", "action == 'deploy'"): +for required in ( + "eligible == 'true'", + "base_refresh_required == 'true'", + "action == 'deploy'", + "image_tag != needs.preview-plan.outputs.base_sha", +): if required not in refresh_if: raise AssertionError(f"preview runtime base refresh lost its {required} gate") refresh_scripts = [ @@ -421,11 +426,23 @@ refresh_scripts = [ and re.fullmatch(r"actions/github-script@[0-9a-f]{40}", step["uses"]) ] if len(refresh_scripts) != 1: - raise AssertionError("preview runtime base refresh must use exactly one pinned GitHub dispatcher") -if 'event_type: "pr-runtime-base-refresh"' not in refresh_scripts[0]: - raise AssertionError("preview runtime base refresh lost its typed dispatch") -if "base_sha" not in refresh_scripts[0] or "head_sha" not in refresh_scripts[0] or "merge_sha" not in refresh_scripts[0]: - raise AssertionError("preview runtime base refresh dispatch lost its exact merge tuple") + raise AssertionError("preview runtime base refresh must use exactly one pinned GitHub Script step") +refresh_script = refresh_scripts[0] +if re.search(r"['\"]pr-runtime-base-refresh['\"]", refresh_script): + raise AssertionError("preview must not start the runtime producer directly") +request = re.search( + r'event_type: "pr-runtime-base-refresh-request",\s*client_payload: \{([^}]+)\}', + refresh_script, +) +if request is None or [line.strip() for line in request[1].strip().splitlines()] != [ + "pr_number: process.env.PR_NUMBER,", + "base_ref: baseRef,", + "base_sha: process.env.BASE_SHA,", + "head_sha: process.env.HEAD_SHA,", + "merge_sha: process.env.MERGE_SHA,", + "preview_only: true,", +]: + raise AssertionError("preview must request durable admission for the exact preview-only runtime tuple") # Keep the permission boundary regression-tested independently of the live # workflow. A render write grant is always forbidden; the trusted dispatcher From 2545e9f789df9b5582e8567c7c56009d1d46295e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:40:51 +1300 Subject: [PATCH 113/199] Bind runtime publication artifacts to the exact producer attempt --- .../workflows/publish-pr-runtime-images.yml | 74 ++++++++--- .github/workflows/runtime-images.yml | 7 +- .github/workflows/smoke.yml | 5 +- .../architecture/system-architecture-cicd.md | 6 +- .../pr-required-gate-context-contract.sh | 15 ++- .../tests/pr-retarget-workflow-contract.sh | 3 +- .../pr-runtime-image-publication-contract.sh | 120 ++++++++++++++++-- 7 files changed, 196 insertions(+), 34 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index b14994d377..a325ce8e41 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -49,6 +49,11 @@ jobs: throw new Error("publication source run ID is not a positive safe integer"); } const sourceId = Number(sourceIdText); + let sourceAttempt = callback ? context.payload.workflow_run.run_attempt : undefined; + const positiveInteger = value => Number.isSafeInteger(value) && value > 0; + if (callback && !positiveInteger(sourceAttempt)) { + throw new Error("publication callback source attempt is not a positive safe integer"); + } const repository = `${context.repo.owner}/${context.repo.repo}`; const { data: workflow } = await github.rest.actions.getWorkflow({ ...context.repo, workflow_id: "runtime-images.yml", @@ -77,6 +82,7 @@ jobs: }); const title = typeof run.display_title === "string" && run.display_title.match(titlePattern); if (run.id !== sourceId || run.workflow_id !== workflow.id || + !positiveInteger(run.run_attempt) || !isTrustedWorkflowPath(run.path) || !title || !["Build Runtime Images", run.display_title].includes(run.name) || !["pull_request", "repository_dispatch"].includes(run.event) || @@ -89,28 +95,40 @@ jobs: } if (callback) { const event = context.payload.workflow_run; - for (const field of ["id", "workflow_id", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { + for (const field of ["id", "workflow_id", "display_title", "event", "status", "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`); } } + sourceAttempt ??= run.run_attempt; + if (run.run_attempt !== sourceAttempt) { + throw new Error("current publication source attempt differs from the pinned attempt"); + } 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 jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + { ...context.repo, run_id: sourceId, attempt_number: sourceAttempt, per_page: 100 }, + ); + const producerJobs = jobs.filter(job => + /^PR Full-Stack Smoke \(runtime-required=(?:true|false)\)$/.test(job.name)); + const [producer] = producerJobs; + if (producerJobs.length !== 1 || !positiveInteger(producer.id) || + producer.run_id !== sourceId || producer.run_attempt !== sourceAttempt || + producer.head_sha !== run.head_sha || producer.status !== "completed" || producer.conclusion !== "success") { + throw new Error("publication requires one successful runtime image job from the exact source attempt"); + } + if ((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; } 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", `pr-runtime-images-pr-merge-${title[4]}-attempt-${sourceAttempt}`); break; } if (callback || !["queued", "in_progress", "waiting", "pending", "requested"].includes(run.status) || @@ -164,6 +182,7 @@ jobs: env: CURRENT_REPOSITORY: ${{ github.repository }} 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 }} @@ -281,6 +300,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 re.fullmatch(r"[1-9][0-9]*", source_run_attempt_text): + fail("source workflow run 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: @@ -307,6 +330,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("current workflow run attempt differs from the pinned source attempt") 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}: @@ -402,7 +427,7 @@ jobs: if path.is_dir() and path.name.startswith("pr-runtime-images-") ) image_tag = f"pr-merge-{merge_sha}" - expected_artifact_name = f"pr-runtime-images-{image_tag}" + expected_artifact_name = f"pr-runtime-images-{image_tag}-attempt-{source_run_attempt}" if artifact_dirs != [artifact_root / expected_artifact_name]: fail("downloaded artifacts do not contain exactly the expected runtime image artifact") artifact_dir = artifact_dirs[0] @@ -424,10 +449,12 @@ jobs: fail(f"runtime provenance JSON is malformed: {error}") expected_provenance_keys = { "repository", "prNumber", "baseSha", "headSha", "mergeSha", - "imageTag", "sourceRunId", "services", + "imageTag", "sourceRunId", "sourceRunAttempt", "services", } - if set(provenance) != expected_provenance_keys: + if not isinstance(provenance, dict) or set(provenance) != expected_provenance_keys: fail("runtime provenance JSON schema contains missing or extra keys") + if type(provenance["sourceRunAttempt"]) is not int or provenance["sourceRunAttempt"] != source_run_attempt: + fail("runtime provenance attempt differs from the pinned source attempt") if provenance != { "repository": repository, "prNumber": pr_number_int, @@ -436,6 +463,7 @@ jobs: "mergeSha": merge_sha, "imageTag": image_tag, "sourceRunId": source_run_id, + "sourceRunAttempt": source_run_attempt, "services": EXPECTED_SERVICES, }: fail("runtime provenance does not exactly match the trusted source run and PR") @@ -451,7 +479,7 @@ jobs: env_file.write(f"HEAD_SHA={head_sha}\n") env_file.write(f"MERGE_SHA={merge_sha}\n") print( - f"Validated source run {source_run_id}, PR #{pr_number}, " + f"Validated source run {source_run_id} attempt {source_run_attempt}, PR #{pr_number}, " f"merge {merge_sha}, artifact {expected_artifact_name}; registry remains untouched." ) PY @@ -459,6 +487,7 @@ jobs: - name: Summarize trusted publication source env: 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_HEAD_BRANCH: ${{ fromJSON(needs.source.outputs.source).head_branch }} @@ -474,13 +503,13 @@ 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 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']}` - Tested merge SHA and immutable image tag: `{os.environ['MERGE_SHA']}` / `{os.environ['IMAGE_TAG']}` - GitHub displays this run in the default-branch context because completion callbacks and typed publication handoffs use the trusted workflow definition. It publishes only the successful source run's exact merge-SHA artifact after validating current PR identity and provenance, and does not check out PR source. + GitHub displays this run in the default-branch context because completion callbacks and typed publication handoffs use the trusted workflow definition. It publishes only the exact merge-SHA artifact from the pinned successful source attempt after validating current PR identity and provenance, and does not check out PR source. """ with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary_file: summary_file.write(summary) @@ -491,6 +520,21 @@ jobs: set -o pipefail gzip -dc "$PR_RUNTIME_ARTIFACT_DIR/pr-runtime-images.tar.gz" | docker load + - name: Fence current source attempt before registry login + env: + CURRENT_REPOSITORY: ${{ github.repository }} + SOURCE_RUN_ID: ${{ fromJSON(needs.source.outputs.source).id }} + SOURCE_RUN_ATTEMPT: ${{ fromJSON(needs.source.outputs.source).run_attempt }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + if ! gh api "repos/${CURRENT_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}" | + jq -e --argjson id "$SOURCE_RUN_ID" --argjson attempt "$SOURCE_RUN_ATTEMPT" \ + '.id == $id and .run_attempt == $attempt and .status == "completed" and .conclusion == "success"' >/dev/null; then + echo "The pinned source attempt is no longer a current completed success; registry remains untouched." >&2 + exit 1 + fi + - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 6a3c02e266..15599fcd01 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1774,6 +1774,7 @@ jobs: "mergeSha": os.environ["MERGE_SHA"], "imageTag": os.environ["IMAGE_TAG"], "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "sourceRunAttempt": int(os.environ["GITHUB_RUN_ATTEMPT"]), "services": services, } with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: @@ -1787,7 +1788,7 @@ jobs: 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 }} + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }}-attempt-${{ github.run_attempt }} path: | /tmp/pr-runtime-images.tar.gz /tmp/pr-runtime-services.txt @@ -1802,7 +1803,7 @@ jobs: 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 }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }}-attempt-${{ github.run_attempt }} run: | { echo "### PR runtime images and applicable full-stack smoke" @@ -1814,7 +1815,7 @@ jobs: 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." + 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 accepts only the exact merge-scoped artifact from this successful run attempt." } >> "$GITHUB_STEP_SUMMARY" - name: Dump Docker Compose logs on failure diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b0523ea892..ce56e076ca 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -580,7 +580,9 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "004af984d2aa7ab023758cbc38c6c20f92976b8f07040c9a4965bda6616d5dd5"; + const canonicalRuntimeWorkflowSha256 = "b1f827caebc7b98e47821f3516afa5472552f7404b284c736864fb4a1dc3a9b4"; + // The previous archive format does not change this definition's independently valid smoke proof. + const canonicalMergeOnlyArtifactRuntimeWorkflowSha256 = "004af984d2aa7ab023758cbc38c6c20f92976b8f07040c9a4965bda6616d5dd5"; const outgoingTrustedRefreshRuntimeWorkflowSha256 = new Set([ "1993dbcd405b657d171339ca7aaf21ff8757098289a8f9121ddc433a00df803e", "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", @@ -705,6 +707,7 @@ jobs: function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { return definitionHash === canonicalRuntimeWorkflowSha256 || + definitionHash === canonicalMergeOnlyArtifactRuntimeWorkflowSha256 || (sourceEvent === "repository_dispatch" && (definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 || outgoingTrustedRefreshRuntimeWorkflowSha256.has(definitionHash))); diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 8a968c8640..3fa7bd3164 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -60,7 +60,7 @@ The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also | Workflow | Execution context | Responsibility | What its GitHub run means | | --- | --- | --- | --- | -| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the successful image artifact under an immutable tag keyed to the tested merge SHA | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | +| [`runtime-images.yml`](../../.github/workflows/runtime-images.yml) (`Build Runtime Images`) | Untrusted PR merge commit with read-only repository permissions | Build the PR merge commit locally, run the explicit held-admission qualification, and upload the image archive named for the tested merge SHA and native run attempt | The recorded base/head/merge input was built without registry-write credentials. Successful smoke preserves direct backend `LOGIN` -> `PLAY` -> `LOOK` proof and verifies Gateway/Telnet fail closed; it does not establish successful public admission. The diagnostic exception below provides no passing `PLAY` or `LOOK` proof. See [player-flow smoke boundaries](system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). | | [`smoke.yml`](../../.github/workflows/smoke.yml) (`PR Smoke Gate`) | PR metadata and Actions API | Decide whether runtime smoke is required and expose the protected `Smoke Gate` by tracking the matching `Build Runtime Images` result | This is a controller and required gate; it does not run a second copy of the runtime qualification. Metadata-only edits skip it under a non-required name and do not dispatch or cancel runtime construction; see [Required Gates on Metadata Edits](#required-gates-on-metadata-edits). | | [`publish-pr-runtime-images.yml`](../../.github/workflows/publish-pr-runtime-images.yml) (`Publish PR Runtime Images`) | Trusted default-branch `workflow_run` or typed `repository_dispatch` definition | Verify the current PR and exact source artifact identity, then publish immutable `pr-merge-` tags in GHCR | GitHub displays the default branch because the trusted publisher runs there; its summary identifies the source PR run and base/head/merge SHAs. | | [`preview.yml`](../../.github/workflows/preview.yml) (`PR Preview Environment`) | PR-scoped untrusted source run | Render and upload a sanitized full-stack chart artifact without deployment credentials | The artifact is bound to the PR head and recorded base/merge SHAs; PR-controlled code never receives cluster or registry credentials. | @@ -70,11 +70,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. -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 verifies the owning runtime workflow and pins the current native attempt of the supplied exact source run. A completion callback must name that same attempt; a typed `source_run_id` dispatch can arrive before completion, so the resolver waits for actual terminal success of the pinned attempt within a two-minute budget. A changed attempt, malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. Publication checks the successful producer job from that exact attempt, excludes the diagnostic exception, and rechecks the current successful attempt before registry login. The only eligible download is `pr-runtime-images-pr-merge--attempt-` from the pinned run ID, with an integer `sourceRunAttempt` in its provenance matching the pinned attempt. An older merge-name-only archive cannot be published; recreating an eligible archive requires running the updated producer definition. This does not invalidate independently valid Smoke Gate proof. 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. 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. +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`. Both can still use the immediately preceding merge-name-only producer definition as smoke proof, not as image publication proof. The older trusted-refresh fingerprint fallback remains available only to verified typed refreshes. 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. Branch-to-environment promotion contract: diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 04ba15909a..e3f7379bf8 100755 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -1231,6 +1231,11 @@ 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 canonicalMergeOnlyArtifactRuntimeWorkflowSha256 = script.match( + /const canonicalMergeOnlyArtifactRuntimeWorkflowSha256 = "([0-9a-f]{64})";/)[1]; +assert.equal(canonicalMergeOnlyArtifactRuntimeWorkflowSha256, "004af984d2aa7ab023758cbc38c6c20f92976b8f07040c9a4965bda6616d5dd5"); +const mergeOnlyArtifactBytes = Buffer.concat([bytes, Buffer.from("\n# Merge-only artifact fixture\n")]); +const mergeOnlyArtifactFixtureSha256 = require("node:crypto").createHash("sha256").update(mergeOnlyArtifactBytes).digest("hex"); const preMergeRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Current default trusted refresh definition\n")]); const preMergeRefreshFixtureSha256 = require("node:crypto").createHash("sha256") .update(preMergeRefreshBytes).digest("hex"); @@ -1307,9 +1312,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", "outgoingTrustedRefreshRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + "canonicalRuntimeWorkflowSha256", "canonicalMergeOnlyArtifactRuntimeWorkflowSha256", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "outgoingTrustedRefreshRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return ${verifier}(data.run, data.candidate, data.identity);`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, + mergeOnlyArtifactFixtureSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, new Set([...outgoingTrustedRefreshRuntimeWorkflowSha256, preMergeRefreshFixtureSha256, outgoingRefreshFixtureSha256]), @@ -1382,6 +1388,13 @@ function markerAccepted(overrides = {}) { return new Function("includes", `return (${expression});`)((values, value) => values.includes(value)); } (async () => { + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(data => { + Object.assign(data.definitions[workflowPath], { + content: mergeOnlyArtifactBytes.toString("base64"), size: mergeOnlyArtifactBytes.length, + }); + }, event, false), true, "the previous archive format must not invalidate independent Smoke Gate proof"); + } for (const event of ["pull_request", "repository_dispatch"]) { for (const stage of ["jobs", "proof", "malformed-jobs"]) { await failedLegacyProof(stage, Object.assign(new Error("unavailable"), {status: 404}), event); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 3f26eb4241..029d14194c 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2006,7 +2006,7 @@ 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}' +require_contains "$pr_image_publisher_path" 'pr-runtime-images-{image_tag}-attempt-{source_run_attempt}' # shellcheck disable=SC2016 # This assertion intentionally matches the unevaluated publisher script. require_contains "$pr_image_publisher_path" 'docker push "$image"' # shellcheck disable=SC2016 # These assertions intentionally match unevaluated publisher shell. @@ -2039,6 +2039,7 @@ with tempfile.NamedTemporaryFile(mode="r+", encoding="utf-8") as summary_file: test_environment = { "GITHUB_STEP_SUMMARY": summary_file.name, "SOURCE_RUN_ID": "123", + "SOURCE_RUN_ATTEMPT": "2", "SOURCE_RUN_URL": "https://github.example/runs/123", "SOURCE_RUN_TITLE": "build `title`