: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
feat(replay-vision): widen rollout flags over the API for EU migration runs (#92666)
Tue Haulund50b3ea7fc34a
diff --git a/products/replay_vision/backend/management/commands/migrate_vision_actions.py b/products/replay_vision/backend/management/commands/migrate_vision_actions.pyindex 7ffc01b40cda..dc1c645c56c0 100644--- a/products/replay_vision/backend/management/commands/migrate_vision_actions.py+++ b/products/replay_vision/backend/management/commands/migrate_vision_actions.py@@ -17,6 +17,7 @@ Every touched row is stamped with a `migrated_to` pointer (or `retired`), whichmakes the command idempotent and the cutover scriptably reversible."""+import osimport refrom dataclasses import dataclass, fieldfrom types import SimpleNamespace@@ -26,6 +27,7 @@ from django.core.management.base import BaseCommand, CommandErrorfrom django.db import transactionfrom django.utils import timezone+import requestsimport structlogfrom posthog.models import Team, User@@ -59,6 +61,90 @@ SCOUTS_FLAG_KEY = "replay-vision-scout-digests"_FREQ_TO_MINUTES = {"MINUTELY": 15, "HOURLY": 60, "DAILY": 1440, "WEEKLY": 10080}+FLAGS_API_KEY_ENV = "POSTHOG_FLAGS_API_KEY"+++class _FlagsApiTargeting:+ """Widens org targeting on flags that live on another PostHog instance.++ EU evaluates the rollout flags against the US instance (`posthog.ph_client` self-capture), so a+ migration run on EU must widen the US flags. Each widen re-reads the flag before the PATCH: the+ run is long, and writing back a cached filters document would revert any concurrent flag edit.+ """++ def __init__(self, host: str, project_id: int, api_key: str) -> None:+ self._host = host.rstrip("/")+ self._base = f"{self._host}/api/projects/{project_id}/feature_flags"+ self._session = requests.Session()+ self._session.headers["Authorization"] = f"Bearer {api_key}"+ self._flag_ids: dict[str, int] = {}++ @property+ def where(self) -> str:+ return self._host++ def preflight(self, keys: tuple[str, ...]) -> None:+ """Resolve flag ids so a wrong host, key, or missing flag fails before any row is migrated."""+ for key in keys:+ response = self._session.get(self._base, params={"key": key}, timeout=15)+ response.raise_for_status()+ results = response.json().get("results", [])+ flag = next((f for f in results if f.get("key") == key and not f.get("deleted")), None)+ if flag is None or flag.get("id") is None:+ raise CommandError(f"flag {key}: not found via {self._base}")+ self._flag_ids[key] = flag["id"]++ def add_group(self, key: str, group_key: str) -> str | None:+ """Widen one flag's org targeting. Returns a problem description, or None on success."""+ url = f"{self._base}/{self._flag_ids[key]}/"+ try:+ response = self._session.get(url, timeout=15)+ response.raise_for_status()+ filters = response.json().get("filters") or {}+ # Mirrors add_group_to_flag_targeting in the feature flags facade; keep in sync.+ conditions = [+ prop+ for group in filters.get("groups") or []+ for prop in group.get("properties", [])+ if prop.get("key") == "$group_key"+ ]+ if not conditions:+ return "no organization targeting to widen"+ values = conditions[0].get("value")+ if not isinstance(values, list):+ return "no organization targeting to widen"+ if group_key not in values:+ values.append(group_key)+ self._session.patch(url, json={"filters": filters}, timeout=15).raise_for_status()+ return None+ except requests.RequestException as error:+ logger.exception("vision_action_migration.flags_api_failed", key=key, error=str(error))+ return f"API request failed ({error})"+++class _LocalFlagTargeting:+ """The same widen contract over this instance's own flags project."""++ def __init__(self, team: Team) -> None:+ self._team = team++ @property+ def where(self) -> str:+ return f"team {self._team.id}"++ def add_group(self, key: str, group_key: str) -> str | None:+ from products.feature_flags.backend.facade.api import ( # noqa: PLC0415 — keeps the flags API surface off the command's import path+ add_group_to_flag_targeting,+ )++ if add_group_to_flag_targeting(team=self._team, key=key, group_key=group_key):+ return None+ return "no organization targeting to widen"+++_FlagTargeting = _FlagsApiTargeting | _LocalFlagTargeting++@dataclass(frozen=False)class _Report:alerts_created: int = 0@@ -127,13 +213,47 @@ class Command(BaseCommand):parser.add_argument("--flag-team-id",type=int,- required=True,- help="Team id of this instance's internal flags project (US: 2).",+ default=None,+ help="Team id of this instance's internal flags project (US: 2). Mutually exclusive with --flags-api-host.",+ )+ parser.add_argument(+ "--flags-api-host",+ default=None,+ help="Widen the rollout flags over the REST API of this PostHog instance instead of the local ORM. "+ "Use from EU: the flags live on the US instance. Requires --flags-api-project and "+ f"a personal API key with feature flag write scope in ${FLAGS_API_KEY_ENV}.",+ )+ parser.add_argument(+ "--flags-api-project",+ type=int,+ default=None,+ help="Project id holding the rollout flags on --flags-api-host (US: 2).",)parser.add_argument("--limit-orgs", type=int, default=None, help="Stop after this many organizations.")def handle(self, *args: Any, **options: Any) -> None:execute: bool = options["execute"]+ api_mode = options["flags_api_host"] is not None or options["flags_api_project"] is not None+ if api_mode and (options["flags_api_host"] is None or options["flags_api_project"] is None):+ raise CommandError("--flags-api-host and --flags-api-project must be passed together.")+ if api_mode == (options["flag_team_id"] is not None):+ raise CommandError("Pass exactly one of --flag-team-id or --flags-api-host/--flags-api-project.")+ targeting: _FlagTargeting+ if api_mode:+ api_key = os.environ.get(FLAGS_API_KEY_ENV)+ if not api_key:+ raise CommandError(f"--flags-api-host requires a personal API key in ${FLAGS_API_KEY_ENV}.")+ if not options["flags_api_host"].startswith("https://"):+ raise CommandError("--flags-api-host must be https:// — the API key crosses the network.")+ api_targeting = _FlagsApiTargeting(options["flags_api_host"], options["flags_api_project"], api_key)+ try:+ # Runs in dry-run mode too, so a rehearsal validates the host, key, and flags.+ api_targeting.preflight((ALERTS_FLAG_KEY, SCOUTS_FLAG_KEY))+ except requests.RequestException as error:+ raise CommandError(f"flags API preflight failed: {error}")+ targeting = api_targeting+ else:+ targeting = _LocalFlagTargeting(Team.objects.get(id=options["flag_team_id"]))report = _Report()actions = (@@ -154,7 +274,7 @@ class Command(BaseCommand):orgs = orgs[: options["limit_orgs"]]for org_id, org_actions in orgs:- self._migrate_org(org_id, org_actions, execute, options["flag_team_id"], report)+ self._migrate_org(org_id, org_actions, execute, targeting, report)mode = "EXECUTED" if execute else "DRY RUN"self.stdout.write(@@ -168,7 +288,7 @@ class Command(BaseCommand):raise CommandError(f"{len(report.problems)} rows need manual attention; see above.")def _migrate_org(- self, org_id: Any, org_actions: list[VisionAction], execute: bool, flag_team_id: int, report: _Report+ self, org_id: Any, org_actions: list[VisionAction], execute: bool, targeting: _FlagTargeting, report: _Report) -> None:# "This org has migrated rows", not "this run migrated something": an interrupted run that# already moved the rows must still be able to flag the org on a re-run, or its users sit on@@ -219,7 +339,7 @@ class Command(BaseCommand):report.problems.append(f"org {org_id}: not flagged, {org_problems} row(s) need attention")returnif migrated_any:- self._flag_org(org_id, execute, flag_team_id, report)+ self._flag_org(org_id, execute, targeting, report)def _plan(self, action: VisionAction) -> str:"""What this row becomes. Shared by the check and the write so they cannot disagree."""@@ -413,20 +533,16 @@ class Command(BaseCommand):action.save(update_fields=["synthesis_config", "enabled", "updated_at"])return True- def _flag_org(self, org_id: Any, execute: bool, flag_team_id: int, report: _Report) -> None:- from products.feature_flags.backend.facade.api import ( # noqa: PLC0415 — keeps the flags API surface off the command's import path- add_group_to_flag_targeting,- )-- team = Team.objects.get(id=flag_team_id)+ def _flag_org(self, org_id: Any, execute: bool, targeting: _FlagTargeting, report: _Report) -> None:widened = Truefor key in (ALERTS_FLAG_KEY, SCOUTS_FLAG_KEY):if not execute:continue- if not add_group_to_flag_targeting(team=team, key=key, group_key=str(org_id)):- report.problems.append(f"flag {key}: no organization targeting to widen on team {flag_team_id}")+ problem = targeting.add_group(key, str(org_id))+ if problem is not None:+ report.problems.append(f"flag {key}: {problem} on {targeting.where}")widened = False- # Counting an org as flagged when the flag never took would report a rollout that did not+ # Counting the org as flagged when a flag never took would report a rollout that did not# happen, and its users would sit on the legacy surface with their rows already migrated.if widened:report.orgs_flagged += 1diff --git a/products/replay_vision/backend/tests/test_migrate_vision_actions.py b/products/replay_vision/backend/tests/test_migrate_vision_actions.pyindex bb05334a5531..4088021d5ee7 100644--- a/products/replay_vision/backend/tests/test_migrate_vision_actions.py+++ b/products/replay_vision/backend/tests/test_migrate_vision_actions.py@@ -1,16 +1,23 @@+import osfrom typing import Anyfrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.core.management import call_commandfrom django.core.management.base import CommandErrorfrom django.test import SimpleTestCase+import requestsfrom parameterized import parameterizedfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.replay_vision.backend.management.commands.migrate_vision_actions import rrule_to_cron+from products.replay_vision.backend.management.commands.migrate_vision_actions import (+ ALERTS_FLAG_KEY,+ SCOUTS_FLAG_KEY,+ _FlagsApiTargeting,+ rrule_to_cron,+)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.models.vision_action import ActionMode, TriggerType, VisionActionfrom products.replay_vision.backend.models.vision_alert import VisionAlertConfiguration, VisionAlertKind@@ -281,6 +288,97 @@ class TestMigrateVisionActions(APIBaseTest):flag = FeatureFlag.objects.get(team=self.team, key=key)assert flag.filters["groups"][0]["properties"][0]["value"] == []+ def test_flag_mode_arguments_are_validated(self) -> None:+ with self.assertRaises(CommandError):+ call_command("migrate_vision_actions")+ with self.assertRaises(CommandError):+ call_command(+ "migrate_vision_actions",+ "--flag-team-id",+ "2",+ "--flags-api-host",+ "https://example.com",+ "--flags-api-project",+ "2",+ )+ with self.assertRaises(CommandError):+ call_command("migrate_vision_actions", "--flags-api-project", "2")+ with patch.dict(os.environ), self.assertRaises(CommandError):+ os.environ.pop("POSTHOG_FLAGS_API_KEY", None)+ call_command(+ "migrate_vision_actions", "--flags-api-host", "https://example.com", "--flags-api-project", "2"+ )+ with patch.dict(os.environ, {"POSTHOG_FLAGS_API_KEY": "phx_test"}), self.assertRaises(CommandError):+ call_command("migrate_vision_actions", "--flags-api-host", "http://example.com", "--flags-api-project", "2")++ def _api_session(self) -> MagicMock:+ flags = {+ ALERTS_FLAG_KEY: {+ "id": 5,+ "key": ALERTS_FLAG_KEY,+ "filters": {"groups": [{"properties": [{"key": "$group_key", "value": []}]}]},+ },+ SCOUTS_FLAG_KEY: {+ "id": 6,+ "key": SCOUTS_FLAG_KEY,+ "filters": {"groups": [{"properties": [{"key": "$group_key", "value": []}]}]},+ },+ }++ def get(url: str, params: dict | None = None, timeout: int | None = None) -> MagicMock:+ assert "/api/projects/2/feature_flags" in url+ response = MagicMock()+ if params is not None:+ response.json.return_value = {"results": [flags[params["key"]]]}+ else:+ flag_id = int(url.rstrip("/").rsplit("/", 1)[-1])+ response.json.return_value = next(f for f in flags.values() if f["id"] == flag_id)+ return response++ session = MagicMock()+ session.get.side_effect = get+ return session++ def test_flags_api_mode_widens_remote_flags(self) -> None:+ action = self._make_action(alert_config={"frequency": "every_match"}, selection={})+ session = self._api_session()+ with (+ patch(f"{_CMD}.requests.Session", return_value=session),+ patch(f"{_CMD}.Command._create_destinations"),+ patch.dict(os.environ, {"POSTHOG_FLAGS_API_KEY": "phx_test"}),+ ):+ call_command(+ "migrate_vision_actions",+ "--execute",+ "--flags-api-host",+ "https://example.com",+ "--flags-api-project",+ "2",+ )+ session.headers.__setitem__.assert_any_call("Authorization", "Bearer phx_test")+ assert session.patch.call_count == 2+ patched_urls = {call.args[0] for call in session.patch.call_args_list}+ assert patched_urls == {+ "https://example.com/api/projects/2/feature_flags/5/",+ "https://example.com/api/projects/2/feature_flags/6/",+ }+ for call in session.patch.call_args_list:+ values = call.kwargs["json"]["filters"]["groups"][0]["properties"][0]["value"]+ assert str(action.team.organization_id) in values++ def test_flags_api_dry_run_preflights_but_never_patches(self) -> None:+ self._make_action(alert_config={"frequency": "every_match"}, selection={})+ session = self._api_session()+ with (+ patch(f"{_CMD}.requests.Session", return_value=session),+ patch.dict(os.environ, {"POSTHOG_FLAGS_API_KEY": "phx_test"}),+ ):+ call_command(+ "migrate_vision_actions", "--flags-api-host", "https://example.com", "--flags-api-project", "2"+ )+ assert session.get.call_count == 2+ session.patch.assert_not_called()+class TestComposeDigestScoutBody(SimpleTestCase):def test_legacy_narrowing_shapes(self) -> None:@@ -294,3 +392,47 @@ class TestComposeDigestScoutBody(SimpleTestCase):malformed = compose_digest_scout_body("sid", selection={"window_days": "7"}, prompt_guide=None)assert "fall back to the last 24 hours" in malformed+++class TestFlagsApiTargeting(SimpleTestCase):+ def _client_with(self, flag: dict) -> tuple[_FlagsApiTargeting, MagicMock]:+ session = MagicMock()+ session.get.return_value.json.return_value = {"results": [flag], **flag}+ with patch(f"{_CMD}.requests.Session", return_value=session):+ client = _FlagsApiTargeting("https://example.com/", 2, "phx_test")+ client.preflight((flag["key"],))+ return client, session++ def test_preflight_rejects_missing_flag(self) -> None:+ session = MagicMock()+ session.get.return_value.json.return_value = {"results": []}+ with patch(f"{_CMD}.requests.Session", return_value=session):+ client = _FlagsApiTargeting("https://example.com", 2, "phx_test")+ with self.assertRaises(CommandError):+ client.preflight(("missing",))++ def test_add_group_is_idempotent_and_fails_closed(self) -> None:+ flag = {+ "id": 5,+ "key": "k",+ "filters": {"groups": [{"properties": [{"key": "$group_key", "value": ["org-a"]}]}]},+ }+ client, session = self._client_with(flag)+ assert client.add_group("k", "org-a") is None+ session.patch.assert_not_called()+ assert client.add_group("k", "org-b") is None+ session.patch.assert_called_once()++ unwidenable = {"id": 6, "key": "k", "filters": {"groups": []}}+ client2, _ = self._client_with(unwidenable)+ assert client2.add_group("k", "org-a") == "no organization targeting to widen"++ def test_request_failure_fails_closed(self) -> None:+ flag = {"id": 5, "key": "k", "filters": {"groups": [{"properties": [{"key": "$group_key", "value": []}]}]}}+ client, session = self._client_with(flag)+ session.patch.side_effect = requests.ConnectionError("boom")+ problem = client.add_group("k", "org-a")+ assert problem is not None and "API request failed" in problem+ session.patch.side_effect = None+ session.patch.return_value = MagicMock()+ assert client.add_group("k", "org-b") is None