: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
chore(ci): report migrations on depot (#103131)
Raúl Negrón-Oteroe405016ca332
diff --git a/.depot/workflows/ci-backend-report.yml b/.depot/workflows/ci-backend-report.ymlnew file mode 100644index 000000000000..8fbf9eab622e--- /dev/null+++ b/.depot/workflows/ci-backend-report.yml@@ -0,0 +1,348 @@+# 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+ && (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: Find the handed-off Depot migration run+ id: source+ env:+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ EVENT_AT: ${{ github.event.pull_request.updated_at }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ HANDOFF_CHECK: Hand off backend tests to Depot CI+ MIGRATION_CHECK: Backend CI on Depot / Validate migrations+ GITHUB_ACTIONS_APP_ID: '15368'+ DEPOT_APP_ID: '219785'+ run: |+ set -euo pipefail++ read_check() {+ local url=$1+ local body=$2+ local code+ code=$(curl -s -o "$body" -w '%{http_code}' --max-time 15 \+ -H "Authorization: Bearer $GH_TOKEN" \+ -H "Accept: application/vnd.github+json" "$url")+ if [ "$code" != 200 ]; then+ echo "::warning::check-runs API returned $code"+ return 1+ fi+ }++ check_url() {+ local app_id=$1+ local name=$2+ printf 'https://api.github.com/repos/%s/commits/%s/check-runs?app_id=%s&check_name=%s' \+ "$REPO" "$HEAD_SHA" "$app_id" "$(jq -rn --arg n "$name" '$n | @uri')"+ }++ handoff_url=$(check_url "$GITHUB_ACTIONS_APP_ID" "$HANDOFF_CHECK")+ handoff=absent+ for _ in $(seq 1 45); do+ if read_check "$handoff_url" /tmp/handoff-checks.json; then+ handoff=$(jq -r --arg since "$EVENT_AT" --argjson pr "$PR_NUMBER" '+ [.check_runs[] | select((.started_at // "") >= $since and any(.pull_requests[]?; .number == $pr))]+ | max_by(.id)+ | if . == null then "absent" elif .status == "completed" then .conclusion else .status end+ ' /tmp/handoff-checks.json)+ fi+ case "$handoff" in+ success) break ;;+ absent|queued|in_progress|pending|waiting|requested) sleep 20 ;;+ *)+ echo "handed_off=false" >> "$GITHUB_OUTPUT"+ echo "GitHub Actions kept the backend tests (hand-off check: $handoff)."+ exit 0+ ;;+ esac+ done+ if [ "$handoff" != success ]; then+ echo "::error::Backend routing did not resolve within 15 minutes"+ exit 1+ fi+ echo "handed_off=true" >> "$GITHUB_OUTPUT"++ migration_url=$(check_url "$DEPOT_APP_ID" "$MIGRATION_CHECK")+ migration_state=absent+ details_url=''+ for _ in $(seq 1 210); do+ if read_check "$migration_url" /tmp/migration-checks.json; then+ readarray -t check < <(jq -r --arg since "$EVENT_AT" --argjson pr "$PR_NUMBER" '+ [.check_runs[] | select((.started_at // "") >= $since and any(.pull_requests[]?; .number == $pr))]+ | max_by(.id)+ | if . == null then "absent", "" else (if .status == "completed" then .conclusion else .status end), (.details_url // "") end+ ' /tmp/migration-checks.json)+ migration_state=${check[0]:-absent}+ details_url=${check[1]:-}+ fi+ case "$migration_state" in+ success|failure|neutral|cancelled|skipped) break ;;+ absent|queued|in_progress|pending|waiting|requested) sleep 20 ;;+ *) echo "::error::Unexpected migration check state: $migration_state"; exit 1 ;;+ esac+ done+ echo "migration_state=$migration_state" >> "$GITHUB_OUTPUT"+ case "$migration_state" in+ success|failure|neutral) ;;+ cancelled|skipped)+ echo "No completed migration report is available (migration check: $migration_state)."+ exit 0+ ;;+ *) echo "::error::Depot migration check did not finish within 70 minutes"; exit 1 ;;+ esac++ if [[ "$details_url" =~ ^https://depot.dev/orgs/[^/]+/workflows/([a-z0-9]+) ]]; then+ echo "workflow_id=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"+ else+ echo "::error::Unexpected Depot migration check URL"+ exit 1+ fi++ - 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 }}+ ref: ${{ github.event.pull_request.base.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 }}+ IS_TRUNK: ${{ startsWith(github.event.pull_request.head.ref, 'trunk-merge/') }}+ 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 [ "$IS_TRUNK" != true ] && [ "$(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 704d669d80ae..a1d6c468c65c 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -22,10 +22,9 @@# - permissions: read-only in every job, so the ambient token never writes. Canonical grants# handle-snapshots' github.token pull-requests:write for its CI report section; here the# section posts with a posthog-tests token scoped to pull-requests:write (see the header of-# .depot/actions/commit-snapshots).-# - Stripped side effects: CI report section posters other than backend snapshots (canonical-# additionally skips these on trunk-merge/** branches to save GITHUB_TOKEN budget;-# the shadow strips them entirely, so that gating has nothing to mirror),+# .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.+# - Stripped side effects: the backend coverage CI report section and# posthog-github-action telemetry (including the# capture-test-selection job — turbo-discover still emits its telemetry outputs to# stay apples-to-apples, they just have no consumer here; canonical mints the@@ -57,11 +56,6 @@# cache. This job and the mig_schema_key output that feeds it remain depot-exempt.# - OpenAPI types: validation remains a separate job like canonical, but its# auto-commit side effect is dropped-# - sqlmigrate SQL preview: canonical's check-migrations resolves changed migration files-# to full names, skips generated squash files by content, and degrades a sqlmigrate-# failure to a placeholder before posting the SQL preview comment. The shadow strips-# comment side effects (above) and runs no sqlmigrate loop, so those changes need no-# depot bump.# - Deterministic-failure self-cancel remains omitted: the injected Depot job token# cannot authorize the CLI's run lookup. Workflow-name expressions also remain# literal, so the role cannot switch names through a variable; the cutover renames@@ -85,8 +79,15 @@# 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. Mints whose# only consumer is a stripped side effect (OpenAPI auto-commit, telemetry) are-# stripped with it. The migration-risk check run is published here-# because stamphog waits for it on every pull request.+# stripped with it. 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.+# - 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+# Repo checks run carries the verdict.# - `depot ci run` fires with event_name `api`; the hand-off wait treats it like# workflow_dispatch: it runs only when GitHub Actions already handed the commit off.# Depot caps an inline workflow at 64 KiB, which this file exceeds, so@@ -181,9 +182,9 @@ env:TEST: 1# 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. (GITHUB_TOKEN is also- # injected ambient and leaks into plugin download auth headers, but GITHUB_-prefixed vars are- # reserved and cannot be overridden via env: — it is unset inside the test run scripts instead.)+ # 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'@@ -1521,6 +1522,20 @@ jobs:enable-cache: false- name: Install Python dependenciesrun: UV_PROJECT_ENVIRONMENT=$pythonLocation 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.+ - 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"+ - 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 productrun: ./bin/hogli product:bootstrap spline_reticulator --non-interactive- name: Lint product structure@@ -1565,15 +1580,6 @@ jobs:elsepytest -p no:cacheprovider posthog/test/test_startup_import_budget.py posthog/test/test_dataclass_defaults.pyfi- # Block deleting historical migration files (see safe-django-migrations.md).- # GITHUB_ACTIONS=false suppresses the command's PR annotations on the shadow.- - name: Check deleted migrations- if: github.event_name == 'pull_request' && needs.changes.outputs.migrations_any == 'true'- env:- GITHUB_ACTIONS: 'false'- REPO: ${{ github.repository }}- PR_NUMBER: ${{ github.event.pull_request.number }}- run: .github/scripts/list-removed-renamed-paths.sh | ./bin/hogli lint:migration-deletionsvalidate-product-yamls:needs: [changes]@@ -1798,85 +1804,128 @@ jobs:- name: Install python dependencies for this PRrun: |UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev- # The migration SQL preview and the CI report section stay stripped (see the- # header). The check run is published, because stamphog waits for it on every- # pull request and a routed PR would otherwise never get a verdict.+ - name: Render Django migration SQL report+ if: github.event_name == 'pull_request' && needs.changes.outputs.migrations == 'true'+ env:+ 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++ # If no migration files changed, exit+ if [ -z "$CHANGED_FILES" ]; then+ echo "No migration files changed"+ 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++ HAS_NEW_MIGRATIONS=false+ 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++ # Only show SQL for new migrations, not modifications to existing ones+ if git cat-file -e "$BASE_SHA:$file" 2>/dev/null; then+ echo "Skipping $file (already exists on base branch)"+ 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+ 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++ 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+ fi+ done++ if [ "$HAS_NEW_MIGRATIONS" = false ]; then+ echo "No new migrations to show (all changed files already exist on base branch)"+ fi+- name: Run migration risk analysisif: github.event_name == 'pull_request'- # A hang fails this step, which the publish below still reports as a verdict.+ # The artifact upload uses always(), so an analyzer failure still reaches the reporter.timeout-minutes: 5- run: python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json > migration_analysis.md 2>/dev/null-- - name: Get app token for Migration risk check- # The posthog-tests app owns the check, so it lands in that app's own check- # suite instead of under an arbitrary run. continue-on-error: a mint failure- # must not redden migration validation; the publish step skips on an empty token.- # !cancelled(): a superseded run leaves the verdict to the run that replaced it.- 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 }}-- - name: Publish Migration risk check- # Same contract as canonical: one completed `Migration risk` check on the head- # commit for every pull request, with the stamphog marker first in the summary.- # An analyzer crash publishes a failure, so consumers never wait forever.- if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false && steps.migration-risk-app-token.outputs.token != '' }}- env:- GITHUB_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- 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+ mkdir -p migration-report++ set +e+ python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json+ 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+ else+ jq -n --argjson exit_code "$EXIT_CODE" \+ '{version: 1, exit_code: $exit_code, analysis: null}' \+ > migration-report/django-migration-risk.jsonfi- 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")- CONCLUSION=success- TITLE="✅ No Django migrations to analyze"- ;;- *)- echo "Unknown max_level '$MAX_LEVEL' — publishing failure"- CONCLUSION=failure- TITLE="❌ Unknown analyzer output"- ;;- esac-- # Stamphog scopes its deny-list bypass to exactly the files the analyzer- # classified, so the marker stays first and survives truncation.- ANALYZED_PATHS=$(jq -c '[.migrations[].file_path | select(. != null)]' migration_analysis.json 2>/dev/null || echo '[]')- MARKER="<!-- stamphog:v1 ${ANALYZED_PATHS} -->"- REPORT_BODY=$([ -s migration_analysis.md ] && head -c 59000 migration_analysis.md || echo "See the workflow log")- 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 -+ # Fail the job if there were blocked migrations+ if [ $EXIT_CODE -ne 0 ]; then+ exit $EXIT_CODE+ fi++ - name: Upload migration analysis 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: migration-analysis+ path: |+ migration-report/django-migration-sql.json+ migration-report/django-migration-risk.json+ if-no-files-found: ignore+- name: Run migrations for this PRrun: |# Run Django migrations first (excluding managed=False models)@@ -1988,9 +2037,74 @@ jobs:echo "::warning::Could not fetch base ref $BASE_REF; counting CH migrations against master instead"fifi+ # 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# Same as above, except now for CH looking at files that were added in posthog/clickhouse/migrations/git diff --name-status "$DIFF_BASE"..HEAD | grep "A\sposthog/clickhouse/migrations/" | grep -v README | awk '{print $2}' | python manage.py test_ch_migrations_are_safe+ - 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'+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ run: |+ DIFF_BASE=upstream/master+ if [ -n "$BASE_REF" ] && [ "$BASE_REF" != "master" ]; then+ if git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"; then+ DIFF_BASE="origin/$BASE_REF"+ else+ echo "::warning::Could not fetch base ref $BASE_REF; rendering CH migrations against master instead"+ fi+ fi+ mkdir -p migration-report+ printf '%s\n' '{"version":1,"count":0,"environments":[]}' > migration-report/ch-migration-sql.json+ CHANGED=$(git diff --name-only --diff-filter=AM "$DIFF_BASE"..HEAD | grep '^posthog/clickhouse/migrations/[0-9]' | grep -v __pycache__ || true)+ 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"+ 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+ mkdir -p ch_sql_env+ DEPLOYMENTS=('' US EU DEV)+ LABELS=(unset US EU DEV)+ for idx in "${!DEPLOYMENTS[@]}"; do+ file="ch_sql_env/${idx}.md"+ 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::"+ 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+ done++ - 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+check-openapi-types:needs: [changes]# Not on master push: master only primes the schema cache.diff --git a/.github/scripts/render-depot-migration-report.mjs b/.github/scripts/render-depot-migration-report.mjsnew file mode 100644index 000000000000..9680648e9e30--- /dev/null+++ b/.github/scripts/render-depot-migration-report.mjs@@ -0,0 +1,303 @@+#!/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.mjsnew file mode 100644index 000000000000..1daf4a956919--- /dev/null+++ b/.github/scripts/render-depot-migration-report.test.mjs@@ -0,0 +1,72 @@+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/workflows/ci-lint-workflows.yml b/.github/workflows/ci-lint-workflows.ymlindex 612d8322e998..84f9e77eadd8 100644--- a/.github/workflows/ci-lint-workflows.yml+++ b/.github/workflows/ci-lint-workflows.yml@@ -48,7 +48,7 @@ jobs:with:persist-credentials: falsesparse-checkout: |- .depot/workflows/ci-backend.yml+ .depot/workflows/ci-backend*.yml.githubtools/workflow-planpatchesdiff --git a/tools/workflow-plan/tests/backend-diff.test.ts b/tools/workflow-plan/tests/backend-diff.test.tsindex f4145765902e..456b09a3242c 100644--- a/tools/workflow-plan/tests/backend-diff.test.ts+++ b/tools/workflow-plan/tests/backend-diff.test.ts@@ -134,6 +134,11 @@ 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 {