: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): post depot migration reports from the migration job (#106888)
Raúl Negrón-Otero455cd822249b
diff --git a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md b/.agents/skills/depot-ci/references/posthog-check-run-semantics.mdindex 40f63c680680..c192b8bc198e 100644--- a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md+++ b/.agents/skills/depot-ci/references/posthog-check-run-semantics.md@@ -73,7 +73,7 @@ In the following cancelled runs, an unstarted job received a `cancelled` check w## Finding one event's Depot run-Check times and `pull_requests` did not pick out the Depot run in these cases, so the event goes into a check name. The Depot wait job's name ends with `(PR <number>, event <pull_request.updated_at>)`, and Depot renders expressions in job names into the check name. `.github/scripts/ci_backend_relay.py` builds the same name from the GitHub run's payload, reads that check, takes the Depot workflow id from its `details_url`, and reads the gate or migration check of that workflow only. Measured 2026-09-24 on PR 105886: Depot posted check `107656013423` named `… (PR 105886, event 2026-09-24T13:33:14Z)`, and GitHub relay job `107655803961` used `EVENT_AT: 2026-09-24T13:33:14Z` and relayed a successful gate.+Check times and `pull_requests` did not pick out the Depot run in these cases, so the event goes into a check name. The Depot wait job's name ends with `(PR <number>, event <pull_request.updated_at>)`, and Depot renders expressions in job names into the check name. `.github/scripts/ci_backend_relay.py` builds the same name from the GitHub run's payload, reads that check, takes the Depot workflow id from its `details_url`, and reads the gate check of that workflow only. Measured 2026-09-24 on PR 105886: Depot posted check `107656013423` named `… (PR 105886, event 2026-09-24T13:33:14Z)`, and GitHub relay job `107655803961` used `EVENT_AT: 2026-09-24T13:33:14Z` and relayed a successful gate.### Racing events@@ -87,6 +87,10 @@ GitHub Actions alone does the same. Among the 946 `ci-backend.yml` pull requestThe newest check per name tells you the verdict. It does not tell you whether the PR can merge. A cancelled run on the same head keeps its checks, and when one of them is a required check, GitHub's merge box and Trunk keep the PR blocked until that run is rerun. `/merging-prs` has the recipe.+## pull_request_target checks++Depot can post a `pull_request_target` job's check on another pull request's head commit. A `pull_request_target` run's `github.sha` is the base branch head, so pull requests opened against the same master commit share it, and every misplaced check measured sat on a commit whose own run shared that base commit. Measured 2026-09-25 on a migration report workflow that ran on `pull_request_target`: 35 of its 42 checks sat on the wrong commit. For example, check `108123656729` on PR 106758's head `0295b92b41` links Depot workflow `ljv421dmlt`, whose run `vpg4b1kvh7` tested PR 106767's head `fb236b6c26`, and both runs had base `7af9307723`. The jobs' own writes, a check posted with an explicit `head_sha` and a comment on an explicit PR number, reached the right pull request. Post pull-request-facing results from a `pull_request` workflow, whose checks land on the right head.+## Depot CI CLI recipesThe CLI needs ids that the GitHub API does not carry. Start from a check run's `details_url`, which encodes the workflow id and job id.diff --git a/.depot/workflows/ci-backend-report.yml b/.depot/workflows/ci-backend-report.ymldeleted file mode 100644index b6a21a174b9b..000000000000--- a/.depot/workflows/ci-backend-report.yml+++ /dev/null@@ -1,276 +0,0 @@-# This pull_request_target workflow runs from the base revision. It must never check out-# or execute pull request code because it holds credentials that write GitHub checks and-# pull request comments. The Backend CI workflow supplies report data through artifacts.-# Scope DEPOT_CI_BACKEND_TRUSTED_TOKEN and GH_APP_POSTHOG_TESTS_* to PostHog/posthog,-# master, and this trusted workflow. Do not configure broader fallback secrets.-name: Backend CI Depot migration reports--on:- pull_request_target:- branches: [master]- types: [opened, synchronize, reopened, ready_for_review]--concurrency:- group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}- cancel-in-progress: true--permissions:- contents: read- checks: read- pull-requests: read--jobs:- report-migrations:- if: >-- github.event.pull_request.head.repo.full_name == github.repository- && !startsWith(github.event.pull_request.head.ref, 'trunk-merge/')- && (github.event.pull_request.draft != true || !contains(github.event.pull_request.labels.*.name, 'no-ci'))- name: Report Depot migration results- runs-on: depot-ubuntu-24.04- timeout-minutes: 90- steps:- - name: Checkout the trusted relay script # nosemgrep: yaml.github-actions.security.pull-request-target-code-checkout.pull-request-target-code-checkout- # v6.0.2 checks out only the trusted base SHA below, never pull request code.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd- with:- repository: ${{ github.repository }}- ref: ${{ github.sha }}- path: trusted-relay- sparse-checkout: .github/scripts/ci_backend_relay.py- sparse-checkout-cone-mode: false- persist-credentials: false-- # First confirm GitHub Actions handed this commit to Depot. The script then finds- # this event's Depot run by its wait check name and waits for its migration check.- - name: Find the handed-off Depot migration run- id: source- env:- GH_TOKEN: ${{ github.token }}- REPO: ${{ github.repository }}- SHA: ${{ github.event.pull_request.head.sha }}- EVENT_AT: ${{ github.event.pull_request.updated_at }}- PR_NUMBER: ${{ github.event.pull_request.number }}- run: python3 trusted-relay/.github/scripts/ci_backend_relay.py migrations-- - name: Set up Depot CLI- if: steps.source.outputs.workflow_id != ''- uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1-- - name: Download migration report artifacts- if: steps.source.outputs.workflow_id != ''- id: artifacts- env:- DEPOT_TOKEN: ${{ secrets.DEPOT_CI_BACKEND_TRUSTED_TOKEN }}- WORKFLOW_ID: ${{ steps.source.outputs.workflow_id }}- HEAD_SHA: ${{ github.event.pull_request.head.sha }}- REPO: ${{ github.repository }}- DEPOT_ORG: ntsdt08fpt- run: |- set -euo pipefail- if [ -z "$DEPOT_TOKEN" ]; then- echo "::error::DEPOT_CI_BACKEND_TRUSTED_TOKEN is not configured for this trusted workflow"- exit 1- fi-- depot ci workflow show "$WORKFLOW_ID" --org "$DEPOT_ORG" --output json > /tmp/depot-workflow.json- RUN_ID=$(jq -r --arg workflow "$WORKFLOW_ID" --arg repo "$REPO" --arg sha "$HEAD_SHA" '- select(.workflow.workflow_id == $workflow and .run.repo == $repo and .run.head_sha == $sha)- | .run.run_id- ' /tmp/depot-workflow.json)- if [[ ! "$RUN_ID" =~ ^[a-z0-9]+$ ]]; then- echo "::error::Depot workflow metadata does not match this pull request"- exit 1- fi-- depot ci artifacts list "$RUN_ID" --org "$DEPOT_ORG" --output json > /tmp/depot-artifacts.json- mkdir -p /tmp/depot-migration-artifacts- download_artifact() {- local name=$1- local output=$2- local max_size=$3- local record- record=$(jq -c --arg workflow "$WORKFLOW_ID" --arg name "$name" '- [.artifacts[]- | select(.workflow_id == $workflow and .job_key == "ci-backend.yml:check-migrations" and .name == $name)]- | sort_by(.attempt, .created_at)- | last // empty- ' /tmp/depot-artifacts.json)- if [ -z "$record" ]; then- return 0- fi- local size- size=$(jq -r '.size_bytes' <<< "$record")- if [[ ! "$size" =~ ^[0-9]+$ ]] || [ "$size" -gt "$max_size" ]; then- echo "::error::$name artifact exceeds its size limit"- exit 1- fi- local artifact_id- artifact_id=$(jq -r '.artifact_id' <<< "$record")- depot ci artifacts download "$artifact_id" --org "$DEPOT_ORG" --output-file "$output"- }-- download_artifact migration-analysis /tmp/depot-migration-artifacts/migration-analysis.zip 2000000- download_artifact ch-migration-report /tmp/depot-migration-artifacts/ch-migration-report.zip 500000-- - name: Validate inert migration report data- if: steps.source.outputs.workflow_id != ''- id: validate- run: |- set -euo pipefail- mkdir -p /tmp/depot-migration-report- python3 - <<'PY'- import zipfile- from pathlib import Path, PurePosixPath-- output = Path("/tmp/depot-migration-report")- archives = {- Path("/tmp/depot-migration-artifacts/migration-analysis.zip"): {- "django-migration-sql.json": 512_000,- "django-migration-risk.json": 1_000_000,- },- Path("/tmp/depot-migration-artifacts/ch-migration-report.zip"): {- "ch-migration-sql.json": 500_000,- },- }- for archive, expected in archives.items():- if not archive.exists():- continue- with zipfile.ZipFile(archive) as uploaded:- entries = [entry for entry in uploaded.infolist() if not entry.is_dir()]- if len(entries) > len(expected):- raise SystemExit(f"{archive.name} contains unexpected entries")- seen = set()- for entry in entries:- basename = PurePosixPath(entry.filename).name- if basename not in expected or basename in seen:- raise SystemExit(f"{archive.name} contains an unexpected or duplicate entry")- seen.add(basename)- limit = expected[basename]- if entry.file_size > limit:- raise SystemExit(f"{basename} is larger than its size limit")- with uploaded.open(entry) as source:- data = source.read(limit + 1)- if len(data) > limit or len(data) != entry.file_size:- raise SystemExit(f"{basename} does not match its declared size")- (output / basename).write_bytes(data)- PY- echo "validated=true" >> "$GITHUB_OUTPUT"-- - name: Checkout trusted report scripts # nosemgrep: yaml.github-actions.security.pull-request-target-code-checkout.pull-request-target-code-checkout- if: steps.validate.outputs.validated == 'true'- # v6.0.2 checks out only the trusted base SHA below, never pull request code.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd- with:- repository: ${{ github.repository }}- # The base branch head this workflow file came from. pull_request.base.sha- # only moves when the PR is opened or force-pushed, so it can predate the scripts.- ref: ${{ github.sha }}- path: trusted-reporter- sparse-checkout: |- .nvmrc- .github/scripts/render-depot-migration-report.mjs- .github/scripts/post-django-migration-section.mjs- .github/scripts/post-ch-migration-section.mjs- frontend/bin/ci-report- sparse-checkout-cone-mode: false- persist-credentials: false-- - name: Set up Node.js- if: steps.validate.outputs.validated == 'true'- uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0- with:- node-version-file: trusted-reporter/.nvmrc-- - name: Render validated migration reports- if: steps.validate.outputs.validated == 'true'- env:- HEAD_SHA: ${{ github.event.pull_request.head.sha }}- REPO: ${{ github.repository }}- run: |- node trusted-reporter/.github/scripts/render-depot-migration-report.mjs \- /tmp/depot-migration-report /tmp/depot-migration-rendered "$REPO" "$HEAD_SHA"-- - name: Get app token for migration reports- if: steps.validate.outputs.validated == '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 }}- permission-checks: write- permission-pull-requests: write-- - name: Publish Migration risk check- if: steps.validate.outputs.validated == 'true'- env:- GH_TOKEN: ${{ steps.app-token.outputs.token }}- HEAD_SHA: ${{ github.event.pull_request.head.sha }}- REPO: ${{ github.repository }}- run: |- set -euo pipefail- metadata=/tmp/depot-migration-rendered/metadata.json- CONCLUSION=$(jq -r '.riskConclusion' "$metadata")- TITLE=$(jq -r '.riskTitle' "$metadata")- ANALYZED_PATHS=$(jq -c '.analyzedPaths' "$metadata")- REPORT_BODY=$(cat /tmp/depot-migration-rendered/migration-risk-check.md)- MARKER="<!-- stamphog:v1 ${ANALYZED_PATHS} -->"- 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: Update migration sections in the CI report- if: steps.validate.outputs.validated == 'true'- working-directory: trusted-reporter- env:- GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}- run: |- set -euo pipefail- data=/tmp/depot-migration-rendered- metadata="$data/metadata.json"- post_django() {- node .github/scripts/post-django-migration-section.mjs "$@"- }-- if [ "$(jq -r '.djangoSqlAvailable' "$metadata")" = true ]; then- count=$(jq -r '.djangoMigrationCount' "$metadata")- if [ "$count" -eq 0 ]; then- post_django sql clear ok "no new migrations" "$data/django-migration-sql.md"- elif [ "$count" -eq 1 ]; then- post_django sql post warn "1 new migration to review" "$data/django-migration-sql.md"- else- post_django sql post warn "$count new migrations to review" "$data/django-migration-sql.md"- fi- fi-- risk_exit=$(jq -r '.riskExitCode' "$metadata")- migration_count=$(jq -r '.riskMigrationCount' "$metadata")- if [ "$risk_exit" -ne 0 ]; then- max_level=$(jq -r '.riskMaxLevel // "none"' "$metadata")- if [ "$max_level" = Blocked ]; then- post_django risk post fail "blocked migration detected" "$data/django-migration-risk.md"- else- post_django risk post fail "migration analysis failed" "$data/django-migration-risk.md"- fi- elif [ "$migration_count" -eq 0 ]; then- post_django risk clear ok "no migrations to analyze" "$data/django-migration-risk.md"- else- post_django risk post ok "migration analysis complete" "$data/django-migration-risk.md"- fi-- if [ "$(jq -r '.chAvailable' "$metadata")" = true ]; then- count=$(jq -r '.chMigrationCount' "$metadata")- if [ "$count" -gt 0 ]; then- cp "$data/ch-migration-sql.md" ch_migration_sql_comment.md- HAS_CHANGES=true CH_MIGRATION_COUNT="$count" node .github/scripts/post-ch-migration-section.mjs- else- HAS_CHANGES=false CH_MIGRATION_COUNT=0 node .github/scripts/post-ch-migration-section.mjs- fi- fi- node frontend/bin/ci-report/delete-legacy-comments.mjsdiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 3ff4a0906712..cdc2ed6ac8b8 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -26,8 +26,10 @@# - permissions: read-only in every job, so the ambient token never writes. Canonical grants# handle-snapshots' and backend-coverage-report's github.token pull-requests:write for their# CI report sections; here those sections post with a posthog-tests token scoped to pull-requests:write (see the header of-# .depot/actions/commit-snapshots). Migration reports cross an artifact boundary into the-# base-controlled ci-backend-report.yml workflow before any write token is minted.+# .depot/actions/commit-snapshots). check-migrations mints that token before its SQL and+# risk steps, and skips each section write when the mint fails, where canonical posts the+# sections with github.token. Its Migration risk check token (checks:write only) is minted+# after those steps, as in canonical.# - Trunk uploads and quarantine verdicts match canonical only when side effects# are enabled. Disabled test steps retain their direct failure verdict.# - dynamic-ci-filter: canonical asks Trunk which jobs a diff needs and records the verdict@@ -70,12 +72,11 @@# - GitHub App tokens: the mint steps' vars.* / secrets.* resolve from Depot's store, not# GitHub's. A name missing there makes the setup-action mints (continue-on-error) fall# back to the ambient GITHUB_TOKEN, the Depot Code Access installation token that every-# Depot CI job across repos shares, and fails the paths-filter mint outright. The trusted-# migration reporter publishes the migration-risk-# check because stamphog waits for it on every pull request.-# - check-migrations uploads inert Django and ClickHouse migration report data. The-# pull_request_target workflow in ci-backend-report.yml validates that data and posts it-# with base-revision scripts, so PR-controlled code never receives a write token.+# Depot CI job across repos shares, and fails the paths-filter mint outright.+# - Migration reports post from check-migrations, as in canonical. 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.# - Workflow-command annotations (::error, ::warning) stay in the Depot job log. Depot CI# does not attach them to the job's GitHub check run. The file annotations from# `hogli lint:migration-deletions` therefore have no GitHub counterpart here; the failing@@ -1876,18 +1877,63 @@ jobs:- name: Install python dependencies for this PRrun: |UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev- - name: Render Django migration SQL report+ - 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: needs.wait-for-handoff.outputs.handed_off == 'true' && 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 reportif: 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_files }}BASE_SHA: ${{ github.event.pull_request.base.sha }}run: |- mkdir -p migration-report- printf '%s\n' '{"version":1,"migrations":[]}' > migration-report/django-migration-sql.json+ # The PR checkout above uses the PR branch, 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, exitif [ -z "$CHANGED_FILES" ]; thenecho "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.mdexit 0fi@@ -1898,7 +1944,9 @@ jobs: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=0mapfile -t migration_files < <(tr ' ' '\n' <<< "$CHANGED_FILES")# Process each changed migration file (excluding Rust migrations)@@ -1940,6 +1988,7 @@ jobs:fiHAS_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@@ -1950,37 +1999,86 @@ jobs:SQL_OUTPUT="-- sqlmigrate failed for this migration (see the Validate migrations job log)"fi- report_tmp=$(mktemp)- jq --arg path "$file" --arg sql "$SQL_OUTPUT" \- '.migrations += [{path: $path, sql: $sql}]' \- migration-report/django-migration-sql.json > "$report_tmp"- mv "$report_tmp" migration-report/django-migration-sql.json+ COMMENT_BODY+="#### [\`$file\`](https://github.com/${{ github.repository }}/blob/${{ github.sha }}/$file)\n\`\`\`sql\n$SQL_OUTPUT\n\`\`\`\n\n"fidoneif [ "$HAS_NEW_MIGRATIONS" = false ]; thenecho "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 0fi- - name: Run migration risk analysis+ 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 reportif: github.event_name == 'pull_request'- # The artifact upload uses always(), so an analyzer failure still reaches the reporter.+ # 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: |- mkdir -p migration-report+ # The PR checkout above uses the PR branch, 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- python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json+ RISK_ANALYSIS=$(python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json 2>/dev/null)EXIT_CODE=$?set -e- if jq -e 'type == "object"' migration_analysis.json > /dev/null 2>&1; then- jq -n --argjson exit_code "$EXIT_CODE" --slurpfile analysis migration_analysis.json \- '{version: 1, exit_code: $exit_code, analysis: $analysis[0]}' \- > migration-report/django-migration-risk.json++ 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.mdelse- jq -n --argjson exit_code "$EXIT_CODE" \- '{version: 1, exit_code: $exit_code, analysis: null}' \- > migration-report/django-migration-risk.json+ 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.mdfi# Fail the job if there were blocked migrations@@ -1988,14 +2086,123 @@ jobs:exit $EXIT_CODEfi+ - 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() && needs.wait-for-handoff.outputs.handed_off == 'true' && 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 }}+ 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 artifactif: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request') }}uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0with:name: migration-analysispath: |- migration-report/django-migration-sql.json- migration-report/django-migration-risk.json+ migration_analysis.md+ migration_analysis.jsonif-no-files-found: ignore- name: Run migrations for this PR@@ -2136,8 +2343,6 @@ jobs:echo "::warning::Could not fetch base ref $BASE_REF; rendering CH migrations against master instead"fifi- mkdir -p migration-report- printf '%s\n' '{"version":1,"count":0,"environments":[]}' > migration-report/ch-migration-sql.jsonCHANGED=$(git diff --name-only --diff-filter=AM "$DIFF_BASE"..HEAD | grep '^posthog/clickhouse/migrations/[0-9]' | grep -v __pycache__ || true)if [ -z "$CHANGED" ]; thenecho "No ClickHouse migrations changed."@@ -2146,36 +2351,72 @@ jobs:fiecho "has_changes=true" >> "$GITHUB_OUTPUT"mapfile -t changed_migrations <<< "$CHANGED"- MIGRATION_COUNT=${#changed_migrations[@]}- echo "migration_count=$MIGRATION_COUNT" >> "$GITHUB_OUTPUT"- jq --argjson count "$MIGRATION_COUNT" '.count = $count' \- migration-report/ch-migration-sql.json > migration-report/ch-migration-sql.tmp- mv migration-report/ch-migration-sql.tmp migration-report/ch-migration-sql.json+ echo "migration_count=${#changed_migrations[@]}" >> "$GITHUB_OUTPUT"+ {+ echo '<!-- ch-migration-sql -->'+ echo '## ClickHouse migration SQL per cloud environment'+ echo ''+ } > ch_migration_sql_comment.mdmkdir -p ch_sql_envDEPLOYMENTS=('' 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[@]}"; dofile="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"+ echo '- _⚠️ failed to render SQL for this environment — see the workflow logs_' > "$file"fiecho "::group::CLOUD_DEPLOYMENT=${LABELS[$idx]}"cat "$file"echo "::endgroup::"- report_tmp=$(mktemp)- jq --arg label "${LABELS[$idx]}" --rawfile output "$file" \- '.environments += [{label: $label, output: $output}]' \- migration-report/ch-migration-sql.json > "$report_tmp"- mv "$report_tmp" migration-report/ch-migration-sql.json+ 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")+ fidone+ 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: Upload CH migration report artifact- if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request') }}- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- with:- name: ch-migration-report- path: migration-report/ch-migration-sql.json- if-no-files-found: ignore+ - 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"+ ficheck-openapi-types:needs: [changes]diff --git a/.github/scripts/ci_backend_relay.py b/.github/scripts/ci_backend_relay.pyindex a8c847dd2c60..4f6711942db2 100644--- a/.github/scripts/ci_backend_relay.py+++ b/.github/scripts/ci_backend_relay.py@@ -50,10 +50,6 @@ EVENT_SUFFIX = " (PR {pr}, event {event_at})"EVENT_TIME = "%Y-%m-%dT%H:%M:%SZ"RACING_EVENT_SECONDS = 2GATE_CHECK = f"{DEPOT_WORKFLOW} / Django Tests Pass on Depot"-MIGRATION_CHECK = f"{DEPOT_WORKFLOW} / Validate migrations"-CHANGES_CHECK = f"{DEPOT_WORKFLOW} / Determine need to run backend and migration checks"-HANDOFF_CHECK = "Hand off backend tests to Depot CI"-GITHUB_ACTIONS_APP_ID = 15368DEPOT_RUN_URL = re.compile(r"^https://depot\.dev/orgs/([^/?]+)/workflows/([a-z0-9]+)(?:[?/]|$)")PENDING_STATES = frozenset({"queued", "in_progress", "pending", "waiting", "requested"})API_ROOT = "https://api.github.com"@@ -66,16 +62,11 @@ class ReadRefusedError(RuntimeError):"""The check-runs API keeps refusing the token, so no verdict can be read."""-class HandoffUnresolvedError(RuntimeError):- """The report cannot determine which engine owns this event."""--@dataclass(frozen=True)class CheckRun:id: int# The conclusion once the check completed, its status before that.state: str- pull_requests: frozenset[int]details_url: str@classmethod@@ -83,7 +74,6 @@ class CheckRun:return cls(id=int(run["id"]),state=str((run.get("conclusion") if run.get("status") == "completed" else run.get("status")) or ""),- pull_requests=frozenset(int(pr["number"]) for pr in run.get("pull_requests") or []),details_url=str(run.get("details_url") or ""),)@@ -120,19 +110,7 @@ def newest_live(runs: Sequence[CheckRun]) -> CheckRun | None:return max(live or runs, key=lambda run: run.id, default=None)-def handoff_decision(runs: Iterable[CheckRun], pr_number: int) -> bool | None:- """Mirror the router's durable decision for this pull request and commit."""- states = {run.state for run in runs if pr_number in run.pull_requests}- if "success" in states:- return True- if "skipped" in states:- return False- return None---def progress(- wait: CheckRun | None, checks: Iterable[CheckRun], skipped_dependency_checks: Iterable[CheckRun] = ()-) -> Progress:+def progress(wait: CheckRun | None, checks: Iterable[CheckRun]) -> Progress:"""Where the Depot run behind `wait` stands, judged by its check among `checks`."""if wait is None:return Progress(Phase.ABSENT)@@ -149,14 +127,6 @@ def progress(key=lambda run: run.id,default=None,)- if check is None:- dependency = max(- (run for run in skipped_dependency_checks if workflow is not None and run.depot_workflow == workflow),- key=lambda run: run.id,- default=None,- )- if dependency is not None and dependency.state == "skipped":- return Progress(Phase.DECLINED, dependency.state, dependency.details_url)if check is None or check.state in PENDING_STATES:return Progress(Phase.RUNNING, check.state if check else "", wait.details_url)if check.state == "cancelled":@@ -169,7 +139,7 @@ class CheckReader(Protocol):class CheckRunReader:- """Reads one commit's check runs for one app by name, with conditional requests.+ """Reads one commit's Depot check runs by name, with conditional requests.A 304 answer is free against the rate limit, so polling stays cheap."""@@ -180,19 +150,17 @@ class CheckRunReader:sha: str,token: str,opener: Callable[..., Any] = urllib.request.urlopen,- app_id: int = DEPOT_APP_ID,) -> None:self._repo = repoself._sha = shaself._token = tokenself._opener = opener- self._app_id = app_idself._cache: dict[str, tuple[str, list[CheckRun]]] = {}self._refusals = 0def _url(self, name: str, page: int) -> str:query = urllib.parse.urlencode(- {"check_name": name, "app_id": self._app_id, "filter": "all", "per_page": PAGE_SIZE, "page": page}+ {"check_name": name, "app_id": DEPOT_APP_ID, "filter": "all", "per_page": PAGE_SIZE, "page": page})return f"{API_ROOT}/repos/{self._repo}/commits/{self._sha}/check-runs?{query}"@@ -268,24 +236,6 @@ def racing_wait(reader: CheckReader, event: Event, followed: set[str]) -> str |return None-def wait_for_handoff(- reader: CheckReader,- event: Event,- *,- clock: Callable[[], float] = time.monotonic,- sleep: Callable[[float], None] = time.sleep,-) -> bool:- """The router's committed engine; an unread decision cannot suppress a report."""- start = clock()- while True:- decision = handoff_decision(reader.read(HANDOFF_CHECK), event.pr_number)- if decision is not None:- return decision- if clock() - start >= 10 * 60:- raise HandoffUnresolvedError(f"Cannot determine the backend hand-off for {event.sha}")- sleep(20)--def poll(reader: CheckReader,event: Event,@@ -298,9 +248,9 @@ def poll() -> Progress:"""Polls until the event's check finishes, Depot declines the hand-off, or a deadline passes.- A duplicate run of the same event can replace a cancelled one. The migration report- gives an absent or cancelled run the full deadline; the required gate uses a shorter grace period.- After the grace period, the run of a racing event stands in for an absent or cancelled one.+ A duplicate run of the same event can replace a cancelled one, so an absent or cancelled+ run gets `absent_minutes` of grace. After the grace period, the run of a racing event+ stands in for an absent or cancelled one."""start = clock()event_name = wait_check_name(event.pr_number, event.event_at)@@ -308,10 +258,7 @@ def poll(while True:wait = newest_live(reader.read(event_name))checks = reader.read(check_name) if wait and wait.state == "success" else []- dependencies = (- reader.read(CHANGES_CHECK) if check_name == MIGRATION_CHECK and wait and wait.state == "success" else []- )- current = progress(wait, checks, dependencies)+ current = progress(wait, checks)sys.stdout.write(f"Depot run for this event: {current.phase.value} {current.state}".rstrip() + "\n")elapsed = clock() - startif current.phase in (Phase.FINISHED, Phase.DECLINED):@@ -380,52 +327,20 @@ def relay_gate(result: Progress, event: Event, run_id: str) -> tuple[int, list[sreturn 1, [f"::error::No Depot verdict for {event.sha} within the relay's deadline"]-def report_migrations(result: Progress) -> tuple[int, list[str], dict[str, str]]:- """The exit code, log lines and step outputs of the migration report's source step."""- if result.phase == Phase.FINISHED and result.state in ("success", "failure", "neutral"):- match = DEPOT_RUN_URL.match(result.details_url)- if not match:- return 1, ["::error::Unexpected Depot migration check URL"], {}- return 0, [], {"migration_state": result.state, "workflow_id": match.group(2)}- if result.phase in (Phase.FINISHED, Phase.CANCELLED) and result.state in ("skipped", "cancelled"):- return 0, [f"No completed migration report is available (migration check: {result.state})."], {}- if result.phase == Phase.FINISHED:- return 1, [f"::error::Unexpected migration check state: {result.state}"], {}- if result.phase == Phase.ABSENT:- return 1, ["::error::Depot posted no event-matched wait check after a confirmed hand-off"], {}- if result.phase == Phase.DECLINED:- return 0, [f"Depot CI ran no backend tests for this event ({result.phase.value} {result.state})."], {}- return 1, ["::error::Depot migration check did not finish within the report's deadline"], {}--def main(argv: Sequence[str]) -> int:- mode = argv[1] if len(argv) > 1 else ""+ if argv[1:] != ["gate"]:+ sys.stderr.write("usage: ci_backend_relay.py gate\n")+ return 2env = os.environevent = Event(repo=env["REPO"], sha=env["SHA"], pr_number=int(env["PR_NUMBER"]), event_at=env["EVENT_AT"])reader = CheckRunReader(event.repo, event.sha, env["GH_TOKEN"])try:- if mode == "gate":- result = poll(reader, event, GATE_CHECK, deadline_minutes=90, absent_minutes=15)- code, lines = relay_gate(result, event, env.get("GITHUB_RUN_ID", ""))- outputs: dict[str, str] = {}- elif mode == "migrations":- handoff_reader = CheckRunReader(event.repo, event.sha, env["GH_TOKEN"], app_id=GITHUB_ACTIONS_APP_ID)- if wait_for_handoff(handoff_reader, event):- result = poll(reader, event, MIGRATION_CHECK, deadline_minutes=70, absent_minutes=70)- else:- result = Progress(Phase.DECLINED, "skipped")- code, lines, outputs = report_migrations(result)- else:- sys.stderr.write("usage: ci_backend_relay.py gate|migrations\n")- return 2- except (ReadRefusedError, HandoffUnresolvedError) as error:+ result = poll(reader, event, GATE_CHECK, deadline_minutes=90, absent_minutes=15)+ except ReadRefusedError as error:sys.stdout.write(f"::error::{error}\n")return 1+ code, lines = relay_gate(result, event, env.get("GITHUB_RUN_ID", ""))sys.stdout.writelines(f"{line}\n" for line in lines)- output_path = env.get("GITHUB_OUTPUT")- if output_path and outputs:- with open(output_path, "a", encoding="utf-8") as handle:- handle.writelines(f"{key}={value}\n" for key, value in outputs.items())return codediff --git a/.github/scripts/render-depot-migration-report.mjs b/.github/scripts/render-depot-migration-report.mjsdeleted file mode 100644index 9680648e9e30..000000000000--- a/.github/scripts/render-depot-migration-report.mjs+++ /dev/null@@ -1,303 +0,0 @@-#!/usr/bin/env node-import fs from 'node:fs'-import path from 'node:path'-import { pathToFileURL } from 'node:url'--const LEVELS = new Set(['Safe', 'Needs Review', 'Blocked'])-const MIGRATION_PATH = /^(?:posthog|ee|products)\/(?:[A-Za-z0-9_.-]+\/)*migrations\/[0-9][A-Za-z0-9_.-]*\.py$/--function fail(message) {- throw new Error(`Invalid Depot migration report: ${message}`)-}--function readJson(file) {- try {- return JSON.parse(fs.readFileSync(file, 'utf8'))- } catch (error) {- fail(`${path.basename(file)} is not valid JSON: ${error.message}`)- }-}--function text(value, name, limit) {- if (typeof value !== 'string' || value.length > limit) {- fail(`${name} must be a string no longer than ${limit} characters`)- }- if (/[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value)) {- fail(`${name} contains control characters`)- }- return value.replaceAll('\r\n', '\n').replaceAll('\r', '\n')-}--function integer(value, name, maximum) {- if (!Number.isInteger(value) || value < 0 || value > maximum) {- fail(`${name} must be an integer from 0 to ${maximum}`)- }- return value-}--function migrationPath(value, name) {- const candidate = text(value, name, 500)- if (!MIGRATION_PATH.test(candidate) || candidate.includes('..')) {- fail(`${name} is not a repository migration path`)- }- return candidate-}--function inert(value) {- return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('@', '@\u200b')-}--function inlineText(value) {- return inert(value).replace(/([\\`*_[\]{}()#+.!|>-])/g, '\\$1')-}--function codeBlock(value) {- const safe = inert(value).replaceAll('\t', ' ')- return safe- .split('\n')- .map((line) => ` ${line}`)- .join('\n')-}--function timestamp(now) {- return now.toISOString().slice(0, 16).replace('T', ' ') + ' UTC'-}--function validateAnalysis(value) {- if (value === null) {- return null- }- if (!value || typeof value !== 'object' || Array.isArray(value)) {- fail('risk analysis must be an object or null')- }- const summary = value.summary- if (!summary || typeof summary !== 'object' || Array.isArray(summary)) {- fail('risk analysis summary must be an object')- }- const counts = {- safe: integer(summary.safe, 'safe migration count', 10000),- needs_review: integer(summary.needs_review, 'needs-review migration count', 10000),- blocked: integer(summary.blocked, 'blocked migration count', 10000),- }- if (!Array.isArray(value.migrations) || value.migrations.length > 10000) {- fail('risk analysis migrations must be an array with at most 10000 entries')- }- const migrations = value.migrations.map((migration, index) => {- if (!migration || typeof migration !== 'object' || Array.isArray(migration)) {- fail(`risk migration ${index} must be an object`)- }- const level = text(migration.level, `risk migration ${index} level`, 32)- if (!LEVELS.has(level)) {- fail(`risk migration ${index} has an unknown level`)- }- return {- label: text(migration.label, `risk migration ${index} label`, 300),- level,- filePath:- migration.file_path === null- ? null- : migrationPath(migration.file_path, `risk migration ${index} file path`),- }- })- const actual = {- safe: migrations.filter(({ level }) => level === 'Safe').length,- needs_review: migrations.filter(({ level }) => level === 'Needs Review').length,- blocked: migrations.filter(({ level }) => level === 'Blocked').length,- }- if (Object.keys(counts).some((key) => counts[key] !== actual[key])) {- fail('risk analysis summary does not match its migrations')- }- const maxLevel = value.max_level- if (maxLevel !== null && !LEVELS.has(maxLevel)) {- fail('risk analysis has an unknown maximum level')- }- const expectedMax = actual.blocked ? 'Blocked' : actual.needs_review ? 'Needs Review' : actual.safe ? 'Safe' : null- if (maxLevel !== expectedMax) {- fail('risk analysis maximum level does not match its migrations')- }- return { summary: counts, maxLevel, migrations }-}--function renderRisk(report, now, repository, headSha) {- const exitCode = integer(report.exit_code, 'risk analyzer exit code', 255)- const analysis = validateAnalysis(report.analysis)- if (report.version !== 1) {- fail('risk report version must be 1')- }- if (analysis === null) {- return {- body: 'Migration analysis failed. Check the Depot migration job logs for details.',- conclusion: 'failure',- title: 'Analyzer failed',- exitCode,- migrationCount: 0,- maxLevel: null,- analyzedPaths: [],- }- }-- const { safe, needs_review: needsReview, blocked } = analysis.summary- const lines = [- 'We analyzed the migrations for potential risks.',- '',- `**Summary:** ${safe} Safe | ${needsReview} Needs Review | ${blocked} Blocked`,- ]- for (const level of ['Blocked', 'Needs Review', 'Safe']) {- const migrations = analysis.migrations.filter((migration) => migration.level === level)- if (!migrations.length) {- continue- }- lines.push('', `## ${level}`)- for (const migration of migrations) {- const label = inlineText(migration.label)- lines.push(migration.filePath ? `- ${label} (\`${migration.filePath}\`)` : `- ${label}`)- }- }- lines.push(- '',- `*Last updated: ${timestamp(now)} ([${headSha.slice(0, 7)}](https://github.com/${repository}/commit/${headSha}))*`- )-- const state = {- Safe: ['success', 'All migrations safe'],- 'Needs Review': ['neutral', 'Migrations need review'],- Blocked: ['failure', 'Blocked migrations'],- }- const [conclusion, title] =- analysis.maxLevel === null ? ['success', 'No Django migrations to analyze'] : state[analysis.maxLevel]- return {- body: lines.join('\n'),- conclusion,- title,- exitCode,- migrationCount: analysis.migrations.length,- maxLevel: analysis.maxLevel,- analyzedPaths: analysis.migrations.flatMap(({ filePath }) => (filePath === null ? [] : [filePath])),- }-}--export function renderReports({ inputDir, outputDir, repository, headSha, now = new Date() }) {- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) {- fail('repository is invalid')- }- if (!/^[a-f0-9]{40}$/.test(headSha)) {- fail('head SHA is invalid')- }-- const djangoSqlPath = path.join(inputDir, 'django-migration-sql.json')- const djangoSqlAvailable = fs.existsSync(djangoSqlPath)- const djangoSql = djangoSqlAvailable ? readJson(djangoSqlPath) : { version: 1, migrations: [] }- if (djangoSql.version !== 1 || !Array.isArray(djangoSql.migrations) || djangoSql.migrations.length > 1000) {- fail('Django SQL report has an invalid schema')- }- const djangoMigrations = djangoSql.migrations.map((migration, index) => {- if (!migration || typeof migration !== 'object' || Array.isArray(migration)) {- fail(`Django SQL migration ${index} must be an object`)- }- return {- path: migrationPath(migration.path, `Django SQL migration ${index} path`),- sql: text(migration.sql, `Django SQL migration ${index} SQL`, 100000),- }- })- const djangoLines = djangoMigrations.length- ? ['We detected new migrations in this pull request. Review the SQL output for each migration:', '']- : ['No new Django migrations need SQL review.']- for (const migration of djangoMigrations) {- djangoLines.push(- `#### [\`${migration.path}\`](https://github.com/${repository}/blob/${headSha}/${migration.path})`,- '',- codeBlock(migration.sql),- ''- )- }- if (djangoMigrations.length) {- djangoLines.push(- `*Last updated: ${timestamp(now)} ([${headSha.slice(0, 7)}](https://github.com/${repository}/commit/${headSha}))*`- )- }-- const riskPath = path.join(inputDir, 'django-migration-risk.json')- const risk = renderRisk(- fs.existsSync(riskPath) ? readJson(riskPath) : { version: 1, exit_code: 1, analysis: null },- now,- repository,- headSha- )-- const chPath = path.join(inputDir, 'ch-migration-sql.json')- const chAvailable = fs.existsSync(chPath)- const ch = chAvailable ? readJson(chPath) : { version: 1, count: 0, environments: [] }- if (ch.version !== 1 || !Array.isArray(ch.environments) || ch.environments.length > 4) {- fail('ClickHouse SQL report has an invalid schema')- }- const chCount = integer(ch.count, 'ClickHouse migration count', 1000)- const allowedLabels = new Set(['unset', 'US', 'EU', 'DEV'])- const seenLabels = new Set()- const environments = ch.environments.map((environment, index) => {- if (!environment || typeof environment !== 'object' || Array.isArray(environment)) {- fail(`ClickHouse environment ${index} must be an object`)- }- const label = text(environment.label, `ClickHouse environment ${index} label`, 16)- if (!allowedLabels.has(label) || seenLabels.has(label)) {- fail(`ClickHouse environment ${index} has an invalid label`)- }- seenLabels.add(label)- return { label, output: text(environment.output, `ClickHouse environment ${index} output`, 200000) }- })- if ((chCount === 0 && environments.length !== 0) || (chCount > 0 && environments.length !== 4)) {- fail('ClickHouse environment count does not match the migration count')- }- const buckets = []- for (const environment of environments) {- const existing = buckets.find(({ output }) => output === environment.output)- if (existing) {- existing.labels.push(environment.label)- } else {- buckets.push({ labels: [environment.label], output: environment.output })- }- }- const chLines = chCount ? ['## ClickHouse migration SQL per cloud environment', ''] : []- if (buckets.length === 1) {- chLines.push(- '_Identical across all cloud environments (unset, US, EU, DEV)._',- '',- codeBlock(buckets[0].output)- )- } else {- for (const bucket of buckets) {- chLines.push(`### ${bucket.labels.join(', ')}`, '', codeBlock(bucket.output), '')- }- }-- fs.mkdirSync(outputDir, { recursive: true })- fs.writeFileSync(path.join(outputDir, 'django-migration-sql.md'), `${djangoLines.join('\n').trim()}\n`)- fs.writeFileSync(path.join(outputDir, 'django-migration-risk.md'), `${risk.body.trim()}\n`)- fs.writeFileSync(path.join(outputDir, 'migration-risk-check.md'), `${risk.body.trim()}\n`)- fs.writeFileSync(path.join(outputDir, 'ch-migration-sql.md'), `${chLines.join('\n').trim()}\n`)- fs.writeFileSync(- path.join(outputDir, 'metadata.json'),- `${JSON.stringify({- djangoSqlAvailable,- djangoMigrationCount: djangoMigrations.length,- riskExitCode: risk.exitCode,- riskMigrationCount: risk.migrationCount,- riskMaxLevel: risk.maxLevel,- riskConclusion: risk.conclusion,- riskTitle: risk.title,- analyzedPaths: risk.analyzedPaths,- chAvailable,- chMigrationCount: chCount,- })}\n`- )-}--if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {- const [inputDir, outputDir, repository, headSha] = process.argv.slice(2)- if (!inputDir || !outputDir || !repository || !headSha) {- console.error(- 'Usage: render-depot-migration-report.mjs <input directory> <output directory> <repository> <head SHA>'- )- process.exit(1)- }- renderReports({ inputDir, outputDir, repository, headSha })-}diff --git a/.github/scripts/render-depot-migration-report.test.mjs b/.github/scripts/render-depot-migration-report.test.mjsdeleted file mode 100644index 1daf4a956919..000000000000--- a/.github/scripts/render-depot-migration-report.test.mjs+++ /dev/null@@ -1,72 +0,0 @@-import assert from 'node:assert/strict'-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-import { describe, it } from 'node:test'--import { renderReports } from './render-depot-migration-report.mjs'--describe('Depot migration report renderer', () => {- it('makes PR-controlled report content inert', () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'depot-migration-report-'))- const inputDir = path.join(root, 'input')- const outputDir = path.join(root, 'output')- fs.mkdirSync(inputDir)- fs.writeFileSync(- path.join(inputDir, 'django-migration-sql.json'),- JSON.stringify({- version: 1,- migrations: [- {- path: 'posthog/migrations/1234_safe.py',- sql: 'SELECT 1;\n```\n<img src=x onerror=alert(1)>\n@posthog/security',- },- ],- })- )- fs.writeFileSync(- path.join(inputDir, 'django-migration-risk.json'),- JSON.stringify({- version: 1,- exit_code: 1,- analysis: {- summary: { safe: 0, needs_review: 0, blocked: 1 },- max_level: 'Blocked',- migrations: [- {- label: '</summary><img src=x> @posthog/security',- level: 'Blocked',- file_path: 'posthog/migrations/1234_safe.py',- },- ],- },- })- )- fs.writeFileSync(- path.join(inputDir, 'ch-migration-sql.json'),- JSON.stringify({- version: 1,- count: 1,- environments: ['unset', 'US', 'EU', 'DEV'].map((label) => ({- label,- output: '```\n</details><img src=x>\n@posthog/security',- })),- })- )-- renderReports({- inputDir,- outputDir,- repository: 'PostHog/posthog',- headSha: '0123456789abcdef0123456789abcdef01234567',- now: new Date('2026-09-21T12:15:00Z'),- })-- for (const file of ['django-migration-sql.md', 'django-migration-risk.md', 'ch-migration-sql.md']) {- const rendered = fs.readFileSync(path.join(outputDir, file), 'utf8')- assert.doesNotMatch(rendered, /<img|<\/details>|<\/summary>|@posthog\/security/)- }- assert.match(fs.readFileSync(path.join(outputDir, 'django-migration-sql.md'), 'utf8'), /^ ```$/m)- assert.match(fs.readFileSync(path.join(outputDir, 'django-migration-risk.md'), 'utf8'), /<\/summary>/)- })-})diff --git a/.github/scripts/test_ci_backend_relay.py b/.github/scripts/test_ci_backend_relay.pyindex a789becfc293..4a574f741383 100644--- a/.github/scripts/test_ci_backend_relay.py+++ b/.github/scripts/test_ci_backend_relay.py@@ -2,7 +2,6 @@ import reimport jsonimport http.clientimport urllib.error-import urllib.parseimport importlib.utilfrom collections.abc import Sequencefrom pathlib import Path@@ -27,13 +26,7 @@ OLDER_RACING_WAIT = relay.wait_check_name(PR, "2026-09-24T09:54:19Z")NEWER_RACING_WAIT = relay.wait_check_name(PR, "2026-09-24T09:54:22Z")-def run(- id: int,- state: str,- workflow: str = "live",- started_at: str = "2026-09-24T09:56:00Z",- prs: Sequence[int] = (PR,),-) -> Any:+def run(id: int, state: str, workflow: str = "live", started_at: str = "2026-09-24T09:56:00Z") -> Any:completed = state not in relay.PENDING_STATESreturn relay.CheckRun.from_api({@@ -41,7 +34,6 @@ def run("status": "completed" if completed else state,"conclusion": state if completed else None,"started_at": started_at,- "pull_requests": [{"number": number} for number in prs],"details_url": f"https://depot.dev/orgs/org1/workflows/{workflow}?job=j1&repo=PostHog%2Fposthog",})@@ -80,12 +72,6 @@ def test_wait_job_name_matches_the_depot_workflow() -> None:(relay.Phase.FINISHED, "success"),id="this run's gate wins over a newer id elsewhere",),- pytest.param(- [run(1, "success", prs=())],- [run(10, "success", prs=())],- (relay.Phase.FINISHED, "success"),- id="checks that list no pull request",- ),pytest.param([run(1, "cancelled", workflow="dup1"), run(2, "success", workflow="dup2")],[run(10, "failure", workflow="dup2")],@@ -265,116 +251,6 @@ def test_poll_does_not_use_an_ambiguous_plain_named_wait() -> None:assert PLAIN_WAIT not in reader.reads- "checks,decision",- [- ([run(1, "success"), run(2, "skipped")], True),- ([run(1, "skipped")], False),- ([run(1, "cancelled"), run(2, "success", prs=(PR + 1,))], None),- ],-)-def test_handoff_decision_matches_the_router(checks: list[Any], decision: bool | None) -> None:- assert relay.handoff_decision(checks, PR) is decision---def test_report_requires_a_confirmed_handoff_before_waiting_for_depot() -> None:- clock = FakeClock()- reader = FakeReader(- [{relay.HANDOFF_CHECK: [run(1, "queued")]}] * 2 + [{relay.HANDOFF_CHECK: [run(1, "success")]}],- advance_on=relay.HANDOFF_CHECK,- )- assert relay.wait_for_handoff(reader, EVENT, clock=clock, sleep=clock.sleep)- assert clock.now == 40---def test_report_fails_when_handoff_cannot_be_read() -> None:- clock = FakeClock()- reader = FakeReader([{}], advance_on=relay.HANDOFF_CHECK)- with pytest.raises(relay.HandoffUnresolvedError):- relay.wait_for_handoff(reader, EVENT, clock=clock, sleep=clock.sleep)- assert clock.now == 10 * 60---def test_report_waits_past_ten_minutes_after_handoff() -> None:- clock = FakeClock()- reader = FakeReader(- [{}] * 23- + [- {- EVENT_WAIT: [run(1, "success")],- relay.MIGRATION_CHECK: [run(2, "success")],- }- ]- )- result = relay.poll(- reader, EVENT, relay.MIGRATION_CHECK, deadline_minutes=70, absent_minutes=70, clock=clock, sleep=clock.sleep- )- assert (result.phase, result.state) == (relay.Phase.FINISHED, "success")- assert clock.now > 10 * 60---def test_migration_report_stops_when_depot_did_not_receive_the_handoff() -> None:- clock = FakeClock()- result = relay.poll(- FakeReader(- [- {- EVENT_WAIT: [run(1, "success")],- relay.CHANGES_CHECK: [run(2, "skipped")],- }- ]- ),- EVENT,- relay.MIGRATION_CHECK,- deadline_minutes=70,- absent_minutes=10,- clock=clock,- sleep=clock.sleep,- )- assert result.phase == relay.Phase.DECLINED- assert relay.report_migrations(result)[0] == 0- assert clock.now == 0--- "late_poll,workflow",- [- pytest.param(- {- EVENT_WAIT: [run(1, "cancelled"), run(2, "success", workflow="replacement")],- relay.MIGRATION_CHECK: [run(3, "success", workflow="replacement")],- },- "replacement",- id="a late replacement of this event's run",- ),- pytest.param(- {- EVENT_WAIT: [run(1, "cancelled")],- OLDER_RACING_WAIT: [run(2, "success", workflow="racing")],- relay.MIGRATION_CHECK: [run(3, "success", workflow="racing")],- },- "racing",- id="a racing event's run at the deadline",- ),- ],-)-def test_migration_report_finds_the_run_that_stands_in_for_a_cancelled_one(- late_poll: dict[str, list[Any]], workflow: str-) -> None:- clock = FakeClock()- result = relay.poll(- FakeReader([{EVENT_WAIT: [run(1, "cancelled")]}] * 25 + [late_poll]),- EVENT,- relay.MIGRATION_CHECK,- deadline_minutes=70,- absent_minutes=70,- clock=clock,- sleep=clock.sleep,- )- assert relay.report_migrations(result)[2] == {"migration_state": "success", "workflow_id": workflow}- assert clock.now > 10 * 60--@pytest.mark.parametrize("result,exit_code,first_line",[@@ -407,27 +283,6 @@ def test_relay_gate_names_the_failed_depot_run_to_retry() -> None:assert " gh run rerun 123 --repo PostHog/posthog --failed # relays the new Depot result" in lines- "result,exit_code,outputs",- [- (- relay.Progress(relay.Phase.FINISHED, "failure", "https://depot.dev/orgs/o/workflows/w1?job=j"),- 0,- {"migration_state": "failure", "workflow_id": "w1"},- ),- (relay.Progress(relay.Phase.FINISHED, "success", "https://example.com/not-depot"), 1, {}),- (relay.Progress(relay.Phase.FINISHED, "skipped"), 0, {}),- (relay.Progress(relay.Phase.CANCELLED, "cancelled"), 0, {}),- (relay.Progress(relay.Phase.ABSENT), 1, {}),- (relay.Progress(relay.Phase.FINISHED, "timed_out"), 1, {}),- (relay.Progress(relay.Phase.RUNNING), 1, {}),- ],-)-def test_report_migrations(result: Any, exit_code: int, outputs: dict[str, str]) -> None:- code, _, written = relay.report_migrations(result)- assert (code, written) == (exit_code, outputs)--class FakeResponse:def __init__(self, body: bytes, etag: str) -> None:self.status = 200@@ -444,26 +299,6 @@ class FakeResponse:return None-def test_handoff_reader_uses_the_github_actions_app() -> None:- requested: list[str] = []-- def opener(request: Any, timeout: int) -> FakeResponse:- requested.append(request.full_url)- return FakeResponse(- b'{"check_runs":[{"id":1,"status":"completed","conclusion":"success",'- b'"pull_requests":[{"number":105723}]}]}',- '"e1"',- )-- reader = relay.CheckRunReader(- "PostHog/posthog", EVENT.sha, "token", opener=opener, app_id=relay.GITHUB_ACTIONS_APP_ID- )- assert relay.handoff_decision(reader.read(relay.HANDOFF_CHECK), PR) is True- assert urllib.parse.parse_qs(urllib.parse.urlsplit(requested[0]).query)["app_id"] == [- str(relay.GITHUB_ACTIONS_APP_ID)- ]--def test_reader_reuses_its_answer_on_304_and_stops_on_repeated_refusals() -> None:sent: list[dict[str, str]] = []answers: list[Any] = [diff --git a/tools/workflow-plan/tests/backend-diff.test.ts b/tools/workflow-plan/tests/backend-diff.test.tsindex 456b09a3242c..f4145765902e 100644--- a/tools/workflow-plan/tests/backend-diff.test.ts+++ b/tools/workflow-plan/tests/backend-diff.test.ts@@ -134,11 +134,6 @@ function requiredGate(wf: Workflow, cwd: string, context: Context): SpawnSyncRet}describe('Backend CI comparison boundaries', () => {- it('restricts the privileged migration reporter to master', () => {- const report = loadWorkflow(path.join(REPO_ROOT, '.depot/workflows/ci-backend-report.yml'))- expect(report.on).toMatchObject({ pull_request_target: { branches: ['master'] } })- })-it.each(WORKFLOWS)('%s selects a stack layer without counting newer trunk files', (file) => {const repo = createGraph()try {