Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

287 KB
Raw Blame
# Only Depot CI reads this file under .depot/. Branch protection requires the gate job's
# `Django Tests Pass on Depot` check and the `Test results` check it posts. Keep the workflow
# and gate job names in sync with the ruleset or pull requests cannot merge.
#
# Depot CI behavior this file works around:
# - Depot's own checks carry no output, so the gate posts a `Test results` check with the
#   failure summary.
# - Depot resolves ./.github/actions/<x> from .depot/actions/<x>. Every local action needs a
#   mirror there or setup fails with "action manifest not found". Mirrors explain intentional
#   differences in their headers; .github/workflows/ci-depot-action-mirrors.yml checks the rest.
# - With no inputs, actions/checkout uses Depot's fast clone, which has no remote.
#   turbo-discover must add `origin` before fetching history.
# - Every job has read-only permissions. CI report sections use a posthog-tests token scoped
#   to pull-requests:write; see .depot/actions/commit-snapshots. check-migrations creates that
#   token before the SQL and risk steps and skips report writes if token creation fails.
#   It creates a separate checks:write token for the Migration risk check after those steps.
# - The hourly schedule skips path filtering and per-commit checks. It controls the events_json
#   cadence in build_django_matrix, events schema recording and upload, and POSTHOG_PYTEST_HARD_EXIT.
#   Master pushes run per-commit checks and dump the schema. Test matrices run on pull requests,
#   manual runs, and the hourly schedule.
# - Master schema dumps go to Depot artifacts and Depot Cache, which GitHub-hosted
#   runners and fork PRs cannot read. .github/workflows/ci-backend-schema-mirror.yml copies the
#   newest dump into a GitHub artifact and GitHub Actions cache every ten minutes.
# - Depot's concurrency policy can keep an older event. Each event therefore gets its own
#   group, and `cancel-superseded-runs` cancels older runs. See "Superseded runs" in
#   .agents/skills/depot-ci/references/posthog-check-run-semantics.md.
# - github.token can only cancel GitHub Actions runs. To stop after a deterministic failure,
#   use `depot ci cancel` with DEPOT_CI_CANCEL_TOKEN.
# - The Actions API cannot look up a Depot run ID. calculate-running-time therefore uses
#   .github/scripts/capture_depot_running_time.py to read `depot ci workflow show` with
#   DEPOT_CI_CANCEL_TOKEN. It sends the same events and property keys as
#   PostHog/posthog-github-action, with runner `depot-ci`. Attempt guards belong on steps
#   because Depot evaluates `github.run_attempt` as empty in a job-level `if`.
# - The test-new-events-schema label doubles the matrices. A manual run uses only the
#   events_json rows so trial runs cover the same schema as PR runs.
# - Per-segment split plans, .test_durations.core and .test_durations.temporal, remain absent
#   from Depot Cache until .github/workflows/ci-backend-update-test-timing.yml saves them.
#   Without those plans, shards use the combined .test_durations file.
# - actions/cache uses Depot Cache, which Depot CI and Depot GitHub Actions runners share.
#   GitHub-hosted runners use a separate GitHub Actions cache.
# - A stalled actions/cache request holds a restore for about 15 minutes and then misses. The
#   client tries each request 5 times with a 3-minute socket timeout, and no input or env var
#   shortens either. SEGMENT_DOWNLOAD_TIMEOUT_MINS covers only the blob download. Restores here
#   and in the Depot composite mirrors set timeout-minutes and continue-on-error, so a stall
#   becomes an early miss. Schema restores get 4 minutes, so one retry runs before a
#   from-scratch migrate. Saves stay unbounded, because a timeout drops what they write. The uv
#   cache inside astral-sh/setup-uv stays unbounded, because a timeout there kills the install.
# - The env block clears GITHUB_TOKEN and OTEL_SERVICE_NAME because Depot provides them by default.
# - Token steps read vars.* and secrets.* from Depot's store. If a value is missing there,
#   setup-action steps with continue-on-error fall back to the default GITHUB_TOKEN, a Depot
#   Code Access installation token shared across repositories. The paths-filter token step fails.
# - Migration reports post from check-migrations. Do not move them to a pull_request_target
#   workflow: Depot posts that workflow's job checks on another pull request's head commit when
#   both events share a base commit. See "pull_request_target checks" in
#   .agents/skills/depot-ci/references/posthog-check-run-semantics.md.
# - Depot keeps ::error and ::warning annotations in the job log. GitHub receives the Repo
#   checks verdict but no file annotations from `hogli lint:migration-deletions`.
# - `depot ci run` uses event_name `api`, which the workflow_dispatch conditions also handle.
#   This file exceeds Depot's 64 KiB inline-workflow limit. To test a branch, use
#   `depot ci dispatch --workflow ci-backend.yml --ref <branch>`.
# - Three data-modeling tests are quarantined because they receive MinIO 403 errors on Depot.
# - COMPOSE_PROJECT_NAME is pinned to posthog because bin/wait-for-docker filters by that
#   project name and checkout directory names are not stable across CI providers.
# - WAIT_FOR_DOCKER_REGISTRY_MIRROR makes bin/ci-wait-for-docker launch pull Docker Hub
#   images from mirrors before `compose up`. Token requests to auth.docker.io time out
#   intermittently from Depot CI sandboxes, and one failed pull leaves the whole stack missing.
#   vars.DEPOT_PULL_THROUGH_REGISTRY (the org registry host, <org>.registry.depot.dev) goes
#   first: its pull-through repositories are created once in the Depot dashboard under the
#   upstream path (library/postgres, valkey/valkey) and need only the job's DEPOT_TOKEN.
#   Unset, or an image without a repository, falls through to mirror.gcr.io, then Docker Hub.
# - Compose launches run under `nohup` with stdin, stdout and stderr redirected to
#   $RUNNER_TEMP/compose-launch.log. Depot ends a step's background processes and closes its
#   output pipes when the step shell exits, so a plain `&` launch dies before it creates any
#   container. The wait steps print that log when they fail.
# - Baseline checkouts and comparisons use PostHog/posthog directly, so a manual run from a
#   fork compares against the upstream master branch.
# - Depot does not resolve env references in the Docker Hub login condition. Read
#   vars.DOCKERHUB_USER and secrets.DOCKERHUB_TOKEN directly. Login can fail without stopping
#   the job because these jobs pull public images and can use anonymous pulls.
# - handle-snapshots needs .depot/actions/commit-snapshots from the PR head. If that action
#   is missing, the PR must rebase before CI can update its report.
# - Shard planning uses test durations from Depot Cache under the posthog-test-durations-
#   prefix. .github/workflows/ci-backend-update-test-timing.yml writes the cache from Depot
#   runners and uploads a `test-durations` artifact that shards use when the cache misses.

name: Backend CI on Depot
on:
    push:
        branches:
            - master
    schedule:
        # Hourly full-matrix run against the newest master state. The merge queue's
        # trunk-merge/** run already gated every commit before it landed, so this is where
        # master's matrix coverage, flaky-test baseline, and per-test timing data come from.
        # Keep the events_json cadence tied to the trigger, even when a job starts late.
        - cron: '23 */3 * * *'
        - cron: '23 1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23 * * *'
    workflow_dispatch:
        inputs:
            clickhouseServerVersion:
                description: ClickHouse server version. Leave blank for default
                type: string
    pull_request:
        # Eligible source PRs run the snob-selected Django subset (one shard per active segment),
        # draft or ready; turbo-tests still skip drafts. When selection can't be
        # trusted, a ready source PR runs the full matrices and a draft skips them.
        # Add the `run-ci-backend` label to force the full matrices on a PR; the
        # `no-ci` label silences the workflow on a draft entirely. No
        # labeled/unlabeled triggers, so a label takes effect from the next push
        # or from ready_for_review. Every pull request event, merge-queue PRs included,
        # runs here.
        # The events_json leg covers .github/new-events-schema-targets.txt wherever legacy
        # tests run, keeping schema coverage consistent between source PRs and the merge queue.
        # The `test-new-events-schema` label runs doubled matrices in place of that leg.
        types: [opened, synchronize, reopened, ready_for_review]
concurrency:
    # PRs: one group per event; cancel-superseded-runs cancels stale runs. Push: per-SHA so master
    # pushes never cancel each other (check-migrations always completes). `depot ci run` (event `api`)
    # gets a per-run group: it has the master ref, and would otherwise queue behind the hourly run.
    group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.event_name == 'pull_request' && format('pr-{0}-{1}-{2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.updated_at) || github.event_name == 'api' && format('api-{0}', github.run_id) || github.head_ref || github.ref }}
    cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
    # Schema cache epoch. Bump to abandon every shared schema cache entry at once
    # (key is posthog-schema-mig-<epoch>-<hash>). Single-sourced so the PR-base
    # and HEAD (push) key computations below can't drift.
    # ci-e2e-playwright.yml, ci-dagster.yml, ci-mcp.yml and ci-rust-flags-integration.yml restore by the same key; keep their copies in sync when bumping.
    SCHEMA_CACHE_EPOCH: v2
    # A Depot step timeout leaves the step's processes running. A stalled uv sync then
    # keeps the env lock, and the step's retry blocks on it. Ending uv before the step
    # timeout frees the lock. Keep this under the 5-minute timeout-minutes of every step that uses it.
    PY_DEPS_SYNC_TIMEOUT: 270s
    SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da' # unsafe - for testing only
    COMPOSE_PROJECT_NAME: posthog
    WAIT_FOR_DOCKER_REGISTRY_MIRROR: ${{ vars.DEPOT_PULL_THROUGH_REGISTRY }} mirror.gcr.io
    DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'
    REDIS_URL: 'redis://localhost'
    CLICKHOUSE_HOST: 'localhost'
    CLICKHOUSE_SECURE: 'False'
    CLICKHOUSE_VERIFY: 'False'
    # Restricted `autoresearch` user defined in docker/clickhouse/users-dev.xml,
    # pointed at the CI test DB (posthog_test, not `default` as in regular dev).
    CLICKHOUSE_TEST_CLUSTER_HOST: 'localhost'
    CLICKHOUSE_TEST_CLUSTER_DATABASE: 'posthog_test'
    CLICKHOUSE_TEST_CLUSTER_USER: 'autoresearch'
    CLICKHOUSE_TEST_CLUSTER_PASSWORD: 'autoresearchpass'
    CLICKHOUSE_TEST_CLUSTER_SECURE: 'False'
    CLICKHOUSE_TEST_CLUSTER_VERIFY: 'False'
    TEST: 1
    # The root conftest ends a green pytest session with os._exit once every report is written.
    # That also hides a crash during interpreter teardown, so the hourly schedule exits normally.
    POSTHOG_PYTEST_HARD_EXIT: ${{ github.event_name == 'schedule' && '0' || '1' }}
    # Scheduled runs test master even when Depot does not populate github.ref. `depot ci run`
    # (event `api`) has the master ref but runs an unreviewed local patch, so it is not master.
    IS_MASTER: ${{ github.event_name == 'schedule' || (github.ref == 'refs/heads/master' && github.event_name != 'api') }}
    # Depot CI runners expose OTEL_SERVICE_NAME=ci-worker ambient; GitHub Actions test steps do not.
    # Left set, it leaks into settings.OTEL_SERVICE_NAME (personhog metric client_name label) and
    # diverges from test assertions. Blank it to match the GHA environment. Depot also injects
    # GITHUB_TOKEN, which test scripts unset because workflow-level replacement is unreliable.
    # Authenticated steps set an explicit step-level token.
    OTEL_SERVICE_NAME: ''
    CLICKHOUSE_SERVER_IMAGE_VERSION: ${{ github.event.inputs.clickhouseServerVersion || '' }}
    CLICKHOUSE_COMPAT_PYTEST_TARGETS: 'posthog/clickhouse ee/clickhouse'
    OBJECT_STORAGE_ENABLED: 'True'
    OBJECT_STORAGE_ENDPOINT: 'http://localhost:19000'
    OBJECT_STORAGE_ACCESS_KEY_ID: 'object_storage_root_user'
    OBJECT_STORAGE_SECRET_ACCESS_KEY: 'object_storage_root_password'
    UV_HTTP_TIMEOUT: 120
    # A 4 GiB thread stack cache avoids the uv exit segfault (code 139) on glibc before 2.43.
    # Remove when uv ships the fix: https://github.com/astral-sh/uv/issues/21428
    GLIBC_TUNABLES: glibc.pthread.stack_cache_size=0x100000000
    # tests would intermittently fail in GH actions
    # with exit code 134 _after passing_ all tests
    # this appears to fix it
    # absolute wild tbh https://stackoverflow.com/a/75503402
    DISPLAY: ':99.0'
    # this is a fake key so this workflow can run for external contributors as they do not have access to secrets (that we don't need here)
    OIDC_RSA_PRIVATE_KEY: ${{ vars.OIDC_RSA_FAKE_PRIVATE_KEY }}
    RUNS_ON_INTERNAL_PR: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false }}
    SANDBOX_JWT_PRIVATE_KEY: ${{ vars.OIDC_RSA_FAKE_PRIVATE_KEY }}
permissions:
    contents: read
    actions: read
    pull-requests: read
