name: CLI 0.15.0 release validation

on:
  push:
    branches: [codex/cli-0150-strict-retries]

permissions:
  contents: read

env:
  CONTROL_SHA: b0c894fe71f927827b0a30ea9f366e3ad04f24d3
  CANDIDATE_SHA: 996b8c10b0627d6f9c9e6a03e1800900bec079c4
  UV_EXCLUDE_NEWER: "14 days"

jobs:
  verify:
    runs-on: ubuntu-24.04
    timeout-minutes: 50
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          ref: ${{ env.CANDIDATE_SHA }}
          fetch-depth: 0
          persist-credentials: false
      # setup-uv fetches a manifest once, with a fixed 5 s limit, even for a pinned version,
      # and a slow answer failed the job; it fetches nothing when the pinned uv is already in
      # the tool cache, where this step puts it with retries (devtools/install_uv.sh).
      - name: Install uv
        run: bash devtools/install_uv.sh 0.11.26 6426a73c3837e6e2483ee344cbc00f36394d179afcba6183cb77437e67db4af0

      - name: Set up uv
        uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
        with:
          version: "0.11.26"
          checksum: "6426a73c3837e6e2483ee344cbc00f36394d179afcba6183cb77437e67db4af0"
          enable-cache: false
          python-version: "3.13"

      # setup-node downloads a Node the runner image lacks and copies it into the tool cache
      # file by file, and each has stalled for over a minute; it does neither when the
      # pinned Node is already in the tool cache, where this step unpacks a checksum-pinned
      # download fetched with retries (devtools/install_node.sh).
      - name: Install Node
        run: bash devtools/install_node.sh 24.18.0

      - name: Set up Node
        uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: "24.18.0"

      - name: Set up Python
        run: uv python install

      - name: Run the complete release gate
        run: make verify

  release-comparison:
    runs-on: ubuntu-24.04
    timeout-minutes: 90
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          fetch-depth: 0
          persist-credentials: false
      - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
        with:
          version: "0.11.26"
          checksum: "6426a73c3837e6e2483ee344cbc00f36394d179afcba6183cb77437e67db4af0"
          python-version: "3.13"
          enable-cache: false
      - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version: "24.18.0"
      - name: Build exact wheels and public corpus
        id: build_exact_wheels
        shell: bash
        run: |
          set -euo pipefail
          test "$(git rev-parse 'v0.14.0^{commit}')" = "$CONTROL_SHA"
          test -z "$(git status --porcelain)"
          command -v xvfb-run
          command -v google-chrome
          support="$RUNNER_TEMP/mb-release-comparison"
          mkdir -p "$support"/{tmp,uv,cargo,evidence}
          export TMPDIR="$support/tmp" UV_CACHE_DIR="$support/uv" CARGO_TARGET_DIR="$support/cargo"
          git worktree add --detach "$support/control" "$CONTROL_SHA"
          git worktree add --detach "$support/candidate" "$CANDIDATE_SHA"
          df -h "$support"
          for side in control candidate; do
            (
              cd "$support/$side"
              uv --config-file uv.toml sync --locked --all-extras --all-groups
              uv --config-file uv.toml build --clear --no-build-isolation --wheel \
                --out-dir "$support/$side-wheel"
              wheel=("$support/$side-wheel"/metabrowser-*.whl)
              test "${#wheel[@]}" -eq 1
              UV_PROJECT_ENVIRONMENT="$support/$side-env" \
                uv --config-file uv.toml sync --locked --no-dev --no-install-project
              uv --config-file uv.toml pip install --no-deps --compile-bytecode \
                --python "$support/$side-env/bin/python" "${wheel[0]}"
              uv --config-file uv.toml pip check --python "$support/$side-env/bin/python"
              expected="$(basename "${wheel[0]}" | cut -d- -f2)"
              test "$("$support/$side-env/bin/metab" --version)" = "metab $expected"
              printf '%s\n' "${wheel[0]}" > "$support/$side.wheel-path"
              sha256sum "${wheel[0]}" | awk '{print $1}' > "$support/evidence/$side.sha256"
              uv --config-file uv.toml pip list --format json \
                --python "$support/$side-env/bin/python" > "$support/evidence/$side-dependencies.json"
            )
          done
          cd "$support/candidate"
          uv --config-file uv.toml export --frozen --no-dev --no-emit-project \
            --output-file "$support/browser-constraints.txt"
          uv --config-file uv.toml venv "$support/browser-env"
          control_wheel="$(cat "$support/control.wheel-path")"
          uv --config-file uv.toml pip install --compile-bytecode \
            --python "$support/browser-env/bin/python" \
            --constraints "$support/browser-constraints.txt" "$control_wheel"
          uv --config-file uv.toml pip check --python "$support/browser-env/bin/python"
          npm ci
          uv --config-file uv.toml run --frozen python -c \
            'import sys; from pathlib import Path; from devtools.bench_serving import build_project_corpus; print(build_project_corpus(Path(sys.argv[1]), 10))' \
            "$support/project-10"
          test -z "$(git status --porcelain)"
          cp "$support/project-10/.bench-corpus.json" "$support/evidence/corpus.json"
      - name: Capture cold paired startup runs
        shell: bash
        run: |
          set -euo pipefail
          support="$RUNNER_TEMP/mb-release-comparison"
          results="$support/evidence"
          export TMPDIR="$support/tmp" UV_CACHE_DIR="$support/uv" CARGO_TARGET_DIR="$support/cargo"
          export XDG_CACHE_HOME="$support/cache" XDG_CONFIG_HOME="$support/config"
          cd "$support/candidate"
          python_run=(uv --config-file uv.toml run --frozen python)
          bench=("${python_run[@]}" explorations/performance-loop/run.py)
          control_label=exp-137-cli-0150-${CANDIDATE_SHA:0:12}-v0140
          candidate_label=exp-137-cli-0150-${CANDIDATE_SHA:0:12}-candidate
          ledger=explorations/performance-loop/results/runs.jsonl
          pending=explorations/performance-loop/results/pending.json
          capture_driver="$PWD/explorations/performance-loop/capture-browser.js"
          capture_probe="$support/diagnostic-probe.js"
          uv --config-file uv.toml run --frozen python - "$PWD/explorations/performance-loop/probe.js" "$capture_probe" <<'PYTHON'
          from pathlib import Path
          import sys

          original, target = map(Path, sys.argv[1:])
          text = original.read_text()
          anchor = "    ttfb_ms: Math.round(nav.responseStart || 0),"
          if text.count(anchor) != 1:
              raise SystemExit("Cannot find the one navigation timing field")
          additions = """
              diagnostic_navigation: {
                request_start_ms: nav.requestStart,
                response_start_ms: nav.responseStart,
                fetch_start_ms: nav.fetchStart,
                connect_start_ms: nav.connectStart,
                connect_end_ms: nav.connectEnd,
                server_timing: (nav.serverTiming || []).map((item) => ({
                  name: item.name, duration_ms: item.duration, description: item.description,
                })),
              },
          """
          target.write_text(text.replace(anchor, anchor + additions))
          PYTHON
          control_wheel="$(cat "$support/control.wheel-path")"
          candidate_wheel="$(cat "$support/candidate.wheel-path")"
          {
            uname -srmo
            lscpu | grep -E '^(CPU\(s\)|Model name|Architecture):'
            node --version
            uv --version
            google-chrome --version
            printf 'ImageOS=%s ImageVersion=%s\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}"
            printf 'control=%s\ncandidate=%s\n' "$CONTROL_SHA" "$CANDIDATE_SHA"
            printf 'diagnostic_driver_commit=%s\n' "$(git -C "$GITHUB_WORKSPACE" rev-parse HEAD)"
          } > "$results/host.txt"
          wait_for_idle() {
            for _ in {1..24}; do
              if awk '$1 < 1.1 {pass=1} END {exit !pass}' /proc/loadavg; then
                cat /proc/loadavg >> "$results/load-before-runs.txt"
                return 0
              fi
              sleep 5
            done
            printf 'Unable to reach 1-minute load below 1.1.\n' >&2
            return 1
          }
          "${bench[@]}" count "$support/project-10" > "$results/count.txt"
          count="$(awk '/^files / {gsub(/,/, "", $2); print $2}' "$results/count.txt")"
          [[ "$count" =~ ^[1-9][0-9]*$ ]]
          wait_for_idle
          backend_status=0
          "${python_run[@]}" -m devtools.compare_builds "$support/project-10" \
            --baseline "$support/control-env/bin/metab" --candidate "$support/candidate-env/bin/metab" \
            --runs 5 --corpus-name project-10 --output "$results/backend.json" \
            > "$results/backend.log" 2>&1 || backend_status=$?

          launch() {
            local side="$1" wheel ref label expected
            if [[ "$side" = control ]]; then
              wheel="$control_wheel"
              ref="$CONTROL_SHA"
              label="$control_label"
            else
              wheel="$candidate_wheel"
              ref="$CANDIDATE_SHA"
              label="$candidate_label"
            fi
            uv --config-file uv.toml pip install --no-deps --compile-bytecode \
              --reinstall-package metabrowser --python "$support/browser-env/bin/python" "$wheel"
            uv --config-file uv.toml pip check --python "$support/browser-env/bin/python"
            expected="$(basename "$wheel" | cut -d- -f2)"
            test "$("$support/browser-env/bin/metab" --version)" = "metab $expected"
            "${bench[@]}" serve --metab "$support/browser-env/bin/metab" \
              --artifact "$wheel" --build-ref "$ref" \
              --tree "$support/project-10" --files "$count" --exp exp-137 --label "$label"
          }

          wait_for_http() {
            local output="$1" socket_epoch="$2" origin probe timing first_request
            local response_epoch spawned_epoch
            origin="$(jq -er '.measurement_origin' "$pending")"
            spawned_epoch="$(jq -er '.server_spawned_epoch_ms' "$pending")"
            first_request="$(date +%s%3N)"
            for probe in {1..15}; do
              if timing="$(curl --silent --show-error --fail --output /dev/null \
                --max-time 2 --write-out '%{http_code} %{time_starttransfer} %{time_total}' \
                "$origin/api/routes" 2>"$output.stderr")" && [[ "$timing" == "200 "* ]]; then
                response_epoch="$(date +%s%3N)"
                jq -nc --argjson spawn "$spawned_epoch" --argjson socket "$socket_epoch" \
                  --argjson first_request "$first_request" --argjson response "$response_epoch" \
                  --argjson attempt "$probe" --arg timing "$timing" \
                  '{server_spawned_epoch_ms:$spawn,socket_ready_observed_epoch_ms:$socket,
                    first_http_probe_epoch_ms:$first_request,http_ready_epoch_ms:$response,
                    probe_attempt:$attempt,http_curl_status_ttfb_total:$timing}' > "$output"
                return 0
              fi
              sleep 0.05
            done
            cat "$output.stderr" >&2
            printf 'No HTTP 200 response from /api/routes after TCP readiness.\n' >&2
            return 1
          }

          wait_for_idle
          launch control > "$results/serve-warmup.log" 2>&1
          "${bench[@]}" fingerprint >> "$results/serve-warmup.log" 2>&1
          candidate_hard_failure=0
          rejected_captures=0
          complete_pairs=0
          capture_manifest="$results/capture-manifest.tsv"
          printf "pair\tside\tstatus\texit_status\n" > "$capture_manifest"
          isolated_outlying_pairs() {
            "${python_run[@]}" - "$results" "$control_label" "$candidate_label" <<'PYTHON'
          import csv
          import json
          import sys
          from collections import defaultdict
          from pathlib import Path

          directory = Path(sys.argv[1])
          labels = dict(zip(("control", "candidate"), sys.argv[2:], strict=True))
          admitted = {}
          for line in (directory / "browser-ledger.jsonl").read_text().splitlines():
              row = json.loads(line)
              nonce = row.get("measurement_run_id")
              if not isinstance(nonce, str) or not nonce or nonce in admitted:
                  raise SystemExit("Admitted ledger has a missing or duplicate measurement ID")
              admitted[nonce] = row
          sides = defaultdict(set)
          with (directory / "capture-manifest.tsv").open() as manifest:
              for row in csv.DictReader(manifest, delimiter="\t"):
                  if row["status"] == "recorded":
                      sides[int(row["pair"])].add(row["side"])
          keys = (
              "ttfb_ms", "fcp_ms", "first_row_ms", "interaction_p95_ms", "walk_elapsed_ms",
          )
          outliers = {key: [] for key in keys}
          original_pairs = []
          for pair, recorded in sorted(sides.items()):
              if recorded != {"control", "candidate"}:
                  continue
              original_pairs.append(pair)
              measured = {}
              for side in ("control", "candidate"):
                  raw = json.loads((directory / f"browser-{side}-{pair}.json").read_text())
                  nonce = raw.get("measurement_run_id")
                  if not isinstance(nonce, str) or nonce not in admitted:
                      raise SystemExit(f"Pair {pair} {side} has no admitted measurement ID")
                  row = admitted[nonce]
                  if row.get("label") != labels[side]:
                      raise SystemExit(f"Pair {pair} {side} has the wrong admitted label")
                  measured[side] = row
              for key in keys:
                  left, right = (measured[side].get(key) for side in ("control", "candidate"))
                  if isinstance(left, (int, float)) and isinstance(right, (int, float)):
                      if left > 0 and right * 10 > left * 13:
                          outliers[key].append(pair)
          # A repeated original crossing already calls for investigation. Otherwise
          # retry each original pair once, even when different metrics name different pairs.
          repeated = any(len(pairs) > 1 for pairs in outliers.values())
          sources = [] if repeated else sorted({pair for pairs in outliers.values() for pair in pairs})
          (directory / "retry-plan.json").write_text(json.dumps({
              "original_pairs": original_pairs,
              "tolerance": 1.3,
              "outlying_pairs_by_metric": outliers,
              "retry_sources": sources,
              "skip_reason": "repeated_original_crossing" if repeated else None,
          }, indent=2) + "\n")
          for pair in sources:
              print(pair)
          PYTHON
          }

          # Keep five original pairs, with at most three refused-pair replacements.
          # Each isolated original crossing gets one same-order admitted retry, with
          # at most two refused-pair replacements. Every original and attempt stays.
          original_pairs=5
          target_pairs=$original_pairs
          retry_source=0
          retry_sources=()
          retry_index=0
          phase=original
          phase_attempts=0
          pair=0
          retry_mapping="$results/retry-pairs.tsv"
          printf 'original_pair\tretry_pair\tstatus\n' > "$retry_mapping"
          while :; do
            if [[ "$phase" = original ]] && (( complete_pairs == original_pairs )); then
              if (( candidate_hard_failure != 0 )); then break; fi
              retry_plan="$(isolated_outlying_pairs)"
              if [[ -z "$retry_plan" ]]; then break; fi
              mapfile -t retry_sources <<< "$retry_plan"
              # Keep the legacy scalar status field; the artifact maps every source.
              retry_source="${retry_sources[0]}"
              target_pairs=$((original_pairs + ${#retry_sources[@]}))
              phase=retry
              phase_attempts=0
            fi
            current_retry_source=0
            if [[ "$phase" = original ]]; then
              if (( phase_attempts >= 8 )); then break; fi
            else
              if (( retry_index == ${#retry_sources[@]} || candidate_hard_failure != 0 )); then break; fi
              if (( phase_attempts >= 3 )); then
                retry_index=$((retry_index + 1))
                phase_attempts=0
                continue
              fi
              current_retry_source="${retry_sources[$retry_index]}"
            fi
            pair=$((pair + 1))
            phase_attempts=$((phase_attempts + 1))
            admitted_in_pair=0
            sides=(control candidate)
            order_pair=$pair
            if (( current_retry_source > 0 )); then order_pair=$current_retry_source; fi
            if (( order_pair % 2 == 0 )); then sides=(candidate control); fi
            for side in "${sides[@]}"; do
              wait_for_idle
              printf 'Starting pair %s: %s\n' "$pair" "$side"
              capture_stem="$results/browser-$side-$pair"
              launch "$side" > "$capture_stem.serve.log" 2>&1
              socket_epoch="$(date +%s%3N)"
              wait_for_http "$capture_stem.readiness.json" "$socket_epoch"
              capture_status=0
              profile_url="$(jq -er '.url' "$pending")"
              xvfb-run -a -s '-screen 0 1920x1200x24' node "$capture_driver" \
                --headed --chrome "$(command -v google-chrome)" --width 1600 --height 1040 \
                --probe "$capture_probe" --url "$profile_url" \
                --output "$capture_stem.json" > "$capture_stem.log" 2>&1 || capture_status=$?
              if (( capture_status == 0 )); then
                jq 'del(.diagnostic_navigation)' "$capture_stem.json" > "$support/record.json"
                "${bench[@]}" record --json-file "$support/record.json" >> "$capture_stem.log" 2>&1 || capture_status=$?
              fi
              if ! grep -q '^recorded ' "$capture_stem.log"; then
                printf 'Unrecorded pair %s %s (exit %s)\n' "$pair" "$side" "$capture_status" \
                  | tee -a "$results/rejected-captures.txt"
                cat "$capture_stem.log"
                rejected_captures=$((rejected_captures + 1))
                printf "%s\t%s\trefused\t%s\n" "$pair" "$side" "$capture_status" >> "$capture_manifest"
                # Preserve fingerprint continuity even when an attempted capture was refused.
                "${bench[@]}" fingerprint --timeout 120 > "$capture_stem.fingerprint.log" 2>&1
                continue
              fi
              admitted_in_pair=$((admitted_in_pair + 1))
              printf "%s\t%s\trecorded\t%s\n" "$pair" "$side" "$capture_status" >> "$capture_manifest"
              if [[ "$side" = candidate && "$capture_status" != 0 ]]; then candidate_hard_failure=1; fi
              jq -c --arg a "$control_label" --arg b "$candidate_label" \
                'select(.label==$a or .label==$b)' "$ledger" > "$results/browser-ledger.jsonl"
            done
            if (( current_retry_source > 0 )); then
              retry_status=refused
              if (( admitted_in_pair == 2 )); then retry_status=recorded; fi
              printf '%s\t%s\t%s\n' "$current_retry_source" "$pair" "$retry_status" >> "$retry_mapping"
            fi
            if (( admitted_in_pair == 2 )); then
              complete_pairs=$((complete_pairs + 1))
              if [[ "$phase" = retry ]]; then
                retry_index=$((retry_index + 1))
                phase_attempts=0
              fi
            fi
          done
          printf 'Complete pairs: %s; rejected captures: %s\n' "$complete_pairs" "$rejected_captures"
          # Both measured wheels use one browser environment and one fixed dependency set.
          compare_status=0
          "${bench[@]}" compare "$control_label" "$candidate_label" \
            --expect-build "$control_label=wheel:sha256:$(cat "$results/control.sha256")" \
            --expect-build "$candidate_label=wheel:sha256:$(cat "$results/candidate.sha256")" \
            > "$results/comparison.log" 2>&1 || compare_status=$?
          cat "$results/comparison.log"
          printf 'backend_status=%s\ncandidate_hard_failure=%s\ncompare_status=%s\ncomplete_pairs=%s\nrejected_captures=%s\nretry_source_pair=%s\n' \
            "$backend_status" "$candidate_hard_failure" "$compare_status" "$complete_pairs" "$rejected_captures" "$retry_source" \
            > "$results/status.txt"
          recorded_captures="$(awk -F '\t' '$3 == "recorded" { total += 1 } END { print total + 0 }' "$capture_manifest")"
          test "$complete_pairs" = "$target_pairs"
          test "$(jq -s length "$results/browser-ledger.jsonl")" = "$recorded_captures"
          test "$backend_status" = 0
          test "$candidate_hard_failure" = 0
          test "$compare_status" = 0
      - name: Upload diagnostic evidence
        if: always()
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: cli-0150-exp-137-${{ env.CANDIDATE_SHA }}
          path: ${{ runner.temp }}/mb-release-comparison/evidence
          if-no-files-found: warn
          retention-days: 7
