: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(stamphog): allow no-op migrations (#55998)
Raúl Negrón-Otero7ec253cf3386
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex b2543b74ce47..56085a648f9b 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -562,6 +562,13 @@ jobs:needs: [changes]if: needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true'timeout-minutes: 20+ # checks: write is needed so the "Publish Migration risk check" step+ # can POST to /repos/.../check-runs. Workflow-level perms only grant+ # contents:read + pull-requests:write.+ permissions:+ contents: read+ pull-requests: write+ checks: writename: Validate migrations and OpenAPI typesruns-on: depot-ubuntu-latest@@ -803,9 +810,11 @@ jobs:env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |- # Get risk analysis for all unapplied migrations (including third-party)+ # 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 # Don't exit immediately on error- RISK_ANALYSIS=$(python manage.py analyze_migration_risk --fail-on-blocked 2>/dev/null)+ RISK_ANALYSIS=$(python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json 2>/dev/null)EXIT_CODE=$?set -e # Re-enable exit on error@@ -864,12 +873,97 @@ jobs:exit $EXIT_CODEfi+ - 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.+ #+ # Always published — even with zero migrations to analyze, or+ # when the analyzer crashed — 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.+ if: always() && github.event_name == 'pull_request'+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_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 — 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 as a PR+ # comment 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 PR comment")+ 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: always() && github.event_name == 'pull_request'uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0with:name: migration-analysis- path: migration_analysis.md+ path: |+ migration_analysis.md+ migration_analysis.jsonif-no-files-found: ignore- name: Run migrations for this PRdiff --git a/posthog/management/commands/analyze_migration_risk.py b/posthog/management/commands/analyze_migration_risk.pyindex a95b3d030ed8..c6e307bbc08f 100644--- a/posthog/management/commands/analyze_migration_risk.py+++ b/posthog/management/commands/analyze_migration_risk.py@@ -1,5 +1,6 @@# ruff: noqa: T201 allow print statements+import osimport sysfrom django.core.management.base import BaseCommand@@ -7,7 +8,7 @@ from django.db import migrationsfrom posthog.management.migration_analysis.analyzer import RiskAnalyzerfrom posthog.management.migration_analysis.deprecated_field_filter import DeprecatedFieldFilter-from posthog.management.migration_analysis.formatters import ConsoleTreeFormatter+from posthog.management.migration_analysis.formatters import ConsoleTreeFormatter, JsonFormatterfrom posthog.management.migration_analysis.models import MigrationRisk, RiskLevel@@ -20,22 +21,31 @@ class Command(BaseCommand):action="store_true",help="Exit with code 1 if any blocked migrations found",)+ parser.add_argument(+ "--output-json",+ metavar="PATH",+ help="Also write structured analyzer output to PATH for programmatic consumers (CI, agents, etc.)",+ )def handle(self, *args, **options):+ json_path = options.get("output_json")+# Check for missing migrations firstmissing_migrations_warning = self.check_missing_migrations()migrations = self.get_unapplied_migrations()if not migrations and not missing_migrations_warning:- # Return silently when no migrations to analyze and no missing migrations (for CI)+ # No migrations to analyze. Still emit empty JSON so consumers can+ # distinguish "analyzer ran, nothing to report" from "analyzer failed".+ self.write_json_report([], json_path)return# Print missing migrations warning if presentif missing_migrations_warning:print(missing_migrations_warning)if not migrations:- # If only missing migrations, exit early+ self.write_json_report([], json_path)return# Check batch-level policies (e.g., multiple migrations per app)@@ -49,10 +59,11 @@ class Command(BaseCommand):results = self.analyze_loaded_migrations(migrations)if not results:- # Return silently when no results (for CI)+ self.write_json_report([], json_path)returnself.print_report(results)+ self.write_json_report(results, json_path)if options.get("fail_on_blocked"):blocked = [r for r in results if r.level == RiskLevel.BLOCKED]@@ -74,9 +85,7 @@ class Command(BaseCommand):try:executor = MigrationExecutor(connection)plan = executor.migration_plan(executor.loader.graph.leaf_nodes())- except Exception as e:- # Log error details for debugging (shows in stderr during CI)- print(f"## ⚠️ Error analyzing migrations: {e}", file=sys.stderr)+ except Exception:# Return empty list if can't connect to DB or load migrationsreturn []@@ -96,24 +105,48 @@ class Command(BaseCommand):try:executor = MigrationExecutor(connection)loader = executor.loader- except Exception as e:- print(f"## ⚠️ Error getting migration loader: {e}", file=sys.stderr)+ except Exception:loader = Nonefor label, migration in migrations:+ # Best-effort: a single un-analyzable migration must not abort the run,+ # otherwise handle() never reaches write_json_report() and the+ # downstream Migration risk check is never published — leaving+ # stamphog stuck in WAITING with no bridge retrigger.try:+ file_path = self._migration_file_path(migration)if loader:- risk = analyzer.analyze_migration_with_context(migration, label, loader)+ risk = analyzer.analyze_migration_with_context(migration, label, loader, file_path=file_path)else:- risk = analyzer.analyze_migration(migration, label)+ risk = analyzer.analyze_migration(migration, label, file_path=file_path)results.append(risk)except Exception as e:print(f"## ⚠️ Error analyzing migration {label}: {e}", file=sys.stderr)- # Skip this migration and continuecontinuereturn results+ def _migration_file_path(self, migration) -> str | None:+ """Resolve the repo-relative file path for a loaded Django migration.++ Uses the migration class's imported module rather than the loader so it+ works for any app — including products with custom MIGRATION_MODULES+ mappings, which still set __module__ to the actual import path.+ """+ module_name = getattr(migration.__class__, "__module__", None)+ if not module_name:+ return None+ module = sys.modules.get(module_name)+ absolute = getattr(module, "__file__", None)+ if not absolute:+ return None+ try:+ return os.path.relpath(absolute)+ except ValueError:+ # Cross-drive or otherwise unrelatable path — fall back to None+ # so consumers know we couldn't pin a path for this migration.+ return None+def check_missing_migrations(self) -> str:"""Check if there are model changes that need migrations."""import sys@@ -160,3 +193,10 @@ class Command(BaseCommand):formatter = ConsoleTreeFormatter()output = formatter.format_report(results)print(output)++ def write_json_report(self, results: list[MigrationRisk], path: str | None) -> None:+ """Write structured analyzer output for programmatic consumers."""+ if not path:+ return+ with open(path, "w") as f:+ f.write(JsonFormatter().format_report(results))diff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.pyindex df8b8be32b0e..9f15cfdd8743 100644--- a/posthog/management/migration_analysis/analyzer.py+++ b/posthog/management/migration_analysis/analyzer.py@@ -58,18 +58,23 @@ class RiskAnalyzer:"SeparateDatabaseAndState": SeparateDatabaseAndStateAnalyzer(),}- def analyze_migration(self, migration, path: str) -> MigrationRisk:+ def analyze_migration(self, migration, path: str, file_path: str | None = None) -> MigrationRisk:"""Analyze migration without migration loader context (for backwards compatibility)."""- return self.analyze_migration_with_context(migration, path, loader=None)+ return self.analyze_migration_with_context(migration, path, loader=None, file_path=file_path)- def analyze_migration_with_context(self, migration, path: str, loader=None) -> MigrationRisk:+ def analyze_migration_with_context(+ self, migration, path: str, loader=None, file_path: str | None = None+ ) -> MigrationRisk:"""Analyze migration with optional migration loader for enhanced validation.Args:migration: Django migration object- path: Path to migration file (for reporting)+ path: Label for reporting (typically "<app>.<name>")loader: Optional Django MigrationLoader for checking migration history+ file_path: Optional repo-relative path to the migration file on disk;+ forwarded to MigrationRisk for downstream consumers that need to+ map analyzer verdicts back to PR file paths."""# Collect newly created models for this migration (normalized to lowercase for case-insensitive matching)# Only count models that are managed=True (skipping unmanaged ones to avoid misleading messages)@@ -140,6 +145,7 @@ class RiskAnalyzer:combination_risks=combination_risks,policy_violations=policy_violations,info_messages=info_messages,+ file_path=file_path,)def _is_safe_on_new_table(self, op, risk: OperationRisk) -> bool:diff --git a/posthog/management/migration_analysis/formatters.py b/posthog/management/migration_analysis/formatters.pyindex b88b68cfd456..7b5c7b83a8ee 100644--- a/posthog/management/migration_analysis/formatters.py+++ b/posthog/management/migration_analysis/formatters.py@@ -1,5 +1,6 @@"""Formatters for displaying migration risk analysis results."""+import jsonimport textwrapfrom abc import ABC, abstractmethod@@ -200,3 +201,63 @@ class ConsoleTreeFormatter(RiskFormatter):lines.append("")return "\n".join(lines)+++class JsonFormatter(RiskFormatter):+ """Machine-readable analyzer output.++ Schema:+ {+ "summary": {"safe": int, "needs_review": int, "blocked": int},+ "max_level": "Safe" | "Needs Review" | "Blocked" | null,+ "migrations": [+ {+ "label": "<app>.<name>",+ "level": "Safe" | "Needs Review" | "Blocked",+ "file_path": "<repo-relative-path>" | null+ }+ ]+ }++ `max_level` is null only when there are no migrations to analyze. CI uses+ this output to publish the Migration risk check; downstream tools (notably+ stamphog) read `file_path` to scope the deny-list bypass to exactly the+ files the analyzer classified — the analyzer is the source of truth.+ """++ def format_report(self, results: list[MigrationRisk]) -> str:+ return json.dumps(self._report_dict(results), indent=2)++ def format_migration(self, risk: MigrationRisk) -> str:+ return json.dumps(self._migration_dict(risk), indent=2)++ def _report_dict(self, results: list[MigrationRisk]) -> dict:+ counts = {RiskLevel.SAFE: 0, RiskLevel.NEEDS_REVIEW: 0, RiskLevel.BLOCKED: 0}+ for risk in results:+ counts[risk.level] += 1++ return {+ "summary": {+ "safe": counts[RiskLevel.SAFE],+ "needs_review": counts[RiskLevel.NEEDS_REVIEW],+ "blocked": counts[RiskLevel.BLOCKED],+ },+ "max_level": self._max_level(results),+ "migrations": [self._migration_dict(r) for r in results],+ }++ def _migration_dict(self, risk: MigrationRisk) -> dict:+ return {+ "label": f"{risk.app}.{risk.name}",+ "level": risk.category,+ "file_path": risk.file_path,+ }++ def _max_level(self, results: list[MigrationRisk]) -> str | None:+ if not results:+ return None+ # Iterate by severity so Blocked > Needs Review > Safe.+ for level in (RiskLevel.BLOCKED, RiskLevel.NEEDS_REVIEW, RiskLevel.SAFE):+ if any(r.level == level for r in results):+ return level.category+ return Nonediff --git a/posthog/management/migration_analysis/models.py b/posthog/management/migration_analysis/models.pyindex 859ae56d320f..2e57ff3e902e 100644--- a/posthog/management/migration_analysis/models.py+++ b/posthog/management/migration_analysis/models.py@@ -49,6 +49,11 @@ class MigrationRisk:combination_risks: list[str] = field(default_factory=list)policy_violations: list[str] = field(default_factory=list) # PostHog-specific coding policiesinfo_messages: list[str] = field(default_factory=list) # Informational messages (not warnings)+ # Repo-relative path of the migration file. Set by the command layer when+ # a Django Migration object is loaded from disk; downstream consumers+ # (CI checks, stamphog) use this to scope bypasses to files the analyzer+ # actually classified.+ file_path: str | None = None@propertydef max_score(self) -> int:diff --git a/posthog/management/migration_analysis/test/test_json_formatter.py b/posthog/management/migration_analysis/test/test_json_formatter.pynew file mode 100644index 000000000000..67bf0fc01beb--- /dev/null+++ b/posthog/management/migration_analysis/test/test_json_formatter.py@@ -0,0 +1,71 @@+import json++import pytest++from posthog.management.migration_analysis.formatters import JsonFormatter+from posthog.management.migration_analysis.models import MigrationRisk, OperationRisk+++def _risk(app: str, name: str, score: int, file_path: str | None = None) -> MigrationRisk:+ return MigrationRisk(+ path=f"{app}.{name}",+ app=app,+ name=name,+ operations=[OperationRisk(type="AddField", score=score, reason="test", details={})],+ file_path=file_path,+ )+++class TestJsonFormatter:+ def setup_method(self):+ self.formatter = JsonFormatter()++ def test_empty_report_uses_null_max_level(self):+ report = json.loads(self.formatter.format_report([]))++ assert report == {+ "summary": {"safe": 0, "needs_review": 0, "blocked": 0},+ "max_level": None,+ "migrations": [],+ }++ def test_single_migration_full_shape(self):+ """Pins the full output contract for the simplest non-empty case,+ including the `app.name` label format and the `file_path` field that+ stamphog uses to scope its deny-list bypass."""+ report = json.loads(+ self.formatter.format_report(+ [_risk("posthog", "1125_x", score=1, file_path="posthog/migrations/1125_x.py")]+ )+ )++ assert report == {+ "summary": {"safe": 1, "needs_review": 0, "blocked": 0},+ "max_level": "Safe",+ "migrations": [{"label": "posthog.1125_x", "level": "Safe", "file_path": "posthog/migrations/1125_x.py"}],+ }++ def test_missing_file_path_emits_null(self):+ """When the command can't resolve a disk path (frozen apps, weird+ loaders), `file_path` is null rather than absent — keeps the schema+ shape stable for consumers."""+ report = json.loads(self.formatter.format_report([_risk("posthog", "1125_x", score=1)]))++ assert report["migrations"] == [{"label": "posthog.1125_x", "level": "Safe", "file_path": None}]++ @pytest.mark.parametrize(+ "scores, expected_max_level",+ [+ pytest.param([0, 1], "Safe", id="all-safe"),+ pytest.param([1, 3], "Needs Review", id="needs-review-when-no-blocked"),+ pytest.param([1, 2, 4], "Blocked", id="blocked-wins-over-everything"),+ ],+ )+ def test_max_level_picks_highest_severity_present(self, scores: list[int], expected_max_level: str):+ """`max_level` is what stamphog and the GitHub check read — must always+ reflect the worst migration in the batch."""+ results = [_risk("posthog", f"m{i}", score=s) for i, s in enumerate(scores)]++ report = json.loads(self.formatter.format_report(results))++ assert report["max_level"] == expected_max_leveldiff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.mdindex 658439f4d0ea..bad01af942e7 100644--- a/tools/pr-approval-agent/README.md+++ b/tools/pr-approval-agent/README.md@@ -102,6 +102,10 @@ Deny-listed categories where even a small diff can have high blast radius:| **public_api** | openapi, api_schema, swagger, public_api || **deps_toolchain** | package.json, requirements.txt, pyproject.toml, pnpm-lock, uv.lock, Cargo.toml, go.mod, etc. |+The **migrations** deny-list is bypassed when the `Migration risk` check on the head commit concludes `success` (all migrations classified Safe). The check is published by `analyze_migration_risk` in `ci-backend.yml` and is the same signal humans see in the PR's Checks tab. See `tools/pr-approval-agent/migration_risk.py` for how stamphog reads it.++If the check hasn't completed yet when stamphog runs, stamphog refuses with a message asking the user to wait for the `Migration risk` check and re-apply the `stamphog` label. The label-strip on non-approved verdicts breaks the auto-rerun loop, so the next labeling action is the one that triggers a fresh review against the now-classified head commit.+### OwnershipUses `.github/CODEOWNERS-soft` as context for the LLM (not a hard gate).diff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.pyindex e164fb3fe10e..efed3dd39848 100644--- a/tools/pr-approval-agent/gates.py+++ b/tools/pr-approval-agent/gates.py@@ -375,9 +375,10 @@ def test_only(categories: dict[str, int]) -> bool:# ── Deny / allow detection ───────────────────────────────────────-def detect_deny_categories(files: list[str], subject: str) -> list[str]:+def detect_deny_categories(files: list[str], subject: str, ignored_files: set[str] | None = None) -> list[str]:hits: set[str] = set()- paths_lower = [f.lower() for f in files]+ ignored_files_lower = {f.lower() for f in ignored_files or set()}+ paths_lower = [f.lower() for f in files if f.lower() not in ignored_files_lower]subject_lower = subject.lower()for category, scopes in DENY_PATTERNS.items():diff --git a/tools/pr-approval-agent/migration_risk.py b/tools/pr-approval-agent/migration_risk.pynew file mode 100644index 000000000000..819015ec2192--- /dev/null+++ b/tools/pr-approval-agent/migration_risk.py@@ -0,0 +1,108 @@+"""Decide whether migrations in a PR are safe enough to bypass the deny-list.++Reads the `Migration risk` GitHub check run posted on the head commit by CI.+That check is a generic CI feature — humans see it in the PR UI and any tool+that consumes check_runs can use it. Stamphog is one such consumer; nothing in+this module is specific to the analyzer's internals, only to the check's+public conclusion plus a small marker the analyzer embeds in the summary.++Conclusion semantics, defined by the analyzer (max risk level across all+migrations the analyzer covered):+ success → all classified migrations Safe (brief or no lock, backwards+ compatible) OR no Django migrations to analyze+ neutral → at least one Needs Review (may have performance impact)+ failure → at least one Blocked, or analyzer crashed++GitHub check runs are bound to a commit SHA at the API level — `pr.check_runs`+only returns checks attached to the current head commit, so a stale check from+an earlier commit can't be read here by construction.++Bypass scoping: the analyzer only covers Django migrations and embeds the+exact list of analyzed file paths in the summary as a `<!-- stamphog:v1 [...] -->`+marker. Stamphog scopes its bypass to the intersection of (analyzed paths) and+(PR diff). Files in directories that share the `migrations/` name but are+managed by other systems (ClickHouse, async migrations, RBAC scripts) never+appear in the analyzer's list and so always fall through to the deny-list.+"""++import re+import json+from pathlib import Path++CHECK_NAME = "Migration risk"++_MARKER_RE = re.compile(r"<!--\s*stamphog:v1\s+(\[[^\]]*\])\s*-->")+++def safe_migration_files(check_runs: list[dict], pr_file_paths: list[str]) -> set[str]:+ """Return migration files (and their max_migration.txt) that may bypass the deny-list.++ Returns an empty set when the check is missing, in-flight, didn't conclude+ `success`, or has no marker (older check pre-rollout). The caller treats+ that as "deny-list applies normally."+ """+ latest = _latest_completed(check_runs, CHECK_NAME)+ if latest is None or latest.get("conclusion") != "success":+ return set()++ analyzed = _analyzed_paths_from_check(latest)+ if not analyzed:+ return set()++ pr_paths = set(pr_file_paths)+ safe = analyzed & pr_paths+ # Pair each analyzed migration with its sibling max_migration.txt — the+ # bumped marker file is part of the same logical change and would+ # otherwise still trigger the deny-list. Only siblings of analyzed files+ # are paired, so unrelated `migrations/` dirs (ClickHouse etc.) stay out.+ for path in list(safe):+ safe.add(str(Path(path).parent / "max_migration.txt"))+ return safe+++def migration_check_pending(check_runs: list[dict], pr_file_paths: list[str]) -> bool:+ """True when the PR touches migration-shaped files and no completed check exists.++ With the always-publish workflow, a missing completed check means CI+ simply hasn't finished yet — the analyzer publishes a verdict for every+ PR, including PRs that touch only non-Django migration directories.+ The `_is_migration_file` heuristic still gates this so PRs that don't+ touch any migration-shaped file aren't held up.+ """+ if not any(_is_migration_file(p) for p in pr_file_paths):+ return False+ return _latest_completed(check_runs, CHECK_NAME) is None+++def _analyzed_paths_from_check(check_run: dict) -> set[str]:+ """Parse the `<!-- stamphog:v1 [...] -->` marker out of the check's summary.++ The marker holds a JSON array of repo-relative file paths the analyzer+ classified. Returns an empty set when the marker is missing, malformed,+ or empty — every failure mode falls back to "no bypass," which is the+ safe default.+ """+ summary = (check_run.get("output") or {}).get("summary") or ""+ match = _MARKER_RE.search(summary)+ if not match:+ return set()+ try:+ paths = json.loads(match.group(1))+ except json.JSONDecodeError:+ return set()+ if not isinstance(paths, list):+ return set()+ return {p for p in paths if isinstance(p, str)}+++def _latest_completed(check_runs: list[dict], name: str) -> dict | None:+ """Pick the most recent completed run for `name`, tolerating duplicates from re-runs."""+ completed = [cr for cr in check_runs if cr.get("name") == name and cr.get("status") == "completed"]+ if not completed:+ return None+ return max(completed, key=lambda cr: cr.get("completed_at") or "")+++def _is_migration_file(path: str) -> bool:+ p = Path(path)+ return p.suffix == ".py" and p.parent.name == "migrations" and p.name != "__init__.py"diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex 22a5bcc031f8..08698d270d78 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -43,6 +43,7 @@ from gates import (test_only,)from github import PRData, check_team_membership, fetch_pr+from migration_risk import migration_check_pending, safe_migration_filesfrom reviewer import Reviewertry:@@ -128,6 +129,9 @@ class Pipeline:self._classify()self._run_gates()+ if self._only_pending_migration_check():+ return self._refuse_pending_migration_check()+gate_verdict = self._gate_verdict()if self.dry_run:@@ -137,6 +141,36 @@ class Pipeline:self._llm_review(gate_verdict)return self.final_verdict+ def _only_pending_migration_check(self) -> bool:+ """True when the only thing blocking approval is a pending Migration risk check.++ Lets us emit a specific deny reason ("wait for the check, re-label")+ instead of the generic deny-list one. Other denies (auth, crypto) or+ gate failures (size, prerequisites) won't clear when the analyzer+ finishes, so we shouldn't promise a re-label will help.+ """+ if self.classification.get("deny_categories", []) != ["migrations"]:+ return False+ if any(not r.passed and r.gate != "deny-list" for r in self.gate_results):+ return False+ return migration_check_pending(self.pr.check_runs, self.pr.file_paths)++ def _refuse_pending_migration_check(self) -> str:+ self.final_verdict = "REFUSED"+ self.reviewer_output = {+ "verdict": "REFUSE",+ "reasoning": (+ "The `Migration risk` check has not completed for this commit. "+ "Wait for it to finish (visible in the PR's Checks tab), then "+ "re-apply the `stamphog` label to retry."+ ),+ "risk": "unknown",+ "issues": [],+ }+ print(f"\n{_warn('REFUSED')} — Migration risk check pending; re-label after it completes")+ self._capture_review_completed("DENIED", "PENDING-MIGRATION-CHECK")+ return self.final_verdict+def _gate_verdict(self) -> str:"""Determine what gates say — this is authoritative."""if self._any_gate_denied():@@ -166,7 +200,8 @@ class Pipeline:top_dirs = file_info["top_dirs"]breadth = scope_breadth(top_dirs)cc = parse_conventional_commit(pr.title)- deny = detect_deny_categories(file_paths, pr.title)+ safe_migrations = safe_migration_files(pr.check_runs, file_paths)+ deny = detect_deny_categories(file_paths, pr.title, ignored_files=safe_migrations)allow_only = is_allow_listed_only(file_paths)is_test = test_only(categories)ownership_rules = parse_codeowners_soft(CODEOWNERS_SOFT)@@ -198,6 +233,7 @@ class Pipeline:"commit_scope": cc["scope"],"categories": categories,"deny_categories": deny,+ "safe_migration_files": sorted(safe_migrations),"allow_listed_only": allow_only,"is_test_only": is_test,"has_dep_changes": has_dependency_changes(file_paths),@@ -414,6 +450,7 @@ class Pipeline:"breadth": self.classification["breadth"],"commit_type": self.classification.get("commit_type"),"deny_categories": self.classification.get("deny_categories", []),+ "safe_migration_files": self.classification.get("safe_migration_files", []),"ownership": self.classification.get("ownership", {}),},"gates": [diff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.pyindex abb2d2c86ef4..e8cf794cb277 100644--- a/tools/pr-approval-agent/test_gates.py+++ b/tools/pr-approval-agent/test_gates.py@@ -139,3 +139,26 @@ def test_no_false_positive(files: list[str], subject: str) -> None:def test_true_positive(files: list[str], subject: str, expected_category: str) -> None:result = detect_deny_categories(files, subject)assert expected_category in result, f"Expected '{expected_category}' in {result}"+++# ── Deny-list bypass via ignored_files ───────────────────────────+++def test_ignored_files_bypass_deny_list() -> None:+ files = [+ "posthog/migrations/1117_alter_integration_kind.py",+ "posthog/migrations/max_migration.txt",+ ]+ ignored = set(files)++ assert detect_deny_categories(files, "feat: add postgresql integration", ignored_files=ignored) == []+++def test_ignored_files_does_not_bypass_other_deny_list_files() -> None:+ files = [+ "posthog/migrations/1117_alter_integration_kind.py",+ "posthog/migrations/1118_add_column.py",+ ]+ ignored = {"posthog/migrations/1117_alter_integration_kind.py"}++ assert detect_deny_categories(files, "feat: integration field", ignored_files=ignored) == ["migrations"]diff --git a/tools/pr-approval-agent/test_migration_risk.py b/tools/pr-approval-agent/test_migration_risk.pynew file mode 100644index 000000000000..3582b7648b02--- /dev/null+++ b/tools/pr-approval-agent/test_migration_risk.py@@ -0,0 +1,200 @@+"""Tests for migration_risk.py — check-run interpretation."""++import json++import pytest++from migration_risk import migration_check_pending, safe_migration_files+++def _check(+ name: str = "Migration risk",+ *,+ status: str = "completed",+ conclusion: str | None = "success",+ completed_at: str = "2026-04-30T12:00:00Z",+ analyzed_paths: list[str] | None = None,+ summary_override: str | None = None,+) -> dict:+ """Build a fake check_run.++ `analyzed_paths` becomes the JSON inside the `<!-- stamphog:v1 [...] -->`+ marker; pass `None` to omit the marker entirely (simulates older checks+ or non-success conclusions). `summary_override` lets tests inject raw+ summary text (e.g. malformed markers).+ """+ if summary_override is not None:+ summary = summary_override+ elif analyzed_paths is None:+ summary = "no marker here"+ else:+ summary = f"<!-- stamphog:v1 {json.dumps(analyzed_paths)} -->\nreport body"+ return {+ "name": name,+ "status": status,+ "conclusion": conclusion,+ "completed_at": completed_at,+ "output": {"summary": summary},+ }+++# ── safe_migration_files ─────────────────────────────────────────+++def test_success_check_pairs_each_migration_with_its_max_migration_txt() -> None:+ """Happy path. Every analyzed migration in the marker that's also in the PR+ diff gets its directory's max_migration.txt paired automatically, across+ multiple migration roots; non-migration paths are ignored."""+ files = [+ "posthog/migrations/1125_x.py",+ "products/signals/backend/migrations/0042_y.py",+ "posthog/api/some.py",+ ]+ check = _check(+ analyzed_paths=[+ "posthog/migrations/1125_x.py",+ "products/signals/backend/migrations/0042_y.py",+ ]+ )++ assert safe_migration_files([check], files) == {+ "posthog/migrations/1125_x.py",+ "posthog/migrations/max_migration.txt",+ "products/signals/backend/migrations/0042_y.py",+ "products/signals/backend/migrations/max_migration.txt",+ }+++def test_bypass_scoped_to_intersection_of_marker_and_pr() -> None:+ """The marker is the source of truth. A path the analyzer never classified+ (e.g. ClickHouse migration in the same PR) must not be bypassed even when+ the Django side concluded success."""+ files = [+ "posthog/migrations/1125_x.py",+ "posthog/clickhouse/migrations/0099_unrelated.py",+ ]+ # Marker only lists the Django one — the analyzer doesn't touch ClickHouse.+ check = _check(analyzed_paths=["posthog/migrations/1125_x.py"])++ assert safe_migration_files([check], files) == {+ "posthog/migrations/1125_x.py",+ "posthog/migrations/max_migration.txt",+ }+++def test_max_migration_txt_paired_only_for_analyzed_dirs() -> None:+ """Sibling pairing must follow the analyzer's scope — a ClickHouse+ `max_migration.txt` should never be added just because some other dir+ contributed a Safe migration."""+ files = [+ "posthog/migrations/1125_x.py",+ "posthog/clickhouse/migrations/0099_x.py",+ ]+ check = _check(analyzed_paths=["posthog/migrations/1125_x.py"])++ safe = safe_migration_files([check], files)++ assert "posthog/clickhouse/migrations/max_migration.txt" not in safe+ assert "posthog/migrations/max_migration.txt" in safe+++def test_empty_marker_means_no_bypass() -> None:+ """Zero Django migrations to analyze still publishes success, but with an+ empty marker — bypass set is empty and the deny-list applies normally."""+ files = ["posthog/clickhouse/migrations/0099_x.py"]+ check = _check(analyzed_paths=[])++ assert safe_migration_files([check], files) == set()+++ "summary",+ [+ pytest.param("no marker here at all", id="no-marker"),+ pytest.param("<!-- stamphog:v1 not-json-array -->", id="malformed-json"),+ pytest.param('<!-- stamphog:v1 ["missing close ', id="truncated"),+ pytest.param('<!-- stamphog:v1 {"shape":"wrong"} -->', id="wrong-shape"),+ ],+)+def test_malformed_or_missing_marker_falls_back_to_no_bypass(summary: str) -> None:+ """Any failure to parse the marker is treated as "no analyzer signal,"+ which is the safe default — deny-list applies normally."""+ check = _check(summary_override=summary)+ assert safe_migration_files([check], ["posthog/migrations/1125_x.py"]) == set()+++ "check_runs",+ [+ pytest.param([], id="no-checks"),+ pytest.param([_check(name="other-ci")], id="different-check-name"),+ pytest.param(+ [_check(conclusion="failure", analyzed_paths=["posthog/migrations/1125_x.py"])], id="completed-failure"+ ),+ pytest.param(+ [_check(conclusion="neutral", analyzed_paths=["posthog/migrations/1125_x.py"])], id="completed-needs-review"+ ),+ pytest.param([_check(status="in_progress", conclusion=None)], id="in-flight"),+ ],+)+def test_no_bypass_unless_check_completed_with_success(check_runs: list[dict]) -> None:+ """Bypass requires an explicit `success` conclusion on a completed+ `Migration risk` check; everything else falls back to the deny-list,+ even when the marker would otherwise list the file."""+ assert safe_migration_files(check_runs, ["posthog/migrations/1125_x.py"]) == set()+++def test_latest_completed_run_wins_over_older_and_in_flight() -> None:+ """CI re-runs leave duplicate checks. The most recent completed run wins,+ even when a newer in-flight run is present (it has no completed_at)."""+ older_failure = _check(+ conclusion="failure",+ completed_at="2026-04-30T10:00:00Z",+ analyzed_paths=["posthog/migrations/1125_x.py"],+ )+ newer_success = _check(+ conclusion="success",+ completed_at="2026-04-30T12:00:00Z",+ analyzed_paths=["posthog/migrations/1125_x.py"],+ )+ in_flight = _check(status="in_progress", conclusion=None, completed_at="")++ assert safe_migration_files([older_failure, newer_success, in_flight], ["posthog/migrations/1125_x.py"]) == {+ "posthog/migrations/1125_x.py",+ "posthog/migrations/max_migration.txt",+ }+++# ── migration_check_pending ──────────────────────────────────────+++ "check_runs",+ [+ pytest.param([], id="no-check"),+ pytest.param([_check(status="in_progress", conclusion=None)], id="in-progress"),+ pytest.param([_check(status="queued", conclusion=None)], id="queued"),+ ],+)+def test_pending_when_pr_has_migrations_and_no_completed_check(check_runs: list[dict]) -> None:+ """Drives the deny-with-retry message: anything short of a completed check+ means the verdict isn't in yet."""+ assert migration_check_pending(check_runs, ["posthog/migrations/1125_x.py"]) is True++[email protected]("conclusion", ["success", "failure"])+def test_not_pending_once_check_has_completed(conclusion: str) -> None:+ """Verdict is in even when not success — caller chooses how to act on it."""+ assert (+ migration_check_pending(+ [_check(conclusion=conclusion, analyzed_paths=["posthog/migrations/1125_x.py"])],+ ["posthog/migrations/1125_x.py"],+ )+ is False+ )+++def test_not_pending_when_pr_has_no_real_migrations() -> None:+ """No migration files means there's nothing to wait for, regardless of+ what other checks are in flight on the same head SHA."""+ assert migration_check_pending([_check(status="in_progress", conclusion=None)], ["posthog/api/views.py"]) is False