jobs:
    cancel-superseded-runs:
        if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        name: Cancel superseded Backend CI runs
        permissions:
            contents: read
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  sparse-checkout: .github/scripts/cancel_superseded_depot_runs.py
                  sparse-checkout-cone-mode: false
            - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
            - name: Cancel this PR's older runs
              continue-on-error: true
              env:
                  DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}
                  REPO: ${{ github.repository }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
              run: python3 .github/scripts/cancel_superseded_depot_runs.py
    # Job to decide if we should run backend ci
    # See .github/actions/paths-filter/README.md for filter semantics
    changes:
        # A draft PR labeled `no-ci` skips this workflow entirely (prototypes):
        # every other job needs this one, and the gates treat skipped as success.
        # ready_for_review re-runs everything, so the merge gate is unaffected.
        # A fork never runs here: its code must not reach this workflow's secrets, and the
        # gate fails closed for it below.
        if: >-
            github.event_name != 'pull_request'
            || (github.event.pull_request.head.repo.full_name == github.repository
            && (github.event.pull_request.draft != true
            || startsWith(github.head_ref, 'trunk-merge/')
            || !contains(github.event.pull_request.labels.*.name, 'no-ci')))
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        name: Determine need to run backend and migration checks
        # Set job outputs to values from filter step
        outputs:
            # run-ci-backend is documented as forcing the full matrices, but every
            # gate reads this output, so the label cannot reach them while the paths
            # filter says false. Nothing under .github/ is in the backend filter, so
            # a sharding or timing script change was untestable on its own PR.
            backend: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && 'true' || ((steps.filter.outputs.backend || 'true') == 'true' || steps.filter.outputs.product_skills_read_at_runtime == 'true') && 'true' || 'false' }}
            timing_scripts: ${{ fromJSON(toJSON(steps.filter.outputs)).timing_scripts }}
            backend_files: ${{ steps.filter.outputs.backend_files }}
            migrations: ${{ steps.filter.outputs.migrations || 'true' }}
            # Added and modified files only. A squash retirement deletes thousands of
            # migrations, and a step env string over 128 KiB fails the spawn (E2BIG).
            migrations_review_files: ${{ steps.filter.outputs.migrations_review_files }}
            migrations_any: ${{ steps.filter.outputs.migrations_any || 'true' }}
            # What the replay gate in check-migrations keys off. A ClickHouse or
            # async-migration change does not pay for a replay of a history the Django
            # planner never sees.
            migration_replay: ${{ steps.filter.outputs.migration_replay || 'true' }}
            tasks_temporal: ${{ steps.filter.outputs.tasks_temporal || 'true' }}
            openapi_types: ${{ steps.filter.outputs.openapi_types || 'true' }}
            # The label has to reach discovery as well: `backend` alone only starts the
            # discover job, which then sees no legacy change and no affected product and
            # emits an empty matrix. A forced legacy change makes it test everything.
            legacy: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && 'true' || (steps.filter.outputs.legacy || 'true') }}
            schema: ${{ steps.filter.outputs.schema || 'true' }}
            product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}
            repo_invariants: ${{ steps.filter.outputs.repo_invariants || 'false' }}
            sdk_manifests: ${{ steps.filter.outputs.sdk_manifests || 'true' }}
            product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}
        steps:
            # For pull requests it's not necessary to checkout the code, but we
            # also want this to run on master so we need to checkout
            # `depot ci run` (event `api`) applies its patch after this step, which fails in a sparse tree.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  clean: false
                  sparse-checkout: ${{ github.event_name != 'api' && '.depot/actions/paths-filter' || '' }}
                  sparse-checkout-cone-mode: false
            - name: Clean up data directories with container permissions
              run: |
                  # Use docker to clean up files created by containers
                  [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
              continue-on-error: true
            - uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              id: app-token
              if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_PATHS_FILTER_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}
            - uses: ./.depot/actions/paths-filter
              id: filter
              # Skipped on master push and on the hourly schedule: every output then
              # defaults to true. See "The hourly master lane" in
              # .agents/skills/authoring-ci-workflows/SKILL.md for why a cron cannot
              # diff, and what breaks if this guard is dropped.
              if: github.event_name != 'push' && github.event_name != 'schedule'
              with:
                  token: ${{ steps.app-token.outputs.token || github.token }}
                  list-files: 'escape'
                  filters: |
                      backend:
                        # Avoid running backend tests for irrelevant changes
                        # NOTE: we are at risk of missing a dependency here. We could make
                        # the dependencies more clear if we separated the backend/frontend
                        # code completely
                        - 'ee/**/*'
                        - '!ee/frontend/**' # frontend code under ee/ must not trigger backend
                        - 'common/__init__.py'
                        - 'common/hogql_parser/**'
                        - 'rust/hogql/parser/**'
                        - 'common/hogvm/**'
                        - 'common/ingestion/**'
                        - 'common/migration_utils/**'
                        - 'common/plugin_transpiler/**'
                        # The personhog gRPC stubs that posthog/personhog_client imports
                        - 'packages/personhog-proto/**'
                        - 'posthog/**/*'
                        - 'products/**/backend/**/*'
                        # Python outside backend/ — products like logs and
                        # posthog_ai point `backend:test` at extra roots
                        # (skills/, scripts/). Catch any .py change so the
                        # backend job triggers when only those files move.
                        - 'products/**/*.py'
                        # products/desktop is the imported desktop app; it has its own
                        # desktop-* CI and must not drag this suite onto its PRs
                        - '!products/desktop/**'
                        # Warehouse source vendors have their own job in ci-python.yml. They
                        # match 'products/**/*.py' above, so a vendor-only diff would start this
                        # suite too. The product code the vendors build on stays under backend/.
                        - '!products/warehouse_sources/sources/**'
                        # Each product's package.json declares the per-product
                        # backend:test script that turbo-discover reads to
                        # compose the Product matrix. Without this entry,
                        # widening or fixing the script doesn't trigger
                        # tests it controls.
                        - 'products/*/package.json'
                        # Tests read these MCP manifests from disk. Each one is a turbo input of
                        # its reader (tasks directly, posthog_ai through feature_flags'
                        # backend:mcp-surface task). Add a manifest here only with that wiring.
                        - products/feature_flags/mcp/tools.yaml
                        - products/tasks/mcp/tools.yaml
                        - 'products/canvas/packages/canvas_builder/**'
                        - bin/build-schema-latest-versions.py
                        - bin/check_uv_python_compatibility.py
                        - bin/find_python_dependencies.py
                        - pyproject.toml
                        - uv.lock
                        - requirements.txt
                        - requirements-dev.txt
                        - mypy.ini
                        - pytest.ini
                        - conftest.py # Root conftest loads for every pytest run
                        - .test_quarantine.json # Un-quarantining must re-run the affected tests
                        # turbo-discover reads the module graph for the dependent
                        # cascade, and `tach check` validates it — a graph-only PR
                        # must still dispatch both.
                        - tach.toml
                        # generates posthog/schema.py
                        - frontend/src/queries/schema.json
                        # Operator parity check
                        - rust/feature-flags/src/properties/property_models.rs
                        - frontend/src/products.json # Loaded at runtime by posthog/products.py
                        - 'products/*/manifest.tsx' # Generates products.json
                        # hogli setup commands this workflow runs: db:restore-test-db
                        # and product:bootstrap/lint. Scoped to the modules those
                        # commands actually import — framework, manifest, boot
                        # modules, db_schema, product — so unrelated hogli commands
                        # (doctor, devbox, ...) don't trigger this suite.
                        - 'tools/hogli/**'
                        - hogli.yaml
                        - 'tools/hogli-commands/hogli_commands/db_schema.py'
                        - 'tools/hogli-commands/hogli_commands/prechecks.py'
                        - 'tools/hogli-commands/hogli_commands/telemetry_props.py'
                        - 'tools/hogli-commands/hogli_commands/hint_hook.py'
                        - 'tools/hogli-commands/hogli_commands/hints.py'
                        - 'tools/hogli-commands/hogli_commands/product/**'
                        - 'tools/hogli-commands/hogli_commands/product_structure.yaml'
                        # owners_yaml is a runtime dependency of product code (stamphog reads
                        # owners.yaml through it), so a resolver change has to re-run its
                        # dependents; turbo-discover finds the products that import it.
                        # Deliberately not in `legacy`, because a leaf-package change should
                        # run its dependents rather than the whole Django suite.
                        - 'packages/owners-yaml/**'
                        # Transitional: branches that predate the move still carry the
                        # resolver at tools/owners.
                        - 'tools/owners/**'
                        # product:lint --all checks these generated files against the tree,
                        # so a baseline-only edit must run it too. The crossings baseline is
                        # also what product:lint reads to let a wiring location leave a
                        # product's turbo.json inputs, so both edits must run the checks.
                        - products/isolation_baseline.txt
                        - products/model_crossing_uses_baseline.txt
                        - 'products/*/turbo.json'
                        # Make sure we run if someone is explicitly changing the workflow
                        - .depot/workflows/ci-backend.yml
                        - .github/new-events-schema-targets.txt
                        - .depot/actions/setup-uv/**
                        - .github/clickhouse-versions.json
                        # We use docker compose for tests, make sure we rerun on
                        # changes to docker-compose.dev.yml e.g. dependency
                        # version changes
                        - docker-compose.dev.yml
                        - docker-compose.profiles.yml
                        - docker-compose.base.yml
                        - bin/wait-for-docker
                        - bin/ci-wait-for-docker
                        - frontend/public/email/*
                        - 'docker/clickhouse/**'
                        # Markdown-only changes (e.g. a README under posthog/) match the
                        # broad globs above but exercise no backend code — exclude them so
                        # a docs-only PR doesn't run the whole backend suite.
                        # These excludes are load-bearing: an over-broad exclude silently
                        # skips the suite rather than over-running it, so only exclude
                        # patterns that truly never affect backend. They also drop matched
                        # files from `backend_files`.
                        - '!**/*.md'
                        - '!**/*.mdx'
                      product_skills_read_at_runtime:
                        - 'products/signals/skills/**'
                        - 'products/review_hog/skills/**'
                      legacy:
                        # Non-product backend code — when only products/ change,
                        # turbo-discover uses Turbo query affectedness to detect changed
                        # products and decide whether Django runs.
                        # Everything from backend: EXCEPT products/**/backend/**/*
                        - 'ee/**/*'
                        - '!ee/frontend/**' # frontend code under ee/ must not trigger backend
                        - 'common/__init__.py'
                        - 'common/hogql_parser/**'
                        - 'rust/hogql/parser/**'
                        - 'common/hogvm/**'
                        - 'common/ingestion/**'
                        - 'common/migration_utils/**'
                        - 'common/plugin_transpiler/**'
                        # The personhog gRPC stubs that posthog/personhog_client imports
                        - 'packages/personhog-proto/**'
                        - 'posthog/**/*'
                        - bin/build-schema-latest-versions.py
                        - bin/check_uv_python_compatibility.py
                        - bin/find_python_dependencies.py
                        - pyproject.toml
                        - uv.lock
                        - requirements.txt
                        - requirements-dev.txt
                        - mypy.ini
                        - pytest.ini
                        - conftest.py
                        - .test_quarantine.json
                        - frontend/src/products.json
                        - 'products/*/manifest.tsx'
                        - rust/feature-flags/src/properties/property_models.rs
                        - .depot/workflows/ci-backend.yml
                        - .github/new-events-schema-targets.txt
                        - .depot/actions/setup-uv/**
                        - .github/clickhouse-versions.json
                        - docker-compose.dev.yml
                        - docker-compose.profiles.yml
                        - docker-compose.base.yml
                        - bin/wait-for-docker
                        - bin/ci-wait-for-docker
                        - frontend/public/email/*
                        - 'docker/clickhouse/**'
                        # Same rationale as the backend filter's excludes above: docs-only
                        # changes match the broad globs but exercise no legacy backend code,
                        # so they shouldn't trigger the Django/turbo-discover path either.
                        - '!**/*.md'
                        - '!**/*.mdx'
                        # Generated from frontend/src/queries/schema.json (see the `schema`
                        # filter below). Excluding them here routes schema-only PRs into
                        # turbo-discover's schema-impact narrowing instead of the
                        # all-products legacy path. This cannot skip Django: the
                        # schemaChanged branch hard-sets run_legacy=true. It also cannot
                        # hide a hand-edit to the generated files — ci-python.yml
                        # regenerates schema.py and fails on any diff, and both files stay
                        # in the `schema` (and `backend`) filters so turbo-discover still
                        # takes the schema path for them.
                        - '!posthog/schema.py'
                        - '!posthog/schema_enums.py'
                      schema:
                        # Tracked separately from `legacy` so turbo-discover can
                        # diff schema.json and narrow the product matrix to
                        # products that import the changed types.
                        - frontend/src/queries/schema.json
                        # The generated outputs are excluded from `legacy` above; listing
                        # them here keeps run_legacy=true (full Django) for any schema
                        # change, including a stray hand-edit to a generated file.
                        - posthog/schema.py
                        - posthog/schema_enums.py
                      migrations:
                        - 'docker/clickhouse/**'
                        - 'posthog/migrations/*.py'
                        - 'products/*/backend/migrations/*.py'
                        - 'products/*/migrations/*.py'  # Legacy structure
                        # The persons SQL migrations share this filter; there is no separate persons-migration job.
                        - 'rust/persons_migrations/*.sql'
                        - 'rust/bin/migrate-persons'
                      migrations_review:
                        - added|modified: 'posthog/migrations/*.py'
                        - added|modified: 'products/*/backend/migrations/*.py'
                        - added|modified: 'products/*/migrations/*.py'
                      # Any migration file in any app (broader than `migrations` above,
                      # which omits ee/ and posthog sub-package dirs). Gates the
                      # deleted-migration check in repo-checks.
                      migrations_any:
                        - '**/migrations/*.py'
                      # Django migration files in any app, plus the routing files that decide
                      # which app labels land in which database. Both change the plan a
                      # from-scratch migrate builds. Match everything and exclude the two
                      # non-Django directories, so a new app is covered without an edit here.
                      # An app missed by a positive list would leave the replay gate silently
                      # off for it.
                      migration_replay:
                        - '**/migrations/*.py'
                        - '!posthog/clickhouse/migrations/*.py'
                        - '!posthog/async_migrations/migrations/*.py'
                        - 'products/db_routing.yaml'
                        - 'posthog/product_db_config.py'
                        - 'posthog/product_db_router.py'
                      timing_scripts:
                        - '.github/scripts/optimize_test_durations.py'
                        - '.github/scripts/turbo-discover.js'
                      tasks_temporal:
                        - 'products/tasks/backend/temporal/**/*'
                      repo_invariants:
                        # posthog/test/repo_invariants/ reads AGENTS.md, the .agents/
                        # guides, and the semgrep rule ids they name. All are excluded
                        # from the backend filter (markdown is dropped outright,
                        # .semgrep is not listed), so a change to any would skip repo-checks and report green while
                        # leaving a tag pointing at a rule that no longer exists.
                        # The out-of-band domain ratchet reads these trees, so a resolver added there must run it.
                        - 'nodejs/src/**'
                        - 'rust/**'
                        - 'products/desktop/**'
                        - 'AGENTS.md'
                        - '.agents/*.md'
                        - '.semgrep/**'
                        - 'pyproject.toml'
                        # A generated file in a frontend-only PR still needs a known producer.
                        - '**/*.generated.*'
                        - '**/generated/**'
                        # test_generated_files_are_registered.py also reads the projection
                        # registry and the ci-python paths filter it must stay in step with.
                        - 'tools/hogli-commands/hogli_commands/projections.py'
                        - '.github/workflows/ci-python.yml'
                        - 'products/ruff.toml'
                        - '.github/scripts/**'
                        # test_signals_scout_tool_citations.py checks the MCP tool names that the
                        # canonical scout skills cite against the committed tool catalog. The backend
                        # filter matches only the .py files in a skill and nothing under services/mcp/.
                        # The same test fails when a file it reads has no match in this filter.
                        - 'products/signals/skills/**'
                        - 'services/mcp/schema/tool-definitions.json'
                        - 'services/mcp/schema/generated-tool-definitions.json'
                        # _EXTERNAL_COMPANION_SKILL_DIRS in products/signals/backend/scout_harness/lazy_seed.py
                        # names this companion skill from another product.
                        - 'products/replay_vision/skills/exploring-replay-vision-observations/**'
                        # A test file added or deleted, Jest included, can change the baseline that
                        # test_unowned_test_directories.py enforces. Keep in step with runner_for_path
                        # in packages/owners-yaml/owners_yaml/census.py.
                        - added|deleted: '**/test_*.py'
                        - added|deleted: '**/*_test.py'
                        - added|deleted: '**/*.{test,spec}.{js,jsx,ts,tsx}'
                      sdk_manifests:
                        # Everything the SDK major-version guard reads. Lockfiles are listed
                        # because a floor-only or `*` spec can move to a new major through
                        # its lock alone.
                        - '**/package.json'
                        - 'pnpm-workspace.yaml'
                        - 'pnpm-lock.yaml'
                        - 'products/desktop/pnpm-workspace.yaml'
                        - 'products/desktop/pnpm-lock.yaml'
                        - 'pyproject.toml'
                        - 'uv.lock'
                        - 'services/llm-gateway/pyproject.toml'
                        - 'services/llm-gateway/uv.lock'
                        - 'common/ingestion/acceptance_tests/requirements.txt'
                        - 'tools/infra-scripts/clitools/requirements.txt'
                        - 'tools/infra-scripts/clitools/constraints.txt'
                        - 'rust/Cargo.toml'
                        - 'rust/Cargo.lock'
                        - 'cli/Cargo.toml'
                        - 'cli/Cargo.lock'
                        - 'bin/hobby-installer/go.mod'
                        - 'bin/hobby-installer/go.sum'
                        - '.github/scripts/check_sdk_majors.py'
                        # The guard scans every package.json for an SDK declaration.
                        - '**/package.json'
                        - 'rust/Cargo.toml'
                        - 'cli/Cargo.toml'
                        - 'bin/hobby-installer/go.mod'
                      product_yamls:
                        - 'products/*/product.yaml'
                        - '**/owners.yaml'
                        # Resolver changes must re-run the owners.yaml lint too.
                        - 'packages/owners-yaml/**'
                        # Transitional: branches that predate the move still carry the
                        # resolver at tools/owners.
                        - 'tools/owners/**'
                      openapi_types:
                        # Generated OpenAPI types - validate they match schema
                        - 'frontend/src/generated/**/*'
                        - 'frontend/src/lib/agentScopes.generated.ts'
                        - 'products/*/frontend/generated/**/*'
                        - 'services/mcp/src/generated/**/*'
                        - 'services/mcp/src/api/generated.ts'
                        - 'tools/openapi-codegen/**/*'
                        - 'services/mcp/scripts/lib/**'
                        - 'frontend/bin/generate-openapi-types.mjs'
                        - 'frontend/src/lib/api-orval-mutator.ts'
                        - 'services/mcp/scripts/**/*'
                        # MCP tool config sources - feed generate-tools.ts
                        - 'services/mcp/definitions/**/*.yaml'
                        - 'services/mcp/definitions/prompts/**/*.md'
                        - 'products/*/mcp/**/*.yaml'
                        - 'products/*/mcp/prompts/**/*.md'
                        - 'services/mcp/schema/tool-definitions.json'
                        - 'services/mcp/schema/tool-definitions-v2.json'
                        - 'services/mcp/src/tools/generated/**/*'
                        - 'services/mcp/schema/generated-tool-definitions.json'
                        - 'services/mcp/schema/tool-definitions-all.json'
                        # Exec command reference templates - feed generate-exec-docs.ts
                        - 'services/mcp/src/templates/sections/**/*'
                        - 'services/mcp/schema/exec-command-reference.md'
                        # WebMCP exec tool - rendered from the templates above by generate-webmcp-exec-tool.ts
                        - 'services/mcp/src/hono/instructions.ts'
                        - 'services/mcp/src/lib/instructions-formatter.ts'
                        - 'services/mcp/src/lib/instructions.ts'
                        - 'products/webmcp/frontend/execTool.generated.ts'
                        # Desktop API client - regenerated by bin/build-desktop-api-client.sh
                        - 'products/desktop/packages/api-client/src/generated.ts'
                        - 'products/desktop/packages/api-client/endpoint-allowlist.json'
                        # Pins typed-openapi exactly, so a generator bump changes this file and not only the desktop lockfile.
                        - 'products/desktop/packages/api-client/package.json'
                        - 'products/desktop/packages/api-client/scripts/**'
                        - 'bin/build-desktop-api-client.sh'

    detect-snapshot-mode:
        name: Detect snapshot mode
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        needs: [changes]
        # Not on master push: only feeds the matrices, which master pushes skip.
        if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'
        outputs:
            mode: ${{ steps.detect.outputs.mode }}
        steps:
            - name: Detect mode
              id: detect
              env:
                  PR_REPO: ${{ github.event.pull_request.head.repo.full_name }}
                  REPO: ${{ github.repository }}
                  HAS_NO_SNAPSHOT_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'no-snapshot-update') }}
                  AUTHOR: ${{ github.actor }}
              run: |
                  if [ "$PR_REPO" != "$REPO" ] && [ -n "$PR_REPO" ]; then
                    echo "mode=check" >> $GITHUB_OUTPUT
                    echo "Fork detected - running in CHECK mode (no commits allowed)"
                  elif [ "$HAS_NO_SNAPSHOT_LABEL" == "true" ]; then
                    echo "mode=check" >> $GITHUB_OUTPUT
                    echo "::notice::🔍 Running in CHECK mode - 'no-snapshot-update' label detected"
                  else
                    echo "Workflow triggered by: $AUTHOR"
                    # Dependabot is excluded - it creates new PRs that may need snapshot updates
                    # Other bots (github-actions, posthog-bot) commit snapshots and must use CHECK mode to avoid loops
                    if [[ "$AUTHOR" != "dependabot[bot]" ]] && \
                       ([[ "$AUTHOR" == *"github-actions"* ]] || [[ "$AUTHOR" == *"[bot]"* ]] || [[ "$AUTHOR" == "posthog-bot" ]]); then
                      echo "mode=check" >> $GITHUB_OUTPUT
                      echo "::notice::🔍 Running in CHECK mode - snapshots must match exactly"
                    else
                      echo "mode=update" >> $GITHUB_OUTPUT
                      echo "::notice::🔄 Running in UPDATE mode - snapshots can be updated"
                    fi
                  fi

    # Fast pre-job: determines which products need testing and if Django should run
    # Only needs pnpm + node — no Python, Docker, or services
    # Runs on depot for turbo remote cache access (cache status drives Django gating)
    turbo-discover:
        needs: [changes]
        # Not on master push: master only primes the schema cache; this cascades the matrices off.
        if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 20
        name: Discover product tests
        env:
            # Whether this run selects backend tests at all: a PR, off the merge queue's
            # trunk-merge/** run (that run is the merge gate and stays full), and without
            # the run-ci-backend label. turbo-discover.js reads it too, so a run that never
            # selects reports an empty mode rather than a selector error.
            SELECTION_APPLIES: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') && !contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && needs.changes.outputs.backend == 'true' }}
            # GitHub tests PRs as synthetic merges. The first parent pins the exact integrated
            # base for ordinary, stacked, and merge-queue PRs.
            TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || '' }}
        outputs:
            run_legacy: ${{ steps.discover.outputs.run_legacy }}
            run_legacy_reason: ${{ steps.discover.outputs.run_legacy_reason }}
            matrix: ${{ steps.discover.outputs.matrix }}
            schema_cache_key: ${{ steps.schema-key.outputs.key }}
            schema_migrations_key: ${{ steps.schema-key.outputs.migrations_key }}
            schema_base_sha: ${{ steps.schema-key.outputs.base_sha }}
            schema_base_timestamp: ${{ steps.schema-key.outputs.base_timestamp }}
            schema_prefix_key: ${{ steps.schema-key.outputs.prefix_key }}
            django_shards: ${{ steps.discover.outputs.django_shards }}
            # Which Django tests this PR runs. Empty mode = this run does not select.
            mode: ${{ steps.discover.outputs.mode }}
            # The rest of that decision (segment file lists, run_poe, run_temporal,
            # segment_shards) as one JSON object; consumers read it with fromJSON.
            selection: ${{ steps.discover.outputs.selection }}
            # The posthog-ci-test-selection event properties, as one JSON object.
            telemetry: ${{ steps.discover.outputs.telemetry }}
        steps:
            # A deep checkout is slow with or without blob:none: the blobless one fetches every file of
            # the tree in a second request. Check out at depth 1, then add the history the merge-base
            # steps read, without file contents.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            - name: Fetch history without file contents
              # --depth, not --deepen: --deepen adds no history once GitHub has replaced the PR's
              # merge ref, because no ref then points at GITHUB_SHA.
              run: |
                  # Depot CI serves an input-less checkout from a fast clone that adds no origin remote.
                  git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
                  git fetch --no-tags --filter=blob:none --depth=1000 origin "$GITHUB_SHA"
                  echo "History depth: $(git rev-list --count HEAD)"
              retry: 2
            - name: Verify PR merge for test selection
              id: verify-merge
              if: github.event_name == 'pull_request'
              env:
                  PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
              run: |
                  set -euo pipefail
                  trap 'echo "::error::Cannot verify the PR merge checkout. Check the checkout ref and the history fetch before retrying." >&2' ERR
                  test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
                  test "$(git rev-list --parents -n 1 HEAD | wc -w)" -eq 3
                  test "$(git rev-parse HEAD^2)" = "$PR_HEAD_SHA"
                  git rev-parse --verify "$TURBO_SCM_BASE^{commit}"

            - name: Compute schema cache key from PR base
              id: schema-key
              if: github.event_name == 'pull_request'
              env:
                  PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
              run: |
                  # The event base is the exact master revision in the synthetic merge checkout.
                  # Use it directly so cache compatibility does not depend on parent ordering.
                  BASE_SHA="$PR_BASE_SHA"
                  if [ -z "$BASE_SHA" ] || ! git cat-file -e "${BASE_SHA}^{commit}" 2>/dev/null; then
                      echo "key=" >> $GITHUB_OUTPUT
                      echo "migrations_key=" >> $GITHUB_OUTPUT
                      echo "base_sha=" >> $GITHUB_OUTPUT
                      echo "base_timestamp=" >> $GITHUB_OUTPUT
                      echo "::notice::PR event base is unavailable — schema cache will be skipped"
                      exit 0
                  fi
                  echo "base_sha=$BASE_SHA" >> $GITHUB_OUTPUT
                  echo "base_timestamp=$(git show -s --format=%ct "$BASE_SHA")" >> $GITHUB_OUTPUT
                  # Routing decides which app labels reach the dump, and the consumers replay them
                  # from the checked-out copy, so these inputs belong in the key below. A PR that
                  # edits any of them matches no master dump, the base one included: drop
                  # both keys and let migrations run from scratch.
                  DB_ROUTING=$(git ls-tree -r --format='%(objectname) %(path)' "$BASE_SHA" -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)
                  DB_ROUTING_HEAD=$(git ls-tree -r --format='%(objectname) %(path)' HEAD -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)
                  if [ "$DB_ROUTING" != "$DB_ROUTING_HEAD" ]; then
                      echo "key=" >> $GITHUB_OUTPUT
                      echo "migrations_key=" >> $GITHUB_OUTPUT
                      echo "::notice::db routing config or router differs from the PR base, so the schema cache is skipped"
                      exit 0
                  fi
                  # Exact base-revision key, kept as the fallback restore key below.
                  echo "key=posthog-schema-master-${BASE_SHA}" >> $GITHUB_OUTPUT
                  # Last-resort restore prefix: matches the newest saved dump of any
                  # migration set, for the window where both exact keys miss. Gated on
                  # checkout age (a day) because a re-run of an old run keeps its original
                  # commit: a stale checkout can lack migrations the newest dump records,
                  # and the migrate top-ups only apply forward, so they cannot repair a
                  # dump that is newer than the code.
                  HEAD_AGE_SECONDS=$(( $(date +%s) - $(git show -s --format=%ct HEAD) ))
                  if [ "$HEAD_AGE_SECONDS" -lt 86400 ]; then
                      echo "prefix_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-" >> $GITHUB_OUTPUT
                  fi
                  # Shared key: hash base schema inputs, not PR head, so PR migrations still
                  # apply as the pytest delta. uv.lock covers third-party migration changes; the
                  # postgres image is folded in so a server-version bump invalidates the key.
                  # Non-Django migration frameworks are excluded from this Postgres schema dump.
                  # SCHEMA_CACHE_EPOCH (workflow env) prefixes the key as a manual cache-bust knob.
                  # SchemaInputs.cache_key in .github/scripts/master_schema_cache.py names the saved
                  # dumps, so this hash must stay byte-identical to it.
                  MIG_FILES=$(git ls-tree -r --format='%(objectname) %(path)' "$BASE_SHA" \
                      | grep -E '/migrations/[^/]+\.py$|^[0-9a-f]+ uv\.lock$' \
                      | grep -vE '/(clickhouse|async_migrations)/migrations/' \
                      | LC_ALL=C sort) || true
                  PG_IMAGE=$(git show "${BASE_SHA}:docker-compose.base.yml" 2>/dev/null \
                      | grep -m1 -E '^[[:space:]]*image:[[:space:]]*postgres:' | tr -d '[:space:]')
                  if [ -z "$MIG_FILES" ]; then
                      echo "migrations_key=" >> $GITHUB_OUTPUT
                      echo "::notice::no migration files matched — restore will fall back to the SHA schema key"
                  else
                      MIG_HASH=$(printf '%s\n%s\n%s' "$MIG_FILES" "$PG_IMAGE" "$DB_ROUTING" | sha256sum | cut -c1-40)
                      echo "migrations_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT
                  fi
            # Dedicated app: every "Mint setup-action GitHub token" step in this file
            # draws on posthog-devex-general rather than the posthog-setup-actions app
            # the other workflows share. Backend CI is the largest single consumer of
            # setup-action calls in the repo, enough to threaten a shared 15k/hr bucket
            # at merge peaks, so it gets one to itself.
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
                  skip-token-revoke: true
            - name: Set up pnpm and Node
              uses: ./.depot/actions/setup-pnpm
              with:
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            - name: Install turbo
              uses: ./.depot/actions/setup-turbo
            # turbo-discover.js runs .github/scripts/tach_map.py under `uv run
            # --no-project` for the dependent cascade; the script pins tach, so no
            # Python project sync is needed. A missing uv widens the cascade to
            # every product rather than failing the job.
            - uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false
              continue-on-error: true
            - name: Restore test durations from cache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: .test_durations
                  key: posthog-test-durations-${{ github.run_id }}
                  restore-keys: |
                      posthog-test-durations-
            - name: Fall back to the last published durations
              # .test_durations is not in the repo. The timing workflow refreshes the
              # cache several times a day and publishes the same files as an artifact
              # of its own runs. On a cache miss (retention lapsed, timing workflow
              # down for two weeks) take the newest artifact; if that is gone too,
              # pytest-split splits by count and turbo-discover sizes from file counts
              # until the next timing run.
              if: ${{ hashFiles('.test_durations') == '' }}
              continue-on-error: true
              env:
                  GH_TOKEN: ${{ github.token }}
              run: |
                  run_id=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow ci-backend-update-test-timing.yml \
                      --branch master --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty')
                  if [ -z "$run_id" ]; then
                      echo "::warning::No successful timing run to fall back to, sharding without durations"
                      exit 0
                  fi
                  gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name test-durations --dir . \
                      || echo "::warning::Timing artifact of run $run_id unavailable, sharding without durations"
            - name: Restore per-segment test durations from cache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: |
                      .test_durations.core
                      .test_durations.temporal
                  key: posthog-segment-durations-${{ github.run_id }}
                  restore-keys: |
                      posthog-segment-durations-
            - name: Restore the events_json prune manifest from cache
              # The timing workflow rebuilds it from the newest hourly recording. A miss
              # leaves the file absent, and the events_json rows then run every listed test.
              if: github.event_name == 'pull_request'
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: events-schema-prune.json
                  key: posthog-events-schema-prune-${{ github.run_id }}
                  restore-keys: |
                      posthog-events-schema-prune-
            # The backend test selector picks the Django tests this PR needs, and on a legacy
            # diff its product list narrows the product matrix too: turbo-discover.js cannot
            # see which products a posthog/ or ee/ edit reaches, and the selector can, because
            # it follows the import graph into products/. Both matrices read one verdict, so
            # they can never disagree about whether the selection is trustworthy.
            # Only on a legacy diff: turbo-discover.js trusts the selection only when the paths
            # filter saw a legacy edit, and falls back without a selector run otherwise. The
            # DISABLE_BACKEND_TEST_SELECTION kill switch skips the run too; the script still
            # reports the `disabled` reason from its own env.
            - name: Install uv
              # Optional setup: a failure here must fall back to the full matrices like a
              # selector failure does, not fail the job that gates every test job.
              continue-on-error: true
              if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'
              uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false

            - name: Snapshot the sharding plan for this run
              # The timing caches float to their newest entry, so a re-run can shard
              # differently from attempt 1 and, under "re-run failed jobs", a failing
              # test can move to a shard that never re-runs while the gate goes green.
              # Every test job applies this snapshot instead, so all attempts shard
              # identically. Best-effort (consumers fall back to the floating caches);
              # overwrite lets a "re-run all jobs" attempt re-snapshot.
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: test-durations-plan
                  path: |
                      .test_durations
                      .test_durations.core
                      .test_durations.temporal
                      events-schema-prune.json
                  include-hidden-files: true
                  overwrite: true
                  # The per-segment files and the prune manifest are cache-only and may legitimately be absent.
                  if-no-files-found: warn
                  # GitHub allows re-runs for 30 days.
                  retention-days: 30

            - name: Run the backend test selector
              id: select
              # A selector failure or hang must not fail this job, which gates every test job
              # in the workflow — turbo-discover.js falls back to the full matrices instead.
              # The step timeout bounds a hang well inside the job's, so the fallback still
              # reaches the matrices rather than taking the whole job down with it.
              continue-on-error: true
              timeout-minutes: 8
              if: env.SELECTION_APPLIES == 'true' && needs.changes.outputs.legacy == 'true' && vars.DISABLE_BACKEND_TEST_SELECTION != 'true'
              shell: bash
              run: |
                  set -euo pipefail
                  uv run tools/snob_backend_test_selection_shadow.py \
                      --base-ref "$TURBO_SCM_BASE" \
                      > /tmp/selection.json

            - name: Discover products to test
              id: discover
              env:
                  # On pushes to master, always run everything.
                  # On PRs, use the path filter to detect legacy changes.
                  LEGACY_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.legacy }}
                  # Empty when the selector did not run or failed, which falls back to the
                  # full matrices on a ready PR and skips them on a draft.
                  SELECTION_JSON: ${{ steps.select.outcome == 'success' && '/tmp/selection.json' || '' }}
                  # Kill switch — set the DISABLE_BACKEND_TEST_SELECTION repo variable to put
                  # every PR back on the full matrices without a code change.
                  SELECTION_DISABLED: ${{ vars.DISABLE_BACKEND_TEST_SELECTION || 'false' }}
                  # A draft has a later ready run to defer to, so an untrusted selection skips
                  # the heavy matrices there instead of running all of them.
                  PR_DRAFT: ${{ github.event.pull_request.draft }}
                  RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}
                  SCHEMA_CHANGED: ${{ github.event_name != 'pull_request' || needs.changes.outputs.schema }}
                  TURBO_SCM_HEAD: ${{ github.sha }}
                  # Kill switch — drop comma-separated products from the matrix; empty = run all.
                  SKIP_PRODUCT_TESTS: ${{ vars.SKIP_PRODUCT_TESTS || '' }}
              run: |
                  # turbo-discover.js uses Turbo's Git affectedness to detect
                  # changed products. Non-isolated product changes trigger the
                  # full suite (all products + Django).
                  RESULT=$(node .github/scripts/turbo-discover.js)
                  echo "Result: $RESULT"
                  echo "matrix=$(echo "$RESULT" | jq -c '.matrix')" >> $GITHUB_OUTPUT
                  echo "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUT
                  echo "run_legacy_reason=$(echo "$RESULT" | jq -r '.run_legacy_reason // empty')" >> "$GITHUB_OUTPUT"
                  echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT
                  echo "$RESULT" | jq -r '"mode=\(.selection.mode)", "selection=\(.selection | tojson)", "telemetry=\(.telemetry | tojson)"' >> "$GITHUB_OUTPUT"

            - name: Upload selection artifact
              # test-selection-verdict reads it instead of running the selector again. An
              # upload failure must not fail this job; the verdict regenerates the selection.
              continue-on-error: true
              if: ${{ always() && steps.select.outcome == 'success' }}
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: select-tests-output
                  path: /tmp/selection.json
                  if-no-files-found: ignore
                  retention-days: 14

    # Build an absent schema dump once before the test matrices fan out.
    # Every test job retains its migration fallback if this optimization fails.
    prime-schema-cache:
        needs: [changes, turbo-discover]
        if: >-
            !cancelled() &&
            github.event_name == 'pull_request' &&
            needs.changes.outputs.backend == 'true' &&
            needs.turbo-discover.result == 'success'
        name: Prime schema cache
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 25
        continue-on-error: true
        steps:
            - name: Look up schema cache
              id: schema-cache
              timeout-minutes: 4
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  key: ${{ needs.turbo-discover.outputs.schema_migrations_key || needs.turbo-discover.outputs.schema_cache_key || format('posthog-schema-run-{0}', github.run_id) }}
                  restore-keys: |
                      ${{ needs.turbo-discover.outputs.schema_cache_key }}
                      ${{ needs.turbo-discover.outputs.schema_prefix_key }}
                  lookup-only: true
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              if: steps.schema-cache.outputs.cache-matched-key == ''
              with:
                  # Shared dumps represent the PR base. Run-scoped dumps include
                  # the PR merge commit because their routing inputs may differ.
                  ref: ${{ needs.turbo-discover.outputs.schema_cache_key != '' && needs.turbo-discover.outputs.schema_base_sha || github.sha }}
            - name: Start database services
              if: steps.schema-cache.outputs.cache-matched-key == ''
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
              run: nohup bin/ci-wait-for-docker launch --background --down db redis7 clickhouse </dev/null >"${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>&1
            - name: Set up Python
              if: steps.schema-cache.outputs.cache-matched-key == ''
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ secrets.POSTHOG_BOT_PAT }}
            - name: Install uv
              id: setup-uv
              if: steps.schema-cache.outputs.cache-matched-key == ''
              uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
              with:
                  version: '0.13.4'
                  enable-cache: true
                  cache-dependency-glob: uv.lock
                  save-cache: false
                  prune-cache: true
            - name: Install SAML dependencies
              if: steps.schema-cache.outputs.cache-matched-key == '' && steps.setup-uv.outputs.cache-hit != 'true'
              run: sudo rm -f /etc/apt/sources.list.d/*twingate* && sudo apt-get update && sudo apt-get install -y libxml2-dev libxmlsec1-dev libxmlsec1-openssl
              retry: 2
            - name: Install Python dependencies
              if: steps.schema-cache.outputs.cache-matched-key == ''
              timeout-minutes: 5
              retry: 1
              run: UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            - name: Wait for database services
              if: steps.schema-cache.outputs.cache-matched-key == ''
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
                  WAIT_FOR_DOCKER_TIMEOUT: 900
              run: |
                  bin/ci-wait-for-docker wait --only db redis7 clickhouse \
                    || { echo "::group::compose launch log"; cat "${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>/dev/null || true; echo "::endgroup::"; exit 1; }
            - name: Build schema dump
              if: steps.schema-cache.outputs.cache-matched-key == ''
              run: |
                  set -e
                  set -o pipefail
                  python manage.py migrate
                  (docker compose -f docker-compose.dev.yml exec -T db pg_dump --schema-only --clean --if-exists -U posthog posthog && \
                   docker compose -f docker-compose.dev.yml exec -T db pg_dump --data-only --table=django_migrations -U posthog posthog) | gzip > schema.sql.gz
                  gunzip -t schema.sql.gz
            - name: Save schema cache
              if: steps.schema-cache.outputs.cache-matched-key == ''
              uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  key: ${{ needs.turbo-discover.outputs.schema_migrations_key || needs.turbo-discover.outputs.schema_cache_key || format('posthog-schema-run-{0}', github.run_id) }}

    build-product-test-matrix:
        name: Build product test matrix
        needs: [turbo-discover]
        if: >-
            !cancelled() && needs.turbo-discover.result == 'success' && needs.turbo-discover.outputs.matrix != '[]' && needs.turbo-discover.outputs.matrix != ''
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        outputs:
            include: ${{ steps.build.outputs.include }}
        steps:
            - name: Build product matrix include list
              id: build
              env:
                  PRODUCT_MATRIX_JSON: ${{ needs.turbo-discover.outputs.matrix }}
                  # The new-events-schema variants double the matrix, so they run only on
                  # opted-in PRs. Other runs cover the product paths in
                  # .github/new-events-schema-targets.txt with the Django matrix's
                  # events_json rows.
                  RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}
              run: |
                  if [[ "$RUN_NEW_EVENTS_SCHEMA" == "true" ]]; then
                      schema_modes='[false, true]'
                  else
                      schema_modes='[false]'
                      echo "Skipping new-events-schema variants (RUN_NEW_EVENTS_SCHEMA is off)"
                  fi
                  include=$(jq -cn --argjson matrix "$PRODUCT_MATRIX_JSON" --argjson schema_modes "$schema_modes" '
                    [
                      $matrix[] as $entry
                      | $schema_modes[] as $new_events_schema
                      | $entry + {"new-events-schema": $new_events_schema}
                    ]
                  ')
                  echo "include=$include" >> "$GITHUB_OUTPUT"
                  echo "Product test matrix size: $(jq -r 'length' <<< "$include")"

    # Runs product tests in parallel — one matrix job per group
    # Each job gets its own runner + Docker stack, so no shared DB conflicts
    # Small products (< 50 tests) are grouped into a single job to avoid setup overhead
    # A status function is required to inspect dependency results after failures.
    # Use !cancelled(), not always(), so superseded matrix jobs still receive cancellation.
    turbo-tests:
        needs:
            [
                changes,
                turbo-discover,
                prime-schema-cache,
                detect-snapshot-mode,
                build-product-test-matrix,
                get_clickhouse_versions,
            ]
        if: >-
            !cancelled() && (github.event.pull_request.draft != true || startsWith(github.head_ref, 'trunk-merge/') || contains(github.event.pull_request.labels.*.name, 'run-ci-backend')) && needs.turbo-discover.result == 'success' && needs.build-product-test-matrix.result == 'success' && needs.build-product-test-matrix.outputs.include != '[]' && needs.build-product-test-matrix.outputs.include != ''
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 40
        name: Product tests (${{ matrix.group }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }})
        strategy:
            fail-fast: false
            matrix:
                include: ${{ fromJson(needs.build-product-test-matrix.outputs.include) }}
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            # Start Docker early (before dependency installs) so containers can pull
            # images and initialize while we install deps. This matches the pattern
            # used by core-tests/django and makes the later wait step negligible.
            - name: Clean up data directories
              run: |
                  [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
              continue-on-error: true
            - name: Log in to Docker Hub
              if: ${{ vars.DOCKERHUB_USER != '' && secrets.DOCKERHUB_TOKEN != '' }}
              continue-on-error: true
              uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
              with:
                  username: ${{ vars.DOCKERHUB_USER }}
                  password: ${{ secrets.DOCKERHUB_TOKEN }}
            - name: Start services
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
                  COMPOSE_PROFILES: temporal,azure
                  CLICKHOUSE_SERVER_IMAGE: ${{ needs.get_clickhouse_versions.outputs.local_image }}
              run: |
                  cp posthog/user_scripts/latest_user_defined_function.xml docker/clickhouse/user_defined_function.xml
                  nohup bin/ci-wait-for-docker launch --background --down \
                    db redis7 clickhouse zookeeper kafka objectstorage \
                    temporal elasticsearch objectstorage-azure </dev/null >"${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>&1
            # Dedicated app: this product matrix alone is ~half the offloadable
            # setup-action volume, enough to threaten any shared 15k/hr bucket.
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_PRODUCT_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_PRODUCT_TESTS_PRIVATE_KEY }}
                  skip-token-revoke: true
            - name: Set up pnpm and Node
              uses: ./.depot/actions/setup-pnpm
              with:
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            - name: Set up Python
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            # Needs pnpm from the step above.
            - name: Install turbo
              uses: ./.depot/actions/setup-turbo

            - name: Install uv
              id: setup-uv
              uses: ./.depot/actions/setup-uv
            - name: Install SAML dependencies
              if: steps.setup-uv.outputs.cache-hit != 'true'
              run: sudo rm -f /etc/apt/sources.list.d/*twingate* && sudo apt-get update && sudo apt-get install -y libxml2-dev libxmlsec1-dev libxmlsec1-openssl
              retry: 2
            - name: Install sqlx-cli
              uses: ./.depot/actions/setup-sqlx-cli
            - name: Install Python dependencies
              timeout-minutes: 5
              retry: 1
              run: UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            - name: Add service hostnames to /etc/hosts
              run: echo "127.0.0.1 db redis7 kafka clickhouse clickhouse-coordinator objectstorage temporal" | sudo tee -a /etc/hosts
            - name: Set up needed files
              run: |
                  mkdir -p frontend/dist
                  touch frontend/dist/index.html frontend/dist/layout.html frontend/dist/exporter.html
                  ./bin/download-mmdb
            - name: Wait for Docker services
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
                  COMPOSE_PROFILES: temporal,azure
                  CLICKHOUSE_SERVER_IMAGE: ${{ needs.get_clickhouse_versions.outputs.local_image }}
              # objectstorage answers InvalidAccessKeyId until its bootstrap registers identities.
              run: |
                  bin/ci-wait-for-docker wait objectstorage \
                    || { echo "::group::compose launch log"; cat "${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>/dev/null || true; echo "::endgroup::"; exit 1; }
            - name: Restore schema cache from master
              if: ${{ github.event_name == 'pull_request' }}
              timeout-minutes: 4
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  # Prefer the shared content key; fall back to the exact PR-base SHA key,
                  # then to the newest dump of any migration set. Right after a migration
                  # lands on master both exact keys miss until ci-backend re-dumps, and a
                  # from-scratch migrate costs ~17 minutes per shard; pytest's keepdb
                  # migrate tops a slightly stale dump up in seconds instead.
                  key: ${{ needs.turbo-discover.outputs.schema_migrations_key || needs.turbo-discover.outputs.schema_cache_key || format('posthog-schema-run-{0}', github.run_id) }}
                  restore-keys: |
                      ${{ needs.turbo-discover.outputs.schema_cache_key }}
                      ${{ needs.turbo-discover.outputs.schema_prefix_key }}
            - name: Prime test_posthog from cached schema
              # Treat cache problems as misses; the migrate step below rebuilds the DB
              # whenever this one reports restored=false.
              id: prime-schema
              if: ${{ github.event_name == 'pull_request' }}
              run: |
                  echo "restored=false" >> "$GITHUB_OUTPUT"
                  if [ ! -f schema.sql.gz ]; then
                      echo "::notice::Schema cache miss; the migrate step will build test_posthog"
                      exit 0
                  fi
                  mkdir -p .postgres-backups
                  mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
                  if ./bin/hogli db:restore-test-db; then
                      echo "restored=true" >> "$GITHUB_OUTPUT"
                  else
                      echo "::warning::Schema restore failed (stale/incompatible cached dump?); the migrate step will build test_posthog"
                  fi
            - name: Migrate test_posthog from scratch
              # Any run without a restored schema cache (master, dispatches, PR cache
              # misses) replays the full migration chain here, in a process that exits
              # before tests: the executor's memory high-water stays resident in
              # whichever process runs it, and pytest must not carry it through the
              # test phase. pytest --reuse-db adopts the DB like the PR prime above;
              # any failure falls back to the in-pytest migrate.
              if: ${{ github.event_name != 'pull_request' || steps.prime-schema.outputs.restored != 'true' }}
              env:
                  DATABASE_URL: postgres://posthog:posthog@localhost:5432/test_posthog
              run: |
                  admin_psql() { docker compose -f docker-compose.dev.yml exec -T db psql -U posthog postgres "$@"; }
                  if ! admin_psql -c "DROP DATABASE IF EXISTS test_posthog;" -c "CREATE DATABASE test_posthog;"; then
                      echo "::warning::Could not recreate test_posthog; pytest --reuse-db will run the full migrate itself"
                      exit 0
                  fi
                  if ! python manage.py migrate; then
                      echo "::warning::Out-of-process migrate failed; pytest --reuse-db will run the full migrate itself"
                      admin_psql -c "DROP DATABASE IF EXISTS test_posthog;" || true
                  fi
            - name: Register Temporal search attributes
              timeout-minutes: 10
              run: |
                  bin/wait-for-docker temporal
                  PYTHONFAULTHANDLER=1 timeout --signal=ABRT --kill-after=30s 3m python manage.py register_temporal_search_attributes
            - name: Restore test durations from cache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: .test_durations
                  key: posthog-test-durations-${{ github.run_id }}
                  restore-keys: |
                      posthog-test-durations-
            - name: Fall back to the last published durations
              # .test_durations is not in the repo. The timing workflow refreshes the
              # cache several times a day and publishes the same files as an artifact
              # of its own runs. On a cache miss (retention lapsed, timing workflow
              # down for two weeks) take the newest artifact; if that is gone too,
              # pytest-split splits by count and turbo-discover sizes from file counts
              # until the next timing run.
              if: ${{ hashFiles('.test_durations') == '' }}
              continue-on-error: true
              env:
                  GH_TOKEN: ${{ github.token }}
              run: |
                  run_id=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow ci-backend-update-test-timing.yml \
                      --branch master --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty')
                  if [ -z "$run_id" ]; then
                      echo "::warning::No successful timing run to fall back to, sharding without durations"
                      exit 0
                  fi
                  gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name test-durations --dir . \
                      || echo "::warning::Timing artifact of run $run_id unavailable, sharding without durations"
            - name: Download the run's sharding plan snapshot
              # Same pinning as the Django job; falls back to the floating cache.
              id: pinned-plan
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  name: test-durations-plan
                  path: /tmp/test-durations-plan

            - name: Apply the pinned sharding plan
              if: ${{ steps.pinned-plan.outcome == 'success' }}
              shell: bash
              run: |
                  if [ ! -f /tmp/test-durations-plan/.test_durations ]; then
                      echo "::warning::Sharding-plan snapshot is incomplete, keeping the floating cache restore"
                      exit 0
                  fi
                  cp /tmp/test-durations-plan/.test_durations .test_durations
                  echo "Sharding plan pinned to this run's snapshot"

            - name: Warn when a re-run reshards unpinned
              if: ${{ github.run_attempt != '1' && steps.pinned-plan.outcome != 'success' }}
              shell: bash
              run: echo "::warning::Sharding-plan snapshot unavailable, this re-run reshards from the floating timing cache and may not re-execute tests that failed in earlier attempts"

            - name: Run product tests
              continue-on-error: true
              id: run-product-tests
              # --force: discover already decided this product needs testing, skip turbo cache
              # --log-order=stream: stream pytest output live instead of buffering until completion
              # legs: one turbo invocation per entry, each with its own pytest-split flags
              # (e.g. "-- --splits 3 --group 1"). A job holds several legs when a split
              # product's last shard had budget left over for whole small products, and
              # pytest-split flags must not leak from that shard onto its job-mates.
              env:
                  PRODUCT_LEGS: ${{ toJSON(matrix.legs) }}
                  LEGACY_FILTERS: ${{ matrix.filters }}
                  LEGACY_PYTEST_ARGS: ${{ matrix.pytest_args }}
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
                  # Person-on-events v2 reads are the production default for every project
                  # created since 2024-06-14, so product tests run with the mode on, as the
                  # Core Django rows do. Without it a product query runner is only ever
                  # tested in the legacy joined mode, and its snapshots record SQL that no
                  # recent project executes. Tests that need the legacy mode pin it
                  # themselves with override_settings.
                  # marker: product-poe-default. The run block keeps legacy mode if the
                  # checked-out workflow lacks this marker and its matching snapshots.
                  PERSON_ON_EVENTS_V2_ENABLED: 'true'
                  # products/tasks/backend/temporal moved here from the Django Temporal
                  # segment, and its conftest and workflows talk to Modal. Injected only
                  # when that directory changed, matching the gate the Django job used.
                  MODAL_TOKEN_ID: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_ID || '' }}
                  MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
                  AWS_S3_ALLOW_UNSAFE_RENAME: 'true'
                  # --reuse-db: keep the test database between sequential product runs to avoid
                  # ClickHouse drop/create race conditions with ReplicatedMergeTree ZK metadata.
                  # --durations-path: turbo runs products from products/<name>/, so pytest-split
                  # needs an explicit path back to the repo-root durations file for balanced sharding.
                  PYTEST_ADDOPTS: >-
                      --reuse-db
                      --durations-path ../../.test_durations
                      ${{ env.IS_MASTER == 'true' && '--store-durations' || '' }}
                      --junitxml=junit-product.xml
                      ${{ needs.detect-snapshot-mode.outputs.mode == 'update' && '--snapshot-update --snapshot-warn-unused' || '' }}
                      ${{ github.event_name == 'pull_request' && '--cov=backend --cov-report=' || '' }}
                  # turbo runs each product's backend:test with the product dir as CWD, so --cov=backend
                  # scopes coverage to that product and saves its data to products/<name>/.coverage. This works
                  # for bin-packed buckets (each product writes its own file) and split products, whose data
                  # the report job combines.
                  # sysmon: Python 3.12+'s low-overhead coverage backend, ~a few % vs ~20% for the C tracer.
                  COVERAGE_CORE: sysmon
              shell: bash
              run: |
                  set +e
                  # Enable retries only when the checkout includes retry diagnostics.
                  if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
                      export PYTEST_ADDOPTS="$PYTEST_ADDOPTS --force-reruns 1 --reruns-delay 1 -r fEsxXR"
                  fi
                  overall=0
                  # A checkout without the matching snapshots must use legacy mode.
                  if [[ "$PERSON_ON_EVENTS_V2_ENABLED" == "true" ]] && ! grep -qF "marker: product-poe-default" .depot/workflows/ci-backend.yml; then
                      echo "::notice::Checked-out revision predates the person-on-events default, running product tests in legacy mode"
                      export PERSON_ON_EVENTS_V2_ENABLED=false
                  fi
                  # Accept a selector that returns the older flat matrix shape.
                  if [ -z "$PRODUCT_LEGS" ] || [ "$PRODUCT_LEGS" = "null" ]; then
                      PRODUCT_LEGS=$(jq -cn --arg f "$LEGACY_FILTERS" --arg a "$LEGACY_PYTEST_ARGS" \
                          '[{filters: $f, pytest_args: $a}]')
                      echo "Matrix entry carries no legs; running the legacy single invocation"
                  fi
                  leg_count=$(jq 'length' <<< "$PRODUCT_LEGS")
                  # Neither shape present means the job would pass having run no tests, and
                  # the rollup gate only reads this step's outcome. Fail loudly instead.
                  if [ -z "$leg_count" ] || [ "$leg_count" -lt 1 ]; then
                      echo "::error::No test legs in this matrix entry; refusing to pass without running tests"
                      exit 1
                  fi
                  for ((leg_index = 0; leg_index < leg_count; leg_index++)); do
                      leg_filters=$(jq -r ".[$leg_index].filters" <<< "$PRODUCT_LEGS")
                      leg_args=$(jq -r ".[$leg_index].pytest_args" <<< "$PRODUCT_LEGS")
                      echo "::group::turbo backend:test $leg_filters $leg_args"
                      # Word splitting is intended here: both variables carry several flags.
                      # shellcheck disable=SC2086
                      turbo run backend:test $leg_filters --concurrency=1 --output-logs=full --force --log-order=stream $leg_args
                      exit_code=$?
                      echo "::endgroup::"
                      if [ $exit_code -eq 5 ]; then
                          echo "No tests collected for this leg, this is expected when splitting tests"
                      elif [ $exit_code -ne 0 ]; then
                          overall=$exit_code
                      fi
                  done
                  set -e
                  exit $overall

            - name: Prepare product JUnit for Trunk
              id: prepare_product_junit
              if: ${{ always() }}
              shell: bash
              env:
                  PRODUCT_FILTERS: ${{ matrix.filters }}
              run: |
                  bash .github/scripts/prepare-product-junit-for-trunk.sh \
                      trunk-junit \
                      "$PRODUCT_FILTERS"

            - name: Quarantine gate
              id: quarantine_gate
              continue-on-error: true
              if: ${{ !cancelled() && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
              uses: ./.github/actions/trunk-quarantine-gate
              with:
                  junit-paths: trunk-junit/junit-product-*.xml
                  test-collection-id: C0LrorjW # backend-product
                  # A native-JSON leg uploads under its own variant, so a failure in that mode
                  # does not read as a flake of the legacy test with the same id.
                  variant: ${{ matrix.new-events-schema && 'events-json' || '' }}
                  previous-step-outcome: ${{ steps.run-product-tests.outcome }}
                  token: ${{ secrets.TRUNK_API_TOKEN }}

            - name: Fail on test failure
              if: ${{ !cancelled() && (steps.prepare_product_junit.outcome == 'failure' || (steps.run-product-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate.outcome != 'success'))) }}
              shell: bash
              run: exit 1

            - name: Stage product JUnit
              if: ${{ always() }}
              shell: bash
              run: |
                  mkdir -p junit-staging
                  for f in products/*/junit-product.xml; do
                      [ -f "$f" ] || continue
                      cp "$f" "junit-staging/junit-product-$(basename "$(dirname "$f")").xml"
                  done

            - name: Upload product test results
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              if: ${{ always() }}
              with:
                  name: product-junit-results-${{ strategy.job-index }}
                  path: junit-staging/junit-product-*.xml
                  if-no-files-found: ignore
                  overwrite: true # artifacts are immutable per run; re-run shards would 409 otherwise

            - name: Upload timing data
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              # Only the legacy-schema variant uploads durations — both schema variants run the
              # same test IDs, and two artifacts for the same tests would race in the merge.
              # A job whose products have no backend tests writes no JUnit, so it has no fresh
              # timings either. Its artifact would hold only the restored map, and the timing
              # refresh then rejects the whole Products slice because the timing and JUnit shard
              # sets differ.
              if: ${{ env.IS_MASTER == 'true' && !matrix.new-events-schema && hashFiles('junit-staging/junit-product-*.xml') != '' }}
              with:
                  name: timing_data-Products-${{ strategy.job-index }}
                  path: .test_durations
                  include-hidden-files: true
                  retention-days: 2

            - name: Stage product coverage
              # Rename each products/<name>/.coverage to <name>.coverage so the product name
              # survives upload-artifact's least-common-ancestor path collapse.
              if: ${{ always() && github.event_name == 'pull_request' }}
              shell: bash
              run: |
                  mkdir -p cov-staging
                  for f in products/*/.coverage; do
                      [ -f "$f" ] || continue
                      product=$(basename "$(dirname "$f")")
                      cp "$f" "cov-staging/${product}.coverage"
                  done

            - name: Upload product coverage
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              # always(): a failing test shard still has partial coverage worth reporting.
              if: ${{ always() && github.event_name == 'pull_request' }}
              with:
                  name: coverage-products-${{ strategy.job-index }}
                  path: cov-staging/*.coverage
                  if-no-files-found: ignore
                  retention-days: 2
                  overwrite: true # artifacts are immutable per run; re-run shards would 409 otherwise

            - name: Verify new snapshots for flakiness
              if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
              shell: bash
              # The reruns must write the same schema mode's snapshot file as the main
              # run, or the new-schema file removed before each rerun never comes back.
              env:
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
              run: |
                  .github/scripts/verify-new-snapshots.sh

            - name: Generate snapshot patch
              if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
              shell: bash
              env:
                  NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
              run: |
                  mkdir -p /tmp/patches
                  git add -N '*.ambr' || true
                  # Same leg scoping as the django job: a leg may only ship its own
                  # schema mode's snapshot files (see the comment there).
                  if [[ "$NEW_EVENTS_SCHEMA" == "true" ]]; then
                    ambr_pathspec=('*.new_events_schema.ambr')
                  else
                    ambr_pathspec=('*.ambr' ':(exclude)*.new_events_schema.ambr')
                  fi
                  if ! git diff --quiet -- "${ambr_pathspec[@]}" 2>/dev/null; then
                    git diff --binary --full-index -- "${ambr_pathspec[@]}" > /tmp/patches/backend-Products-${{ strategy.job-index }}.patch
                    echo "Generated patch with $(wc -l < /tmp/patches/backend-Products-${{ strategy.job-index }}.patch) lines"
                  else
                    echo "No snapshot changes to patch"
                  fi

            - name: Upload snapshot patch
              if: ${{ always() && needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: snapshot-patch-Products-${{ strategy.job-index }}
                  path: /tmp/patches/
                  if-no-files-found: ignore
                  retention-days: 1

    # Lightweight repo-wide checks that only need Python + uv (no Docker/DB).
    # Consolidates checks that previously each spun up their own runner.
    # Every PostHog SDK this repo installs must stay on its pinned major; the release
    # bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.
    sdk-major-guard:
        needs: [changes]
        if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'schedule'
        timeout-minutes: 5
        permissions:
            contents: read
        name: SDK major-version guard (depot-ubuntu-24.04)
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            - name: Check every SDK stays on its pinned major
              run: python3 .github/scripts/check_sdk_majors.py

    repo-checks:
        needs: [changes]
        # product_yamls: ownership-only PRs still need the owners.yaml lint below.
        if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'schedule'
        timeout-minutes: 10
        outputs:
            deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
        permissions:
            contents: read
            pull-requests: read # list PR files for the deleted-migration check
        name: Repo checks (depot-ubuntu-24.04)
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
                  skip-token-revoke: true
            - name: Set up Python
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            - name: Install uv
              uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false
            - name: Install Python dependencies
              timeout-minutes: 5
              retry: 1
              run: UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            # Block deleting historical migration files (see safe-django-migrations.md).
            # Two steps, so a failed PR-files read fails the job instead of handing the
            # check an empty list. The read uses the ambient token, which only reads here.
            # Above the boundary: a gh-api flake here is retryable setup, not a
            # run-cancelling deterministic failure. The classifier runs below.
            - name: Fetch deleted migration paths
              id: fetch-deleted-migrations
              if: github.event_name == 'pull_request' && needs.changes.outputs.migrations_any == 'true'
              env:
                  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
                  REPO: ${{ github.repository }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
              run: .github/scripts/list-removed-renamed-paths.sh > "$RUNNER_TEMP/deleted-migration-paths.txt"
            # Above the boundary for the same reason. product:lint compares the crossings ledger
            # with the merge commit's first parent, so the clone needs one more level of history.
            - name: Fetch the pull request base
              if: github.event_name == 'pull_request'
              run: |
                  git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
                  git fetch --no-tags --depth=2 origin "$GITHUB_SHA"
              retry: 2
            # Boundary between network-dependent setup and the deterministic
            # checks below. The "Flag deterministic failure" step keys off this
            # step's outcome so a transient setup failure doesn't cancel the run.
            - name: Mark setup complete
              id: setup-complete
              run: echo "Setup complete — any failure below is a deterministic check failure"
            - name: Check deleted migrations
              if: steps.fetch-deleted-migrations.outcome == 'success'
              run: ./bin/hogli lint:migration-deletions < "$RUNNER_TEMP/deleted-migration-paths.txt"
            - name: Bootstrap scaffold product
              run: ./bin/hogli product:bootstrap spline_reticulator --non-interactive
            - name: Lint product structure
              env:
                  CROSSINGS_LEDGER_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }}
              run: ./bin/hogli product:lint --all
            # Distributed owners.yaml tree: schema, product.yaml/owners.yaml
            # conflicts, dead rule globs, coverage (warn-only). No --live, so no
            # secrets — fork PRs get validated too (the --live slug check runs in
            # the fork-gated validate-product-yamls job instead).
            - parallel:
                  - name: Lint owners.yaml files
                    run: ./bin/hogli owners:lint
                  - name: Check version specifiers
                    run: python .github/scripts/check-version-specifiers.py
                  - name: Check IDOR model coverage
                    run: python .github/scripts/check-idor-model-coverage.py
                  - name: Check DWH presentation layer stays source-agnostic
                    run: python .github/scripts/check-dwh-source-agnostic.py
                  - name: Check operator parity
                    run: python .github/scripts/check-operator-parity.py
                  - name: Check module boundaries (tach)
                    # Two passes: tests are in the interface graph but not the dependency graph.
                    # A branch that predates the command still excludes tests in tach.toml, so
                    # the old single pass is the right check there.
                    run: |
                        if ./bin/hogli lint:tach --help >/dev/null 2>&1; then
                            ./bin/hogli lint:tach
                        else
                            tach check --dependencies --interfaces
                        fi
                  - name: Check product facade enforcement (import-linter)
                    run: lint-imports
                  # These guards take the whole repo as input (import graph after
                  # django.setup(), signal registries, repo-wide AST scans), so diff-based
                  # test selection can't pick them and the Django matrix skips them on
                  # products-only diffs and drafts. They need no service containers.
                  # Branches that predate the directory still carry the guards at their
                  # old paths, so fall back to those rather than failing on a missing arg.
                  - name: Run repo invariants (whole-repo pytest guards)
                    run: |
                        if [ -d posthog/test/repo_invariants ]; then
                            pytest -p no:cacheprovider posthog/test/repo_invariants
                        else
                            pytest -p no:cacheprovider posthog/test/test_startup_import_budget.py posthog/test/test_dataclass_defaults.py
                        fi
            # New files in `ee/` need a human decision, and a path comparison sees an empty
            # file that a content scan cannot. Exemptions live in the script.
            - name: Check for new files under ee/
              if: github.event_name == 'pull_request'
              run: python .github/scripts/check-no-new-ee-files.py --against HEAD^1 --committed
            # Deterministic = a static check above failed after setup completed.
            # A retry can't fix it, so this signals the cancellation gate to stop the run.
            - name: Flag deterministic failure
              id: deterministic-failure
              if: failure() && steps.setup-complete.outcome == 'success'
              run: echo "deterministic_failure=true" >> "$GITHUB_OUTPUT"

    cancel-backend-on-repo-check-failure:
        needs: [repo-checks]
        if: >
            always() &&
            needs.repo-checks.outputs.deterministic_failure == 'true' &&
            github.event_name == 'pull_request' &&
            github.event.pull_request.head.repo.full_name == github.repository
        timeout-minutes: 5
        permissions:
            contents: read
        name: Cancel Backend CI after repo check failure
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
            - name: Cancel run
              env:
                  DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}
                  REPO: ${{ github.repository }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
                  HEAD_SHA: ${{ github.event.pull_request.head.sha }}
              run: |
                  echo "::notice title=Repo checks failed deterministically::Canceling remaining Backend CI jobs. A retry cannot fix this failure; push a fix to start a new run."
                  depot ci workflow list --repo "$REPO" --pr "$PR_NUMBER" --status running -o json \
                      | jq -r --arg sha "$HEAD_SHA" '.[] | select(.workflow_path == "ci-backend.yml" and .head_sha == $sha) | "\(.run_id) \(.workflow_id)"' \
                      | while read -r run workflow; do depot ci cancel "$run" --workflow "$workflow"; done

    validate-product-yamls:
        needs: [changes]
        if: >
            needs.changes.outputs.product_yamls == 'true' &&
            github.event_name == 'pull_request' &&
            github.event.pull_request.head.repo.full_name == github.repository
        timeout-minutes: 5
        name: Validate product.yaml owners (depot-ubuntu-24.04)
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            - name: Get app token
              id: app-token
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_PRIVATE_KEY }}
                  owner: ${{ github.repository_owner }}
                  repositories: ${{ github.event.repository.name }}
            - name: Set up Python
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ steps.app-token.outputs.token || github.token }}
            - name: Install uv
              uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false
            - name: Install Python dependencies
              run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
            - name: Validate changed product.yaml owners
              env:
                  GH_TOKEN: ${{ steps.app-token.outputs.token }}
                  CHANGED_FILES: ${{ needs.changes.outputs.product_yamls_files }}
              run: |
                  mapfile -t names < <(echo "$CHANGED_FILES" | tr ' ' '\n' | sed -n 's|^products/\([^/]*\)/product.yaml$|\1|p')
                  existing=()
                  for n in "${names[@]}"; do
                    [ -f "products/$n/product.yaml" ] && existing+=("$n")
                  done
                  if [ "${#existing[@]}" -eq 0 ]; then
                    echo "No existing product.yaml files in diff after filtering"
                    exit 0
                  fi
                  ./bin/hogli product:lint:owners "${existing[@]}"
            - name: Validate owners.yaml identities against GitHub
              env:
                  GH_TOKEN: ${{ steps.app-token.outputs.token }}
                  CHANGED_FILES: ${{ needs.changes.outputs.product_yamls_files }}
              # Scoped to the diff: unscoped, one stale slug fails every owners.yaml PR.
              # xargs re-parses the paths-filter escape format, keeping escaped paths whole.
              run: printf '%s' "$CHANGED_FILES" | xargs -r ./bin/hogli owners:lint --live

    # Migration validation.
    # This job needs Docker + DB. Master is checked out beside the comparison
    # branch so repository switches cannot disturb live Compose bind mounts.
    check-migrations:
        needs: [changes]
        # migration_replay is listed because it reaches files the others miss:
        # products/db_routing.yaml is neither Python nor under a backend/ directory, and
        # a migration in a future top-level app matches none of them. Without it the
        # replay gate could be on while the job that runs it never starts.
        if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.migrations == 'true' || needs.changes.outputs.migration_replay == 'true') && github.event_name != 'schedule'
        # On master this job replays the full migration history from scratch to
        # produce the schema dump every PR job restores, and a merge queue batch that
        # changes a Django migration replays it a second time onto an empty database.
        # That replay grows with every merged migration, so the limit needs headroom
        # over two of them: it is there to cancel a hang, not to cap how long the
        # history takes.
        timeout-minutes: 60
        name: Validate migrations
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  clean: false
            - name: Clean up data directories with container permissions
              run: |
                  # Use docker to clean up files created by containers
                  [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
              continue-on-error: true
            - name: Log in to Docker Hub
              if: ${{ vars.DOCKERHUB_USER != '' && secrets.DOCKERHUB_TOKEN != '' }}
              continue-on-error: true
              uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
              with:
                  username: ${{ vars.DOCKERHUB_USER }}
                  password: ${{ secrets.DOCKERHUB_TOKEN }}
            - name: Stop/Start stack with Docker Compose
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
              run: nohup bin/ci-wait-for-docker launch --background --down db redis7 clickhouse </dev/null >"${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>&1
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
                  skip-token-revoke: true
            - name: Set up Python
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            # Direct install: The job later checks out the PR head, which may predate the local action, so its post step would fail.
            - name: Install uv
              id: setup-uv
              uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
              with:
                  version: '0.13.4'
                  enable-cache: true
                  cache-dependency-glob: uv.lock
                  save-cache: ${{ env.IS_MASTER == 'true' }}
                  prune-cache: true
            - name: Install SAML (python3-saml) dependencies
              if: steps.setup-uv.outputs.cache-hit != 'true'
              run: |
                  sudo rm -f /etc/apt/sources.list.d/*twingate*
                  sudo apt-get update
                  sudo apt-get install libxml2-dev libxmlsec1-dev libxmlsec1-openssl
              retry: 2
            - name: Install sqlx-cli
              uses: ./.depot/actions/setup-sqlx-cli
            # First running migrations from master, to simulate the real-world scenario
            - name: Checkout upstream master
              uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  repository: PostHog/posthog
                  # The schema dump takes its cache key from the pushed commit, so a push
                  # migrates from that commit. A newer master can carry migrations that the
                  # pushed commit does not have.
                  ref: ${{ github.event_name == 'push' && github.sha || 'master' }}
                  path: upstream-master
            - name: Install python dependencies for master
              working-directory: upstream-master
              timeout-minutes: 5
              retry: 1
              run: |
                  UV_PROJECT_ENVIRONMENT=.venv-master timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev --no-install-package pytest-split
            - name: Compute master schema cache key
              # Keyed off the master checkout (HEAD here), so an exact hit is the state
              # that "Run migrations up to master" would build from scratch.
              if: github.event_name != 'push'
              id: master-schema-key
              run: |
                  KEY=$(upstream-master/.venv-master/bin/python .github/scripts/master_schema_cache.py \
                      --repository upstream-master --epoch "$SCHEMA_CACHE_EPOCH" key)
                  echo "key=$KEY" >> "$GITHUB_OUTPUT"
            - name: Restore master schema dump from cache
              id: master-schema-cache
              if: github.event_name != 'push' && steps.master-schema-key.outputs.key != ''
              timeout-minutes: 4
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  key: ${{ steps.master-schema-key.outputs.key }}
                  # The newest master snapshot is the one most likely to pass the check below.
                  # A merge queue or stacked base has no saved dump, and an older PR base often
                  # predates a uv.lock change that the check rejects.
                  restore-keys: |
                      posthog-schema-master-
            - name: Validate fallback master schema
              id: validate-master-schema
              if: steps.master-schema-cache.outputs.cache-matched-key != '' && steps.master-schema-cache.outputs.cache-matched-key != steps.master-schema-key.outputs.key
              env:
                  CACHED_KEY: ${{ steps.master-schema-cache.outputs.cache-matched-key }}
              run: >-
                  upstream-master/.venv-master/bin/python .github/scripts/master_schema_cache.py
                  --repository upstream-master --epoch "$SCHEMA_CACHE_EPOCH"
                  validate --dump schema.sql.gz --cache-key "$CACHED_KEY"
            - name: Wait for Docker services
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
              run: |
                  bin/ci-wait-for-docker wait --only db redis7 clickhouse \
                    || { echo "::group::compose launch log"; cat "${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>/dev/null || true; echo "::endgroup::"; exit 1; }
            - name: Prime posthog DB from cached schema
              # Leaves "Run migrations up to master" below to apply only the migrations
              # the dump lacks, instead of a full migration run.
              if: github.event_name != 'push'
              run: |
                  if [ ! -f schema.sql.gz ]; then
                      echo "::notice::Master schema cache miss — the next step runs all migrations from scratch"
                      exit 0
                  fi
                  # The load is atomic: on failure the transaction rolls back and
                  # the fallback below recreates an empty DB for a full migrate.
                  # The migrate in the next step seeds the data-migration rows the
                  # schema-only dump lacks.
                  if gunzip -c schema.sql.gz | docker compose -f docker-compose.dev.yml exec -T db psql -q -v ON_ERROR_STOP=1 --single-transaction -U posthog posthog > /dev/null; then
                      echo "Primed posthog DB from cached master schema"
                  else
                      echo "::warning::Cached schema restore failed — recreating empty DB; the next step runs all migrations from scratch"
                      # Terminate lingering sessions first or DROP DATABASE fails
                      # (same guard as _recreate_database in hogli's db_schema.py).
                      docker compose -f docker-compose.dev.yml exec -T db psql -U posthog postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'posthog' AND pid <> pg_backend_pid();"
                      docker compose -f docker-compose.dev.yml exec -T db psql -U posthog postgres -c "DROP DATABASE IF EXISTS posthog;"
                      docker compose -f docker-compose.dev.yml exec -T db psql -U posthog postgres -c "CREATE DATABASE posthog;"
                  fi
                  rm -f schema.sql.gz
            - name: Run migrations up to master
              working-directory: upstream-master
              run: |
                  # Run Django migrations first (excluding managed=False models)
                  .venv-master/bin/python manage.py migrate
                  # Then run persons migrations using sqlx; comment out until we've merged
                  # DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
                  #   sqlx database create
                  # DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
                  #   sqlx migrate run --source rust/persons_migrations/
            - name: Register upstream baseline for migration checks
              run: git fetch --no-tags --prune --depth=1 "$GITHUB_WORKSPACE/upstream-master" HEAD:refs/remotes/upstream/master
            # Now we can consider this PR's migrations
            - name: Checkout this PR
              uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  # For same-repo PRs, checkout the PR head commit (not the merge commit)
                  # so upstream/master..HEAD reflects PR files. Fork PRs fall back
                  # to the default merge commit. The SHA, not the branch name, because
                  # Trunk can delete a trunk-merge/ branch before this step runs.
                  ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.sha || github.event_name == 'push' && github.sha || github.ref }}
                  clean: false
            - name: Install python dependencies for this PR
              timeout-minutes: 5
              retry: 1
              run: |
                  UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            - name: Get app token for CI report
              # Depot's ambient token must not write, so the CI report sections post with a
              # posthog-tests token that can write pull requests and nothing else. When the
              # mint fails, the CI report check below marks the report unavailable, so a mint
              # failure never reddens migration validation.
              if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
              id: ci-report-app-token
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-pull-requests: write
            - name: Set up Node.js
              if: steps.ci-report-app-token.outputs.token != ''
              continue-on-error: true
              uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
              with:
                  node-version-file: .nvmrc
                  token: ${{ steps.ci-report-app-token.outputs.token }}
            - name: Check for CI report tooling
              # A checkout whose update-ci-report.mjs does not adopt tests-posthog[bot] comments
              # would add a new comment on every write, so the report steps skip it.
              id: ci-report
              if: steps.ci-report-app-token.outputs.token != ''
              run: |
                  if command -v node > /dev/null && grep -qF 'tests-posthog[bot]' frontend/bin/ci-report/update-ci-report.mjs 2>/dev/null; then
                      echo "available=true" >> "$GITHUB_OUTPUT"
                  else
                      echo "Skipping the CI report sections: Node.js is missing, or this checkout predates Depot CI authorship"
                  fi
            - name: Check migrations and post SQL to CI report
              if: github.event_name == 'pull_request' && needs.changes.outputs.migrations == 'true'
              env:
                  CI_REPORT_TOKEN: ${{ steps.ci-report.outputs.available == 'true' && steps.ci-report-app-token.outputs.token || '' }}
                  CHANGED_FILES: ${{ needs.changes.outputs.migrations_review_files }}
                  BASE_SHA: ${{ github.event.pull_request.base.sha }}
              run: |
                  # The PR checkout above uses the PR head commit, which on unrebased PRs
                  # predates this script, so skip the CI report section rather than fail.
                  # An empty token would leave the ambient Depot token in place, so the
                  # section skips without one too.
                  post_migration_section() {
                    if [ -z "$CI_REPORT_TOKEN" ]; then
                      echo "Skipping Django migration section: the CI report is not available"
                    elif [ -f .github/scripts/post-django-migration-section.mjs ]; then
                      GITHUB_TOKEN="$CI_REPORT_TOKEN" node .github/scripts/post-django-migration-section.mjs "$@"
                    else
                      echo "Skipping Django migration section — script not present on this checkout"
                    fi
                  }

                  # If no migration files changed, exit
                  if [ -z "$CHANGED_FILES" ]; then
                    echo "No migration files changed"
                    echo "No new Django migrations need SQL review." > /tmp/django-migration-sql.md
                    post_migration_section sql clear ok "no new migrations" /tmp/django-migration-sql.md
                    exit 0
                  fi

                  if [ -z "$BASE_SHA" ]; then
                    echo "::warning::BASE_SHA is empty — all changed migrations will be treated as new"
                  else
                    # Ensure the base commit is available for comparison
                    git fetch --no-tags --prune --depth=1 origin "$BASE_SHA" || echo "::warning::Could not fetch base SHA $BASE_SHA — all changed migrations will be shown as new"
                  fi

                  COMMENT_BODY="We've detected new migrations on this PR. Review the SQL output for each migration:\n\n"
                  HAS_NEW_MIGRATIONS=false
                  MIGRATION_COUNT=0
                  mapfile -t migration_files < <(tr ' ' '\n' <<< "$CHANGED_FILES")

                  # Process each changed migration file (excluding Rust migrations)
                  for file in "${migration_files[@]}"; do
                    [ -n "$file" ] || continue
                    # Skip Rust migrations as they're handled separately by sqlx
                    if [[ $file =~ rust/persons_migrations ]]; then
                      continue
                    fi
                    # Full migration name, not the bare numeric prefix: squash
                    # files (0001_squash_*) share prefixes with the historical
                    # files they replace, and sqlmigrate errors on an ambiguous
                    # prefix.
                    if [[ $file =~ migrations/([0-9]+_[^/]+)\.py$ ]]; then
                      migration_number="${BASH_REMATCH[1]}"
                      # Get app name by looking at the directory structure
                      # For new structure products/user_interviews/backend/migrations, we want user_interviews
                      # For old structure products/user_interviews/migrations, we want user_interviews
                      if [[ $file =~ products/([^/]+)/backend/migrations/ ]]; then
                        app_name="${BASH_REMATCH[1]}"
                      else
                        app_name=$(sed -E 's|^([^/]+/)*([^/]+)/migrations/.*|\2|' <<< "$file")
                      fi

                      # A stacked PR can carry master's migration at this path. Keep a
                      # conflicting version visible even when master has the same path.
                      if git cat-file -e "$BASE_SHA:$file" 2>/dev/null || git diff --quiet upstream/master HEAD -- "$file"; then
                        echo "Skipping $file (already exists on the base branch or matches master)"
                        continue
                      fi

                      # Generated squash files carry replaces= lists thousands
                      # of names long; their SQL dump is unreviewable and the
                      # state replay per file adds up across an entire squash
                      # PR. Detect by content, not by name, so the check can't
                      # go stale.
                      if grep -q "replaces = \[" "$file"; then
                        echo "Skipping $file (squash migration)"
                        continue
                      fi

                      HAS_NEW_MIGRATIONS=true
                      MIGRATION_COUNT=$((MIGRATION_COUNT + 1))
                      echo "Checking migration $migration_number for app $app_name"

                      # Get SQL output. A sqlmigrate failure degrades to a
                      # placeholder — this comment is informational, and the
                      # real migrate step below still gates the job.
                      if ! SQL_OUTPUT=$(python manage.py sqlmigrate "$app_name" "$migration_number" 2>&1); then
                        echo "::warning::sqlmigrate failed for $app_name $migration_number — see job log"
                        SQL_OUTPUT="-- sqlmigrate failed for this migration (see the Validate migrations job log)"
                      fi

                      COMMENT_BODY+="#### [\`$file\`](https://github.com/${{ github.repository }}/blob/${{ github.sha }}/$file)\n\`\`\`sql\n$SQL_OUTPUT\n\`\`\`\n\n"
                    fi
                  done

                  if [ "$HAS_NEW_MIGRATIONS" = false ]; then
                      echo "No new migrations to show (all changed files already exist on base branch)"
                      echo "No new Django migrations need SQL review." > /tmp/django-migration-sql.md
                      post_migration_section sql clear ok "no new migrations" /tmp/django-migration-sql.md
                      exit 0
                  fi

                  TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')
                  COMMIT_SHA="${{ github.event.pull_request.head.sha }}"
                  COMMIT_SHORT="${COMMIT_SHA:0:7}"
                  COMMENT_BODY+="\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"

                  COMMENT_BODY=$(printf '%b' "$COMMENT_BODY")
                  printf '%s' "$COMMENT_BODY" > /tmp/django-migration-sql.md
                  if [ "$MIGRATION_COUNT" -eq 1 ]; then
                    MIGRATION_SUMMARY="1 new migration to review"
                  else
                    MIGRATION_SUMMARY="$MIGRATION_COUNT new migrations to review"
                  fi
                  post_migration_section sql post warn "$MIGRATION_SUMMARY" /tmp/django-migration-sql.md

            - name: Run migration risk analysis and update CI report
              if: github.event_name == 'pull_request'
              # Step timeout: an analyzer hang fails THIS step (a failure, which
              # !cancelled() still publishes as a definitive verdict) instead of
              # running out the job timeout. A job timeout counts as a
              # cancellation, which the publish step skips, silently stranding
              # the consumer. Normal analysis finishes in well under a minute.
              timeout-minutes: 5
              env:
                  CI_REPORT_TOKEN: ${{ steps.ci-report.outputs.available == 'true' && steps.ci-report-app-token.outputs.token || '' }}
              run: |
                  # The PR checkout above uses the PR head commit, which on unrebased PRs
                  # predates this script, so skip the CI report section rather than fail.
                  # An empty token would leave the ambient Depot token in place, so the
                  # section skips without one too.
                  post_migration_section() {
                    if [ -z "$CI_REPORT_TOKEN" ]; then
                      echo "Skipping Django migration section: the CI report is not available"
                    elif [ -f .github/scripts/post-django-migration-section.mjs ]; then
                      GITHUB_TOKEN="$CI_REPORT_TOKEN" node .github/scripts/post-django-migration-section.mjs "$@"
                    else
                      echo "Skipping Django migration section — script not present on this checkout"
                    fi
                  }

                  # Get risk analysis for all unapplied migrations (including third-party).
                  # --output-json gives downstream consumers (the check-run step
                  # below, and any other tool) a stable structured shape to read.
                  set +e
                  RISK_ANALYSIS=$(python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json 2>/dev/null)
                  EXIT_CODE=$?
                  set -e

                  if [ -n "$RISK_ANALYSIS" ]; then
                    echo "$RISK_ANALYSIS" > migration_analysis.md
                  fi

                  if [ -n "$RISK_ANALYSIS" ] && echo "$RISK_ANALYSIS" | grep -q "Summary:"; then
                    TIMESTAMP=$(date -u '+%Y-%m-%d %H:%M UTC')
                    COMMIT_SHA="${{ github.event.pull_request.head.sha }}"
                    COMMIT_SHORT="${COMMIT_SHA:0:7}"
                    RISK_COMMENT="We've analyzed your migrations for potential risks.\n\n$RISK_ANALYSIS\n\n*Last updated: $TIMESTAMP ([${COMMIT_SHORT}](https://github.com/${{ github.repository }}/commit/${COMMIT_SHA}))*"
                    RISK_COMMENT=$(printf '%b' "$RISK_COMMENT")
                    printf '%s' "$RISK_COMMENT" > /tmp/django-migration-risk.md
                    if [ $EXIT_CODE -ne 0 ]; then
                      post_migration_section risk post fail "blocked migration detected" /tmp/django-migration-risk.md
                    else
                      post_migration_section risk post ok "migration analysis complete" /tmp/django-migration-risk.md
                    fi
                  elif [ $EXIT_CODE -ne 0 ]; then
                    echo "Migration risk analysis failed. Check the workflow logs for details." > /tmp/django-migration-risk.md
                    post_migration_section risk post fail "migration analysis failed" /tmp/django-migration-risk.md
                  else
                    echo "No Django migrations need risk analysis." > /tmp/django-migration-risk.md
                    post_migration_section risk clear ok "no migrations to analyze" /tmp/django-migration-risk.md
                  fi

                  # Fail the job if there were blocked migrations
                  if [ $EXIT_CODE -ne 0 ]; then
                    exit $EXIT_CODE
                  fi

            - name: Get app token for Migration risk check
              # A separate token with checks:write only, minted after the steps that run
              # PR code, so that code never holds a token that can publish this check.
              # continue-on-error: publishing the check is auxiliary. On failure the
              # token output is empty and the publish step below is skipped.
              if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false }}
              id: migration-risk-app-token
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-checks: write

            - name: Publish Migration risk check
              # Migration risk classification is published as a GitHub check on
              # the head commit so it shows up in the PR UI alongside CI checks
              # and so any tool that already reads check_runs (review bots,
              # branch-protection rules, dashboards) can consume it without
              # parsing the comment. The check is a CI feature; consumers and
              # the analyzer are decoupled.
              #
              # Published via the posthog-tests app token (see the token step
              # above) so the check lands in that app's own check suite.
              #
              # Published on success or genuine failure (including an analyzer
              # crash, or zero migrations to analyze) so every PR ends up with a
              # definitive verdict on its head SHA. Consumers can then treat
              # "no completed check yet" purely as "CI hasn't finished" and
              # don't need a fallback heuristic.
              #
              # !cancelled(): a cancelled job skipped the analyzer, leaving no
              # migration_analysis.json, so an always() publish would stamp a
              # spurious "❌ Analyzer failed". The newer run that superseded it
              # publishes the real verdict; genuine crashes still publish here.
              #
              # Also skipped when the token step failed: its output is then
              # empty and the check-runs POST would fall back to the ambient
              # Depot token.
              if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false && steps.migration-risk-app-token.outputs.token != '' }}
              env:
                  GH_TOKEN: ${{ steps.migration-risk-app-token.outputs.token }}
                  HEAD_SHA: ${{ github.event.pull_request.head.sha }}
                  REPO: ${{ github.repository }}
              # A repeated POST adds a second identical check run, and GitHub shows the newest one.
              retry:
                  retries: 3
                  backoff: exponential
                  delay-seconds: 5
              run: |
                  if [ ! -f migration_analysis.json ]; then
                    # Analyzer crashed before writing JSON. Publish a failure
                    # check so stamphog (or any consumer) gets a definitive
                    # verdict instead of looping in "wait for the check."
                    echo "No migration_analysis.json — analyzer didn't run; publishing failure check"
                    jq -n \
                      --arg name "Migration risk" \
                      --arg head_sha "$HEAD_SHA" \
                      '{name: $name, head_sha: $head_sha, status: "completed",
                        conclusion: "failure",
                        output: {title: "❌ Analyzer failed",
                                 summary: "<!-- stamphog:v1 [] -->\nMigration analyzer did not produce migration_analysis.json. Re-run the Backend CI job; if it keeps failing, inspect the analyzer step logs."}}' \
                      | gh api "repos/$REPO/check-runs" --method POST --input -
                    exit 0
                  fi

                  MAX_LEVEL=$(jq -r '.max_level // "none"' migration_analysis.json)

                  case "$MAX_LEVEL" in
                    "Safe")          CONCLUSION=success; TITLE="✅ All migrations safe" ;;
                    "Needs Review")  CONCLUSION=neutral; TITLE="⚠️ Needs review" ;;
                    "Blocked")       CONCLUSION=failure; TITLE="❌ Blocked migrations" ;;
                    "none"|"null")
                      # Zero Django migrations to analyze. Publish success so
                      # PRs that touch only ClickHouse/async/rbac migrations
                      # (which the analyzer doesn't cover) don't leave
                      # consumers waiting on a check that would never come.
                      CONCLUSION=success
                      TITLE="✅ No Django migrations to analyze"
                      ;;
                    *)
                      echo "Unknown max_level '$MAX_LEVEL' — publishing failure"
                      CONCLUSION=failure
                      TITLE="❌ Unknown analyzer output"
                      ;;
                  esac

                  # Embed the analyzed file paths in the summary as a hidden
                  # marker. Stamphog parses this to scope its deny-list bypass
                  # to exactly the files the analyzer classified, because heuristics
                  # over directory names produce false bypasses for unrelated
                  # systems (ClickHouse, async migrations) that share the
                  # `migrations/` directory naming.
                  ANALYZED_PATHS=$(jq -c '[.migrations[].file_path | select(. != null)]' migration_analysis.json 2>/dev/null || echo '[]')
                  MARKER="<!-- stamphog:v1 ${ANALYZED_PATHS} -->"

                  # Truncate the human report to fit the check-run output
                  # limit (~64KB); the full markdown is also posted in the CI
                  # report for humans. The marker stays at the top so it's
                  # never lost to truncation.
                  REPORT_BODY=$(head -c 59000 migration_analysis.md 2>/dev/null || echo "See the CI report")
                  SUMMARY=$(printf '%s\n%s' "$MARKER" "$REPORT_BODY")

                  jq -n \
                    --arg name "Migration risk" \
                    --arg head_sha "$HEAD_SHA" \
                    --arg conclusion "$CONCLUSION" \
                    --arg title "$TITLE" \
                    --arg summary "$SUMMARY" \
                    '{name: $name, head_sha: $head_sha, status: "completed",
                      conclusion: $conclusion,
                      output: {title: $title, summary: $summary}}' \
                    | gh api "repos/$REPO/check-runs" --method POST --input -

            - name: Upload migration analysis artifact
              if: ${{ always() && github.event_name == 'pull_request' }}
              timeout-minutes: 7
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: migration-analysis
                  path: |
                      migration_analysis.md
                      migration_analysis.json
                  if-no-files-found: ignore

            - name: Run migrations for this PR
              run: |
                  # Run Django migrations first (excluding managed=False models)
                  python manage.py migrate
                  # Then run persons migrations using sqlx
                  DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
                    sqlx migrate run --source rust/persons_migrations/
            - name: Replay the full migration history from scratch
              # The steps above prime the database from the cached master schema dump, so
              # the migrate that follows only applies the migrations this branch adds.
              # That hides a branch whose new migration moves an older one's position in
              # the plan, because the older one is already recorded as applied and never
              # runs against its new neighbours. A replay onto an empty database is the
              # only step that runs the whole history in the order this branch produces.
              # Master pushes already replay from scratch, which is where such a break
              # surfaces today, one merge too late.
              #
              # Queue lane only. The trunk-merge/** branch is master plus the batch, so it
              # sees the ordering every merged migration produces together; a PR branch
              # sees it only while it is current with master. The replay is by far the
              # most expensive part of this job, so paying it once per batch rather than
              # on every push of every migration branch is what keeps it affordable.
              if: github.event_name == 'pull_request' && startsWith(github.head_ref, 'trunk-merge/') && needs.changes.outputs.migration_replay == 'true'
              env:
                  REPLAY_DB: posthog_migration_replay
              run: |
                  set -euo pipefail
                  docker compose -f docker-compose.dev.yml exec -T db psql -q -U posthog postgres \
                      -c "DROP DATABASE IF EXISTS ${REPLAY_DB};" \
                      -c "CREATE DATABASE ${REPLAY_DB};"
                  if ! DATABASE_URL="postgres://posthog:posthog@localhost:5432/${REPLAY_DB}" python manage.py migrate; then
                      echo "::error::The migration history does not apply to an empty database. A merge to master fails the same way. Read the traceback above for the migration that stopped, and check whether another migration this branch adds moved it in the plan."
                      exit 1
                  fi
            - name: Dump migrated schema
              if: github.event_name == 'push'
              run: |
                  set -e
                  set -o pipefail
                  # Dump schema + django_migrations data so Django knows which migrations are applied
                  # Run pg_dump inside container to ensure version match (host has pg_dump 16, container has 15)
                  (docker compose -f docker-compose.dev.yml exec -T db pg_dump --schema-only --clean --if-exists -U posthog posthog && \
                   docker compose -f docker-compose.dev.yml exec -T db pg_dump --data-only --table=django_migrations -U posthog posthog) | gzip > schema.sql.gz
                  # Verify the dump is valid
                  gunzip -t schema.sql.gz

            - name: Compute migration-set schema key
              if: github.event_name == 'push'
              id: mig-schema-key
              run: |
                  KEY=$(python .github/scripts/master_schema_cache.py --repository . --epoch "$SCHEMA_CACHE_EPOCH" key)
                  if [ -z "$KEY" ]; then
                      echo "::notice::no migration files matched, so the migration-set schema save is skipped"
                  fi
                  echo "key=$KEY" >> $GITHUB_OUTPUT
                  printf '%s' "$KEY" > schema-cache-key
            - name: Upload migrated schema artifact
              if: ${{ github.event_name == 'push' }}
              timeout-minutes: 7
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: migrated-schema
                  # .github/workflows/ci-backend-schema-mirror.yml copies the dump into GitHub
                  # artifacts and cache; the key file tells it the migration-set cache key.
                  path: |
                      schema.sql.gz
                      schema-cache-key
                  # Consumers only ever take the newest artifact, so a longer window just
                  # adds pages to the artifacts listing that db:download-schema walks.
                  retention-days: 7
            - name: Save schema to Actions cache for PR shards
              # Consumers restore this key by their PR base or merge base. check-migrations
              # also restores the newest one by prefix and validates it first.
              if: github.event_name == 'push'
              uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  key: posthog-schema-master-${{ github.sha }}
            - name: Save schema to Actions cache (migration-set key)
              if: github.event_name == 'push' && steps.mig-schema-key.outputs.key != ''
              uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  key: ${{ steps.mig-schema-key.outputs.key }}
            - name: Check migrations
              # Skip migration safety check on master push (no migration_files from path filter)
              if: github.event_name != 'push'
              run: |
                  DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
                    sqlx migrate info --source rust/persons_migrations/
                  python manage.py makemigrations --check --dry-run
            - name: List this PR's ClickHouse migrations
              env:
                  BASE_SHA: ${{ github.event.pull_request.base.sha }}
              run: |
                  set -euo pipefail
                  export LC_ALL=C
                  DIFF_BASE=upstream/master
                  if [ -n "$BASE_SHA" ]; then
                      if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
                          git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
                          git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_SHA"
                      fi
                      DIFF_BASE="$BASE_SHA"
                  fi
                  ch_migrations() {
                      # Migrations share most of their text, so rename detection would pair this PR's
                      # migration with one master added later and report it as R, dropping it here.
                      git diff --no-renames --name-only --diff-filter="$1" "$2"..HEAD -- 'posthog/clickhouse/migrations/[0-9]*' | sort
                  }
                  ch_migrations A upstream/master > "$RUNNER_TEMP/ch-master-added.txt"
                  ch_migrations AM upstream/master > "$RUNNER_TEMP/ch-master-changed.txt"
                  # A stacked branch can carry master's migrations, and master can edit one later.
                  # Only a file that master lacks counts as this PR's addition.
                  ch_migrations A "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-added.txt" > "$RUNNER_TEMP/ch-migrations-added.txt"
                  ch_migrations AM "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-changed.txt" > "$RUNNER_TEMP/ch-migrations-changed.txt"
                  cat "$RUNNER_TEMP/ch-migrations-changed.txt"

            - name: Check CH migrations
              run: |
                  # test_ch_migrations_are_safe requires a local master branch, while the
                  # comparison checkout is registered as upstream/master.
                  git show-ref --verify --quiet refs/heads/master || git branch master upstream/master
                  python manage.py test_ch_migrations_are_safe < "$RUNNER_TEMP/ch-migrations-added.txt"

            - name: Render CH migration SQL per cloud environment
              # CH migrations can build different `operations` lists at import time depending on
              # `settings.CLOUD_DEPLOYMENT` (e.g. cloud-only Kafka tables). Render the SQL each
              # environment will execute so reviewers can spot per-env divergence and verify gated
              # branches don't sneak in ON CLUSTER or other forbidden patterns. We render once per
              # environment and reuse the output both for the Actions log groups and the CI report
              # (environment -> node type(s) -> SQL). Environments that render identically are
              # grouped together; if all environments match, the environment level is collapsed.
              id: render_ch_sql
              if: github.event_name == 'pull_request'
              run: |
                  CHANGED=$(cat "$RUNNER_TEMP/ch-migrations-changed.txt")
                  if [ -z "$CHANGED" ]; then
                      echo "No ClickHouse migrations changed."
                      echo "has_changes=false" >> "$GITHUB_OUTPUT"
                      exit 0
                  fi
                  echo "has_changes=true" >> "$GITHUB_OUTPUT"
                  mapfile -t changed_migrations <<< "$CHANGED"
                  echo "migration_count=${#changed_migrations[@]}" >> "$GITHUB_OUTPUT"
                  {
                      echo '<!-- ch-migration-sql -->'
                      echo '## ClickHouse migration SQL per cloud environment'
                      echo ''
                  } > ch_migration_sql_comment.md
                  mkdir -p ch_sql_env
                  DEPLOYMENTS=('' US EU DEV)
                  LABELS=(unset US EU DEV)
                  # Bucket environments by identical rendered output (parallel indexed arrays;
                  # avoids bash 4 associative arrays) so divergent SQL prints once.
                  BUCKET_HASH=()
                  BUCKET_LABEL=()
                  BUCKET_FILE=()
                  for idx in "${!DEPLOYMENTS[@]}"; do
                      file="ch_sql_env/${idx}.md"
                      # Render once per environment; the same output feeds both the log group and the comment.
                      # On failure (e.g. an import error in the migration) write a visible marker rather than
                      # silently dropping the environment. stderr still shows in the step log for debugging.
                      if ! CLOUD_DEPLOYMENT="${DEPLOYMENTS[$idx]}" python manage.py print_ch_migration_sql --format markdown "${changed_migrations[@]}" > "$file"; then
                          echo '- _⚠️ failed to render SQL for this environment — see the workflow logs_' > "$file"
                      fi
                      echo "::group::CLOUD_DEPLOYMENT=${LABELS[$idx]}"
                      cat "$file"
                      echo "::endgroup::"
                      h=$(sha1sum "$file" | cut -d' ' -f1)
                      found=-1
                      for b in "${!BUCKET_HASH[@]}"; do
                          if [ "${BUCKET_HASH[$b]}" = "$h" ]; then found=$b; break; fi
                      done
                      if [ "$found" -ge 0 ]; then
                          BUCKET_LABEL[$found]="${BUCKET_LABEL[$found]}, ${LABELS[$idx]}"
                      else
                          BUCKET_HASH+=("$h")
                          BUCKET_LABEL+=("${LABELS[$idx]}")
                          BUCKET_FILE+=("$file")
                      fi
                  done
                  if [ "${#BUCKET_HASH[@]}" -eq 1 ]; then
                      echo '_Identical across all cloud environments (unset, US, EU, DEV)._' >> ch_migration_sql_comment.md
                      echo '' >> ch_migration_sql_comment.md
                      cat "${BUCKET_FILE[0]}" >> ch_migration_sql_comment.md
                  else
                      for b in "${!BUCKET_HASH[@]}"; do
                          echo "- **${BUCKET_LABEL[$b]}**" >> ch_migration_sql_comment.md
                          sed 's/^/  /' "${BUCKET_FILE[$b]}" >> ch_migration_sql_comment.md
                      done
                  fi

            - name: Post CH migration SQL to CI report comment
              # Sticky section in the shared CI report comment so pushes don't spam the PR.
              # Skipped on trunk-merge/** branches: merge-queue draft PRs are ephemeral and
              # unread. Skipped when the CI report is not available, because an empty token
              # would leave the ambient Depot token in place.
              if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && !startsWith(github.head_ref, 'trunk-merge/') && steps.ci-report.outputs.available == 'true'
              env:
                  HAS_CHANGES: ${{ steps.render_ch_sql.outputs.has_changes }}
                  CH_MIGRATION_COUNT: ${{ steps.render_ch_sql.outputs.migration_count }}
                  GITHUB_TOKEN: ${{ steps.ci-report-app-token.outputs.token }}
              run: |
                  if [ -f .github/scripts/post-ch-migration-section.mjs ]; then
                      node .github/scripts/post-ch-migration-section.mjs
                      node frontend/bin/ci-report/delete-legacy-comments.mjs
                  else
                      echo "Skipping CH migration section — script not present on this checkout"
                  fi

    check-openapi-types:
        needs: [changes]
        if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'schedule'
        timeout-minutes: 20
        outputs:
            deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
        name: Validate OpenAPI types
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.sha || github.event_name == 'push' && github.sha || github.ref }}
                  clean: false
            - name: Clean up data directories with container permissions
              run: |
                  [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
              continue-on-error: true
            - name: Log in to Docker Hub
              if: ${{ vars.DOCKERHUB_USER != '' && secrets.DOCKERHUB_TOKEN != '' }}
              continue-on-error: true
              uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
              with:
                  username: ${{ vars.DOCKERHUB_USER }}
                  password: ${{ secrets.DOCKERHUB_TOKEN }}
            - name: Stop/Start stack with Docker Compose
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
              run: nohup bin/ci-wait-for-docker launch --background --down db clickhouse </dev/null >"${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>&1
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
                  skip-token-revoke: true
            - name: Set up Python
              uses: ./.depot/actions/setup-python-cached
              with:
                  python-version: 3.14.7
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            # Direct install: Generated changes target the PR head, which may predate the local action.
            - name: Install uv
              id: setup-uv
              uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
              with:
                  version: '0.13.4'
                  enable-cache: true
                  cache-dependency-glob: uv.lock
                  save-cache: ${{ env.IS_MASTER == 'true' }}
                  prune-cache: true
            - name: Install SAML (python3-saml) dependencies
              if: steps.setup-uv.outputs.cache-hit != 'true'
              run: |
                  sudo rm -f /etc/apt/sources.list.d/*twingate*
                  sudo apt-get update
                  sudo apt-get install libxml2-dev libxmlsec1-dev libxmlsec1-openssl
              retry: 2
            - name: Install python dependencies
              timeout-minutes: 5
              retry: 1
              run: UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            - name: Install pnpm dependencies
              uses: ./.depot/actions/pnpm-install
              with:
                  install-command: pnpm --filter=@posthog/root --filter=@posthog/frontend... --filter=@posthog/mcp... install --frozen-lockfile
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            - name: Install desktop API client generator
              working-directory: products/desktop
              run: |
                  if [ ! -f ../../bin/build-desktop-api-client.sh ]; then
                      echo "This branch predates the desktop API client regen, so there is nothing to install."
                      exit 0
                  fi
                  pnpm install --frozen-lockfile --filter @posthog/api-client --ignore-scripts --config.node-linker=isolated
              retry: 2
            - name: Wait for Docker services
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
              run: |
                  bin/ci-wait-for-docker wait --only db clickhouse \
                    || { echo "::group::compose launch log"; cat "${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>/dev/null || true; echo "::endgroup::"; exit 1; }
            - name: Add OpenAPI Problem Matcher
              run: echo "::add-matcher::.github/openapi-problem-matcher.json"
            - name: Check and update OpenAPI types
              id: openapi-check
              env:
                  EVENT_NAME: ${{ github.event_name }}
                  HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
                  BRANCH: ${{ github.event.pull_request.head.ref }}
                  HEAD_SHA: ${{ github.event.pull_request.head.sha }}
              run: |
                  if ! ./bin/hogli build:openapi; then
                      echo ""
                      echo "::error::OpenAPI schema generation failed."
                      echo ""
                      echo "If the failure above mentions \"enum naming encountered a non-optimally"
                      echo "resolvable collision\" or \"SchemaGenerationError: Failing as requested due"
                      echo "to warnings\", drf-spectacular found a problem in a serializer/viewset and"
                      echo "\`--fail-on-warn\` turned it into an error."
                      echo ""
                      echo "Diagnose locally:"
                      echo "  python manage.py find_enum_collisions   # prints a suggested override entry to add"
                      echo "  hogli build:openapi-schema              # to reproduce the full warning set"
                      echo ""
                      echo "Where to fix:"
                      echo "  posthog/settings/web.py                 # ENUM_NAME_OVERRIDES (see comment block at the top)"
                      echo "  /improving-drf-endpoints                # invoke this skill for the full serializer/viewset guide"
                      echo ""
                      exit 1
                  fi
                  pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
                  if git diff --exit-code; then
                      echo "OpenAPI types are up to date"
                      echo "needs-commit=false" >> $GITHUB_OUTPUT
                      exit 0
                  fi

                  echo "OpenAPI types are out of date"

                  # A push to a merge queue branch ends the queue attempt.
                  if [[ "$BRANCH" == trunk-merge/* ]]; then
                      echo "::error::OpenAPI types are out of date once this pull request is merged with master: $(git diff --name-only | tr '\n' ' ')"
                      echo "Merge master into the pull request branch and push. CI regenerates the types on that branch."
                      exit 1
                  fi

                  # On non-PR builds or fork PRs, fail with instructions
                  if [ "$EVENT_NAME" != "pull_request" ] || \
                     [ "$HEAD_REPO" != "PostHog/posthog" ]; then
                      echo ""
                      echo "::error::OpenAPI types are out of date!"
                      echo ""
                      echo "The TypeScript API types in products/*/frontend/generated/ are auto-generated"
                      echo "from Django serializers and views. When you modify the backend API, you need"
                      echo "to regenerate these types."
                      echo ""
                      echo "To fix, run locally:  hogli build:openapi"
                      echo "Then commit the updated generated files."
                      echo ""
                      echo "More info: https://posthog.com/handbook/engineering/type-system"
                      echo ""
                      echo "Questions? #team-devex on Slack"
                      exit 1
                  fi

                  echo "::notice::Committing updated OpenAPI types to PR branch"

                  # Verify branch hasn't advanced since CI started
                  CURRENT_SHA=$(git ls-remote origin "refs/heads/$BRANCH" | cut -f1)
                  if [ "$CURRENT_SHA" != "$HEAD_SHA" ]; then
                      echo "::error::Branch advanced during workflow ($HEAD_SHA -> $CURRENT_SHA) — cannot auto-commit OpenAPI types."
                      echo ""
                      echo "OpenAPI types are out of date and could not be auto-committed because the branch"
                      echo "was updated while this workflow was running. Please run locally and push:"
                      echo ""
                      echo "  hogli build:openapi"
                      echo ""
                      echo "Then commit the updated generated files."
                      echo "needs-commit=false" >> $GITHUB_OUTPUT
                      exit 1
                  fi

                  # Commit exactly the files this check flagged. A hand-listed pattern
                  # silently dropped generated paths it did not cover, so the PR passed on
                  # an empty commit and every later master push failed this same check.
                  DRIFTED_FILES=$(git diff --name-only | tr '\n' ' ')
                  echo "Committing: $DRIFTED_FILES"
                  echo "drifted-files=$DRIFTED_FILES" >> $GITHUB_OUTPUT
                  echo "needs-commit=true" >> $GITHUB_OUTPUT

            # Deterministic = the OpenAPI check step itself failed (not a transient
            # setup or commit-step failure), so a retry can't fix it. Mirrors repo-checks.
            - name: Flag deterministic failure
              id: deterministic-failure
              if: failure() && steps.openapi-check.outcome == 'failure'
              run: echo "deterministic_failure=true" >> "$GITHUB_OUTPUT"

            - name: Get app token for OpenAPI type commits
              if: steps.openapi-check.outputs.needs-commit == 'true'
              id: openapi-app-token
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}

            - name: Disable auto-merge before OpenAPI type commit
              if: steps.openapi-check.outputs.needs-commit == 'true'
              env:
                  GH_TOKEN: ${{ steps.openapi-app-token.outputs.token }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
              run: gh pr merge --disable-auto "$PR_NUMBER" || echo "Auto-merge was not enabled"

            - name: Commit OpenAPI types via GitHub API (signed)
              id: openapi-commit
              if: steps.openapi-check.outputs.needs-commit == 'true'
              continue-on-error: true
              uses: planetscale/ghcommit-action@25309d8005ac7c3bcd61d3fe19b69e0fe47dbdde # v0.2.20
              with:
                  commit_message: 'chore: update OpenAPI generated types'
                  repo: ${{ github.repository }}
                  branch: ${{ github.event.pull_request.head.ref }}
                  file_pattern: ${{ steps.openapi-check.outputs.drifted-files }}
              env:
                  GITHUB_TOKEN: ${{ steps.openapi-app-token.outputs.token }}

            # Depot rejects retry: on a uses: step, so a failed commit gets one more attempt here.
            - name: Retry OpenAPI types commit
              if: steps.openapi-commit.outcome == 'failure'
              uses: planetscale/ghcommit-action@25309d8005ac7c3bcd61d3fe19b69e0fe47dbdde # v0.2.20
              with:
                  commit_message: 'chore: update OpenAPI generated types'
                  repo: ${{ github.repository }}
                  branch: ${{ github.event.pull_request.head.ref }}
                  file_pattern: ${{ steps.openapi-check.outputs.drifted-files }}
              env:
                  GITHUB_TOKEN: ${{ steps.openapi-app-token.outputs.token }}

    cancel-backend-on-openapi-check-failure:
        needs: [check-openapi-types]
        if: >
            always() &&
            needs.check-openapi-types.outputs.deterministic_failure == 'true' &&
            github.event_name == 'pull_request' &&
            github.event.pull_request.head.repo.full_name == github.repository
        timeout-minutes: 5
        permissions:
            contents: read
        name: Cancel Backend CI after OpenAPI check failure
        runs-on: depot-ubuntu-24.04
        steps:
            - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
            - name: Cancel run
              env:
                  DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}
                  REPO: ${{ github.repository }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
                  HEAD_SHA: ${{ github.event.pull_request.head.sha }}
              run: |
                  echo "::notice title=OpenAPI check failed deterministically::Canceling remaining Backend CI jobs. A retry cannot fix this failure; push a fix to start a new run."
                  depot ci workflow list --repo "$REPO" --pr "$PR_NUMBER" --status running -o json \
                      | jq -r --arg sha "$HEAD_SHA" '.[] | select(.workflow_path == "ci-backend.yml" and .head_sha == $sha) | "\(.run_id) \(.workflow_id)"' \
                      | while read -r run workflow; do depot ci cancel "$run" --workflow "$workflow"; done

    build_django_matrix:
        name: Build Django matrix
        needs: [changes, get_clickhouse_versions, turbo-discover, prime-schema-cache]
        if: |
            !cancelled() &&
            needs.changes.outputs.backend == 'true' &&
            needs.get_clickhouse_versions.result == 'success'
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        outputs:
            include: ${{ steps.build.outputs.include }}
        steps:
            - name: Build matrix include list
              id: build
              env:
                  OLDEST_SUPPORTED_IMAGE: ${{ needs.get_clickhouse_versions.outputs.oldest_supported_image }}
                  COMPAT_MATRIX_JSON: ${{ needs.get_clickhouse_versions.outputs.compat_matrix }}
                  DJANGO_SHARDS_JSON: ${{ needs.turbo-discover.outputs.django_shards }}
                  MODE: ${{ needs.turbo-discover.outputs.mode }}
                  RUN_POE: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_poe }}
                  RUN_TEMPORAL: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').run_temporal }}
                  CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}
                  COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}
                  SEGMENT_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').segment_shards }}
                  # A trunk-merge/** PR opens as a draft but is the merge gate, and
                  # turbo-discover deliberately does not select for it. Reporting it as a
                  # draft here would turn that empty MODE into "skip" and build an
                  # empty matrix, so the queue would merge having run no Django tests
                  # at all. Not-draft makes the empty MODE fall through to the full
                  # matrix, which is what the queue has to run.
                  IS_DRAFT: ${{ github.event.pull_request.draft && !startsWith(github.head_ref, 'trunk-merge/') }}
                  IS_PR_RUN: ${{ github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/') }}
                  FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') }}
                  # The new-events-schema variants double the matrix, so they run only on
                  # opted-in PRs. Every other run takes the events_json rows, which cover
                  # .github/new-events-schema-targets.txt only.
                  RUN_NEW_EVENTS_SCHEMA: ${{ contains(github.event.pull_request.labels.*.name, 'test-new-events-schema') }}
                  # Narrowed events_json paths and their shard count. Empty files on a run
                  # that takes the whole list.
                  JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}
                  JSON_TARGETS_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_shards }}
                  RUN_JSON_TARGETS: ${{ github.event_name != 'schedule' || github.event.schedule == '23 */3 * * *' }}
                  # Same rule as the django job's condition: the suite runs for a legacy
                  # edit, for a product change that reaches legacy code, and when discovery
                  # failed, which leaves run_legacy empty. Without it only the events_json
                  # rows for the product matrix run.
                  DJANGO_SUITE: ${{ needs.changes.outputs.legacy == 'true' || needs.turbo-discover.outputs.run_legacy != 'false' }}
              run: |
                  # :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.
                  # Consult #team-devex before changing.

                  # A draft PR must never fall back to the full matrix. turbo-discover sets
                  # MODE to "skip"/"full"/"selected"; an empty MODE on a
                  # draft means turbo-discover was cancelled or failed (typically
                  # ready_for_review superseding it mid-flight). Skip here and defer to the
                  # ready run. The run-ci-backend label intentionally forces full on a draft.
                  if [[ -z "$MODE" && "$IS_DRAFT" == "true" && "$FORCE_FULL" != "true" ]]; then
                      echo "::notice::Draft PR with no trusted Django selection — skipping heavy matrices; the ready-for-review run is the full gate"
                      MODE="skip"
                  fi

                  if [[ "$MODE" == "skip" ]]; then
                      # Draft PR where selection couldn't be trusted: skip the heavy
                      # matrices and defer to the full run on ready for review.
                      echo "include=[]" >> "$GITHUB_OUTPUT"
                      echo "Django matrix size: 0 (mode=skip)"
                      exit 0
                  fi
                  if [[ "$DJANGO_SUITE" != "true" ]]; then
                      # A product change that reaches no legacy code skips the Django suite.
                      # The product jobs read the legacy events table only, so the events_json
                      # rows still run the listed paths of the products in the product matrix.
                      core="[]"
                      core_new_events_schema="[]"
                      core_persons_on_events="[]"
                      core_persons_on_events_new_schema="[]"
                      temporal="[]"
                      temporal_new_events_schema="[]"
                      compat="[]"
                      json_targets_count=0
                      [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"
                  elif [[ "$MODE" == "selected" ]]; then
                      # Selected mode: run only the segments that have selected files. Shard
                      # counts come from turbo-discover, which applies its per-shard budget to
                      # the selected tests' recorded seconds. A wide selection therefore
                      # spreads over several jobs instead of running to the job timeout in
                      # one. No counts means one shard per segment.
                      segment_shards="${SEGMENT_SHARDS:-}"
                      [[ -z "$segment_shards" ]] && segment_shards='{"core": 1, "poe": 1, "temporal": 1}'

                      core_count=0
                      [[ -n "$CORE_FILES" ]] && core_count=$(jq -r '.core' <<< "$segment_shards")
                      core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$core_count" '
                        [range(1; $n + 1) | {
                          segment: "Core",
                          "person-on-events": false,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("core-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      core_new_events_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$core_count" '
                        [range(1; $n + 1) | {
                          segment: "Core",
                          "person-on-events": false,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("core-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      poe_count=0
                      [[ "$IS_PR_RUN" != "true" && "$RUN_POE" == "true" ]] && poe_count=$(jq -r '.poe' <<< "$segment_shards")
                      core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$poe_count" '
                        [range(1; $n + 1) | {
                          segment: "Core",
                          "person-on-events": true,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("core-poe-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      core_persons_on_events_new_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$poe_count" '
                        [range(1; $n + 1) | {
                          segment: "Core",
                          "person-on-events": true,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("core-poe-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      temporal_count=0
                      [[ "$RUN_TEMPORAL" == "true" ]] && temporal_count=$(jq -r '.temporal' <<< "$segment_shards")
                      temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$temporal_count" '
                        [range(1; $n + 1) | {
                          segment: "Temporal",
                          "person-on-events": false,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("temporal-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      temporal_new_events_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$temporal_count" '
                        [range(1; $n + 1) | {
                          segment: "Temporal",
                          "person-on-events": false,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $n,
                          group: .,
                          artifact_key: ("temporal-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')
                      # Compat covers the older supported ClickHouse versions over
                      # CLICKHOUSE_COMPAT_PYTEST_TARGETS. Selection can drop it only when the
                      # diff touches none of those paths — otherwise a narrowed run would
                      # silently lose the one signal the full matrix has about old servers.
                      # One unsharded entry per version, over the selected compat files.
                      if [[ -n "$COMPAT_FILES" ]]; then
                          compat=$(jq -cn --argjson compat "${COMPAT_MATRIX_JSON:-[]}" '
                            [ $compat
                              | map(."clickhouse-server-image") | unique | to_entries[]
                              | {
                                  "clickhouse-server-image": .value,
                                  segment: "Core",
                                  "person-on-events": false,
                                  "new-events-schema": false,
                                  "python-version": "3.14.7",
                                  concurrency: 1,
                                  group: 1,
                                  compat: true,
                                  artifact_key: ("compat-" + ((.key + 1)|tostring))
                                }
                            ]
                          ')
                      else
                          compat="[]"
                      fi
                      # The narrowed events_json paths: selected files under a listed path,
                      # plus the listed paths of the products in the narrowed product matrix.
                      json_targets_count=0
                      [[ -n "$JSON_TARGETS_FILES" ]] && json_targets_count="${JSON_TARGETS_SHARDS:-1}"
                  else
                      # Full run: auto-shard counts from turbo-discover (Amdahl's law on .test_durations).
                      # Falls back to hardcoded defaults if turbo-discover failed or data is missing.
                      CORE_SHARDS=38
                      CORE_POE_SHARDS=7
                      TEMPORAL_SHARDS=7
                      JSON_TARGETS_FULL_SHARDS=5
                      if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then
                        CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')
                        CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')
                        TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')
                        JSON_TARGETS_FULL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r --argjson fallback "$JSON_TARGETS_FULL_SHARDS" '.JsonTargets.shards // $fallback')
                        echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"
                      else
                        echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS, JsonTargets=$JSON_TARGETS_FULL_SHARDS"
                      fi
                      # A full run takes every listed events_json path, unless discovery
                      # shortened the list: a skipped product, or a product-only diff whose
                      # legacy paths the merge queue runs. An empty list gives 0 rows.
                      json_targets_count="$JSON_TARGETS_FULL_SHARDS"
                      if [[ -n "$JSON_TARGETS_SHARDS" ]] && (( JSON_TARGETS_SHARDS < json_targets_count )); then
                          json_targets_count="$JSON_TARGETS_SHARDS"
                          echo "::notice::Discovery shortened the events_json list to $json_targets_count shard(s)"
                      fi

                      # The legacy-mode safeguard leg runs only where a regression must not
                      # land: merge queue and master. Ordinary PR lanes run the
                      # customer-default mode only, so a PR pays no shards for the legacy
                      # mode. The queue's trunk-merge/** run is a pull_request event as well,
                      # so it is exempted by branch. Compat keeps its own legacy-mode rows in
                      # every lane, because it guards old servers, not this.
                      if [[ "$IS_PR_RUN" == "true" ]]; then
                          CORE_POE_SHARDS=0
                      fi

                      core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Core",
                          "person-on-events": false,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("core-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      core_new_events_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Core",
                          "person-on-events": false,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("core-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Core",
                          "person-on-events": true,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("core-poe-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      core_persons_on_events_new_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Core",
                          "person-on-events": true,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("core-poe-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Temporal",
                          "person-on-events": false,
                          "new-events-schema": false,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("temporal-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      temporal_new_events_schema=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '
                        [range(1; $shards + 1) | {
                          segment: "Temporal",
                          "person-on-events": false,
                          "new-events-schema": true,
                          "python-version": "3.14.7",
                          "clickhouse-server-image": $image,
                          concurrency: $shards,
                          group: .,
                          artifact_key: ("temporal-events-json-" + (.|tostring)),
                          compat: false
                        }]
                      ')

                      compat_source="${COMPAT_MATRIX_JSON:-[]}"
                      compat=$(jq -cn --argjson compat "$compat_source" '
                        [
                          $compat
                          | to_entries[]
                          | .value + {
                              segment: "Core",
                              "person-on-events": false,
                              "new-events-schema": false,
                              "python-version": "3.14.7",
                              compat: true,
                              artifact_key: ("compat-" + ((.key + 1)|tostring))
                            }
                        ]
                      ')
                  fi

                  if [[ "$RUN_NEW_EVENTS_SCHEMA" != "true" ]]; then
                      # Without the schema copies, only the events_json rows below refresh
                      # *.new_events_schema.ambr files, so a module outside
                      # .github/new-events-schema-targets.txt lets its file go stale.
                      echo "Skipping new-events-schema variants (RUN_NEW_EVENTS_SCHEMA is off)"
                      core_new_events_schema="[]"
                      core_persons_on_events_new_schema="[]"
                      temporal_new_events_schema="[]"
                  else
                      # The doubled matrices exclude some curated paths, such as Dagster tests.
                      # Discovery keeps only those paths so the other tests do not run a third time.
                      json_targets_count="${JSON_TARGETS_SHARDS:-0}"
                  fi

                  if [[ "$RUN_JSON_TARGETS" != "true" ]]; then
                      echo "Skipping the events_json rows on this hourly run"
                      json_targets_count=0
                  fi

                  # The events_json rows: Core jobs over the listed paths with the
                  # native-JSON events table. They keep Core's person-on-events default.
                  json_targets=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$json_targets_count" '
                    [range(1; $n + 1) | {
                      segment: "Core",
                      "json-targets": true,
                      "person-on-events": false,
                      "new-events-schema": true,
                      "python-version": "3.14.7",
                      "clickhouse-server-image": $image,
                      concurrency: $n,
                      group: .,
                      artifact_key: ("json-targets-" + (.|tostring)),
                      compat: false
                    }]
                  ')

                  include=$(jq -cn \
                    --argjson core "$core" \
                    --argjson core_new_events_schema "$core_new_events_schema" \
                    --argjson core_persons_on_events "$core_persons_on_events" \
                    --argjson core_persons_on_events_new_schema "$core_persons_on_events_new_schema" \
                    --argjson temporal "$temporal" \
                    --argjson temporal_new_events_schema "$temporal_new_events_schema" \
                    --argjson compat "$compat" \
                    --argjson json_targets "$json_targets" \
                    '$core + $core_new_events_schema + $core_persons_on_events + $core_persons_on_events_new_schema + $temporal + $temporal_new_events_schema + $compat + $json_targets')

                  echo "include=$include" >> "$GITHUB_OUTPUT"
                  echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"
    django:
        needs: [changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix]
        # Run legacy pytest if:
        # 1. Legacy code directly changed (ee/, posthog/)
        # 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)
        # 3. OR turbo-discover itself failed (conservative: run Django on detection failure)
        # 4. OR a product-only change has events_json paths to run. build_django_matrix
        #    then builds only the events_json rows, because the Django suite does not run.
        # The non-empty include guard covers drafts in skip mode and selected runs
        # that chose zero files — an empty matrix would otherwise fail the job.
        # A status function is required to inspect dependency results after failures.
        # Use !cancelled(), not always(), so superseded matrix jobs still receive cancellation.
        if: |
            !cancelled() &&
            needs.changes.outputs.backend == 'true' &&
            needs.build_django_matrix.result == 'success' &&
            needs.build_django_matrix.outputs.include != '[]' &&
            (needs.changes.outputs.legacy == 'true' ||
             needs.turbo-discover.outputs.run_legacy == 'true' ||
             (needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped') ||
             fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files != '')
        # increase for tmate testing
        timeout-minutes: 45
        name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }}${{ matrix.json-targets && ' json-targets' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})
        # Shards restore the master-primed schema cache (turbo-discover key + check-migrations
        # save), so they skip migrations once a master run has warmed Depot Cache.
        runs-on: depot-ubuntu-24.04
        strategy:
            fail-fast: false
            matrix:
                include: ${{ fromJson(needs.build_django_matrix.outputs.include) }}
        steps:
            # The default ref, which is the PR merge commit. turbo-discover selects the test files
            # from this tree, so a checkout of any other ref can lack a file that the selection lists.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
            - name: Install signal-fanout
              shell: bash
              run: sudo install -m 0755 .github/scripts/signal-fanout /usr/local/bin/signal-fanout
            - name: Clean up data directories with container permissions
              run: |
                  # Use docker to clean up files created by containers
                  [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true
              continue-on-error: true
            - name: 'Safeguard: ensure no stray Python modules at product root'
              run: |
                  echo "Checking that products/* only contain backend/, frontend/, or shared/ as Python code roots..."
                  BAD_FILES=$(find products -maxdepth 2 -type f -name "*.py" ! -path "*/backend/*" ! -name "__init__.py" ! -name "conftest.py" -o -maxdepth 2 -type d -name "migrations" ! -path "*/backend/*")
                  if [ -n "$BAD_FILES" ]; then
                    echo "❌ Found Python code or migrations outside backend/:"
                    echo "$BAD_FILES"
                    echo "Please move these into the appropriate backend/ folder."
                    exit 1
                  fi
                  echo "✅ No stray Python files or migrations found at product roots."
            # Pre-tests
            # Copies the fully versioned UDF xml file for use in CI testing
            - name: Log in to Docker Hub
              if: ${{ vars.DOCKERHUB_USER != '' && secrets.DOCKERHUB_TOKEN != '' }}
              continue-on-error: true
              uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
              with:
                  username: ${{ vars.DOCKERHUB_USER }}
                  password: ${{ secrets.DOCKERHUB_TOKEN }}
            - name: Stop/Start stack with Docker Compose
              shell: bash
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
                  COMPOSE_PROFILES: temporal,azure
                  CLICKHOUSE_SERVER_IMAGE: ${{ matrix.clickhouse-server-image || needs.get_clickhouse_versions.outputs.oldest_supported_image }}
                  WAIT_FOR_DOCKER_LAUNCH_RETRY_DELAY: 5
              run: |
                  cp posthog/user_scripts/latest_user_defined_function.xml docker/clickhouse/user_defined_function.xml
                  nohup bin/ci-wait-for-docker launch --background --down-all-profiles </dev/null >"${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>&1
            - name: Add service hostnames to /etc/hosts
              shell: bash
              run: echo "127.0.0.1 db redis7 kafka clickhouse clickhouse-coordinator objectstorage seaweedfs temporal" | sudo tee -a /etc/hosts
            - name: Mint setup-action GitHub token
              id: setup-gh-token
              if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ vars.GH_APP_POSTHOG_DEVEX_GENERAL_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_DEVEX_GENERAL_PRIVATE_KEY }}
                  skip-token-revoke: true
            # Restore before setup-python so the tool cache is warm when it starts.
            - name: Restore Python tool cache
              id: python-toolcache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: ${{ runner.tool_cache }}/Python/${{ matrix.python-version }}
                  key: python-toolcache-${{ runner.os }}-${{ runner.arch }}-${{ matrix.python-version }}
            - name: Set up Python
              uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
              with:
                  python-version: ${{ matrix.python-version }}
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            - name: Save Python tool cache
              if: env.IS_MASTER == 'true' && steps.python-toolcache.outputs.cache-hit != 'true'
              uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: ${{ runner.tool_cache }}/Python/${{ matrix.python-version }}
                  key: python-toolcache-${{ runner.os }}-${{ runner.arch }}-${{ matrix.python-version }}
            # Direct install: Tests run the explicit PR head, which may predate the local action.
            - name: Install uv
              id: setup-uv-tests
              uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
              with:
                  version: '0.13.4'
                  enable-cache: true
                  cache-dependency-glob: uv.lock
                  save-cache: ${{ env.IS_MASTER == 'true' }}
                  prune-cache: true
            - name: Install SAML (python3-saml) dependencies
              if: ${{ needs.changes.outputs.backend == 'true' && steps.setup-uv-tests.outputs.cache-hit != 'true' }}
              shell: bash
              run: |
                  sudo rm -f /etc/apt/sources.list.d/*twingate* && sudo apt-get update && sudo apt-get install libxml2-dev libxmlsec1-dev libxmlsec1-openssl
              retry: 2
            - name: Install sqlx-cli
              if: needs.changes.outputs.backend == 'true'
              uses: ./.depot/actions/setup-sqlx-cli
            - name: Determine if hogql-parser has changed compared to upstream master
              shell: bash
              id: hogql-parser-diff
              run: |
                  git fetch --no-tags --prune --depth=1 https://github.com/PostHog/posthog.git master
                  changed=$(git diff --quiet HEAD FETCH_HEAD -- common/hogql_parser/ && echo "false" || echo "true")
                  echo "changed=$changed" >> $GITHUB_OUTPUT
                  # A branch that predates the crate has nothing to install.
                  rust_changed=false
                  if [[ -f rust/hogql/parser/pyproject.toml ]]; then
                      crate_version=$(grep -m1 '^version = ' rust/hogql/parser/pyproject.toml | sed -E 's/version = "(.*)"/\1/')
                      # Publishing is a manual step after merge, so master can carry a crate version that
                      # the root pin does not name yet. That version builds from source too.
                      if ! git diff --quiet HEAD FETCH_HEAD -- rust/hogql/parser/ || ! grep -q "\"hogql-parser-rs==$crate_version\"" pyproject.toml; then
                          rust_changed=true
                      fi
                  fi
                  echo "rust_changed=$rust_changed" >> $GITHUB_OUTPUT
              retry: 2
            # tests would intermittently fail in GH actions
            # with exit code 134 _after passing_ all tests
            # this appears to fix it
            # absolute wild tbh https://stackoverflow.com/a/75503402

            # Cache Qt library packages to reduce network dependency and flakiness
            # Using cache-apt-pkgs-action instead of setup-qt-libs to avoid network issues
            - name: Cache and install Qt libraries
              uses: awalsh128/cache-apt-pkgs-action@acb598e5ddbc6f68a970c5da0688d2f3a9f04d05 # v1.6.0
              with:
                  packages: libegl1 libdbus-1-3 libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 libxcb-xinput0 libxcb-xfixes0 x11-utils libxcb-cursor0 libopengl0
                  version: 1.0
            - name: Install Python dependencies
              shell: bash
              timeout-minutes: 5
              retry: 1
              run: |
                  UV_PROJECT_ENVIRONMENT=$pythonLocation timeout --kill-after=10s "$PY_DEPS_SYNC_TIMEOUT" uv sync --frozen --dev
            - name: Set up Node.js for canvas builder
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' && hashFiles('products/canvas/packages/canvas_builder/package.json') != '' }}
              uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
              with:
                  node-version-file: .nvmrc
                  token: ${{ steps.setup-gh-token.outputs.token || github.token }}
            # A single `npm ci` on an empty npm cache intermittently fails with EEXIST or ENOENT on a
            # `_cacache/tmp` file, with no other process using the cache.
            - name: Install canvas builder dependencies
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}
              shell: bash
              retry: 2
              run: |
                  if [[ -f products/canvas/packages/canvas_builder/package.json ]]; then
                      npm ci --ignore-scripts --omit=dev --no-audit --no-fund --prefix products/canvas/packages/canvas_builder
                  fi
            - name: Install the working version of hogql-parser
              if: ${{ needs.changes.outputs.backend == 'true' && steps.hogql-parser-diff.outputs.changed == 'true' }}
              shell: bash
              # This is not cached, because the current HEAD version of hogql-parser must be built if it has
              # changed (requirements.txt has the already-published version)
              run: |
                  # Short budget: the `||` mirror is the real fallback for a host that is down.
                  fetch=(curl --fail --location --retry 3 --retry-all-errors --retry-max-time 30 --connect-timeout 10)
                  "${fetch[@]}" https://www.antlr.org/download/antlr4-cpp-runtime-4.13.1-source.zip --output antlr4-source.zip \
                      || "${fetch[@]}" https://raw.githubusercontent.com/antlr/website-antlr4/gh-pages/download/antlr4-cpp-runtime-4.13.1-source.zip --output antlr4-source.zip
                  # Check that the downloaded archive is the expected runtime - a security measure
                  anltr_known_md5sum="c875c148991aacd043f733827644a76f"
                  antlr_found_ms5sum="$(md5sum antlr4-source.zip | cut -d' ' -f1)"
                  if [[ "$anltr_known_md5sum" != "$antlr_found_ms5sum" ]]; then
                      echo "Unexpected MD5 sum of antlr4-source.zip!"
                      echo "Known: $anltr_known_md5sum"
                      echo "Found: $antlr_found_ms5sum"
                      exit 64
                  fi
                  unzip antlr4-source.zip -d antlr4-source && cd antlr4-source
                  cmake .
                  DESTDIR=out make install
                  sudo cp -r out/usr/local/include/antlr4-runtime /usr/include/
                  sudo cp out/usr/local/lib/libantlr4-runtime.so* /usr/lib/
                  sudo ldconfig
                  cd ..
                  pip install ./common/hogql_parser
            - name: Install Rust to build hogql-parser-rs
              if: ${{ needs.changes.outputs.backend == 'true' && steps.hogql-parser-diff.outputs.rust_changed == 'true' }}
              uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9
              with:
                  toolchain: 1.91.1
                  components: cargo
            - name: Install the working version of hogql-parser-rs
              if: ${{ needs.changes.outputs.backend == 'true' && steps.hogql-parser-diff.outputs.rust_changed == 'true' }}
              shell: bash
              # rust-py is the production parser, so its tests must run against this branch's
              # crate rather than the version pinned in the root pyproject.toml.
              run: pip install ./rust/hogql/parser
            - name: Set up needed files
              shell: bash
              run: |
                  mkdir -p frontend/dist
                  touch frontend/dist/index.html
                  touch frontend/dist/layout.html
                  touch frontend/dist/exporter.html
                  ./bin/download-mmdb
            - name: Wait for Docker services
              shell: bash
              # Read-only health poll for core services only. Can't use --wait here
              # because it blocks on ALL project containers including temporal, which
              # boots slowly (auto-setup runs DB migrations). Temporal was started in
              # background above and will be ready by the time temporal tests run.
              env:
                  COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml
                  COMPOSE_PROFILES: temporal,azure
                  CLICKHOUSE_SERVER_IMAGE: ${{ matrix.clickhouse-server-image || needs.get_clickhouse_versions.outputs.oldest_supported_image }}
              run: |
                  bin/ci-wait-for-docker wait \
                    || { echo "::group::compose launch log"; cat "${RUNNER_TEMP:-/tmp}/compose-launch.log" 2>/dev/null || true; echo "::endgroup::"; exit 1; }
            - name: Restore schema cache from master
              if: ${{ github.event_name == 'pull_request' }}
              timeout-minutes: 4
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: schema.sql.gz
                  # Prefer the shared content key; fall back to the exact PR-base SHA key,
                  # then to the newest dump of any migration set. Right after a migration
                  # lands on master both exact keys miss until ci-backend re-dumps, and a
                  # from-scratch migrate costs ~17 minutes per shard; pytest's keepdb
                  # migrate tops a slightly stale dump up in seconds instead.
                  key: ${{ needs.turbo-discover.outputs.schema_migrations_key || needs.turbo-discover.outputs.schema_cache_key || format('posthog-schema-run-{0}', github.run_id) }}
                  restore-keys: |
                      ${{ needs.turbo-discover.outputs.schema_cache_key }}
                      ${{ needs.turbo-discover.outputs.schema_prefix_key }}
            - name: Prime test_posthog from cached schema
              # Treat cache problems as misses; the migrate step below rebuilds the DB
              # whenever this one reports restored=false.
              id: prime-schema
              if: ${{ github.event_name == 'pull_request' }}
              run: |
                  echo "restored=false" >> "$GITHUB_OUTPUT"
                  if [ ! -f schema.sql.gz ]; then
                      echo "::notice::Schema cache miss; the migrate step will build test_posthog"
                      exit 0
                  fi
                  mkdir -p .postgres-backups
                  mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
                  if ./bin/hogli db:restore-test-db; then
                      echo "restored=true" >> "$GITHUB_OUTPUT"
                  else
                      echo "::warning::Schema restore failed (stale/incompatible cached dump?); the migrate step will build test_posthog"
                  fi
            - name: Migrate test_posthog from scratch
              # Any run without a restored schema cache (master, dispatches, PR cache
              # misses) replays the full migration chain here, in a process that exits
              # before tests: the executor's memory high-water stays resident in
              # whichever process runs it, and pytest must not carry it through the
              # test phase. pytest --reuse-db adopts the DB like the PR prime above;
              # any failure falls back to the in-pytest migrate.
              if: ${{ github.event_name != 'pull_request' || steps.prime-schema.outputs.restored != 'true' }}
              env:
                  DATABASE_URL: postgres://posthog:posthog@localhost:5432/test_posthog
              run: |
                  admin_psql() { docker compose -f docker-compose.dev.yml exec -T db psql -U posthog postgres "$@"; }
                  if ! admin_psql -c "DROP DATABASE IF EXISTS test_posthog;" -c "CREATE DATABASE test_posthog;"; then
                      echo "::warning::Could not recreate test_posthog; pytest --reuse-db will run the full migrate itself"
                      exit 0
                  fi
                  if ! python manage.py migrate; then
                      echo "::warning::Out-of-process migrate failed; pytest --reuse-db will run the full migrate itself"
                      admin_psql -c "DROP DATABASE IF EXISTS test_posthog;" || true
                  fi
            - name: Restore test durations from cache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: .test_durations
                  key: posthog-test-durations-${{ github.run_id }}
                  restore-keys: |
                      posthog-test-durations-
            - name: Fall back to the last published durations
              # .test_durations is not in the repo. The timing workflow refreshes the
              # cache several times a day and publishes the same files as an artifact
              # of its own runs. On a cache miss (retention lapsed, timing workflow
              # down for two weeks) take the newest artifact; if that is gone too,
              # pytest-split splits by count and turbo-discover sizes from file counts
              # until the next timing run.
              if: ${{ hashFiles('.test_durations') == '' }}
              continue-on-error: true
              env:
                  GH_TOKEN: ${{ github.token }}
              run: |
                  run_id=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow ci-backend-update-test-timing.yml \
                      --branch master --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty')
                  if [ -z "$run_id" ]; then
                      echo "::warning::No successful timing run to fall back to, sharding without durations"
                      exit 0
                  fi
                  gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name test-durations --dir . \
                      || echo "::warning::Timing artifact of run $run_id unavailable, sharding without durations"
            - name: Restore per-segment test durations from cache
              timeout-minutes: 2
              continue-on-error: true
              uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
              with:
                  path: |
                      .test_durations.core
                      .test_durations.temporal
                  key: posthog-segment-durations-${{ github.run_id }}
                  restore-keys: |
                      posthog-segment-durations-
            # Tests
            - name: Set snapshot update flags
              if: ${{ needs.changes.outputs.backend == 'true' && (needs.detect-snapshot-mode.outputs.mode == 'update' || matrix.person-on-events) }}
              shell: bash
              run: echo "PYTEST_ARGS=--snapshot-update --snapshot-warn-unused" >> "$GITHUB_ENV"
            - name: Set compat snapshot flags
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.compat }}
              shell: bash
              run: echo "PYTEST_ARGS=--snapshot-update --snapshot-warn-unused" >> "$GITHUB_ENV"
            - name: Set check-mode snapshot flags
              if: ${{ needs.changes.outputs.backend == 'true' && needs.detect-snapshot-mode.outputs.mode != 'update' && !matrix.person-on-events && !matrix.compat }}
              shell: bash
              run: echo "PYTEST_ARGS=--snapshot-warn-unused" >> "$GITHUB_ENV"
            - name: Log test environment diagnostics
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}
              shell: bash
              env:
                  SHARD_GROUP: ${{ matrix.group }}
                  SHARD_CONCURRENCY: ${{ matrix.concurrency }}
                  CLICKHOUSE_IMAGE: ${{ matrix.clickhouse-server-image }}
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
                  COMMIT_SHA: ${{ github.sha }}
                  BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
              run: |
                  echo "=== Test Environment Diagnostics ==="
                  echo "Shard: $SHARD_GROUP/$SHARD_CONCURRENCY"
                  echo "Python version: $(python --version)"
                  echo "ClickHouse version: $CLICKHOUSE_IMAGE"
                  echo "Events schema: $CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA"
                  echo "Commit: $COMMIT_SHA"
                  echo "Branch: $BRANCH_NAME"
                  echo "Runner: $(uname -a)"
                  echo "Memory: $(free -h | head -2)"
                  echo "Disk: $(df -h / | tail -1)"
                  echo "Docker containers:"
                  docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" || true
                  echo "==================================="
            - name: Download the run's sharding plan snapshot
              # Pin every attempt to the plan turbo-discover snapshotted (rationale on
              # that step); a missing snapshot falls back to the floating caches above.
              id: pinned-plan
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  name: test-durations-plan
                  path: /tmp/test-durations-plan

            - name: Apply the pinned sharding plan
              if: ${{ steps.pinned-plan.outcome == 'success' }}
              shell: bash
              run: |
                  if [ ! -f /tmp/test-durations-plan/.test_durations ]; then
                      echo "::warning::Sharding-plan snapshot is incomplete, keeping the floating cache restores"
                      exit 0
                  fi
                  # rm first so segment files the snapshot lacks don't survive the floating restore
                  rm -f .test_durations.core .test_durations.temporal
                  cp /tmp/test-durations-plan/.test_durations .test_durations
                  for f in .test_durations.core .test_durations.temporal events-schema-prune.json; do
                      if [ -f "/tmp/test-durations-plan/$f" ]; then cp "/tmp/test-durations-plan/$f" "$f"; fi
                  done
                  echo "Sharding plan pinned to this run's snapshot"

            - name: Warn when a re-run reshards unpinned
              if: ${{ github.run_attempt != '1' && steps.pinned-plan.outcome != 'success' }}
              shell: bash
              run: echo "::warning::Sharding-plan snapshot unavailable, this re-run reshards from the floating timing caches and may not re-execute tests that failed in earlier attempts"

            - name: Run Core tests
              continue-on-error: true
              id: run-core-tests
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}
              env:
                  # Person-on-events v2 reads are the production default for every
                  # project created since 2024-06-14, so the full Core rows run with the
                  # mode on. matrix.person-on-events marks the safeguard allowlist leg
                  # that keeps the legacy joined mode covered, not the mode itself: every
                  # other condition keyed on it (targets, snapshot ownership, timing
                  # artifacts) selects the leg. Compat rows run the legacy mode as well,
                  # as the old-server safeguard.
                  # marker: person-on-events-default. The run block below greps the
                  # checked-out workflow for this token to tell a head that carries the
                  # flip from one that predates it.
                  PERSON_ON_EVENTS_V2_ENABLED: ${{ !matrix.person-on-events && !matrix.compat && 'true' || 'false' }}
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
                  MODE: ${{ needs.turbo-discover.outputs.mode }}
                  CORE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').core_files }}
                  POE_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').poe_files }}
                  COMPAT_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').compat_files }}
                  JSON_TARGETS: ${{ matrix.json-targets && 'true' || 'false' }}
                  # The narrowed events_json paths. Empty when the row takes the whole list.
                  JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}
                  # devex: measure core (posthog/ee) coverage on PRs to size the gap vs products. sysmon = low overhead.
                  COVERAGE_CORE: sysmon
                  # The coverage report skips narrowed runs, so
                  # instrumenting one is pure overhead, and the events_json rows rerun
                  # tests the legacy rows already measure.
                  COV_ARGS: ${{ github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && !matrix.json-targets && '--cov=posthog --cov=ee --cov-config=.github/coverage-core.cfg --cov-report=' || '' }}
              shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'
              run: |
                  unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
                  set +e
                  # Enable retries only when the checkout includes retry diagnostics.
                  RETRY_ARGS=()
                  if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
                      RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
                  fi
                  # A missing --cov-config file aborts pytest, so skip coverage if it is absent.
                  if [[ -n "$COV_ARGS" && ! -f .github/coverage-core.cfg ]]; then
                      COV_ARGS=""
                  fi
                  # A checkout without the matching test pins must use legacy mode.
                  if [[ "$PERSON_ON_EVENTS_V2_ENABLED" == "true" ]] && ! grep -qF "marker: person-on-events-default" .depot/workflows/ci-backend.yml; then
                      echo "::notice::Checked-out revision predates the person-on-events default, running Core in legacy mode"
                      export PERSON_ON_EVENTS_V2_ENABLED=false
                  fi
                  # Unsupported pytest-split flags abort collection, so probe the installed plugin.
                  SPLITTING_ALGORITHM=duration_based_chunks
                  SPLIT_GRANULARITY=()
                  if python -c "from pytest_split.algorithms import Algorithms; from pytest_split.plugin import PytestSplitFilePlugin; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
                      SPLITTING_ALGORITHM=optimal_chunks
                      SPLIT_GRANULARITY=(--split-granularity=file)
                      # Scope the file-mode plan to Core's clean per-segment durations when the
                      # pinned pytest-split supports it; only persons-on-events-off, non-compat Core
                      # matches the .core run-set (the events_json rows do not), and a missing
                      # file falls back to the union. A selected run needs a plugin that scopes
                      # the plan file to its targets.
                      PLAN_CAPABILITY=SUPPORTS_SPLIT_PLAN_PATH
                      if [[ "$MODE" == "selected" ]]; then
                          PLAN_CAPABILITY=SCOPES_SPLIT_PLAN_PATH
                      fi
                      if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && [[ "$JSON_TARGETS" != "true" ]] && python -c "from pytest_split.plugin import $PLAN_CAPABILITY" 2>/dev/null; then
                          SPLIT_GRANULARITY+=(--split-plan-path .test_durations.core)
                      fi
                  fi
                  if [[ "$JSON_TARGETS" == "true" ]]; then
                      # The events_json leg. The job checks out the PR head, and a head without
                      # the list also predates the JSON-mode test fixes that came before it, so
                      # its listed tests would fail on code the PR did not touch. The merge
                      # queue's trunk-merge/** head always has the list, so the gate still runs.
                      if [[ ! -f .github/new-events-schema-targets.txt ]]; then
                          echo "::notice::The checked-out revision predates .github/new-events-schema-targets.txt, so the events_json leg runs nothing until this branch rebases onto master"
                          exit 0
                      fi
                      # A narrowed run hands over its paths, and every other run takes the
                      # whole list. Parse it the way turbo-discover.js does.
                      if [[ -n "$JSON_TARGETS_FILES" ]]; then
                          read -r -a json_candidates <<< "$JSON_TARGETS_FILES"
                      else
                          mapfile -t json_candidates < <(sed -e 's/#.*//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's:/*$::' -e '/^$/d' .github/new-events-schema-targets.txt)
                      fi
                      # The PR head can lack a path that the merged list names. pytest stops
                      # with a usage error on a missing path, so skip that path and say so.
                      json_targets=()
                      for target in "${json_candidates[@]}"; do
                          if [[ -e "$target" ]]; then
                              json_targets+=("$target")
                          else
                              echo "::warning::events_json path $target does not exist in this checkout, so it does not run"
                          fi
                      done
                      if [[ ${#json_targets[@]} -eq 0 ]]; then
                          exit 0
                      fi
                      JSON_SPLIT=()
                      if [[ "${{ matrix.concurrency }}" -gt 1 ]]; then
                          JSON_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"
                                      --splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")
                      fi
                      if [[ "$GITHUB_EVENT_NAME" == "schedule" ]]; then
                          # The hourly run keeps every listed test and records which ones read the
                          # JSON tables. The timing workflow builds the prune manifest from it.
                          export POSTHOG_EVENTS_SCHEMA_RECORD_PATH=events-schema-record.json
                      elif [[ "$GITHUB_EVENT_NAME" == "pull_request" && "$GITHUB_HEAD_REF" != trunk-merge/* && -f events-schema-prune.json ]]; then
                          # Skips the tests that a recording showed never read the JSON tables. The
                          # merge queue runs every listed test, so a skipped test whose code starts
                          # to read those tables still fails before the change reaches master.
                          export POSTHOG_EVENTS_SCHEMA_PRUNE_MANIFEST=events-schema-prune.json
                      fi
                      # No --store-durations, because the timing data describes legacy-table runs only.
                      # shellcheck disable=SC2086
                      pytest -v --tb=short --reuse-db -o junit_duration_report=call "${json_targets[@]}" -m "not async_migrations" \
                          "${JSON_SPLIT[@]}" \
                          "${RETRY_ARGS[@]}" -r fEsxXR \
                          --junitxml=junit-core.xml \
                          $COV_ARGS \
                          $PYTEST_ARGS
                  elif [[ "$MODE" == "selected" ]]; then
                      # Selected mode: run only the test files chosen by the snob shadow selector.
                      # Sharded only when build_django_matrix sized the segment above one
                      # shard. One pytest retry.
                      if [[ "${{ matrix.compat }}" == "true" ]]; then
                          targets="$COMPAT_FILES"
                      elif [[ "${{ matrix.person-on-events }}" == "true" ]]; then
                          targets="$POE_FILES"
                      else
                          targets="$CORE_FILES"
                      fi
                      SELECTED_SPLIT=()
                      if [[ "${{ matrix.concurrency }}" -gt 1 ]]; then
                          SELECTED_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"
                                          --splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")
                      fi
                      # shellcheck disable=SC2086
                      pytest -v --tb=short --reuse-db -o junit_duration_report=call $targets -m "not async_migrations" \
                          "${SELECTED_SPLIT[@]}" \
                          "${RETRY_ARGS[@]}" -r fEsxXR \
                          --junitxml=junit-core.xml \
                          $COV_ARGS \
                          $PYTEST_ARGS
                  else
                    full_targets="posthog ee/"
                    full_ignores=()
                    if [[ "${{ matrix.compat }}" == "true" ]]; then
                        full_targets="$CLICKHOUSE_COMPAT_PYTEST_TARGETS"
                    elif [[ "${{ matrix.person-on-events }}" == "true" ]]; then
                        full_targets="./posthog/clickhouse/ ./posthog/api/test/dashboards/test_dashboard.py ee/clickhouse/"
                        full_ignores+=(--ignore=posthog/hogql_queries --ignore=posthog/hogql)
                    fi
                    # shellcheck disable=SC2086
                    pytest -v --tb=short --reuse-db -o junit_duration_report=call $full_targets -m "not async_migrations" \
                        --ignore=posthog/temporal \
                        --ignore=posthog/dags \
                        --ignore=common/hogvm/python/test \
                        --ignore=posthog/test/repo_invariants \
                        "${full_ignores[@]}" \
                        --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
                        --durations=1000 --durations-min=1.0 --store-durations \
                        --pytest-durations=100 \
                        --splitting-algorithm="$SPLITTING_ALGORITHM" \
                        "${SPLIT_GRANULARITY[@]}" \
                        "${RETRY_ARGS[@]}" -r fEsxXR \
                        --junitxml=junit-core.xml \
                        $COV_ARGS \
                        $PYTEST_ARGS
                  fi
                  exit_code=$?
                  set -e
                  if [ $exit_code -eq 5 ]; then
                      echo "No tests collected for this shard, this is expected when splitting tests"
                      exit 0
                  else
                      exit $exit_code
                  fi

            - name: Log test environment diagnostics
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Temporal' }}
              shell: bash
              env:
                  SHARD_GROUP: ${{ matrix.group }}
                  SHARD_CONCURRENCY: ${{ matrix.concurrency }}
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
                  COMMIT_SHA: ${{ github.sha }}
                  BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
              run: |
                  echo "=== Test Environment Diagnostics ==="
                  echo "Shard: $SHARD_GROUP/$SHARD_CONCURRENCY"
                  echo "Python version: $(python --version)"
                  echo "Events schema: $CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA"
                  echo "Commit: $COMMIT_SHA"
                  echo "Branch: $BRANCH_NAME"
                  echo "Runner: $(uname -a)"
                  echo "Memory: $(free -h | head -2)"
                  echo "Disk: $(df -h / | tail -1)"
                  echo "Docker containers:"
                  docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" || true
                  echo "==================================="
            - name: Run Temporal tests
              continue-on-error: true
              id: run-temporal-tests
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Temporal' }}
              shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'
              env:
                  AWS_S3_ALLOW_UNSAFE_RENAME: 'true'
                  MODAL_TOKEN_ID: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_ID || '' }}
                  MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
                  MODE: ${{ needs.turbo-discover.outputs.mode }}
                  TEMPORAL_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').temporal_files }}
              run: |
                  unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
                  set +e
                  # Open PR heads must have retry diagnostics before blanket retries are enabled.
                  RETRY_ARGS=()
                  if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
                      RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
                  fi
                  # Pick the split algorithm and granularity at runtime (see Run Core tests).
                  SPLITTING_ALGORITHM=duration_based_chunks
                  SPLIT_GRANULARITY=()
                  if python -c "from pytest_split.algorithms import Algorithms; from pytest_split.plugin import PytestSplitFilePlugin; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
                      SPLITTING_ALGORITHM=optimal_chunks
                      SPLIT_GRANULARITY=(--split-granularity=file)
                      # Plan path disabled while the cached plan predates the temporal
                      # routing move, see the .github workflow for the full note.
                      :
                  fi
                  # Depot-only quarantine: the data-modeling materialize path (get_s3_client) 403s on
                  # MinIO on Depot-native CI only — MinIO itself is reachable with the standard test creds
                  # (verified via boto3 LIST/CREATE/HEAD), so root cause is env-specific and not yet
                  # isolated (tracked for follow-up). All three tests below run that materialize path; the
                  # two timeout tests fail downstream (hogql_table never reached).
                  # The --deselect guards stay on both branches so a selected run can't re-enable them.
                  if [[ "$MODE" == "selected" ]]; then
                      # Selected mode uses the same single-retry budget as the full run.
                      SELECTED_SPLIT=()
                      if [[ "${{ matrix.concurrency }}" -gt 1 ]]; then
                          SELECTED_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"
                                          --splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")
                      fi
                      # shellcheck disable=SC2086
                      pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \
                          "${SELECTED_SPLIT[@]}" \
                          "${RETRY_ARGS[@]}" -r fEsxXR \
                          --junitxml=junit-temporal.xml \
                          $PYTEST_ARGS
                  else
                      # No per-test pytest --timeout; rely on the job-level timeout-minutes as the single
                      # safety net. The per-test timeout also terminates the whole process, so it adds
                      # no protection beyond the job timeout.
                      pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/signals/backend/emission -m "not async_migrations" \
                          --splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
                          --durations=100 --durations-min=1.0 --store-durations \
                          --pytest-durations=100 \
                          --splitting-algorithm="$SPLITTING_ALGORITHM" \
                          "${SPLIT_GRANULARITY[@]}" \
                          "${RETRY_ARGS[@]}" -r fEsxXR \
                          --junitxml=junit-temporal.xml \
                          $PYTEST_ARGS
                  fi
                  exit_code=$?
                  set -e
                  if [ $exit_code -eq 5 ]; then
                      echo "No tests collected for this shard, this is expected when splitting tests"
                      exit 0
                  else
                      exit $exit_code
                  fi
            # Post tests
            - name: Show docker compose logs on failure
              if: failure() && (needs.changes.outputs.backend == 'true' && steps.run-core-tests.outcome != 'failure' && steps.run-temporal-tests.outcome != 'failure')
              shell: bash
              run: docker compose -f docker-compose.dev.yml logs

            - name: Upload test results
              timeout-minutes: 7
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              if: ${{ always() }}
              with:
                  # Re-run attempts suffix the name: a same-name upload supersedes attempt 1's
                  # artifact, and the timing reporter needs both to pair a re-run recovery
                  # (attempt-N pass) with the attempt-1 failure it proves flaky.
                  name: junit-results-backend-${{ matrix.artifact_key }}${{ github.run_attempt != '1' && format('-attempt{0}', github.run_attempt) || '' }}
                  path: |
                      junit-*.xml
                      !junit-*-retry-failures.xml

            - name: Upload events schema recording
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              if: ${{ always() && matrix.json-targets && github.event_name == 'schedule' }}
              with:
                  name: events-schema-record-${{ matrix.artifact_key }}${{ github.run_attempt != '1' && format('-attempt{0}', github.run_attempt) || '' }}
                  path: events-schema-record.json
                  # A successful run must carry every shard's recording, because the prune
                  # manifest is built from successful runs only.
                  if-no-files-found: error
                  retention-days: 14

            - name: Archive email renders
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              if: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' && !matrix.person-on-events && !matrix.new-events-schema && !matrix.compat }}
              with:
                  name: email_renders-${{ github.sha }}-${{ github.run_attempt }}-${{ matrix.segment }}-${{ matrix.person-on-events }}-${{ matrix.group }}
                  path: posthog/tasks/test/__emails__
                  retention-days: 1

            - name: Upload core coverage
              continue-on-error: true
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              if: ${{ always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core' && !matrix.json-targets }}
              with:
                  name: coverage-core-${{ strategy.job-index }}
                  path: .coverage
                  include-hidden-files: true
                  if-no-files-found: ignore
                  retention-days: 2
                  overwrite: true # artifacts are immutable per run; re-run shards would 409 otherwise

            - name: Upload updated timing data as artifacts
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              # Upload on master, or on PRs that change timing/sharding scripts (for validation)
              if: ${{ (env.IS_MASTER == 'true' || needs.changes.outputs.timing_scripts == 'true') && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && !matrix.new-events-schema && matrix.clickhouse-server-image == needs.get_clickhouse_versions.outputs.oldest_supported_image }}
              with:
                  name: timing_data-${{ matrix.segment }}-${{ matrix.group }}
                  path: .test_durations
                  include-hidden-files: true
                  retention-days: 2

            - name: Prepare snapshot patch
              id: snapshot-patch
              if: ${{ needs.detect-snapshot-mode.outputs.mode == 'update' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && !matrix.compat && steps.run-core-tests.outcome != 'failure' && steps.run-temporal-tests.outcome != 'failure' }}
              shell: bash
              # The reruns must write the same schema mode's snapshot file as the main
              # run, or the new-schema file removed before each rerun never comes back.
              env:
                  CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: ${{ matrix.new-events-schema && 'true' || 'false' }}
              run: |
                  # Each schema leg may only ship its own snapshot files. A leg still
                  # *claims* the other schema mode's snapshot names without writing them,
                  # so syrupy deletes them from the working tree as unused; scoping the
                  # patch keeps those deletions out of the committed diff.
                  if [[ "$CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA" == "true" ]]; then
                    ambr_pathspec=('*.new_events_schema.ambr')
                  else
                    ambr_pathspec=('*.ambr' ':(exclude)*.new_events_schema.ambr')
                  fi
                  if [[ -z "$(git ls-files --others --exclude-standard -- "${ambr_pathspec[@]}")" ]] && git diff --quiet -- "${ambr_pathspec[@]}"; then
                    echo "No snapshot changes"
                    exit 0
                  fi

                  unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
                  .github/scripts/verify-new-snapshots.sh
                  mkdir -p /tmp/patches
                  # Stage any new/modified .ambr files so they appear in git diff
                  git add -N '*.ambr' || true
                  # Generate patch if there are changes
                  if ! git diff --quiet -- "${ambr_pathspec[@]}" 2>/dev/null; then
                    git diff --binary --full-index -- "${ambr_pathspec[@]}" > /tmp/patches/backend-${{ matrix.artifact_key }}.patch
                    echo "Generated patch with $(wc -l < /tmp/patches/backend-${{ matrix.artifact_key }}.patch) lines"
                    echo "changed=true" >> "$GITHUB_OUTPUT"
                  else
                    echo "No snapshot changes to patch"
                  fi

            - name: Upload snapshot patch
              if: ${{ steps.snapshot-patch.outputs.changed == 'true' }}
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: snapshot-patch-${{ matrix.artifact_key }}
                  path: /tmp/patches/
                  if-no-files-found: ignore
                  retention-days: 1

            # The helper sets TRUNK_CODEOWNERS_PATH so Trunk attributes uploaded tests to their owners.
            - name: Build the Trunk ownership map
              if: ${{ !cancelled() && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
              shell: bash
              run: |
                  script=.github/scripts/trunk-codeowners.sh
                  if [ -x "$script" ]; then "$script" "$RUNNER_TEMP/trunk-codeowners" "junit-*.xml"; fi

            - name: Quarantine gate (Core)
              id: quarantine_gate_core
              continue-on-error: true
              if: ${{ !cancelled() && matrix.segment == 'Core' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
              uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2
              with:
                  junit-paths: junit-core.xml,junit-core-retry-failures.xml
                  org-slug: posthog-inc
                  test-collection-id: AA6dvTdI # backend-core
                  # Non-default rows upload under their own variant, so a failure only that mode
                  # hits does not quarantine the default test with the same id.
                  variant: ${{ matrix.compat && format('compat-{0}', matrix.clickhouse-server-image) || matrix.person-on-events && (matrix.new-events-schema && 'poe-off-events-json' || 'poe-off') || matrix.new-events-schema && 'events-json' || '' }}
                  cli-version: '0.15.4'
                  quarantine: true
                  previous-step-outcome: ${{ steps.run-core-tests.outcome }}
                  token: ${{ secrets.TRUNK_API_TOKEN }}

            - name: Quarantine gate (Temporal)
              id: quarantine_gate_temporal
              continue-on-error: true
              if: ${{ !cancelled() && matrix.segment == 'Temporal' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
              uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2
              with:
                  junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xml
                  org-slug: posthog-inc
                  test-collection-id: smyQjxZ3 # backend-temporal
                  # A native-JSON row uploads under its own variant, so a failure in that mode
                  # does not read as a flake of the legacy test with the same id.
                  variant: ${{ matrix.new-events-schema && 'events-json' || '' }}
                  cli-version: '0.15.4'
                  quarantine: true
                  previous-step-outcome: ${{ steps.run-temporal-tests.outcome }}
                  token: ${{ secrets.TRUNK_API_TOKEN }}

            - name: Fail on test failure
              if: ${{ !cancelled() && ((steps.run-core-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_core.outcome != 'success')) || (steps.run-temporal-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_temporal.outcome != 'success'))) }}
              shell: bash
              run: exit 1

    # Read ClickHouse versions for the compat test matrix.
    get_clickhouse_versions:
        name: Get ClickHouse versions
        needs: [changes]
        if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        outputs:
            # Oldest supported version as plain string (for comparisons)
            oldest_supported_image: ${{ steps.read-versions.outputs.oldest_supported_image }}
            # Local dev / hobby image, mirrored from clickhouse-versions.json `local`
            local_image: ${{ steps.read-versions.outputs.local_image }}
            # Fully expanded compat matrix (version x shard group)
            compat_matrix: ${{ steps.read-versions.outputs.compat_matrix }}
        steps:
            # Merge ref: turbo-tests and django check out the merge ref and mount its config.xml.
            # Reading the version from another ref would split an atomic version+config bump.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  sparse-checkout: .github/clickhouse-versions.json
                  sparse-checkout-cone-mode: false
            - name: Read ClickHouse versions from JSON
              id: read-versions
              run: |
                  compat_shards="2"
                  echo "Using $compat_shards shard(s) per compat version"

                  # Oldest supported version for main Django tests (for max compatibility)
                  oldest_supported=$(jq -r '.oldest_supported' .github/clickhouse-versions.json)
                  if [ -z "$oldest_supported" ] || [ "$oldest_supported" = "null" ]; then
                    echo "::error::No oldest_supported version found in .github/clickhouse-versions.json"
                    exit 1
                  fi
                  echo "oldest_supported_image=$oldest_supported" >> $GITHUB_OUTPUT
                  echo "Oldest supported version for Django tests: $oldest_supported"

                  # Local dev / hobby image — the version product (turbo) tests run against.
                  local_image=$(jq -r '.local' .github/clickhouse-versions.json)
                  if [ -z "$local_image" ] || [ "$local_image" = "null" ]; then
                    echo "::error::No local version found in .github/clickhouse-versions.json"
                    exit 1
                  fi
                  echo "local_image=$local_image" >> $GITHUB_OUTPUT
                  echo "Local dev/hobby image for product tests: $local_image"

                  # Read all unique versions so we can derive compat coverage.
                  all=$(jq -c '[.[]] | unique' .github/clickhouse-versions.json)
                  if [ "$all" = "[]" ] || [ -z "$all" ]; then
                    echo "::error::No versions found in .github/clickhouse-versions.json"
                    exit 1
                  fi
                  echo "All CH versions found: $all"

                  # Compat coverage is only needed for non-oldest versions.
                  compat_versions=$(jq -c --arg oldest "$oldest_supported" '[.[]] | unique | map(select(. != $oldest))' .github/clickhouse-versions.json)
                  echo "Compat versions (excluding oldest): $compat_versions"

                  compat_count=$(jq -r 'length' <<< "$compat_versions")
                  echo "compat_count=$compat_count" >> $GITHUB_OUTPUT

                  if [ "$compat_count" -eq 0 ]; then
                    echo "compat_matrix=[]" >> $GITHUB_OUTPUT
                    echo "No non-oldest CH versions found — compat tests provide no additional coverage, skipping"
                  else
                    compat_matrix=$(jq -cn --argjson versions "$compat_versions" --argjson shards "$compat_shards" '
                      [
                        $versions[] as $version
                        | range(1; $shards + 1) as $group
                        | {
                            "clickhouse-server-image": $version,
                            "concurrency": $shards,
                            "group": $group
                          }
                      ]
                    ')
                    echo "compat_matrix=$compat_matrix" >> $GITHUB_OUTPUT
                    echo "Compat matrix: $compat_matrix"
                  fi
    # Aggregate and commit snapshot changes from all matrix jobs
    handle-snapshots:
        name: Commit snapshot changes
        needs: [changes, detect-snapshot-mode, django, turbo-tests]
        # Only in UPDATE mode - CHECK mode verifies snapshots match exactly
        # Run even if some matrix jobs failed (to commit snapshots from passing jobs)
        if: ${{ !cancelled() && needs.detect-snapshot-mode.outputs.mode == 'update' && needs.changes.outputs.backend == 'true' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog' }}
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        steps:
            # Look for patches before the checkout. Most runs have none, and the required
            # gate waits for this job.
            - name: Download all snapshot patches
              id: download-patches
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  pattern: snapshot-patch-*
                  path: /tmp/snapshot-patches
                  merge-multiple: true

            - name: Check for patches
              id: check-patches
              run: |
                  if [ "${{ steps.download-patches.outcome }}" == "failure" ] || [ ! -d /tmp/snapshot-patches ]; then
                    echo "has-patches=false" >> $GITHUB_OUTPUT
                    echo "No snapshot patches found"
                    exit 0
                  fi

                  if [ -n "$(find /tmp/snapshot-patches -name '*.patch' -type f -size +0c 2>/dev/null)" ]; then
                    echo "has-patches=true" >> $GITHUB_OUTPUT
                    echo "Found patches:"
                    ls -la /tmp/snapshot-patches/
                  else
                    echo "has-patches=false" >> $GITHUB_OUTPUT
                    echo "Patch files empty or missing - no snapshot changes"
                  fi

            # Use GitHub app token so Actions run after commiting updated snapshots
            - name: Get app token
              if: steps.check-patches.outputs.has-patches == 'true'
              id: app-token
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}

            - name: Checkout
              if: steps.check-patches.outputs.has-patches == 'true'
              uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  ref: ${{ github.event.pull_request.head.sha }}
                  repository: ${{ github.event.pull_request.head.repo.full_name }}
                  token: ${{ steps.app-token.outputs.token }}
                  fetch-depth: 1

            - name: Require snapshot conflict checks
              if: steps.check-patches.outputs.has-patches == 'true'
              run: |
                  if ! grep -Fq 'marker: snapshot-conflict-exit' .depot/actions/commit-snapshots/action.yml; then
                      echo "::error::Rebase onto master before committing snapshots. This PR head cannot reject conflicting snapshot patches."
                      exit 1
                  fi

            - name: Get app token for CI report
              # continue-on-error: an empty token skips the CI report section, not the commit.
              if: steps.check-patches.outputs.has-patches == 'true'
              id: ci-report-app-token
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-pull-requests: write

            - name: Set up Node.js
              if: steps.ci-report-app-token.outputs.token != ''
              uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
              with:
                  node-version-file: .nvmrc
                  token: ${{ steps.ci-report-app-token.outputs.token }}

            - name: Commit snapshots
              if: steps.check-patches.outputs.has-patches == 'true'
              uses: ./.depot/actions/commit-snapshots
              with:
                  workflow-type: backend
                  patch-path: /tmp/snapshot-patches
                  snapshot-path: '.'
                  commit-message: 'test(backend): update query snapshots'
                  pr-number: ${{ github.event.pull_request.number }}
                  repository: ${{ github.repository }}
                  commit-sha: ${{ github.event.pull_request.head.sha }}
                  branch-name: ${{ github.event.pull_request.head.ref }}
                  github-token: ${{ steps.app-token.outputs.token }}
                  ci-report-token: ${{ steps.ci-report-app-token.outputs.token }}

    # Job just to collate the status of the matrix jobs for requiring passing status
    # Must depend on handle-snapshots to prevent auto-merge before commits complete
    django_tests:
        needs:
            [
                changes,
                get_clickhouse_versions,
                build_django_matrix,
                django,
                check-migrations,
                check-openapi-types,
                turbo-discover,
                build-product-test-matrix,
                turbo-tests,
                detect-snapshot-mode,
                handle-snapshots,
                repo-checks,
                sdk-major-guard,
            ]
        name: Django Tests Pass on Depot
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 8
        # !cancelled() collates skipped/failed matrix jobs without reporting failure on a
        # superseded run.
        if: >
            !cancelled()
            || needs.repo-checks.outputs.deterministic_failure == 'true'
            || needs.check-openapi-types.outputs.deterministic_failure == 'true'
        env:
            # The gate check posts the summary as its output, titled by the first line of the title file.
            GATE_SUMMARY: /tmp/gate-check-summary.md
            GATE_TITLE: /tmp/gate-check-title
        steps:
            - name: Refuse a fork pull request
              if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
              run: |
                  echo "::error::Depot CI does not run fork pull requests. Re-create the change on a branch in this repository after review."
                  exit 1
            - name: Summarize dependency results
              run: |
                  {
                    echo "### Backend CI dependency results"
                    echo "| Dependency | Result |"
                    echo "| --- | --- |"
                    echo "| changes | ${{ needs.changes.result }} |"
                    echo "| get_clickhouse_versions | ${{ needs.get_clickhouse_versions.result }} |"
                    echo "| build_django_matrix | ${{ needs.build_django_matrix.result }} |"
                    echo "| django | ${{ needs.django.result }} |"
                    echo "| check-migrations | ${{ needs.check-migrations.result }} |"
                    echo "| check-openapi-types | ${{ needs.check-openapi-types.result }} |"
                    echo "| repo-checks | ${{ needs.repo-checks.result }} |"
                    echo "| sdk-major-guard | ${{ needs.sdk-major-guard.result }} |"
                    echo "| turbo-discover | ${{ needs.turbo-discover.result }} |"
                    echo "| build-product-test-matrix | ${{ needs.build-product-test-matrix.result }} |"
                    echo "| turbo-tests | ${{ needs.turbo-tests.result }} |"
                    echo "| handle-snapshots | ${{ needs.handle-snapshots.result }} |"
                    if [[ "${{ needs.repo-checks.outputs.deterministic_failure }}" == "true" ]]; then
                      echo ""
                      echo "**Root cause:** Repo checks failed deterministically. Open the repo checks job logs; downstream cancelled jobs are expected."
                    fi
                    if [[ "${{ needs.check-openapi-types.outputs.deterministic_failure }}" == "true" ]]; then
                      echo ""
                      echo "**Root cause:** OpenAPI type checks failed deterministically. Open the OpenAPI type check job logs; downstream cancelled jobs are expected."
                    fi
                  } | tee -a "$GITHUB_STEP_SUMMARY" "$GATE_SUMMARY"

            - name: Download shard JUnit results
              if: ${{ always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success') }}
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  pattern: '{junit-results-backend,product-junit-results}-*'
                  path: /tmp/junit-gate/

            - name: Keep only each shard's latest attempt
              if: ${{ always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success') }}
              continue-on-error: true
              run: |
                  cd /tmp/junit-gate 2>/dev/null || exit 0
                  shopt -s nullglob
                  for d in *-attempt[0-9]*; do
                      base="${d%-attempt*}"
                      latest="$(printf '%s\n' "$base"-attempt[0-9]* | sort -V | tail -1)"
                      rm -rf "$base"
                      [[ "$d" == "$latest" ]] || rm -rf "$d"
                  done

            - name: Check dependency results
              id: verdict
              run: |
                  # Per-test failure rollup, emitted from THIS step because GitHub only
                  # auto-expands the failed step in the log view. Best-effort via `|| true`
                  # so a parser hiccup never changes the verdict computed below.
                  python3 <<'PY' || true
                  import glob, os, xml.etree.ElementTree as ET

                  ROOT = "/tmp/junit-gate"
                  rows = []  # (shard, nodeid, repo_file, message)

                  def clean(s):
                      # Collapse newlines so PR-authored test names can't inject ::workflow-commands::
                      return " ".join((s or "").split())

                  for path in glob.glob(os.path.join(ROOT, "**", "junit-*.xml"), recursive=True):
                      artifact = os.path.relpath(path, ROOT).split(os.sep)[0]
                      base = os.path.basename(path)
                      # Product JUnit is staged as junit-product-<name>.xml; backend keeps its key.
                      product = base[len("junit-product-"):-len(".xml")] if base.startswith("junit-product-") else ""
                      shard = f"products/{product}" if product else artifact.removeprefix("junit-results-backend-")
                      with open(path, "rb") as fh:
                          raw = fh.read()
                      # Refuse DTD/entity payloads (XXE, billion-laughs). pytest JUnit has neither,
                      # so real failures are never dropped; a crafted file is simply skipped.
                      if b"<!DOCTYPE" in raw or b"<!ENTITY" in raw:
                          continue
                      try:
                          tree = ET.fromstring(raw)
                      except ET.ParseError:
                          continue
                      for tc in tree.iter("testcase"):
                          bad = tc.find("failure")
                          if bad is None:
                              bad = tc.find("error")
                          if bad is None:
                              continue
                          name = tc.get("name", "")
                          file_ = tc.get("file", "") or tc.get("classname", "")
                          repo_file = f"products/{product}/{file_}" if product and file_ else file_
                          nodeid = clean("::".join(p for p in (repo_file, name) if p))
                          msg = clean(bad.get("message") or bad.text or "")[:200]
                          rows.append((clean(shard), nodeid, clean(repo_file), msg))

                  # Print only when something failed; on a green gate this stays silent.
                  if rows:
                      out = ["### Failing backend & product tests", "", f"{len(rows)} failing test(s):",
                             "", "| Shard | Test | Message |", "| --- | --- | --- |"]
                      for shard, nodeid, _f, msg in rows[:100]:
                          out.append(f"| {shard} | `{nodeid.replace('|', r'\|')}` | {msg.replace('|', r'\|')} |")
                      if len(rows) > 100:
                          out += ["", f"…and {len(rows) - 100} more."]
                      text = "\n".join(out) + "\n"
                      for path in (os.environ["GITHUB_STEP_SUMMARY"], os.environ["GATE_SUMMARY"]):
                          with open(path, "a") as fh:
                              fh.write(text)
                      with open(os.environ["GATE_TITLE"], "a") as fh:
                          fh.write(f"{len(rows)} failing test{'s' if len(rows) != 1 else ''}\n")
                      print(text)
                      for shard, nodeid, repo_file, msg in rows[:30]:
                          title = f"Backend test failed ({shard})"
                          body = f"{nodeid}: {msg}" if msg else nodeid
                          loc = f"file={repo_file}," if repo_file else ""
                          print(f"::error {loc}title={title}::{body}")
                  PY

                  if [[ "${{ needs.repo-checks.outputs.deterministic_failure }}" == "true" ]]; then
                    echo "::error title=Repo checks failed deterministically::Open the repo checks job for the root failure. Backend CI cancelled downstream jobs to save runners; retrying will not fix this."
                  fi

                  if [[ "${{ needs.check-openapi-types.outputs.deterministic_failure }}" == "true" ]]; then
                    echo "::error title=OpenAPI type checks failed deterministically::Open the OpenAPI type check job for the root failure. Backend CI cancelled downstream jobs to save runners; retrying will not fix this."
                  fi

                  check_required_result() {
                    local label="$1"
                    local result="$2"

                    if [[ "$result" != "success" && "$result" != "skipped" ]]; then
                      echo "::error::$label did not succeed (result: '$result')."
                      echo "$label did not succeed on Depot" >> "$GATE_TITLE"
                      exit 1
                    fi
                  }

                  # Upstream jobs whose failure would otherwise only cascade into django
                  # being *skipped*, which this gate reads as success — a green gate with
                  # zero backend tests run. Naming them makes the failure hit the gate
                  # directly; legitimate skips (frontend-only PRs) and plain successes still pass.
                  check_required_result "Change detection" "${{ needs.changes.result }}"
                  check_required_result "ClickHouse versions" "${{ needs.get_clickhouse_versions.result }}"
                  check_required_result "Django matrix build" "${{ needs.build_django_matrix.result }}"
                  check_required_result "Django test matrix" "${{ needs.django.result }}"
                  check_required_result "Migration checks" "${{ needs.check-migrations.result }}"
                  check_required_result "OpenAPI type checks" "${{ needs.check-openapi-types.result }}"
                  check_required_result "Repo checks" "${{ needs.repo-checks.result }}"
                  check_required_result "SDK major guard" "${{ needs.sdk-major-guard.result }}"
                  check_required_result "Turbo discover" "${{ needs.turbo-discover.result }}"
                  check_required_result "Product test matrix build" "${{ needs.build-product-test-matrix.result }}"
                  check_required_result "Product/Turbo tests" "${{ needs.turbo-tests.result }}"
                  check_required_result "Snapshot mode detection" "${{ needs.detect-snapshot-mode.result }}"
                  check_required_result "Snapshot commit job" "${{ needs.handle-snapshots.result }}"

                  echo "All backend and product checks passed."

            # A separate checks:write token, minted in a job that runs no pull request code.
            - name: Mint gate check token
              id: gate-token
              if: ${{ always() && github.event_name == 'pull_request' }}
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-checks: write
            # Depot's own checks carry no output and their pages need a Depot login, so this
            # check carries the gate summary: GitHub shows the title on the PR's check row
            # and the summary on the Checks tab. Branch protection requires this check, so a
            # failed post must fail the gate.
            - name: Post the test results check
              if: ${{ always() && steps.gate-token.outputs.token != '' }}
              env:
                  GH_TOKEN: ${{ steps.gate-token.outputs.token }}
                  REPO: ${{ github.repository }}
                  SHA: ${{ github.event.pull_request.head.sha }}
                  GATE_CHECK: Backend CI on Depot / Test results
                  # A `no-ci` draft skips change detection and every check.
                  CONCLUSION: ${{ job.status == 'cancelled' && 'cancelled' || needs.changes.result == 'skipped' && 'skipped' || (steps.verdict.outcome == 'success' && 'success' || 'failure') }}
                  # A completed check stays on the commit, so a draft's passing verdict would satisfy
                  # branch protection the moment the PR turns ready. Merge-queue PRs are drafts whose
                  # run is the verdict.
                  IS_DRAFT: ${{ github.event.pull_request.draft && !startsWith(github.head_ref, 'trunk-merge/') }}
              run: |
                  if [[ "$IS_DRAFT" == "true" && "$CONCLUSION" != "failure" ]]; then
                      echo "Draft run: the ready-for-review run posts the $GATE_CHECK check."
                      exit 0
                  fi
                  case "$CONCLUSION" in
                      success) title="Backend tests passed on Depot" ;;
                      skipped) title="No backend checks ran on Depot" ;;
                      cancelled) title="Backend tests cancelled on Depot" ;;
                      *) title=$(head -1 "$GATE_TITLE" 2>/dev/null || true); title="${title:-Backend tests failed on Depot}" ;;
                  esac
                  # One request carries the verdict and the output. A PATCH sent right after the POST
                  # can answer 404, because GitHub does not always find a check it just created.
                  # GitHub rejects a summary over 65535 characters, and the byte budget below stays
                  # under that however the characters are encoded.
                  # The retry hint goes first, because the byte budget trims the summary from the end.
                  touch "$GATE_SUMMARY"
                  jq -n --arg name "$GATE_CHECK" --arg sha "$SHA" --arg conclusion "$CONCLUSION" --arg url "$DEPOT_JOB_URL" \
                      --arg title "$title" --rawfile summary "$GATE_SUMMARY" \
                      '{name: $name, head_sha: $sha, status: "completed", conclusion: $conclusion, details_url: $url,
                        output: {title: $title, summary: ((if $conclusion == "failure" then "To retry the failed jobs without a new push, comment `/depot retry` on this pull request.\n\n" else "" end) + $summary | if utf8bytelength > 60000 then until(utf8bytelength <= 60000; .[:-1000]) + "\n\n(truncated)" else . end)}}' \
                      | gh api "repos/$REPO/check-runs" --method POST --input - --silent && exit 0
                  # A rejected output must not lose the check.
                  echo "::warning::Could not post the gate check with its summary. Posting it without."
                  gh api "repos/$REPO/check-runs" --method POST -f name="$GATE_CHECK" \
                      -f head_sha="$SHA" -f status=completed -f conclusion="$CONCLUSION" -f details_url="$DEPOT_JOB_URL" --silent
    test-selection-verdict:
        needs: [django, turbo-tests, changes, turbo-discover]
        name: Test selection verdict
        # The verdict scores the selection against the JUnit a run produced, so it needs
        # a test job to have run. changes is skipped on no-ci drafts. Both matrices are
        # skipped on a draft whose selection was untrusted, which defers to the ready run
        # — there is no selection to score and no JUnit to score it against. The decision
        # itself is still recorded, by capture-test-selection.
        if: >-
            !cancelled() && github.event_name == 'pull_request' &&
            needs.changes.result != 'skipped' &&
            (needs.django.result != 'skipped' || needs.turbo-tests.result != 'skipped')
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 10
        permissions:
            contents: read
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  fetch-depth: 1000
                  filter: blob:none

            - name: Install uv
              uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false

            - name: Download JUnit artifacts
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  pattern: junit-results-backend-*
                  path: /tmp/junit-results/
              continue-on-error: true

            # Re-run attempts upload under suffixed names; without this the verdict double-counts
            # re-executed shards and resurrects failures the re-run already recovered.
            - name: Keep only each shard's latest attempt
              continue-on-error: true
              run: |
                  cd /tmp/junit-results 2>/dev/null || exit 0
                  shopt -s nullglob
                  for d in *-attempt[0-9]*; do
                      base="${d%-attempt*}"
                      latest="$(printf '%s\n' "$base"-attempt[0-9]* | sort -V | tail -1)"
                      rm -rf "$base"
                      [[ "$d" == "$latest" ]] || rm -rf "$d"
                  done

            # Reuse the selection artifact from the turbo-discover job rather than
            # re-running the snob script. Falls through if the artifact wasn't
            # produced (the selector did not run or failed) — the next step
            # regenerates it so we still get a shadow verdict for those PRs.
            - name: Download selection artifact
              id: download-selection
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  name: select-tests-output
                  path: /tmp/verdict/

            - name: Download the run's sharding plan snapshot
              # The verdict reports selected seconds per segment from .test_durations,
              # which is not in the repo; use the union turbo-discover snapshotted.
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  name: test-durations-plan
                  path: .

            - name: Run test selection and verdict
              env:
                  DIFF_BASE: ${{ format('{0}^1', github.sha) }}
                  PR_NUMBER: ${{ github.event.pull_request.number }}
                  PR_SHA: ${{ github.event.pull_request.head.sha }}
              run: |
                  set -euo pipefail
                  mkdir -p /tmp/verdict

                  if [[ ! -s /tmp/verdict/selection.json ]]; then
                      test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
                      test "$(git rev-list --parents -n 1 HEAD | wc -w)" -eq 3
                      test "$(git rev-parse HEAD^2)" = "$PR_SHA"
                      git rev-parse --verify "$DIFF_BASE^{commit}"

                      uv run tools/snob_backend_test_selection_shadow.py \
                          --base-ref "$DIFF_BASE" \
                          --pretty \
                          > /tmp/verdict/selection.json
                  fi

                  uv run tools/test_selection_verdict.py \
                      /tmp/verdict/selection.json \
                      /tmp/junit-results/ \
                      --summary-path "$GITHUB_STEP_SUMMARY" \
                      --pretty \
                      > /tmp/verdict/verdict.json

            - name: Upload verdict
              if: always()
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: test-selection-verdict-pr${{ github.event.pull_request.number }}
                  path: /tmp/verdict/
                  retention-days: 90

    capture-test-selection:
        name: Capture test selection
        needs: [turbo-discover]
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        # An empty mode means this run never selected, so there is no decision to report.
        # DevEx project only, mirroring monitor-github-rate-limit; continue-on-error so
        # telemetry never reds CI. Skipped on forks/Dependabot, which never have the secret.
        if: |
            !cancelled()
            && github.actor != 'dependabot[bot]'
            && github.event.pull_request.head.repo.full_name == 'PostHog/posthog'
            && needs.turbo-discover.result == 'success'
            && needs.turbo-discover.outputs.mode != ''
        steps:
            - name: Capture test selection to DevEx PostHog
              # Depot CI evaluates github.run_attempt as an empty string in a job-level if,
              # so this guard stays on the step for the Depot copy of this job to run.
              if: github.run_attempt == '1'
              continue-on-error: true
              uses: PostHog/posthog-github-action@58dea254b598fb5d469c0699c98af8288a7f7650 # v1.2.0
              with:
                  posthog-token: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
                  event: 'posthog-ci-test-selection'
                  properties: ${{ needs.turbo-discover.outputs.telemetry }}

    report-test-timings:
        name: Report per-test traces
        # django and turbo-tests are here for their results only; django_tests already
        # waits for both, so this adds no wall time.
        needs: [django_tests, django, turbo-tests]
        runs-on: depot-ubuntu-24.04
        continue-on-error: true
        timeout-minutes: 10
        # Runs on every attempt: a re-run passing what an earlier attempt failed is the same-commit
        # flake proof the test-health queue reads, and the shards a re-run re-executed upload under
        # attempt-suffixed artifact names so only they are emitted for the new attempt.
        # Scheduled master runs and all in-repo PRs. Skip forks (no secrets access)
        # and master pushes (their matrices are skipped, so there are no traces).
        # Both matrices skipped also means no JUnit was uploaded, so there are no
        # traces to emit. This job sits on the tail of the run, so skipping it takes
        # its whole duration off the wall of a draft that ran no tests.
        if: >-
            !cancelled() &&
            github.repository == 'PostHog/posthog' &&
            (needs.django.result != 'skipped' || needs.turbo-tests.result != 'skipped') &&
            (
            github.event_name == 'schedule' ||
            (github.event_name != 'pull_request' && github.event_name != 'push' && github.event_name != 'api' && github.ref == 'refs/heads/master') ||
            (github.event_name == 'pull_request' &&
            github.event.pull_request.head.repo.full_name == 'PostHog/posthog')
            )
        steps:
            # Labelled PRs run the trusted base parser, so the same PR can't swap the script that receives secrets.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.sha }}
                  fetch-depth: 1
            - name: Check for trusted timing reporter
              id: timing-reporter
              shell: bash
              run: |
                  # The owners resolver is a path dep of the reporter, so a base ref predating it
                  # can't resolve its deps. A base ref from before the move to packages/owners-yaml still
                  # carries it at tools/owners, so both locations count as available.
                  available=false
                  if [[ -f .github/scripts/report_test_timings.py && ( -d packages/owners-yaml || -d tools/owners ) ]]; then
                    available=true
                  fi
                  # A re-run may emit only through an attempt-aware reporter: an older script would
                  # re-report every attempt-1 shard under the new attempt's resource attributes.
                  if [[ "$GITHUB_RUN_ATTEMPT" != "1" ]] && ! grep -q "def partition_run_attempt" .github/scripts/report_test_timings.py 2>/dev/null; then
                    available=false
                  fi
                  if [[ "$available" != "true" ]]; then
                    echo "Trusted timing reporter is not available on the checked-out ref for attempt $GITHUB_RUN_ATTEMPT; skipping emit."
                  fi
                  echo "available=$available" >> "$GITHUB_OUTPUT"
            # Direct install: The trusted PR base used for reporting may predate the local action.
            - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
              if: steps.timing-reporter.outputs.available == 'true'
              with:
                  version: '0.13.4'
            - name: Download junit artifacts
              if: steps.timing-reporter.outputs.available == 'true'
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  path: ./junit-artifacts
                  pattern: '{junit-results-backend,product-junit-results}-*'
            - name: Emit per-test traces
              if: steps.timing-reporter.outputs.available == 'true'
              continue-on-error: true
              env:
                  POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
                  # dual emission while per-test traces migrate to the project behind POSTHOG_API_TOKEN
                  POSTHOG_CI_TRACES_EXTRA_TOKEN: ${{ secrets.POSTHOG_API_TOKEN }}
                  POSTHOG_OTLP_TRACES_ENDPOINT: ${{ vars.POSTHOG_OTLP_TRACES_ENDPOINT || 'https://us.i.posthog.com/i/v1/traces' }}
              run: |
                  uv run --script .github/scripts/report_test_timings.py \
                      --min-duration-seconds=0.5 \
                      ./junit-artifacts

    backend-coverage-report:
        name: Backend coverage report
        needs: [changes, django, turbo-tests, django_tests, turbo-discover]
        runs-on: depot-ubuntu-24.04
        continue-on-error: true
        timeout-minutes: 10
        permissions:
            contents: read
        if: >-
            !cancelled() &&
            github.event_name == 'pull_request' &&
            github.event.pull_request.draft == false &&
            needs.turbo-discover.outputs.mode != 'selected' &&
            github.event.pull_request.head.repo.full_name == 'PostHog/posthog' &&
            (needs.turbo-tests.result != 'skipped' || needs.django.result != 'skipped')
        steps:
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              with:
                  fetch-depth: 0
                  filter: blob:none
            - name: Check for coverage reporter
              id: reporter
              shell: bash
              run: |
                  if [[ -f .github/scripts/coverage_report.py ]]; then
                      echo "available=true" >> "$GITHUB_OUTPUT"
                  else
                      echo "available=false" >> "$GITHUB_OUTPUT"
                      echo "Coverage reporter not present on this ref; skipping (branch may predate the check)."
                  fi
            - name: Download coverage artifacts
              if: steps.reporter.outputs.available == 'true'
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  path: ./cov-artifacts
                  pattern: coverage-products-*
            - name: Download core coverage artifacts
              if: steps.reporter.outputs.available == 'true'
              continue-on-error: true
              uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
              with:
                  path: ./core-artifacts
                  pattern: coverage-core-*
            - uses: ./.depot/actions/setup-uv
              with:
                  enable-cache: false
              if: steps.reporter.outputs.available == 'true'
            - name: Build coverage report
              if: steps.reporter.outputs.available == 'true'
              run: |
                  mkdir -p cov-artifacts core-artifacts
                  git fetch --no-tags --filter=blob:none --quiet origin master
                  uv run --script .github/scripts/coverage_report.py \
                      --artifacts cov-artifacts \
                      --core-artifacts core-artifacts \
                      --combined-out combined-coverage.xml \
                      --compare-branch origin/master \
                      --patch-json-out patch-coverage.json \
                      --out coverage-comment.md
            - name: Get app token for CI report
              if: steps.reporter.outputs.available == 'true'
              id: ci-report-app-token
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-pull-requests: write
            - name: Set up Node.js
              if: steps.reporter.outputs.available == 'true'
              uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
              with:
                  node-version-file: .nvmrc
                  token: ${{ steps.ci-report-app-token.outputs.token }}
            - name: Post to CI report comment
              if: steps.reporter.outputs.available == 'true'
              env:
                  GITHUB_TOKEN: ${{ steps.ci-report-app-token.outputs.token }}
              run: |
                  if [ -f .github/scripts/post-coverage-section.mjs ]; then
                      node .github/scripts/post-coverage-section.mjs coverage-comment.md patch-coverage.json
                  fi
            - name: Upload patch coverage payload
              if: ${{ always() && steps.reporter.outputs.available == 'true' }}
              uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
              with:
                  name: patch-coverage
                  path: |
                      patch-coverage.json
                      combined-coverage.xml
                      coverage-comment.md
                  if-no-files-found: ignore
                  retention-days: 2
                  overwrite: true

    calculate-running-time:
        name: Calculate running time
        needs: [changes, django, turbo-tests, django_tests]
        runs-on: depot-ubuntu-24.04
        timeout-minutes: 5
        # Run on pull requests to PostHog/posthog + on PostHog/posthog outside of PRs - but never on forks or Dependabot (no secrets access)
        if: >-
            !cancelled() && github.actor != 'dependabot[bot]' && (
            (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') ||
            (github.event_name != 'pull_request' && github.repository == 'PostHog/posthog'))
            && needs.changes.result == 'success'
        permissions:
            contents: read
        steps:
            - name: Check whether stale backend coverage can be cleared
              id: coverage-cleanup
              if: >-
                  github.event_name == 'pull_request' &&
                  github.event.pull_request.draft == false &&
                  needs.changes.outputs.backend == 'false' &&
                  needs.django.result == 'skipped' &&
                  needs.turbo-tests.result == 'skipped' &&
                  needs.django_tests.result == 'success'
              run: echo "needed=true" >> "$GITHUB_OUTPUT"
            # Depot evaluates github.run_attempt as empty in a job-level `if`, so the attempt guard sits on the steps.
            - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
              id: checkout
              if: github.run_attempt == '1' || steps.coverage-cleanup.outputs.needed == 'true'
              continue-on-error: true
              with:
                  sparse-checkout: |
                      .github/scripts/capture_depot_running_time.py
                      frontend/bin/ci-report/update-ci-report.mjs
                      .nvmrc
                  sparse-checkout-cone-mode: false
            - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
              id: setup-depot
              if: github.run_attempt == '1' && steps.checkout.outcome == 'success'
              continue-on-error: true
            - name: Capture running time to PostHog and DevEx PostHog
              if: github.run_attempt == '1' && steps.setup-depot.outcome == 'success'
              continue-on-error: true
              env:
                  DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}
                  POSTHOG_API_TOKEN: ${{ secrets.POSTHOG_API_TOKEN }}
                  POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
                  STATUS_JOB: django_tests
              run: python3 .github/scripts/capture_depot_running_time.py
            - name: Get app token for coverage cleanup
              id: coverage-cleanup-token
              if: steps.coverage-cleanup.outputs.needed == 'true' && steps.checkout.outcome == 'success' && hashFiles('frontend/bin/ci-report/update-ci-report.mjs') != ''
              continue-on-error: true
              uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
              with:
                  client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
                  private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
                  permission-pull-requests: write
            - name: Set up Node.js for coverage cleanup
              if: steps.coverage-cleanup-token.outcome == 'success'
              id: coverage-cleanup-node
              continue-on-error: true
              uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
              with:
                  node-version-file: .nvmrc
                  token: ${{ steps.coverage-cleanup-token.outputs.token }}
            - name: Clear stale backend coverage warning
              if: steps.coverage-cleanup-node.outcome == 'success' && hashFiles('frontend/bin/ci-report/update-ci-report.mjs') != ''
              continue-on-error: true
              env:
                  GITHUB_TOKEN: ${{ steps.coverage-cleanup-token.outputs.token }}
              run: |
                  node --input-type=module -e "import { clearSectionIfPresent } from './frontend/bin/ci-report/update-ci-report.mjs'; await clearSectionIfPresent({ id: 'backend-coverage', summary: 'no backend files changed', body: 'No backend coverage report is needed for this change.' })"