name: Release

# Cut a release by pushing a v* tag (e.g. `git tag v0.2.1 && git push --tags`).
# Builds a packaged pg_pinecone extension per OS/arch and Postgres major (17, 18),
# smoke-tests each tarball on its Postgres, attaches the tarballs to a draft
# GitHub release, then publishes it (draft so uploads work under immutable
# releases, which lock a release on publish). workflow_dispatch re-runs the build against an existing tag; it refuses to replace
# assets already attached to that release unless `overwrite` is set (a re-run of a tag push's own
# run replaces its earlier upload). postgresapp-sign also attaches
# pg_pinecone-pg18-<version>.pkg; a notarization failure does not block the tarball upload.
# pgxn-release uploads the source zip to PGXN. PGXN will not replace a version, so a
# repeat of the same tag leaves the existing PGXN release in place. A missing
# credential or a PGXN failure does not block the tarball upload.
#
# Dry run: a PR touching this file, the smoke script, packaging/postgresapp, or the
# PGXN packaging also runs the full six-leg build matrix (same jobs, same matrix),
# the unsigned Postgres.app build, and `make pgxn-zip`, but skips
# create-release/upload/publish/postgresapp-sign/pgxn-release
# — it never touches a real release. This exists because v0.5.0 shipped a
# release.yml change (per-arch RUSTFLAGS) that broke both arm64 legs, and the
# matrix only ever builds at tag time, so nothing caught it pre-tag. Now editing
# this file proves every platform x Postgres leg still builds before the edit merges.
#
# Every file asset gets a build-provenance attestation (`gh attestation verify`), the
# source SBOM is attached and attested, and the Docker images are cosign-signed and attested
# (see "Verifying releases" in the README). Attestations are made in jobs that run no PR code.
#
# A tag with a suffix (v0.13.0-rc.1) is a pre-release: it builds, signs, and attaches like a
# release but is marked pre-release, never Latest, never moves pgNN/latest, and skips PGXN.
# Use one to rehearse a release without burning its version. The suffix is ignored when
# matching the crate version.
#
# The build runs PR-controlled code (build scripts, proc-macros, the smoke script), so it gets
# a read-only token that is not persisted in .git/config. Only create-release, upload, publish, and
# postgresapp-sign hold `contents: write`. None of them run on a PR. postgresapp-sign does run
# packaging scripts, but only on a tag or a dispatch. pgxn-release uploads to PGXN on a tag
# or a dispatch; it does not run on a PR, and its password lives on the `pgxn` environment.
on:
  push:
    tags: ['v*']
  pull_request:
    paths: ['.github/workflows/release.yml', 'scripts/release-smoke.sh', 'Dockerfile', '.dockerignore', 'packaging/postgresapp/**', 'Makefile', 'META.json.in', '.gitattributes']
  workflow_dispatch:
    inputs:
      tag:
        description: 'Existing tag to build and attach (e.g. v0.2.1)'
        required: true
      overwrite:
        description: 'Replace assets already attached to the release (default: refuse)'
        type: boolean
        default: false

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  PGRX_VERSION: 0.19.2
  IMAGE: pineconeteam/pg_pinecone
  # No real tag on a dry-run PR — "dry-run" is a safe, slash-free stand-in
  # (it only ever names a build artifact that never reaches a release).
  RELEASE_TAG: ${{ github.event.inputs.tag || (github.event_name == 'pull_request' && 'dry-run' || github.ref_name) }}
  PRERELEASE: ${{ contains(github.event.inputs.tag || github.ref_name, '-') }}

