Skip to content

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

fix(flags): keep the replay linked flag key in sync on rename (#77598)

Phil Haack0595967e3ad0
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 5faa69e16670..aa12da50ae4e 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -35,6 +35,7 @@ model_activity:products.data_tools.backend.activity_logging.handle_expression_ac
model_activity:products.experiments.backend.activity_logging.handle_experiment_change
model_activity:products.exports.backend.models.subscription.log_subscription_activity
model_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_change
+model_activity:products.feature_flags.backend.session_recording_links.relink_teams_on_key_change
model_activity:products.legal_documents.backend.signals.handle_legal_document_change
model_activity:products.logs.backend.activity_logging.handle_logs_alert_activity
model_activity:products.logs.backend.activity_logging.handle_logs_retention_rule_activity
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 5ff814fd89a1..b54053b07824 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -105,6 +105,7 @@ from products.feature_flags.backend.models.feature_flag import (
FeatureFlagDashboards,
set_feature_flags_for_team_in_cache,
)
+from products.feature_flags.backend.session_recording_links import teams_linking_flag
from products.feature_flags.backend.types import PropertyFilterType
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius
from products.feature_flags.backend.version_history import (
@@ -1047,10 +1048,7 @@ class FeatureFlagSerializer(
if not hasattr(feature_flag, "team") or feature_flag.team is None:
return False
# Fallback to database query if annotation is not available
- return Team.objects.filter(
- project_id=feature_flag.team.project_id,
- session_recording_linked_flag__contains={"id": feature_flag.id},
- ).exists()
+ return teams_linking_flag(feature_flag).exists()
def validate(self, attrs):
"""Validate feature flag creation/update including evaluation tag requirements."""
@@ -1901,10 +1899,7 @@ class FeatureFlagSerializer(
raise_if_flag_has_dependents(instance, action="delete")
# Check if flag is used in session replay settings
- if Team.objects.filter(
- project_id=instance.team.project_id,
- session_recording_linked_flag__contains={"id": instance.id},
- ).exists():
+ if teams_linking_flag(instance).exists():
raise exceptions.ValidationError(
"This feature flag is used in session replay settings. Please remove it from replay settings before deleting."
)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 938cabc64db9..4aed8ddc3ad0 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -26,6 +26,7 @@ from parameterized import parameterized
from prometheus_client import REGISTRY
from rest_framework import status
from rest_framework.relations import ManyRelatedField
+from rest_framework.response import Response
from posthog import redis
from posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flag
@@ -14116,3 +14117,93 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
self.assertIn("error", response.json())
+
+
+class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
+ def _link_flag(self, team: Team, linked_flag: dict[str, Any]) -> None:
+ team.session_recording_linked_flag = linked_flag
+ team.save()
+
+ def _rename(self, flag: FeatureFlag, new_key: str) -> Response:
+ # The relink runs on transaction commit, which a TestCase never reaches on its own.
+ with self.captureOnCommitCallbacks(execute=True):
+ return self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"key": new_key})
+
+ def test_rename_outside_the_api_still_rewrites_the_stored_key(self) -> None:
+ # A rename from the Django admin or a shell never reaches FeatureFlagSerializer, so the
+ # relink hangs off the model signal instead.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ self._link_flag(self.team, {"id": flag.id, "key": "replay-gate"})
+
+ flag.key = "replay-gate-v2"
+ with self.captureOnCommitCallbacks(execute=True):
+ flag.save()
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+
+ @parameterized.expand([("same_project", True, "replay-gate-v2"), ("other_project", False, "replay-gate")])
+ def test_rename_rewrites_stored_key_only_within_the_project(
+ self, _name: str, same_project: bool, expected_key: str
+ ) -> None:
+ # A sibling team can gate recording on a flag owned by another team in its project, so the
+ # lookup is project-scoped; a team in a different project holding the same id must not move.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ linking_team = Team.objects.create(
+ organization=self.organization, **({"project": self.team.project} if same_project else {})
+ )
+ self._link_flag(linking_team, {"id": flag.id, "key": "replay-gate"})
+
+ response = self._rename(flag, "replay-gate-v2")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ linking_team.refresh_from_db()
+ assert linking_team.session_recording_linked_flag == {"id": flag.id, "key": expected_key}
+
+ def test_rename_rewrites_stored_key_for_the_flags_own_team_and_keeps_the_variant(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ self._link_flag(self.team, {"id": flag.id, "key": "replay-gate", "variant": "control"})
+
+ response = self._rename(flag, "replay-gate-v2")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {
+ "id": flag.id,
+ "key": "replay-gate-v2",
+ "variant": "control",
+ }
+
+ @patch("posthog.models.remote_config._update_team_remote_config")
+ def test_rename_refreshes_remote_config_for_a_relinked_sibling_team(self, mock_refresh: MagicMock) -> None:
+ # The flag's own team is refreshed by the FeatureFlag post_save receiver, but a sibling
+ # team that gates recording on the same flag only gets a fresh SDK payload if we save it.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ self._link_flag(sibling_team, {"id": flag.id, "key": "replay-gate"})
+
+ response = self._rename(flag, "replay-gate-v2")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert sibling_team.id in {call.args[0] for call in mock_refresh.call_args_list}
+
+ @parameterized.expand([("stored_key_already_matches",), ("links_a_different_flag",)])
+ @patch("posthog.models.remote_config._update_team_remote_config")
+ def test_rename_does_not_save_teams_it_has_nothing_to_change(self, scope: str, mock_refresh: MagicMock) -> None:
+ # Every team save enqueues a RemoteConfig sync, so a rewrite that changes nothing costs a
+ # write and a Celery task for no benefit.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ if scope == "stored_key_already_matches":
+ self._link_flag(sibling_team, {"id": flag.id, "key": "replay-gate-v2"})
+ else:
+ other_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-gate")
+ self._link_flag(sibling_team, {"id": other_flag.id, "key": "other-gate"})
+ linked_flag_before = sibling_team.session_recording_linked_flag
+
+ response = self._rename(flag, "replay-gate-v2")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ sibling_team.refresh_from_db()
+ assert sibling_team.session_recording_linked_flag == linked_flag_before
+ assert sibling_team.id not in {call.args[0] for call in mock_refresh.call_args_list}
diff --git a/products/feature_flags/backend/apps.py b/products/feature_flags/backend/apps.py
index 25b8b719df70..d645e98c38a4 100644
--- a/products/feature_flags/backend/apps.py
+++ b/products/feature_flags/backend/apps.py
@@ -20,9 +20,12 @@ class FeatureFlagsConfig(AppConfig):
# because the flag viewset pulls scipy via the dashboard -> error-tracking query runners.
# flag_version_sync wires here for the same reason: cohort edits happen in
# non-web processes too, and its version bump must land wherever cohorts save.
+ # session_recording_links likewise: a rename from the admin or a shell must keep each
+ # linking team's replay gate pointing at the new key, or that team stops recording.
from products.feature_flags.backend import ( # noqa: F401, PLC0415
activity_logging, # noqa: F401, PLC0415
flag_version_sync,
flags_cache,
local_evaluation,
+ session_recording_links,
)
diff --git a/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py b/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py
new file mode 100644
index 000000000000..aaf7efe5b7b3
--- /dev/null
+++ b/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py
@@ -0,0 +1,186 @@
+"""Repair `Team.session_recording_linked_flag` rows whose stored key no longer matches the flag.
+
+Renaming a feature flag used to leave the stored key behind, and the SDKs read the key rather
+than the id, so those teams stopped recording sessions entirely. `relink_teams_on_key_change` in
+`session_recording_links` now keeps the key in step for every rename that goes through
+`FeatureFlag.save()`; this command fixes the rows that were already stale when it was wired up,
+plus any left by a writer that bypasses `save()`, such as the `bulk_update` in `bulk_delete`.
+
+Only rows whose stored id resolves to a live flag in the team's own project are rewritten. Rows
+pointing at a soft-deleted flag or at a flag in another project are counted and reported but
+left alone, because neither has a safe new key to adopt: a human has to decide whether the team
+still wants a recording gate at all.
+"""
+
+import json
+from collections import Counter
+from collections.abc import Iterator
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db.models import QuerySet
+
+from posthog.models import Team
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.session_recording_links import update_linked_flag_key
+
+
+class Outcome(StrEnum):
+ REPAIRED = "repaired"
+ ALREADY_CORRECT = "already_correct"
+ FLAG_SOFT_DELETED = "flag_soft_deleted"
+ FLAG_IN_OTHER_PROJECT = "flag_in_other_project"
+ FLAG_MISSING = "flag_missing"
+ MALFORMED = "malformed"
+
+
+@dataclass(frozen=True, kw_only=True)
+class _FlagRow:
+ key: str
+ deleted: bool
+ project_id: int
+
+
+def _iter_team_chunks(queryset: QuerySet[Team], chunk_size: int) -> Iterator[list[Team]]:
+ # Keyset pagination instead of .iterator(): prod runs behind PgBouncer with server-side
+ # cursors disabled, so .iterator() buffers the whole result set client-side on execute.
+ base = queryset.order_by("id")
+ last_id = 0
+ while True:
+ chunk = list(base.filter(id__gt=last_id)[:chunk_size])
+ if not chunk:
+ return
+ yield chunk
+ last_id = chunk[-1].id
+
+
+def _linked_flag_id(linked_flag: Any) -> int | None:
+ if not isinstance(linked_flag, dict):
+ return None
+ stored_id = linked_flag.get("id")
+ # The column is schemaless, so anything an API client or the admin's JSON widget sent can be
+ # here. Only an int is acted on; every other shape is reported as malformed for a human to
+ # look at rather than coerced. `bool` is excluded explicitly because it subclasses `int`, so
+ # `{"id": true}` would otherwise repair against flag 1.
+ if isinstance(stored_id, bool) or not isinstance(stored_id, int):
+ return None
+ return stored_id
+
+
+class Command(BaseCommand):
+ help = "Rewrite stale flag keys in teams' session replay linked flag settings"
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
+ parser.add_argument("--team-id", type=int, nargs="+", help="Only scan these teams (defaults to every team)")
+ parser.add_argument("--chunk-size", type=int, default=500, help="Teams to load per query (default: 500)")
+ parser.add_argument("--json", action="store_true", help="Emit the report as JSON instead of prose")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ # Dry-run by default, matching the other flags repair commands: a bare invocation rewrites
+ # every team's replay config and enqueues a RemoteConfig rebuild per row, so writing has
+ # to be asked for.
+ dry_run: bool = not options["live_run"]
+ as_json: bool = options["json"]
+ chunk_size: int = options["chunk_size"]
+ if chunk_size < 1:
+ # A zero chunk slices to an empty list, so the scan would report a clean run having
+ # looked at nothing.
+ raise CommandError("--chunk-size must be at least 1")
+
+ queryset = Team.objects.exclude(session_recording_linked_flag__isnull=True)
+ if options["team_id"]:
+ queryset = queryset.filter(id__in=options["team_id"])
+
+ scanned = 0
+ # Every row except already_correct, which needs no follow-up and would dwarf the rest.
+ details: list[dict[str, Any]] = []
+
+ for teams in _iter_team_chunks(queryset, chunk_size):
+ flags_by_id = self._load_flags(teams)
+ for team in teams:
+ scanned += 1
+ outcome, detail = self._repair_team(team, flags_by_id, dry_run=dry_run)
+ if outcome != Outcome.ALREADY_CORRECT:
+ details.append({"outcome": outcome, **detail})
+
+ outcomes: Counter[Outcome] = Counter(row["outcome"] for row in details)
+ if already_correct := scanned - len(details):
+ outcomes[Outcome.ALREADY_CORRECT] = already_correct
+ report = {
+ "dry_run": dry_run,
+ "scanned": scanned,
+ "outcomes": dict(outcomes),
+ "repairs": [row for row in details if row["outcome"] == Outcome.REPAIRED],
+ "unrepairable": [row for row in details if row["outcome"] != Outcome.REPAIRED],
+ }
+ self._report(report, as_json=as_json)
+
+ def _load_flags(self, teams: list[Team]) -> dict[int, _FlagRow]:
+ flag_ids = {
+ flag_id for team in teams if (flag_id := _linked_flag_id(team.session_recording_linked_flag)) is not None
+ }
+ if not flag_ids:
+ return {}
+ rows = FeatureFlag.objects_including_soft_deleted.filter(id__in=flag_ids).values_list(
+ "id", "key", "deleted", "team__project_id"
+ )
+ return {
+ flag_id: _FlagRow(key=key, deleted=deleted, project_id=project_id)
+ for flag_id, key, deleted, project_id in rows
+ }
+
+ def _repair_team(
+ self, team: Team, flags_by_id: dict[int, _FlagRow], *, dry_run: bool
+ ) -> tuple[Outcome, dict[str, Any]]:
+ linked_flag = team.session_recording_linked_flag
+ detail: dict[str, Any] = {"team_id": team.id, "project_id": team.project_id, "linked_flag": linked_flag}
+
+ stored_id = _linked_flag_id(linked_flag)
+ if stored_id is None:
+ return Outcome.MALFORMED, detail
+
+ detail["flag_id"] = stored_id
+ flag = flags_by_id.get(stored_id)
+ if flag is None:
+ return Outcome.FLAG_MISSING, detail
+ if flag.project_id != team.project_id:
+ return Outcome.FLAG_IN_OTHER_PROJECT, detail
+ if flag.deleted:
+ return Outcome.FLAG_SOFT_DELETED, detail
+ if linked_flag.get("key") == flag.key:
+ return Outcome.ALREADY_CORRECT, detail
+
+ detail["old_key"] = linked_flag.get("key")
+ detail["new_key"] = flag.key
+ if not dry_run:
+ update_linked_flag_key(team, stored_id, flag.key)
+ return Outcome.REPAIRED, detail
+
+ def _report(self, report: dict[str, Any], *, as_json: bool) -> None:
+ if as_json:
+ self.stdout.write(json.dumps(report, indent=2, default=str))
+ return
+
+ verb = "Would repair" if report["dry_run"] else "Repaired"
+ self.stdout.write(f"Scanned {report['scanned']} team(s) with a session replay linked flag.")
+ self.stdout.write(f"{verb} {len(report['repairs'])} team(s):")
+ for repair in report["repairs"]:
+ self.stdout.write(
+ f" team {repair['team_id']} (project {repair['project_id']}): "
+ f"flag {repair['flag_id']} {repair['old_key']!r} -> {repair['new_key']!r}"
+ )
+
+ for outcome, count in sorted(report["outcomes"].items()):
+ if outcome != Outcome.REPAIRED and count:
+ self.stdout.write(f"{outcome}: {count}")
+
+ if report["unrepairable"]:
+ self.stdout.write("Not repaired:")
+ for row in report["unrepairable"]:
+ self.stdout.write(
+ f" team {row['team_id']} (project {row['project_id']}) [{row['outcome']}]: {row['linked_flag']!r}"
+ )
diff --git a/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py b/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py
new file mode 100644
index 000000000000..c354eaef58fd
--- /dev/null
+++ b/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py
@@ -0,0 +1,129 @@
+import json
+from io import StringIO
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestRepairReplayLinkedFlagKeys(BaseTest):
+ def _link_flag(self, team: Team, linked_flag: dict[str, Any] | None) -> None:
+ team.session_recording_linked_flag = linked_flag
+ team.save()
+
+ def _run(self, *args: str, teams: list[Team]) -> dict[str, Any]:
+ # Scope to this test's teams: the local test DB is reused across suites and can carry
+ # leftover rows from other tests.
+ out = StringIO()
+ call_command(
+ "repair_replay_linked_flag_keys",
+ "--json",
+ "--team-id",
+ *[str(team.id) for team in teams],
+ *args,
+ stdout=out,
+ )
+ return json.loads(out.getvalue())
+
+ def test_repairs_a_stale_key_and_is_idempotent(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")
+ self._link_flag(self.team, {"id": flag.id, "key": "replay-gate", "variant": "control"})
+
+ report = self._run("--live-run", teams=[self.team])
+
+ assert report["outcomes"] == {"repaired": 1}
+ assert report["repairs"] == [
+ {
+ "outcome": "repaired",
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "linked_flag": {"id": flag.id, "key": "replay-gate", "variant": "control"},
+ "flag_id": flag.id,
+ "old_key": "replay-gate",
+ "new_key": "replay-gate-v2",
+ }
+ ]
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {
+ "id": flag.id,
+ "key": "replay-gate-v2",
+ "variant": "control",
+ }
+
+ assert self._run("--live-run", teams=[self.team])["outcomes"] == {"already_correct": 1}
+
+ def test_reports_the_repair_without_writing_unless_asked(self) -> None:
+ # Writing has to be opted into: a bare run rewrites every team's replay config and
+ # enqueues a RemoteConfig rebuild per row.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")
+ self._link_flag(self.team, {"id": flag.id, "key": "replay-gate"})
+
+ report = self._run(teams=[self.team])
+
+ assert report["dry_run"] is True
+ assert report["outcomes"] == {"repaired": 1}
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate"}
+
+ @parameterized.expand(
+ [
+ ("flag_soft_deleted", "flag_soft_deleted"),
+ ("flag_in_other_project", "flag_in_other_project"),
+ ("flag_missing", "flag_missing"),
+ ("missing_id", "malformed"),
+ ("bool_id", "malformed"),
+ ("non_numeric_id", "malformed"),
+ ]
+ )
+ def test_leaves_links_it_cannot_safely_repair_alone(self, case: str, outcome: str) -> None:
+ # Clearing an unrepairable link would remove the recording gate, taking a team from
+ # recording a filtered subset to recording every session. `bool` subclasses `int`, so
+ # without the explicit guard `{"id": true}` would repair the team against flag 1.
+ linked_flag: dict[str, Any]
+ if case == "flag_missing":
+ linked_flag = {"id": 987654321, "key": "replay-gate"}
+ elif case == "missing_id":
+ linked_flag = {"key": "replay-gate"}
+ elif case == "bool_id":
+ linked_flag = {"id": True, "key": "replay-gate"}
+ elif case == "non_numeric_id":
+ linked_flag = {"id": "abc", "key": "replay-gate"}
+ else:
+ flag_team = (
+ self.team if case == "flag_soft_deleted" else Team.objects.create(organization=self.organization)
+ )
+ flag = FeatureFlag.objects.create(
+ team=flag_team,
+ created_by=self.user,
+ key="replay-gate-v2",
+ deleted=case == "flag_soft_deleted",
+ )
+ linked_flag = {"id": flag.id, "key": "replay-gate"}
+ self._link_flag(self.team, linked_flag)
+
+ # `--live-run` so the row surviving proves the command declined to rewrite it, rather than
+ # just proving dry-run writes nothing.
+ report = self._run("--live-run", teams=[self.team])
+
+ assert report["outcomes"] == {outcome: 1}
+ assert report["unrepairable"][0]["outcome"] == outcome
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == linked_flag
+
+ def test_repairs_a_sibling_team_linking_another_teams_flag(self) -> None:
+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")
+ self._link_flag(sibling_team, {"id": flag.id, "key": "replay-gate"})
+
+ report = self._run("--live-run", teams=[sibling_team])
+
+ assert report["outcomes"] == {"repaired": 1}
+ sibling_team.refresh_from_db()
+ assert sibling_team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.py
new file mode 100644
index 000000000000..7a9a17262fe8
--- /dev/null
+++ b/products/feature_flags/backend/session_recording_links.py
@@ -0,0 +1,115 @@
+"""Keeps `Team.session_recording_linked_flag` in step with the flag key it points at.
+
+The stored dict carries both the flag `id` and its `key`, but the SDK payload that
+`RemoteConfig._build_session_recording_config` builds is derived from the key alone. Both the
+browser and React Native SDKs treat a linked flag they can't resolve as "do not record", so a
+stale key silently turns replay off for the team rather than surfacing an error anywhere.
+"""
+
+from typing import Any
+
+from django.db import transaction
+from django.db.models import QuerySet
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+from posthog.models.signals import model_activity_signal, mutable_receiver
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+logger = structlog.get_logger(__name__)
+
+
+def teams_linking_flag(feature_flag: FeatureFlag) -> QuerySet[Team]:
+ """Every team gating session recording on this flag."""
+ # Scoped by project rather than by team: any team in the project can gate recording on a flag
+ # owned by a sibling team.
+ return Team.objects.filter(
+ project_id=feature_flag.team.project_id,
+ session_recording_linked_flag__contains={"id": feature_flag.id},
+ )
+
+
+def update_linked_flag_key(team: Team, expected_flag_id: int, new_key: str) -> None:
+ """Rewrite the stored key on a team's replay link, leaving teams that no longer need it alone."""
+ # Locks the row and re-reads inside the lock, rather than trusting `team`'s in-memory copy:
+ # callers load teams in a batch before looping over them, so another edit to this team's
+ # linked flag could land before its turn comes up. The lock closes the window between the
+ # read and the save below; taking it here is safe because it's the only row this function
+ # locks and the transaction commits before returning, so it can't deadlock against another
+ # call doing the same for a different team (see `relink_teams_on_key_change` for the case
+ # that does require avoiding a lock).
+ with transaction.atomic():
+ linked_flag = (
+ Team.objects.select_for_update()
+ .filter(pk=team.pk)
+ .values_list("session_recording_linked_flag", flat=True)
+ .first()
+ )
+ if not isinstance(linked_flag, dict) or linked_flag.get("id") != expected_flag_id:
+ # Someone pointed the team at a different flag since the caller looked it up; that
+ # edit isn't ours to touch, and this rename has nothing left to fix here.
+ return
+ if linked_flag.get("key") == new_key:
+ # A no-op save would still spend a write, a Celery task, and a RemoteConfig rebuild.
+ return
+
+ team.session_recording_linked_flag = {**linked_flag, "key": new_key}
+ # Saving the instance rather than issuing a queryset `update()` is what fires the `post_save`
+ # receiver that refreshes the team's RemoteConfig; a bulk update would leave the cached SDK
+ # payload holding the old key.
+ team.save(update_fields=["session_recording_linked_flag"])
+
+
+def relink_teams(feature_flag: FeatureFlag) -> None:
+ """Point every team gating replay on this flag at its current key."""
+ # Reads the key fresh rather than trusting feature_flag.key from the signal: two renames of
+ # the same flag committed close together fire their on_commit callbacks with no ordering
+ # guarantee between them, and update_linked_flag_key's guard only checks the flag id and
+ # whether the key differs - not which rename is newer. A stale callback that reads its key
+ # from memory can overwrite a team a later rename's callback already brought up to date. This
+ # re-read makes every callback converge on whatever key is actually stored, regardless of
+ # which rename triggered it or the order the callbacks run in.
+ current_key = (
+ FeatureFlag.objects_including_soft_deleted.filter(pk=feature_flag.pk).values_list("key", flat=True).first()
+ )
+ if current_key is None:
+ # The row is gone entirely, not just soft-deleted; repair_replay_linked_flag_keys reports
+ # these teams as flag_missing on its next run.
+ return
+
+ for team in teams_linking_flag(feature_flag):
+ try:
+ update_linked_flag_key(team, feature_flag.id, current_key)
+ except Exception:
+ # This runs after the rename has committed, so raising would fail a request that
+ # already succeeded, and the retry would find the key unchanged and skip the relink
+ # entirely. Report instead and leave the row for `repair_replay_linked_flag_keys`.
+ # Per team, so one unwritable row doesn't strand the others.
+ logger.exception("replay_relink_failed", flag_id=feature_flag.pk, team_id=team.pk)
+ capture_exception()
+
+
+@mutable_receiver(model_activity_signal, sender=FeatureFlag)
+def relink_teams_on_key_change(
+ sender: Any, before_update: FeatureFlag | None, after_update: FeatureFlag | None, **kwargs: Any
+) -> None:
+ # Wired to the model signal rather than to FeatureFlagSerializer so renames from the Django
+ # admin, a shell, or a Celery task keep the link intact too. `before_update` is None on create;
+ # `after_update` is None on delete.
+ if before_update is None or after_update is None or before_update.key == after_update.key:
+ return
+
+ # Unlike `repair_replay_linked_flag_keys`, this has no `after_update.deleted` guard, including
+ # for the tombstone rename `_free_key_held_by_soft_deleted_flags` does when freeing a
+ # soft-deleted flag's key for reuse. That's intentional: relinking still rewrites a team's
+ # stored key to the flag's new, id-suffixed tombstone, which no live flag's key can equal.
+ # Skipping the rewrite would leave the team pointing at the now-freed original key, which a
+ # new flag could reuse next, silently gating replay on a flag the team never linked.
+
+ # Deferred to commit because the serializer renames inside a transaction that holds
+ # `select_for_update` on the flag row, and taking team locks in that window invites deadlocks.
+ # Outside a transaction (admin, shell) `on_commit` runs the callback immediately.
+ transaction.on_commit(lambda: relink_teams(after_update))
diff --git a/products/feature_flags/backend/test/test_session_recording_links.py b/products/feature_flags/backend/test/test_session_recording_links.py
new file mode 100644
index 000000000000..47633bf62c9c
--- /dev/null
+++ b/products/feature_flags/backend/test/test_session_recording_links.py
@@ -0,0 +1,60 @@
+from posthog.test.base import BaseTest
+
+from posthog.models import Team
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.session_recording_links import relink_teams, update_linked_flag_key
+
+
+class TestUpdateLinkedFlagKey(BaseTest):
+ def test_preserves_a_concurrent_edit_to_the_linked_flag(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": "replay-gate", "variant": "control"}
+ self.team.save()
+ # Stands in for a team a caller loaded earlier in a batch, before the edit below lands.
+ stale_team = Team.objects.get(pk=self.team.pk)
+
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": "replay-gate", "variant": "test"}
+ self.team.save()
+
+ update_linked_flag_key(stale_team, flag.id, "replay-gate-v2")
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {
+ "id": flag.id,
+ "key": "replay-gate-v2",
+ "variant": "test",
+ }
+
+ def test_skips_the_write_when_the_team_now_links_a_different_flag(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ other_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-gate")
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": "replay-gate"}
+ self.team.save()
+ stale_team = Team.objects.get(pk=self.team.pk)
+
+ # Concurrent edit: an admin repoints the team at a different flag entirely.
+ self.team.session_recording_linked_flag = {"id": other_flag.id, "key": "other-gate"}
+ self.team.save()
+
+ update_linked_flag_key(stale_team, flag.id, "replay-gate-v2")
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": other_flag.id, "key": "other-gate"}
+
+
+class TestRelinkTeams(BaseTest):
+ def test_converges_on_the_current_key_despite_a_stale_signal_snapshot(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-c")
+ # Stands in for an on_commit callback's captured snapshot from an earlier rename that
+ # committed first but is only now getting around to relinking teams: the DB has already
+ # moved on to a newer key by the time this callback runs.
+ stale_flag = FeatureFlag(pk=flag.pk, team=flag.team, key="gate-b")
+ # A faster, later rename's callback already brought this team up to date.
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": "gate-c"}
+ self.team.save()
+
+ relink_teams(stale_flag)
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}