jobs:
  # Guard the tag against Cargo.toml and ensure a release exists to upload
  # into. Skipped entirely on the dry-run PR trigger — there's no tag and
  # nothing should be created.
  create-release:
    if: github.event_name != 'pull_request'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ env.RELEASE_TAG }}
          persist-credentials: false

      - name: Verify tag matches crate version
        run: |
          crate_version=$(grep -m1 '^version' pg_pinecone/Cargo.toml | cut -d'"' -f2)
          if [ "${RELEASE_TAG%%-*}" != "v$crate_version" ]; then
            echo "Tag $RELEASE_TAG does not match pg_pinecone/Cargo.toml version $crate_version" >&2
            exit 1
          fi

      # Attestations name the workflow ref that made them; keep that to main or a tag.
      - name: Dispatch only from main
        if: github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main'
        run: |
          echo "::error::Dispatch this workflow from main, not $GITHUB_REF" >&2
          exit 1

      # A draft, so the upload jobs can attach assets: immutable releases lock a
      # release on publish, which refused the post-publish upload before. The
      # publish job flips it live once every asset is attached.
      - name: Create release if missing
        env:
          GH_TOKEN: ${{ github.token }}
          OVERWRITE: ${{ inputs.overwrite }}
        run: |
          if ! gh release view "$RELEASE_TAG" >/dev/null 2>&1; then
            flags=(--draft)
            [ "$PRERELEASE" = true ] && flags+=(--prerelease)
            gh release create "$RELEASE_TAG" --title "$RELEASE_TAG" --generate-notes "${flags[@]}"
          elif [ "$GITHUB_EVENT_NAME" = workflow_dispatch ] && [ "$OVERWRITE" != true ]; then
            attached=$(gh release view "$RELEASE_TAG" --json assets \
              --jq '[.assets[].name | select(startswith("pg_pinecone-"))] | join(", ")')
            if [ -n "$attached" ]; then
              echo "::error::Release $RELEASE_TAG already has assets attached ($attached). Dispatch again with overwrite: true to replace them."
              exit 1
            fi
          fi

  # Source SBOM (Cargo.lock) for the release. Read-only; `upload` attaches and attests it.
  sbom:
    needs: create-release
    if: always() && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event_name != 'pull_request' && env.RELEASE_TAG || '' }}
          persist-credentials: false
      - name: Name the SBOM
        run: echo "SBOM=pg_pinecone-${RELEASE_TAG#v}.cdx.json" >> "$GITHUB_ENV"
      - uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c # v0.24.3
        with:
          file: Cargo.lock
          format: cyclonedx-json
          output-file: ${{ env.SBOM }}
          upload-artifact: false
          upload-release-assets: false
      - uses: actions/upload-artifact@v7
        with:
          name: pg_pinecone-sbom
          path: ${{ env.SBOM }}
          if-no-files-found: error
          retention-days: 7

  package:
    name: package (pg${{ matrix.pg }}, ${{ matrix.os }}-${{ matrix.arch }})
    needs: create-release
    # create-release is skipped (not failed) on the dry-run PR trigger; the
    # default `needs` gate only admits an upstream `success()`, so it has to
    # be relaxed to also admit `skipped()` or this job would never run there.
    if: always() && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped')
    strategy:
      fail-fast: false
      matrix:
        # platform x pg; each include entry attaches that platform's runner and flags.
        pg: [17, 18]
        platform: [linux-x86_64, linux-arm64, darwin-arm64]
        include:
          # rustflags: the x86_64 artifact must NOT build at Rust's generic
          # x86-64 baseline — that baseline predates POPCNT, and the local
          # engine's Hamming scan measured 2.6x slower there than a
          # target-cpu=native build (recall bit-identical; GCP campaign,
          # objdump-verified zero POPCNT in the generic artifact).
          # x86-64-v3 (Haswell 2013+: POPCNT+AVX2) matches every cloud x86
          # of the last decade; older CPUs need a source build (README's
          # install section documents this floor).
          - platform: linux-x86_64
            runner: ubuntu-latest
            os: linux
            arch: x86_64
            rustflags: '-C target-cpu=x86-64-v3'
          # arm64 stays at the default baseline deliberately: CNT (the
          # POPCNT equivalent) is aarch64-baseline, so there is no
          # equivalent tax — and the explicit empty RUSTFLAGS guards
          # against any environment-inherited downgrade.
          - platform: linux-arm64
            runner: ubuntu-24.04-arm
            os: linux
            arch: arm64
            rustflags: ''
          # macOS needs -Wl,-undefined,dynamic_lookup (Postgres symbols like
          # CopyErrorData only exist inside the backend at runtime) — normally
          # supplied by pg_pinecone/.cargo/config.toml, but the RUSTFLAGS env var
          # below unconditionally shadows that file's target.rustflags
          # (Cargo's env-vs-config precedence is all-or-nothing), so it must
          # be repeated here explicitly or the darwin-arm64 link step fails.
          - platform: darwin-arm64
            runner: macos-26
            os: darwin
            arch: arm64
            rustflags: '-Clink-arg=-Wl,-undefined,dynamic_lookup'
    runs-on: ${{ matrix.runner }}
    steps:
      # On the dry-run PR trigger there's no RELEASE_TAG ref to check out —
      # an empty `ref` falls back to actions/checkout's default (the PR's
      # merge commit), same as omitting the input entirely.
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event_name != 'pull_request' && env.RELEASE_TAG || '' }}
          persist-credentials: false
      - uses: dtolnay/rust-toolchain@stable
      # One cache per Postgres major: pgrx-pg-sys builds differently on each.
      - uses: Swatinem/rust-cache@v2
        with:
          key: pg${{ matrix.pg }}

      - name: Install PostgreSQL ${{ matrix.pg }} (Linux, PGDG)
        if: matrix.os == 'linux'
        run: |
          sudo apt-get update
          sudo apt-get install -y postgresql-common
          sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
          sudo apt-get install -y postgresql-${{ matrix.pg }} postgresql-server-dev-${{ matrix.pg }}
          echo "PG_CONFIG=/usr/lib/postgresql/${{ matrix.pg }}/bin/pg_config" >> "$GITHUB_ENV"

      - name: Install PostgreSQL ${{ matrix.pg }} (macOS)
        if: matrix.os == 'darwin'
        run: |
          brew install postgresql@${{ matrix.pg }}
          echo "PG_CONFIG=$(brew --prefix postgresql@${{ matrix.pg }})/bin/pg_config" >> "$GITHUB_ENV"

      - name: Install cargo-pgrx
        run: cargo install cargo-pgrx --version "$PGRX_VERSION" --locked

      - name: cargo pgrx init
        run: cargo pgrx init --pg${{ matrix.pg }} "$PG_CONFIG"

      - name: Package extension
        working-directory: pg_pinecone
        env:
          # Per-arch target features — see the matrix's rustflags comments.
          RUSTFLAGS: ${{ matrix.rustflags }}
        run: cargo pgrx package --pg-config "$PG_CONFIG"

      - name: Build tarball
        run: |
          version="${RELEASE_TAG#v}"
          pkg=$(find target -type d -name 'pg_pinecone-pg${{ matrix.pg }}' | head -1)
          if [ -z "$pkg" ]; then echo "package dir not found" >&2; exit 1; fi
          asset="pg_pinecone-${version}-pg${{ matrix.pg }}-${{ matrix.os }}-${{ matrix.arch }}.tar.gz"
          tar -C "$pkg" -czf "$asset" .
          shasum -a 256 "$asset" > "$asset.sha256"
          echo "ASSET=$asset" >> "$GITHUB_ENV"

      - name: Release smoke
        run: ./scripts/release-smoke.sh "$PG_CONFIG" "$ASSET"

      # Also on the dry-run PR trigger: exercises the hand-off to `upload`.
      - name: Keep the tarball for the upload job
        uses: actions/upload-artifact@v7
        with:
          name: pg_pinecone-pg${{ matrix.pg }}-${{ matrix.os }}-${{ matrix.arch }}
          path: |
            ${{ env.ASSET }}
            ${{ env.ASSET }}.sha256
          if-no-files-found: error
          retention-days: 7

  # Attaches the tarballs and SBOM to the release once all six legs passed, with their
  # attestations. Holds the write token, runs no repo code (no checkout), never runs on a PR.
  upload:
    if: github.event_name != 'pull_request'
    needs: [package, sbom]
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
      attestations: write
    steps:
      - uses: actions/download-artifact@v8
        with:
          pattern: pg_pinecone-*
          path: dist
          merge-multiple: true

      - name: Attest build provenance
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-path: dist/*

      - name: Name the SBOM
        run: echo "SBOM=dist/pg_pinecone-${RELEASE_TAG#v}.cdx.json" >> "$GITHUB_ENV"

      - name: Attest SBOM
        uses: actions/attest-sbom@c604332985a26aa8cf1bdc465b92731239ec6b9e # v4.1.0
        with:
          subject-path: dist/*.tar.gz
          sbom-path: ${{ env.SBOM }}

      - name: Upload to release
        env:
          GH_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
          OVERWRITE: ${{ inputs.overwrite }}
        run: |
          # A tag push may be re-run over its own earlier upload. A dispatch replaces released
          # tarballs only on request (create-release has already refused otherwise).
          flags=()
          if [ "$GITHUB_EVENT_NAME" = push ] || [ "$OVERWRITE" = true ]; then
            flags+=(--clobber)
          fi
          gh release upload "$RELEASE_TAG" dist/* "${flags[@]}"

  # Flips the draft live once the tarballs are up (and the Postgres.app package,
  # when the sign job produced one). The tarball upload must have succeeded; the
  # signed package and the PGXN upload are best-effort, so a skipped or failed
  # sign or PGXN job still ships.
  publish:
    if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.upload.result == 'success' }}
    needs: [upload, postgresapp-sign, pgxn-release]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Publish the release
        env:
          GH_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
        run: gh release edit "$RELEASE_TAG" --draft=false --latest="${{ github.event_name == 'push' && env.PRERELEASE != 'true' }}"

  # Unsigned Postgres.app build. Runs on a PR dry run too. No signing secrets:
  # the signed package is a separate job so a pull request cannot read them.
  postgresapp:
    name: package (postgres.app pg18 arm64)
    needs: create-release
    if: always() && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped')
    runs-on: macos-26
    outputs:
      present: ${{ steps.present.outputs.present }}
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event_name != 'pull_request' && env.RELEASE_TAG || '' }}
          persist-credentials: false
      # A dispatch for a tag older than this job has no packaging/postgresapp:
      # skip the build, and the sign job with it, instead of failing the run.
      - id: present
        run: |
          if [ -f packaging/postgresapp/build.zsh ]; then
            echo "present=true" >> "$GITHUB_OUTPUT"
          else
            echo "::notice::$RELEASE_TAG has no packaging/postgresapp; skipping the Postgres.app package"
            echo "present=false" >> "$GITHUB_OUTPUT"
          fi
      - uses: dtolnay/rust-toolchain@stable
        if: steps.present.outputs.present == 'true'
      - uses: Swatinem/rust-cache@v2
        if: steps.present.outputs.present == 'true'
        with:
          key: pg18-postgresapp

      # The pg18-only disk image, not the combined 14-through-18 image, which
      # also ends in -18.dmg.
      - name: Install Postgres.app
        if: steps.present.outputs.present == 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          ASSET=$(gh release view --repo PostgresApp/PostgresApp --json assets \
            --jq '[.assets[].name | select(test("^Postgres-[0-9.]+-18\\.dmg$"))][0]')
          if [ -z "$ASSET" ] || [ "$ASSET" = "null" ]; then
            echo "no PostgreSQL 18 Postgres.app disk image on the latest release" >&2
            exit 1
          fi
          echo "Downloading $ASSET"
          gh release download --repo PostgresApp/PostgresApp --pattern "$ASSET" --output postgres.dmg
          MOUNT=$(hdiutil attach -nobrowse -noverify -noautoopen postgres.dmg | tail -1 | awk '{print $3}')
          if [ ! -d "$MOUNT/Postgres.app" ]; then
            echo "Postgres.app not found at $MOUNT" >&2
            exit 1
          fi
          cp -R "$MOUNT/Postgres.app" /Applications/Postgres.app
          hdiutil detach "$MOUNT"
          /Applications/Postgres.app/Contents/Versions/18/bin/pg_config --version

      - name: Install cargo-pgrx
        if: steps.present.outputs.present == 'true'
        run: cargo install cargo-pgrx --version "$PGRX_VERSION" --locked

      - name: Build unsigned install root
        if: steps.present.outputs.present == 'true'
        id: build
        run: |
          set -euo pipefail
          SIGN=0 packaging/postgresapp/build.zsh
          root=$(cat target/postgresapp-install-root.txt)
          echo "root=$root" >> "$GITHUB_OUTPUT"

      - name: Smoke against Postgres.app
        if: steps.present.outputs.present == 'true'
        run: packaging/postgresapp/smoke.sh "${{ steps.build.outputs.root }}"

      # upload-artifact zips files as mode 644. A tar keeps the build's modes
      # for the sign job's pkgbuild.
      - name: Tar install root
        if: steps.present.outputs.present == 'true'
        run: COPYFILE_DISABLE=1 tar -C "${{ steps.build.outputs.root }}" -czf postgresapp-install-root.tar.gz .

      - uses: actions/upload-artifact@v7
        if: steps.present.outputs.present == 'true'
        with:
          name: postgresapp-pg18-arm64
          path: postgresapp-install-root.tar.gz
          if-no-files-found: error
          retention-days: 7

  # Sign and notarize on a Mac. Does not gate `upload`: tarballs still publish
  # if Apple notarization fails. Re-run the failed job to retry; that does not
  # pass through create-release again.
  postgresapp-sign:
    name: sign (postgres.app pg18 arm64)
    needs: [create-release, postgresapp]
    if: github.event_name != 'pull_request' && needs.create-release.result == 'success' && needs.postgresapp.result == 'success' && needs.postgresapp.outputs.present == 'true'
    runs-on: macos-26
    environment: postgresapp-signing
    permissions:
      contents: write
      id-token: write
      attestations: write
    steps:
      # Until the environment holds the Apple secrets, skip with a warning
      # instead of failing every release run.
      - id: secrets
        env:
          APPLE_DEVELOPER_ID_APPLICATION_CERT: ${{ secrets.APPLE_DEVELOPER_ID_APPLICATION_CERT }}
          APPLE_DEVELOPER_ID_INSTALLER_CERT: ${{ secrets.APPLE_DEVELOPER_ID_INSTALLER_CERT }}
          APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
          APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
          APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }}
          APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
        run: |
          missing=()
          for name in APPLE_DEVELOPER_ID_APPLICATION_CERT APPLE_DEVELOPER_ID_INSTALLER_CERT APPLE_CERT_PASSWORD \
                      APPLE_API_KEY_ID APPLE_API_ISSUER_ID APPLE_API_KEY_P8; do
            [ -n "${!name}" ] || missing+=("$name")
          done
          if [ ${#missing[@]} -eq 0 ]; then
            echo "ready=true" >> "$GITHUB_OUTPUT"
          else
            echo "::warning::postgresapp-signing is missing ${missing[*]}; no Postgres.app package for $RELEASE_TAG"
            echo "ready=false" >> "$GITHUB_OUTPUT"
          fi

      - uses: actions/checkout@v7
        if: steps.secrets.outputs.ready == 'true'
        with:
          ref: ${{ env.RELEASE_TAG }}
          persist-credentials: false

      - uses: actions/download-artifact@v8
        if: steps.secrets.outputs.ready == 'true'
        with:
          name: postgresapp-pg18-arm64
          path: postgresapp-artifact

      - name: Untar install root
        if: steps.secrets.outputs.ready == 'true'
        run: |
          set -euo pipefail
          mkdir -p install-root
          COPYFILE_DISABLE=1 tar -xzf postgresapp-artifact/postgresapp-install-root.tar.gz -C install-root

      # Secrets live on the postgresapp-signing environment (v* tags and the
      # default branch). Certs and the API key are base64. A pull-request ref
      # matches neither rule, so PR code cannot read them.
      - name: Import Apple Developer ID certificates
        if: steps.secrets.outputs.ready == 'true'
        env:
          APPLE_DEVELOPER_ID_APPLICATION_CERT: ${{ secrets.APPLE_DEVELOPER_ID_APPLICATION_CERT }}
          APPLE_DEVELOPER_ID_INSTALLER_CERT: ${{ secrets.APPLE_DEVELOPER_ID_INSTALLER_CERT }}
          APPLE_CERT_PASSWORD: ${{ secrets.APPLE_CERT_PASSWORD }}
        run: |
          set -euo pipefail
          KEYCHAIN_PATH="$RUNNER_TEMP/app-signing.keychain-db"
          KEYCHAIN_PASSWORD="$(openssl rand -base64 24)"
          security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
          security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
          echo "$APPLE_DEVELOPER_ID_APPLICATION_CERT" | base64 --decode > "$RUNNER_TEMP/application.p12"
          echo "$APPLE_DEVELOPER_ID_INSTALLER_CERT" | base64 --decode > "$RUNNER_TEMP/installer.p12"
          security import "$RUNNER_TEMP/application.p12" -P "$APPLE_CERT_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
          security import "$RUNNER_TEMP/installer.p12" -P "$APPLE_CERT_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
          rm -f "$RUNNER_TEMP/application.p12" "$RUNNER_TEMP/installer.p12"
          security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
          security list-keychain -d user -s "$KEYCHAIN_PATH"

      - name: Sign, package, and notarize
        if: steps.secrets.outputs.ready == 'true'
        env:
          SIGN: "1"
          INSTALL_ROOT: ${{ github.workspace }}/install-root
          APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
          APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }}
          APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
        run: packaging/postgresapp/build.zsh

      - name: Locate the package
        if: steps.secrets.outputs.ready == 'true'
        id: pkg
        run: |
          set -euo pipefail
          version=$(grep -m1 '^version' pg_pinecone/Cargo.toml | cut -d'"' -f2)
          pkg="target/pg_pinecone-pg18-${version}.pkg"
          test -f "$pkg"
          echo "path=$pkg" >> "$GITHUB_OUTPUT"

      - name: Attest build provenance
        if: steps.secrets.outputs.ready == 'true'
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-path: ${{ steps.pkg.outputs.path }}

      - name: Upload package to the release
        if: steps.secrets.outputs.ready == 'true'
        env:
          GH_TOKEN: ${{ github.token }}
          OVERWRITE: ${{ inputs.overwrite }}
          PKG: ${{ steps.pkg.outputs.path }}
        run: |
          set -euo pipefail
          pkg="$PKG"
          flags=()
          if [ "$GITHUB_EVENT_NAME" = push ] || [ "$OVERWRITE" = true ]; then
            flags+=(--clobber)
          fi
          # bash 3.2 on macOS: an empty array is unbound under set -u.
          gh release upload "$RELEASE_TAG" "$pkg" ${flags[@]+"${flags[@]}"}

  # Source zip PGXN indexes. Runs on a PR dry run too: `make pgxn-zip` does not
  # compile, and it does not upload. A tag older than this packaging skips it.
  pgxn-pack:
    name: package (pgxn)
    needs: create-release
    if: always() && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped')
    runs-on: ubuntu-latest
    outputs:
      present: ${{ steps.present.outputs.present }}
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event_name != 'pull_request' && env.RELEASE_TAG || '' }}
          persist-credentials: false
      - id: present
        run: |
          if [ -f Makefile ] && [ -f META.json.in ] && [ -f .gitattributes ]; then
            echo "present=true" >> "$GITHUB_OUTPUT"
          else
            echo "::notice::$RELEASE_TAG has no PGXN packaging; skipping the PGXN zip"
            echo "present=false" >> "$GITHUB_OUTPUT"
          fi
      - name: Pack the PGXN zip
        if: steps.present.outputs.present == 'true'
        run: |
          set -euo pipefail
          version=$(grep -m1 '^version' pg_pinecone/Cargo.toml | cut -d'"' -f2)
          make pgxn-zip
          zipfile="pg_pinecone-${version}.zip"
          test -f "$zipfile"
          list=$(unzip -Z1 "$zipfile")
          printf '%s\n' "$list" | grep -qx "pg_pinecone-${version}/Makefile"
          printf '%s\n' "$list" | grep -qx "pg_pinecone-${version}/META.json"
          printf '%s\n' "$list" | grep -qx "pg_pinecone-${version}/pg_pinecone/src/lib.rs"
          if printf '%s\n' "$list" | grep -q 'META.json.in$'; then
            echo "META.json.in must stay out of the PGXN zip" >&2
            exit 1
          fi
      - uses: actions/upload-artifact@v7
        if: steps.present.outputs.present == 'true'
        with:
          name: pgxn-zip
          path: pg_pinecone-*.zip
          if-no-files-found: error
          retention-days: 7

  # Uploads the zip to PGXN. Does not gate `publish`: the GitHub tarballs still
  # ship if this is skipped or fails. Re-run the failed job to retry; that does
  # not pass through create-release again. PGXN refuses a repeated version, so
  # a second run of the same tag succeeds and leaves the existing release.
  pgxn-release:
    name: release (pgxn)
    needs: [create-release, pgxn-pack]
    if: github.event_name != 'pull_request' && !contains(github.event.inputs.tag || github.ref_name, '-') && needs.create-release.result == 'success' && needs.pgxn-pack.result == 'success' && needs.pgxn-pack.outputs.present == 'true'
    runs-on: ubuntu-latest
    environment: pgxn
    permissions:
      contents: read
      id-token: write
      attestations: write
    steps:
      # Until the environment holds the PGXN login, skip with a warning
      # instead of failing every release run.
      - id: secrets
        env:
          PGXN_USERNAME: ${{ secrets.PGXN_USERNAME }}
          PGXN_PASSWORD: ${{ secrets.PGXN_PASSWORD }}
        run: |
          missing=()
          for name in PGXN_USERNAME PGXN_PASSWORD; do
            [ -n "${!name}" ] || missing+=("$name")
          done
          if [ ${#missing[@]} -eq 0 ]; then
            echo "ready=true" >> "$GITHUB_OUTPUT"
          else
            echo "::warning::pgxn environment is missing ${missing[*]}; no PGXN release for $RELEASE_TAG"
            echo "ready=false" >> "$GITHUB_OUTPUT"
          fi

      - uses: actions/download-artifact@v8
        with:
          name: pgxn-zip
          path: dist

      # The zip is only ever published on PGXN; attest it here, before the upload.
      - name: Attest build provenance
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-path: dist/pg_pinecone-*.zip

      - name: Upload to PGXN
        if: steps.secrets.outputs.ready == 'true'
        env:
          PGXN_USERNAME: ${{ secrets.PGXN_USERNAME }}
          PGXN_PASSWORD: ${{ secrets.PGXN_PASSWORD }}
        run: |
          set -euo pipefail
          zipfile=$(find dist -type f -name 'pg_pinecone-*.zip')
          test -f "$zipfile"
          body=$(mktemp)
          status=$(curl --silent --show-error \
            --user "${PGXN_USERNAME}:${PGXN_PASSWORD}" \
            -F 'submit=Release It!' \
            -F "archive=@${zipfile}" \
            -H 'X-Requested-With: XMLHttpRequest' \
            --output "$body" --write-out '%{http_code}' \
            https://manager.pgxn.org/upload)
          echo "PGXN upload HTTP ${status}"
          cat "$body"
          # A form POST succeeds with 303 See Other. The XHR header usually
          # yields 200 instead. 409 is the documented conflict for a version
          # that is already published.
          case "$status" in
            2??|303)
              echo "PGXN upload succeeded (HTTP ${status})"
              exit 0
              ;;
            409)
              echo "::warning::PGXN already has this version; leaving the existing release in place"
              exit 0
              ;;
            *)
              if grep -q 'not greater than previous' "$body"; then
                echo "::warning::PGXN already has this version; leaving the existing release in place"
                exit 0
              fi
              echo "::error::PGXN release failed (HTTP ${status})"
              exit 1
              ;;
          esac

  # Build the Docker image from source (no push) so a PR editing the Dockerfile
  # or this workflow proves it still builds before merge. One representative leg.
  docker-dry-run:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          build-args: PG_MAJOR=17
          platforms: linux/amd64
          push: false

  # One image per Postgres major x arch, built on a native runner and pushed by
  # digest; docker-manifest then assembles the version tags from the digests.
  docker:
    if: github.event_name != 'pull_request'
    # Gate on the version check and every build leg: never push to Hub when the
    # GitHub release is blocked or a package leg failed.
    needs: [create-release, package]
    strategy:
      fail-fast: false
      matrix:
        pg: [17, 18]
        arch: [amd64, arm64]
        include:
          - arch: amd64
            runner: ubuntu-latest
          - arch: arm64
            runner: ubuntu-24.04-arm
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      id-token: write
      attestations: write
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ env.RELEASE_TAG }}
          persist-credentials: false
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - id: build
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          build-args: PG_MAJOR=${{ matrix.pg }}
          platforms: linux/${{ matrix.arch }}
          provenance: false
          outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
      - name: Attest image provenance
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-name: index.docker.io/${{ env.IMAGE }}
          subject-digest: ${{ steps.build.outputs.digest }}
          push-to-registry: true
          create-storage-record: false
      - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
      - name: Sign image
        env:
          DIGEST: ${{ steps.build.outputs.digest }}
        run: cosign sign --yes "${IMAGE}@${DIGEST}"
      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          touch "/tmp/digests/${DIGEST#sha256:}"
        env:
          DIGEST: ${{ steps.build.outputs.digest }}
      - uses: actions/upload-artifact@v7
        with:
          name: digests-pg${{ matrix.pg }}-${{ matrix.arch }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  # Assemble the multi-arch tags for each Postgres major from the pushed digests.
  docker-manifest:
    if: github.event_name != 'pull_request'
    needs: docker
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
      attestations: write
    strategy:
      fail-fast: false
      matrix:
        pg: [17, 18]
    steps:
      - uses: actions/download-artifact@v8
        with:
          pattern: digests-pg${{ matrix.pg }}-*
          path: /tmp/digests
          merge-multiple: true
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Create and push manifest tags
        working-directory: /tmp/digests
        run: |
          version="${RELEASE_TAG#v}"
          tags=(-t "${IMAGE}:${version}-pg${{ matrix.pg }}")
          # Move pgNN/latest only on a release tag push — a dispatch rebuild of an older
          # tag or a pre-release must not retarget them.
          if [ "$GITHUB_EVENT_NAME" = push ] && [ "$PRERELEASE" != true ]; then
            tags+=(-t "${IMAGE}:pg${{ matrix.pg }}")
            [ "${{ matrix.pg }}" = 18 ] && tags+=(-t "${IMAGE}:latest")
          fi
          digests=()
          for d in *; do
            digests+=("${IMAGE}@sha256:$d")
          done
          docker buildx imagetools create "${tags[@]}" "${digests[@]}"
          docker buildx imagetools inspect "${IMAGE}:${version}-pg${{ matrix.pg }}"

      # Sign and attest the multi-arch index, the digest users pull.
      - id: digest
        run: |
          version="${RELEASE_TAG#v}"
          digest=$(docker buildx imagetools inspect "${IMAGE}:${version}-pg${{ matrix.pg }}" --format '{{json .Manifest}}' | jq -r .digest)
          echo "digest=$digest" >> "$GITHUB_OUTPUT"
      - name: Attest image provenance
        uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
        with:
          subject-name: index.docker.io/${{ env.IMAGE }}
          subject-digest: ${{ steps.digest.outputs.digest }}
          push-to-registry: true
          create-storage-record: false
      - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
      - name: Sign image
        env:
          DIGEST: ${{ steps.digest.outputs.digest }}
        run: cosign sign --yes "${IMAGE}@${DIGEST}"
