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): stop renames and deletes breaking replay trigger groups (#81575)

Phil Haack3cd5c72248f8
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 0146d2220d0e..0866d8c60b65 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -304,10 +304,11 @@ def clean_varying_query_parts(query, replace_all_numbers):
query,
)
- # session_recording_linked_flag embeds feature flag IDs in JSON, normalize them
+ # Both replay gate columns embed feature flag IDs in their containment probes, the linked
+ # flag directly and a trigger group nested inside `conditions.flag`. Normalize every one.
query = re.sub(
- r"""session_recording_linked_flag" @> '{"id": \d+}'::jsonb""",
- r"""session_recording_linked_flag" @> '{"id": 99999}'::jsonb""",
+ r"""session_recording_(?:linked_flag|trigger_groups)" @> '[^']*'""",
+ lambda probe: re.sub(r'"id": \d+', '"id": 99999', probe.group(0)),
query,
)
diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.py
index 5fd54bf365ea..8a5c08330d68 100644
--- a/products/access_control/backend/tests/test_access_control.py
+++ b/products/access_control/backend/tests/test_access_control.py
@@ -1329,15 +1329,17 @@ class TestAccessControlQueryCounts(BaseAccessControlTest):
baseline = 16 # This is a lot! There is currently an n+1 issue with the legacy access control system
- # +8: org, roles, preloaded permissions acs, preloaded acs for the list, survey internal flag IDs
- with self.assertNumQueries(baseline + 7):
+ # +8: org, roles, preloaded permissions acs, preloaded acs for the list, survey internal flag
+ # IDs, the project's replay gates
+ with self.assertNumQueries(baseline + 8):
self.client.get("/api/projects/@current/feature_flags/")
for i in range(10):
FeatureFlag.objects.create(team=self.team, created_by=self.other_user, key=f"flag-{10 + i}")
- # +8: org, roles, preloaded permissions acs, preloaded acs for the list, survey internal flag IDs
- with self.assertNumQueries(baseline + 7):
+ # +8: org, roles, preloaded permissions acs, preloaded acs for the list, survey internal flag
+ # IDs, the project's replay gates
+ with self.assertNumQueries(baseline + 8):
self.client.get("/api/projects/@current/feature_flags/")
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index af2005e85512..d84769f3b2b0 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -3313,8 +3313,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
).json()
# TODO: Make sure permission bool doesn't cause n + 1
- # +1 query for survey internal flag IDs lookup
- with self.assertNumQueries(22):
+ # +1 query for survey internal flag IDs lookup, +1 for the project's replay gates
+ with self.assertNumQueries(23):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
result = response.json()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index fded04d46382..8f20a2170620 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -15,7 +15,6 @@ from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg
from django.db import IntegrityError, transaction
from django.db.models import Count, Prefetch, Q, QuerySet, deletion
-from django.db.models.functions import JSONObject
import grpc
import requests
@@ -124,10 +123,10 @@ from products.feature_flags.backend.models.evaluation_context import normalize_c
from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards
from products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tags
from products.feature_flags.backend.session_recording_links import (
- REPLAY_LINKED_FLAG_DELETE_ERROR,
- replay_linked_flag_ids,
- teams_linking_flag,
- teams_linking_flag_in_project,
+ REPLAY_GATE_DELETE_ERROR,
+ ReplayFlagGates,
+ replay_gated_flags,
+ teams_gating_replay_on_flag,
)
from products.feature_flags.backend.types import PropertyFilterType
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius
@@ -1342,7 +1341,7 @@ class FeatureFlagSerializer(
# ignoring type because mypy doesn't know about the surveys_linked_flag `related_name` relationship
def get_is_used_in_replay_settings(self, feature_flag: FeatureFlag) -> bool:
- """Check if this feature flag is used in any team's session recording linked flag setting."""
+ """Check if any team gates session recording on this flag, by linked flag or trigger group."""
# Use annotated value if available (set by queryset annotation)
if hasattr(feature_flag, "is_used_in_replay_settings_annotation"):
return bool(feature_flag.is_used_in_replay_settings_annotation)
@@ -1350,7 +1349,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 teams_linking_flag(feature_flag).exists()
+ return teams_gating_replay_on_flag(feature_flag, key=feature_flag.key).exists()
def validate(self, attrs):
"""Validate feature flag creation/update including evaluation tag requirements."""
@@ -2057,6 +2056,10 @@ class FeatureFlagSerializer(
# the tombstone instead — same scheme as the soft-delete update path.
# Only safe when no active dependent references it; re-check that
# invariant and error clearly if violated.
+ #
+ # `teams_gating_replay_on_flag` reads `flag.team.project_id` below. That lazy load
+ # inherits `TeamManager`'s deferrals. `select_related("team")` builds its own projection
+ # and pulls the deprecated taxonomy columns once per row.
soft_deleted_qs = FeatureFlag.objects_including_soft_deleted.filter(
key=key,
team__project_id=self.context["project_id"],
@@ -2066,12 +2069,12 @@ class FeatureFlagSerializer(
soft_deleted_qs = soft_deleted_qs.exclude(pk=exclude_pk)
for flag in soft_deleted_qs:
- if teams_linking_flag_in_project(self.context["project_id"], flag.id).exists():
+ if teams_gating_replay_on_flag(flag, key=flag.key).exists():
# Hard-deleting fires no save, so nothing relinks the teams gating replay on
# this tombstone and they keep the key the new flag is about to claim. Rename
# instead and `relink_teams_on_key_change` moves them onto the tombstone. The
# blocker check still runs first: renaming a flag an active dependent references
- # would silently break that dependent, whether or not a team links it for replay.
+ # would silently break that dependent, whether or not a team gates replay on it.
self._raise_if_key_reuse_blocked(flag)
flag.key = flag.tombstoned_key()
flag.save(update_fields=["key"])
@@ -2197,9 +2200,11 @@ class FeatureFlagSerializer(
# Check for other flags that depend on this flag
raise_if_flag_has_dependents(instance, action="delete")
- # Check if flag is used in session replay settings
- if teams_linking_flag(instance).exists():
- raise exceptions.ValidationError(REPLAY_LINKED_FLAG_DELETE_ERROR)
+ # Asks the database rather than reading `is_used_in_replay_settings`. That field is
+ # annotated on the list action alone, so a delete never sees it today, and querying
+ # here keeps the guard reading live state if the annotation ever widens.
+ if teams_gating_replay_on_flag(instance, key=instance.key).exists():
+ raise exceptions.ValidationError(REPLAY_GATE_DELETE_ERROR)
# If the flag is linked to any experiment, rename the key to free it up.
# Append ID to the key when soft-deleting to prevent key conflicts.
@@ -3364,9 +3369,16 @@ class FeatureFlagViewSet(
"""Apply filters from request query params to queryset."""
return self._apply_filters(request.GET.dict(), queryset)
- def safely_get_queryset(self, queryset) -> QuerySet:
- from django.db.models import Exists, OuterRef
+ @functools.cached_property
+ def _replay_gates(self) -> ReplayFlagGates:
+ """The project's replay gates, scanned once per request.
+
+ `bulk_delete` tests every flag in the batch against these, and `safely_get_queryset` runs
+ more than once per request, so both share one scan.
+ """
+ return replay_gated_flags(self.project_id)
+ def safely_get_queryset(self, queryset) -> QuerySet:
from products.early_access_features.backend.models import EarlyAccessFeature
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
@@ -3397,19 +3409,12 @@ class FeatureFlagViewSet(
)
)
- # Matches the containment check in FeatureFlagSerializer.get_is_used_in_replay_settings,
- # so the annotated and unannotated paths agree. Containment never casts, so a
- # non-integer id in the JSON yields False instead of erroring the query.
- queryset = queryset.annotate(
- is_used_in_replay_settings_annotation=Exists(
- Team.objects.filter(
- project_id=OuterRef("team__project_id"),
- session_recording_linked_flag__contains=JSONObject(id=OuterRef("id")),
- )
- )
- )
-
if self.action == "list":
+ # Only the list page serializes enough flags to earn the scan. Elsewhere the
+ # serializer's per-flag fallback costs the same single query, and most detail actions
+ # never read the field.
+ queryset = queryset.annotate(is_used_in_replay_settings_annotation=self._replay_gates.as_q())
+
queryset = (
queryset.filter(deleted=False)
.prefetch_related("analytics_dashboards")
@@ -4322,8 +4327,6 @@ class FeatureFlagViewSet(
# Batch query for dependent flags
dependent_flags_map = find_dependent_flags_batch(flags_list)
- replay_linked_ids = replay_linked_flag_ids(self.project_id, [flag.id for flag in flags_list])
-
deleted = []
errors = []
@@ -4394,12 +4397,12 @@ class FeatureFlagViewSet(
# Deleting a flag a team gates recording on stops that team recording, and the
# tombstone rename below fires no signal to relink them.
- if flag_id in replay_linked_ids:
+ if self._replay_gates.gates(flag):
errors.append(
{
"id": flag_id,
"key": flag.key,
- "reason": REPLAY_LINKED_FLAG_DELETE_ERROR,
+ "reason": REPLAY_GATE_DELETE_ERROR,
}
)
continue
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index a3fec10ac71d..0ec28a9d153c 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -1857,12 +1857,6 @@
"posthog_featureflag"."evaluation_runtime",
"posthog_featureflag"."bucketing_identifier",
"posthog_featureflag"."last_called_at",
- EXISTS
- (SELECT 1 AS "a"
- FROM "posthog_team" U0
- WHERE (U0."project_id" = ("posthog_team"."project_id")
- AND U0."session_recording_linked_flag" @> (JSONB_BUILD_OBJECT(('id')::text, "posthog_featureflag"."id")))
- LIMIT 1) AS "is_used_in_replay_settings_annotation",
"posthog_user"."id",
"posthog_user"."password",
"posthog_user"."last_login",
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index 2baa72b24a17..414e507ffacd 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -953,8 +953,11 @@
'''
SELECT 1 AS "a"
FROM "posthog_team"
- WHERE ("posthog_team"."project_id" = 99999
- AND "posthog_team"."session_recording_linked_flag" @> '{"id": 99999}'::jsonb)
+ WHERE (("posthog_team"."session_recording_linked_flag" @> '{"id": 99999}'::jsonb
+ OR "posthog_team"."session_recording_trigger_groups" @> '{"groups": [{"conditions": {"flag": "copied-flag-key"}}]}'::jsonb
+ OR "posthog_team"."session_recording_trigger_groups" @> '{"groups": [{"conditions": {"flag": {"key": "copied-flag-key"}}}]}'::jsonb
+ OR "posthog_team"."session_recording_trigger_groups" @> '{"groups": [{"conditions": {"flag": {"id": 99999}}}]}'::jsonb)
+ AND "posthog_team"."project_id" = 99999)
LIMIT 1
'''
# ---
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 10a919a80479..65f1075aee0d 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -76,6 +76,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
from products.feature_flags.backend.flag_status import FeatureFlagStatus
from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards
from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
+from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag, set_trigger_groups, trigger_groups
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_persons
from products.product_analytics.backend.facade.models import Insight
from products.product_tours.backend.models import ProductTour
@@ -4281,22 +4282,71 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
== "This feature flag is used in session replay settings. Please remove it from replay settings before deleting."
)
- def test_is_used_in_replay_settings_serializer_field(self):
+ @parameterized.expand(["string_form", "object_form", "object_form_with_a_stale_key"])
+ def test_soft_delete_blocked_when_a_replay_trigger_group_gates_on_the_flag(self, stored_shape: str) -> None:
flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-flag")
+ stored_by_shape: dict[str, Any] = {
+ "string_form": flag.key,
+ "object_form": {"id": flag.id, "key": flag.key, "variant": "test"},
+ "object_form_with_a_stale_key": {"id": flag.id, "key": "what-it-used-to-be"},
+ }
+ stored_flag: Any = stored_by_shape[stored_shape]
+ set_trigger_groups(self.team, {"flag": stored_flag})
- # Initially should be False
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/")
- assert response.status_code == 200
- assert response.json()["is_used_in_replay_settings"] is False
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"deleted": True})
- # Set the flag as the session recording linked flag
- self.team.session_recording_linked_flag = {"id": flag.id, "key": flag.key}
- self.team.save()
+ assert response.status_code == 400
+ assert (
+ response.json()["detail"]
+ == "This feature flag is used in session replay settings. Please remove it from replay settings before deleting."
+ )
- # Now should be True
- response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/")
- assert response.status_code == 200
- assert response.json()["is_used_in_replay_settings"] is True
+ @parameterized.expand(
+ [
+ ("key_only_appears_in_events", {"events": ["replay-flag"]}),
+ ("another_flag_whose_key_starts_the_same", {"flag": "replay-flag-v2"}),
+ ("group_gates_on_no_flag_at_all", {"urls": [{"url": "/checkout", "matching": "regex"}]}),
+ ]
+ )
+ def test_soft_delete_allowed_when_no_replay_trigger_group_gates_on_the_flag(
+ self, _name: str, conditions: dict[str, Any]
+ ) -> None:
+ # The probes have to reach `conditions.flag` exactly. A looser match would make flags that
+ # merely share a prefix, or appear elsewhere in the group, permanently undeletable.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-flag")
+ set_trigger_groups(self.team, conditions)
+
+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"deleted": True})
+
+ assert response.status_code == 200, response.content
+ flag.refresh_from_db()
+ assert flag.deleted is True
+
+ @parameterized.expand(["linked_flag", "trigger_group"])
+ def test_is_used_in_replay_settings_serializer_field(self, gated_by: str):
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-flag")
+ unrelated = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated-flag")
+
+ def field_for(flag_id: int, listed: bool) -> bool:
+ if listed:
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/")
+ assert response.status_code == 200
+ return next(f for f in response.json()["results"] if f["id"] == flag_id)["is_used_in_replay_settings"]
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/")
+ assert response.status_code == 200
+ return response.json()["is_used_in_replay_settings"]
+
+ assert field_for(flag.id, listed=False) is False
+ assert field_for(flag.id, listed=True) is False
+
+ if gated_by == "linked_flag":
+ set_linked_flag(self.team, {"id": flag.id, "key": flag.key})
+ else:
+ set_trigger_groups(self.team, {"flag": flag.key})
+
+ assert field_for(flag.id, listed=False) is True
+ assert field_for(flag.id, listed=True) is True
+ assert field_for(unrelated.id, listed=True) is False
def test_archive_flag_requires_disabled(self):
flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="enabled-flag", active=True)
@@ -8711,7 +8761,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert body["updated"] == [{"id": flag.id, "tags": ["foo"]}]
assert body["skipped"] == []
- def test_bulk_update_tags_with_non_integer_replay_linked_flag_id(self):
+ def test_bulk_update_tags_with_malformed_replay_gate_columns(self):
# Replay usage must be computed by JSONB containment, never by casting the stored id
# to integer: a sibling team's non-integer session_recording_linked_flag id would
# error every flags queryset in the project, including bulk_update_tags and list.
@@ -8723,6 +8773,16 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
project=self.team.project,
session_recording_linked_flag={"id": "not-an-int", "key": "some-key"},
)
+ Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ session_recording_trigger_groups={"groups": "not-a-list"},
+ )
+ Team.objects.create(
+ organization=self.organization,
+ project=self.team.project,
+ session_recording_trigger_groups={"groups": ["not-a-dict"]},
+ )
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/bulk_update_tags/",
@@ -13123,31 +13183,32 @@ class TestFeatureFlagBulkDelete(APIBaseTest):
# Key is freed up for reuse
assert flag.key == f"stopped_experiment_flag:deleted:{flag.id}"
- def test_bulk_delete_blocks_a_flag_used_in_session_replay(self):
- # bulk_delete bypasses the serializer, so it needs its own replay guard; without one,
- # this delete would silently stop the linking team's recording.
- linked_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay_gate")
- unlinked_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated")
- self.team.session_recording_linked_flag = {"id": linked_flag.id, "key": "replay_gate"}
- self.team.save()
+ @parameterized.expand(["linked_flag", "trigger_group"])
+ def test_bulk_delete_blocks_a_flag_gating_session_replay(self, stored_in: str):
+ # Deleting a flag a team gates recording on stops that team recording, and bulk_delete
+ # writes through bulk_update, so no signal fires to relink them.
+ gated_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay_gate")
+ unrelated_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="unrelated")
+ if stored_in == "linked_flag":
+ set_linked_flag(self.team, {"id": gated_flag.id, "key": "replay_gate"})
+ else:
+ set_trigger_groups(self.team, {"flag": "replay_gate"})
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",
- {"ids": [linked_flag.id, unlinked_flag.id]},
+ {"ids": [gated_flag.id, unrelated_flag.id]},
)
assert response.status_code == 200
data = response.json()
- # The rest of the batch still deletes, so one linked flag does not block the whole call.
- assert {d["id"] for d in data["deleted"]} == {unlinked_flag.id}
- assert len(data["errors"]) == 1
- assert data["errors"][0]["id"] == linked_flag.id
+ assert {d["id"] for d in data["deleted"]} == {unrelated_flag.id}
+ assert [e["id"] for e in data["errors"]] == [gated_flag.id]
assert "session replay settings" in data["errors"][0]["reason"]
- linked_flag.refresh_from_db()
- unlinked_flag.refresh_from_db()
- assert linked_flag.deleted is False
- assert unlinked_flag.deleted is True
+ gated_flag.refresh_from_db()
+ unrelated_flag.refresh_from_db()
+ assert gated_flag.deleted is False
+ assert unrelated_flag.deleted is True
def test_bulk_delete_blocks_a_flag_a_sibling_team_links(self):
# Replay links are project-scoped: a team can gate recording on a flag owned by a sibling
@@ -13200,6 +13261,25 @@ class TestFeatureFlagBulkDelete(APIBaseTest):
flag.refresh_from_db()
assert flag.deleted is True
+ @parameterized.expand([("same_project", True, False), ("other_project", False, True)])
+ def test_bulk_delete_gate_reaches_trigger_groups_within_the_project_only(
+ self, _name: str, same_project: bool, expect_deleted: bool
+ ) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay_gate")
+ gating_team = Team.objects.create(
+ organization=self.organization, **({"project": self.team.project} if same_project else {})
+ )
+ set_trigger_groups(gating_team, {"flag": "replay_gate"})
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",
+ {"ids": [flag.id]},
+ )
+
+ assert response.status_code == 200
+ flag.refresh_from_db()
+ assert flag.deleted is expect_deleted
+
def test_bulk_delete_requires_filters_or_ids(self):
"""Test validation error when neither filters nor ids provided."""
response = self.client.post(
@@ -14953,10 +15033,6 @@ class TestFeatureFlagFiltersMetrics(APIBaseTest):
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):
@@ -14966,7 +15042,7 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
# 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"})
+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate"})
flag.key = "replay-gate-v2"
with self.captureOnCommitCallbacks(execute=True):
@@ -14985,7 +15061,7 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
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"})
+ set_linked_flag(linking_team, {"id": flag.id, "key": "replay-gate"})
response = self._rename(flag, "replay-gate-v2")
@@ -14995,7 +15071,7 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
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"})
+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate", "variant": "control"})
response = self._rename(flag, "replay-gate-v2")
@@ -15013,14 +15089,16 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
# 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"})
+ set_linked_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",)])
+ @parameterized.expand(
+ [("stored_key_already_matches",), ("links_a_different_flag",), ("trigger_group_key_already_matches",)]
+ )
@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
@@ -15028,17 +15106,23 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
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"})
+ set_linked_flag(sibling_team, {"id": flag.id, "key": "replay-gate-v2"})
+ elif scope == "trigger_group_key_already_matches":
+ # The stored id still selects this team, so the rewrite has to decide there is
+ # nothing to move rather than rely on the team never being picked up.
+ set_trigger_groups(sibling_team, {"flag": {"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"})
+ set_linked_flag(sibling_team, {"id": other_flag.id, "key": "other-gate"})
linked_flag_before = sibling_team.session_recording_linked_flag
+ trigger_groups_before = sibling_team.session_recording_trigger_groups
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.session_recording_trigger_groups == trigger_groups_before
assert sibling_team.id not in {call.args[0] for call in mock_refresh.call_args_list}
def test_rename_still_relinks_teams_while_the_activity_signal_is_muted(self) -> None:
@@ -15046,7 +15130,7 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
# signal thousands of times would be wasteful, but it silences every @mutable_receiver
# indiscriminately. Muting the audit log must not also stop teams recording sessions.
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"})
+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate"})
with self.captureOnCommitCallbacks(execute=True):
with mute_selected_signals():
@@ -15056,8 +15140,17 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
self.team.refresh_from_db()
assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
- @parameterized.expand([("create",), ("rename",)])
- def test_freeing_a_tombstoned_key_relinks_teams_to_the_tombstone(self, mode: str) -> None:
+ @parameterized.expand(
+ [
+ ("create_linked_flag", "create", "linked_flag"),
+ ("rename_linked_flag", "rename", "linked_flag"),
+ ("create_trigger_group", "create", "trigger_group"),
+ ("rename_trigger_group", "rename", "trigger_group"),
+ ]
+ )
+ def test_freeing_a_tombstoned_key_relinks_teams_to_the_tombstone(
+ self, _name: str, mode: str, gated_by: str
+ ) -> None:
# Nothing here blocks the hard delete, which is what makes this the interesting case:
# a hard delete fires no save, so a team gating replay on this tombstone would be left
# on the key the new flag is about to claim. _free_key_held_by_soft_deleted_flags keeps
@@ -15065,7 +15158,10 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
# path frees the key inside the update transaction, where the tombstone and the claiming
# flag each schedule their own relink, so it needs its own coverage.
old_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate", deleted=True)
- self._link_flag(self.team, {"id": old_flag.id, "key": "replay-gate"})
+ if gated_by == "linked_flag":
+ set_linked_flag(self.team, {"id": old_flag.id, "key": "replay-gate"})
+ else:
+ set_trigger_groups(self.team, {"flag": "replay-gate"})
with self.captureOnCommitCallbacks(execute=True):
if mode == "create":
@@ -15084,4 +15180,88 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
old_flag.refresh_from_db()
assert old_flag.key == f"replay-gate:deleted:{old_flag.id}"
self.team.refresh_from_db()
- assert self.team.session_recording_linked_flag == {"id": old_flag.id, "key": old_flag.key}
+ if gated_by == "linked_flag":
+ assert self.team.session_recording_linked_flag == {"id": old_flag.id, "key": old_flag.key}
+ else:
+ assert self.team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == old_flag.key
+
+ @parameterized.expand(
+ [
+ ("string_form", lambda flag: "replay-gate", lambda flag: "replay-gate-v2"),
+ (
+ "object_form",
+ lambda flag: {"id": flag.id, "key": "replay-gate", "variant": "control"},
+ lambda flag: {"id": flag.id, "key": "replay-gate-v2", "variant": "control"},
+ ),
+ # The stored id names the flag whatever key the reference still holds, so the rename
+ # brings a reference that has drifted off the key up to date too.
+ (
+ "object_form_with_a_stale_key",
+ lambda flag: {"id": flag.id, "key": "long-gone"},
+ lambda flag: {"id": flag.id, "key": "replay-gate-v2"},
+ ),
+ ]
+ )
+ def test_rename_rewrites_a_trigger_group_reference_in_its_stored_shape(
+ self, _name: str, build_stored: Any, build_expected: Any
+ ) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ set_trigger_groups(self.team, {"flag": build_stored(flag)})
+
+ 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_trigger_groups["groups"][0]["conditions"]["flag"] == build_expected(flag)
+
+ def test_rename_rewrites_only_the_group_that_names_the_flag(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ set_trigger_groups(
+ self.team,
+ {"events": ["$pageview"]},
+ {"flag": "another-gate"},
+ {"flag": "replay-gate", "minDurationMs": 5000},
+ )
+ groups_before = self.team.session_recording_trigger_groups["groups"]
+
+ 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_trigger_groups["groups"] == [
+ groups_before[0],
+ groups_before[1],
+ {**groups_before[2], "conditions": {**groups_before[2]["conditions"], "flag": "replay-gate-v2"}},
+ ]
+
+ def test_rename_leaves_a_linked_flag_naming_a_different_flag_alone(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")
+ set_linked_flag(self.team, {"id": other_flag.id, "key": "other-gate"})
+ set_trigger_groups(self.team, {"flag": "replay-gate"})
+
+ 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": other_flag.id, "key": "other-gate"}
+ assert self.team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == "replay-gate-v2"
+
+ @patch("posthog.models.remote_config._update_team_remote_config")
+ def test_rename_saves_a_team_holding_both_kinds_of_reference_once(self, mock_refresh: MagicMock) -> None:
+ 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)
+ sibling_team.session_recording_linked_flag = {"id": flag.id, "key": "replay-gate"}
+ sibling_team.session_recording_trigger_groups = trigger_groups({"flag": "replay-gate"})
+ # Drained here so the setup's own rebuild doesn't land inside the rename's capture block.
+ with self.captureOnCommitCallbacks(execute=True):
+ sibling_team.save()
+ mock_refresh.reset_mock()
+
+ response = self._rename(flag, "replay-gate-v2")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [call.args[0] for call in mock_refresh.call_args_list].count(sibling_team.id) == 1
+ sibling_team.refresh_from_db()
+ assert sibling_team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+ assert sibling_team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == "replay-gate-v2"
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
index 5390230c2cbc..149dc211ade0 100644
--- 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
@@ -9,7 +9,10 @@ plus any left by a writer that bypasses `save()`, such as the `bulk_update` in `
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.
+still wants a recording gate at all. A flag soft-deleted between the scan and the write is the
+one exception. The write reads the key under the team's row lock, so that team follows the flag
+onto its current key, which is the tombstone key when the soft delete freed the original for a
+new flag to claim.
"""
import json
@@ -25,7 +28,12 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.feature_flags.backend.session_recording_links import linked_flag_id, update_linked_flag_key
+from products.feature_flags.backend.session_recording_links import (
+ ReplayGateRewrite,
+ rewritten_linked_flag,
+ save_replay_gate_rewrites,
+ stored_flag_id,
+)
class Outcome(StrEnum):
@@ -34,9 +42,16 @@ class Outcome(StrEnum):
FLAG_SOFT_DELETED = "flag_soft_deleted"
FLAG_IN_OTHER_PROJECT = "flag_in_other_project"
FLAG_MISSING = "flag_missing"
+ TEAM_MISSING = "team_missing"
MALFORMED = "malformed"
+@frozen
+class _ReplayLinkWrite:
+ outcome: Outcome
+ written_key: str | None = None
+
+
@frozen
class _FlagRow:
key: str
@@ -108,7 +123,7 @@ class Command(BaseCommand):
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
+ flag_id for team in teams if (flag_id := stored_flag_id(team.session_recording_linked_flag)) is not None
}
if not flag_ids:
return {}
@@ -126,7 +141,7 @@ class Command(BaseCommand):
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)
+ stored_id = stored_flag_id(linked_flag)
if stored_id is None:
return Outcome.MALFORMED, detail
@@ -142,10 +157,57 @@ class Command(BaseCommand):
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
+ if dry_run:
+ # No lock is taken, so this is the key the chunk read, not one this run will write.
+ detail["new_key"] = flag.key
+ return Outcome.REPAIRED, detail
+
+ write = self._write_current_key(team.pk, stored_id)
+ if write.written_key is not None:
+ detail["new_key"] = write.written_key
+ return write.outcome, detail
+
+ def _write_current_key(self, team_id: int, flag_id: int) -> _ReplayLinkWrite:
+ """Point a team's replay link at the flag's key, and report what the write did.
+
+ `written_key` is set only when this run rewrote the row, so the caller can count a repair
+ it actually made.
+
+ `_load_flags` reads each key once per chunk, so a whole page of teams can be written after
+ it. A rename landing in that window has already relinked this team, and writing the key
+ the chunk read would put a key no flag holds back over the new one. Reading the key inside
+ the lock converges on the value `relink_teams` writes, because that relink takes this same
+ row lock.
+ """
+ # `save_replay_gate_rewrites` skips `rewrite` when the team row is gone, so this stands
+ # until the lock is held.
+ write = _ReplayLinkWrite(outcome=Outcome.TEAM_MISSING)
+
+ def rewrite(locked: Team) -> ReplayGateRewrite:
+ nonlocal write
+ # `objects_including_soft_deleted` so a soft delete landing in the same window keeps
+ # the team on the tombstone key that `_free_key_held_by_soft_deleted_flags` gives the
+ # flag. That rename frees the original key for a new flag to claim, and a team left on
+ # it would gate recording on a flag it never linked.
+ current_key = (
+ FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id).values_list("key", flat=True).first()
+ )
+ if current_key is None:
+ write = _ReplayLinkWrite(outcome=Outcome.FLAG_MISSING)
+ return ReplayGateRewrite()
+ linked_flag = rewritten_linked_flag(
+ locked.session_recording_linked_flag, flag_id=flag_id, new_key=current_key
+ )
+ if linked_flag is None:
+ # The team was relinked or repointed since the chunk read, so this run changes
+ # nothing. Reporting a repair here would name a key it never wrote.
+ write = _ReplayLinkWrite(outcome=Outcome.ALREADY_CORRECT)
+ return ReplayGateRewrite()
+ write = _ReplayLinkWrite(outcome=Outcome.REPAIRED, written_key=current_key)
+ return ReplayGateRewrite(linked_flag=linked_flag)
+
+ save_replay_gate_rewrites(team_id, rewrite)
+ return write
def _report(self, report: dict[str, Any], *, as_json: bool) -> None:
if as_json:
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
index d16b7650ac0b..c156ae6cdc57 100644
--- 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
@@ -3,6 +3,7 @@ from io import StringIO
from typing import Any
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
@@ -11,14 +12,12 @@ from parameterized import parameterized
from posthog.models import Team
+from products.feature_flags.backend.management.commands import repair_replay_linked_flag_keys as repair_command
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag
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.
@@ -35,7 +34,7 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
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"})
+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate", "variant": "control"})
report = self._run("--live-run", teams=[self.team])
@@ -64,7 +63,7 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
# 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"})
+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate"})
report = self._run(teams=[self.team])
@@ -107,7 +106,7 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
deleted=case == "flag_soft_deleted",
)
linked_flag = {"id": flag.id, "key": "replay-gate"}
- self._link_flag(self.team, linked_flag)
+ set_linked_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.
@@ -121,7 +120,7 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
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"})
+ set_linked_flag(sibling_team, {"id": flag.id, "key": "replay-gate"})
report = self._run("--live-run", teams=[sibling_team])
@@ -129,6 +128,86 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
sibling_team.refresh_from_db()
assert sibling_team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+ def test_a_rename_landing_mid_scan_is_not_written_back(self) -> None:
+ # Every flag key is read once per chunk, before the first team row of that chunk is
+ # locked. A rename in that window relinks the team on its own, so writing the key the
+ # chunk read leaves the team gating on a key no flag holds, which is the failure this
+ # command exists to repair.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-b")
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-a"})
+
+ real_save = repair_command.save_replay_gate_rewrites
+
+ def rename_then_save(team_id: int, compute: Any) -> None:
+ flag.key = "gate-c"
+ with self.captureOnCommitCallbacks(execute=True):
+ flag.save()
+ real_save(team_id, compute)
+
+ with patch.object(repair_command, "save_replay_gate_rewrites", side_effect=rename_then_save):
+ report = self._run("--live-run", teams=[self.team])
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}
+ # The relink did the write, so this run has nothing left to repair and claims none.
+ assert report["repairs"] == []
+ assert report["outcomes"] == {"already_correct": 1}
+
+ def test_a_repoint_mid_scan_is_not_reported_as_a_repair(self) -> None:
+ # An admin can send the gate to a different flag between the chunk read and the lock.
+ # That edit is not this command's to touch, and reporting a repair here would name a key
+ # the team does not hold, on a flag it no longer points at.
+ stale_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-current")
+ other_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-current")
+ set_linked_flag(self.team, {"id": stale_flag.id, "key": "gate-stale"})
+
+ real_save = repair_command.save_replay_gate_rewrites
+
+ def repoint_then_save(team_id: int, compute: Any) -> None:
+ admin = Team.objects.get(pk=team_id)
+ admin.session_recording_linked_flag = {"id": other_flag.id, "key": "other-current"}
+ admin.save()
+ real_save(team_id, compute)
+
+ with patch.object(repair_command, "save_replay_gate_rewrites", side_effect=repoint_then_save):
+ report = self._run("--live-run", teams=[self.team])
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": other_flag.id, "key": "other-current"}
+ assert report["repairs"] == []
+
+ def test_a_flag_hard_deleted_at_write_time_writes_nothing(self) -> None:
+ # The key is read again inside the team's row lock. A hard delete landing in that window
+ # leaves no key to adopt, and writing the None it reads would store a gate the SDKs
+ # cannot resolve, which stops the team recording.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-current")
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-stale"})
+
+ real_save = repair_command.save_replay_gate_rewrites
+
+ def hard_delete_then_save(team_id: int, compute: Any) -> None:
+ FeatureFlag.objects_including_soft_deleted.filter(pk=flag.id).delete()
+ real_save(team_id, compute)
+
+ with patch.object(repair_command, "save_replay_gate_rewrites", side_effect=hard_delete_then_save):
+ report = self._run("--live-run", teams=[self.team])
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-stale"}
+ assert report["repairs"] == []
+ assert report["outcomes"] == {"flag_missing": 1}
+
+ def test_a_team_row_gone_at_write_time_is_not_reported_as_a_missing_flag(self) -> None:
+ # `save_replay_gate_rewrites` skips the rewrite when the team row is gone, which reads the
+ # same as a flag that resolved to nothing. Filing it under flag_missing sends whoever runs
+ # the repair looking at the wrong row.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-live")
+
+ write = repair_command.Command()._write_current_key(team_id=self.team.pk + 10_000_000, flag_id=flag.id)
+
+ assert write.outcome == repair_command.Outcome.TEAM_MISSING
+ assert write.written_key is None
+
def test_repairs_every_team_across_chunk_boundaries(self) -> None:
# A chunk size smaller than the number of scanned teams forces _iter_team_chunks through
# more than one page; every team must still be repaired, not just the first chunk's.
@@ -137,7 +216,7 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
]
flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")
for team in teams:
- self._link_flag(team, {"id": flag.id, "key": "replay-gate"})
+ set_linked_flag(team, {"id": flag.id, "key": "replay-gate"})
report = self._run("--live-run", "--chunk-size", "1", teams=teams)
diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.py
index a50d872448c1..55d67f10a281 100644
--- a/products/feature_flags/backend/session_recording_links.py
+++ b/products/feature_flags/backend/session_recording_links.py
@@ -1,21 +1,30 @@
-"""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.
+"""Keeps a team's session replay recording gate in step with the flag key it points at.
+
+A team can gate recording on a flag in two columns. `Team.session_recording_linked_flag` stores the
+flag `id` alongside its `key`. Each V2 trigger group in `Team.session_recording_trigger_groups`
+stores an optional `conditions.flag`, holding either a bare key string or an object carrying the
+same `id`/`key`/`variant` shape. The SDK payload that `RemoteConfig._build_session_recording_config`
+builds resolves both by key alone, and both the browser and React Native SDKs treat a 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.
+
+The replay settings UI writes the bare string form, so a reference usually has no id to match on.
+Flag keys are unique within a project, so a key alone identifies one flag there, which is why every
+matcher here is project-scoped.
"""
-from collections.abc import Collection
+from collections import defaultdict
+from collections.abc import Callable, Collection, Mapping
from typing import Any
from django.db import transaction
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
import structlog
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
@@ -24,123 +33,323 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
-REPLAY_LINKED_FLAG_DELETE_ERROR = (
+REPLAY_GATE_DELETE_ERROR = (
"This feature flag is used in session replay settings. Please remove it from replay settings before deleting."
)
-def linked_flag_id(linked_flag: Any) -> int | None:
- """The flag id a stored replay link points at, or None when it holds no usable one."""
- if not isinstance(linked_flag, dict):
+@frozen
+class TriggerGroupFlagRef:
+ """One trigger group's reference to a feature flag, and where in the stored config it sits."""
+
+ group_index: int
+ stored_flag: Any
+ key: str | None
+ flag_id: int | None
+
+
+@frozen
+class ReplayGateRewrite:
+ """New values for a team's gate columns. `None` leaves that column alone."""
+
+ linked_flag: dict[str, Any] | None = None
+ trigger_groups: dict[str, Any] | None = None
+
+
+@frozen
+class ReplayFlagGates:
+ """Which flags a project's teams gate recording on, keyed the way each column stores it."""
+
+ flag_ids: frozenset[int]
+ flag_keys: frozenset[str]
+
+ def gates(self, feature_flag: FeatureFlag) -> bool:
+ return feature_flag.id in self.flag_ids or feature_flag.key in self.flag_keys
+
+ def as_q(self) -> Q:
+ """`gates` as a queryset predicate, for annotating a page of flags in one go.
+
+ Sorted so the `IN` lists keep a stable order: set iteration order varies per process,
+ which would churn query snapshots.
+ """
+ return Q(id__in=sorted(self.flag_ids)) | Q(key__in=sorted(self.flag_keys))
+
+
+def stored_flag_id(stored_flag: Any) -> int | None:
+ """The flag id a stored replay reference points at, or None when it holds no usable one.
+
+ Covers both columns: `session_recording_linked_flag` and the object form of a trigger group's
+ `conditions.flag` share a shape.
+ """
+ if not isinstance(stored_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 usable, and every other shape is left for the caller to handle rather
- # than coerced. `bool` is excluded explicitly because it subclasses `int`, so `{"id": true}`
- # would otherwise read as a link to flag 1.
- if isinstance(stored_id, bool) or not isinstance(stored_id, int):
+ flag_id = stored_flag.get("id")
+ # `bool` subclasses `int`, so `{"id": true}` would otherwise read as a link to flag 1.
+ if isinstance(flag_id, bool):
return None
- return stored_id
+ if isinstance(flag_id, int):
+ return flag_id
+ # Postgres compares JSON numbers numerically, so a stored `7.0` satisfies the `{"id": 7}`
+ # containment probe. Reading it the same way here keeps the SQL matcher and the Python scan
+ # from answering differently for the same team.
+ if isinstance(flag_id, float) and flag_id.is_integer():
+ return int(flag_id)
+ return None
+
+
+def _trigger_group_flag_key(stored_flag: Any) -> str | None:
+ """The flag key a trigger group's `conditions.flag` names, in either stored shape."""
+ if isinstance(stored_flag, str):
+ return stored_flag or None
+ if isinstance(stored_flag, dict):
+ key = stored_flag.get("key")
+ return key if isinstance(key, str) and key else None
+ return None
+
+
+def trigger_group_flag_refs(trigger_groups: Any) -> list[TriggerGroupFlagRef]:
+ """Every `conditions.flag` reference in a team's stored trigger groups.
+
+ Empty for a column that gates on no flag and for one too malformed to read, since neither holds
+ a reference to act on.
+ """
+ if not isinstance(trigger_groups, dict) or not isinstance(trigger_groups.get("groups"), list):
+ return []
+
+ groups = trigger_groups["groups"]
+ refs = []
+ for index, group in enumerate(groups):
+ conditions = group.get("conditions") if isinstance(group, dict) else None
+ stored_flag = conditions.get("flag") if isinstance(conditions, dict) else None
+ if stored_flag is None:
+ continue
+ refs.append(
+ TriggerGroupFlagRef(
+ group_index=index,
+ stored_flag=stored_flag,
+ key=_trigger_group_flag_key(stored_flag),
+ flag_id=stored_flag_id(stored_flag),
+ )
+ )
+ return refs
-def teams_linking_flag(feature_flag: FeatureFlag) -> QuerySet[Team]:
- """Every team gating session recording on this flag."""
- return teams_linking_flag_in_project(feature_flag.team.project_id, feature_flag.id)
+def _trigger_group_flag_probe(stored_flag: Any) -> dict[str, Any]:
+ """A JSONB containment probe matching a trigger group whose `conditions.flag` is `stored_flag`.
+ Containment reaches a group at any index in the array and never casts, so a malformed stored
+ shape yields False rather than erroring the query. A probe for the bare string form never
+ matches the object form, or the reverse, so a caller that wants both sends both.
+ """
+ return {"groups": [{"conditions": {"flag": stored_flag}}]}
-def teams_linking_flag_in_project(project_id: int, flag_id: int) -> QuerySet[Team]:
- """Every team in this project gating session recording on the flag with this id."""
- # Scoped by project rather than by team: any team in the project can gate recording on a flag
- # owned by a sibling team.
+
+def teams_gating_replay_on_flag(feature_flag: FeatureFlag, *, key: str) -> QuerySet[Team]:
+ """Every team gating session recording on this flag, through either column.
+
+ `key` is separate from `feature_flag.key` so the relink can find teams by the key they still
+ hold, which is the one the flag has just stopped having.
+ """
return Team.objects.filter(
- project_id=project_id,
- session_recording_linked_flag__contains={"id": flag_id},
+ Q(session_recording_linked_flag__contains={"id": feature_flag.id})
+ | Q(session_recording_trigger_groups__contains=_trigger_group_flag_probe(key))
+ | Q(session_recording_trigger_groups__contains=_trigger_group_flag_probe({"key": key}))
+ # An object reference holding a key the flag no longer has still names it by id. Matching
+ # that too is what stops a delete stranding a reference the repair command could have
+ # fixed, since deleting the flag takes away the only record of what the key meant.
+ | Q(session_recording_trigger_groups__contains=_trigger_group_flag_probe({"id": feature_flag.id})),
+ project_id=feature_flag.team.project_id,
)
-def replay_linked_flag_ids(project_id: int, flag_ids: Collection[int]) -> set[int]:
- """Single-project form of `replay_linked_flag_ids_for_projects`."""
- return replay_linked_flag_ids_for_projects([project_id], flag_ids)
+def replay_gated_flags(project_id: int) -> ReplayFlagGates:
+ """Single-project form of `replay_gated_flags_for_projects`."""
+ return replay_gated_flags_for_projects([project_id]).get(
+ project_id, ReplayFlagGates(flag_ids=frozenset(), flag_keys=frozenset())
+ )
-def replay_linked_flag_ids_for_projects(project_ids: Collection[int], flag_ids: Collection[int]) -> set[int]:
- """Which of the given flags a team in these projects gates session recording on.
+def replay_gated_flags_for_projects(project_ids: Collection[int]) -> Mapping[int, ReplayFlagGates]:
+ """Every flag a team in each project gates session recording on, from both columns.
- The batch equivalent of `teams_linking_flag`, in one query. Matching ids inside jsonb keeps
- that check's comparison semantics, so the single-flag and bulk delete guards agree on what
- counts as linked; a malformed value like `{"id": true}` matches no flag, because jsonb never
- equates booleans with numbers.
+ One query for every project named, for callers checking many flags at once;
+ `teams_gating_replay_on_flag` is the per-flag equivalent. Keyed by project because a flag key
+ identifies one flag only within its own project, so pooling the keys would let a key stored
+ in one project match a same-keyed flag in another. A project that gates on nothing is absent
+ from the result rather than present and empty.
"""
- if not flag_ids or not project_ids:
- return set()
- stored_ids = Team.objects.filter(
+ stored = Team.objects.filter(
+ Q(session_recording_linked_flag__isnull=False) | Q(session_recording_trigger_groups__isnull=False),
project_id__in=project_ids,
- session_recording_linked_flag__id__in=flag_ids,
- ).values_list("session_recording_linked_flag__id", flat=True)
- # jsonb also equates numbers regardless of representation, so a stored float id can match an
- # int flag id; normalize for the int membership checks callers do.
- return {int(stored_id) for stored_id in stored_ids}
-
-
-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()
+ ).values_list("project_id", "session_recording_linked_flag", "session_recording_trigger_groups")
+
+ flag_ids: dict[int, set[int]] = defaultdict(set)
+ flag_keys: dict[int, set[str]] = defaultdict(set)
+ for project_id, linked_flag, trigger_groups in stored:
+ if (flag_id := stored_flag_id(linked_flag)) is not None:
+ flag_ids[project_id].add(flag_id)
+ for ref in trigger_group_flag_refs(trigger_groups):
+ if ref.key is not None:
+ flag_keys[project_id].add(ref.key)
+ if ref.flag_id is not None:
+ flag_ids[project_id].add(ref.flag_id)
+ return {
+ project_id: ReplayFlagGates(
+ flag_ids=frozenset(flag_ids[project_id]), flag_keys=frozenset(flag_keys[project_id])
)
- # Don't route this through `linked_flag_id`: it stays loose to match the jsonb comparison
- # `teams_linking_flag` selected on, where a stored float id equals an int one.
- 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.
+ for project_id in flag_ids.keys() | flag_keys.keys()
+ }
+
+
+def rewritten_linked_flag(linked_flag: Any, *, flag_id: int, new_key: str) -> dict[str, Any] | None:
+ """A team's replay link with its key rewritten, or None when there is nothing to change."""
+ if stored_flag_id(linked_flag) != flag_id:
+ # Team selection matches either column, so a team can be in hand because of its trigger
+ # groups while this one points at an unrelated flag. Rewriting it then would gate that
+ # team's recording on a key the flag it names never had.
+ return None
+ if linked_flag.get("key") == new_key:
+ return None
+ return {**linked_flag, "key": new_key}
+
+
+def rewritten_trigger_groups(trigger_groups: Any, renames: Mapping[int, str]) -> dict[str, Any] | None:
+ """A team's named trigger groups with their flag keys rewritten, or None when nothing changes.
+
+ Keyed by group index, so which references move stays the decision of the caller that
+ classified them. Keying by flag key instead would drag in every other group holding the same
+ one, including references the caller deliberately left alone, and would collapse two groups
+ naming one stale key onto whichever flag was resolved first.
+
+ RemoteConfig hands these groups to the SDK nearly verbatim, so a rewrite that dropped
+ `sampleRate`, `urls`, or the group id would break the gate outright rather than merely
+ mistarget it. Every reference therefore keeps the shape it was stored in.
+ """
+ refs = trigger_group_flag_refs(trigger_groups)
+ if not refs:
+ return None
+
+ groups = list(trigger_groups["groups"])
+ changed = False
+ for ref in refs:
+ new_key = renames.get(ref.group_index)
+ if new_key is None or new_key == ref.key:
+ continue
+ group = groups[ref.group_index]
+ rewritten = new_key if isinstance(ref.stored_flag, str) else {**ref.stored_flag, "key": new_key}
+ groups[ref.group_index] = {**group, "conditions": {**group["conditions"], "flag": rewritten}}
+ changed = True
+ return {**trigger_groups, "groups": groups} if changed else None
+
+
+def save_replay_gate_rewrites(team_id: int, compute: Callable[[Team], ReplayGateRewrite]) -> None:
+ """Rewrite a team's gate columns under a row lock, in a single save.
+
+ `compute` is handed the team as it exists inside the lock rather than a copy the caller read
+ earlier. Callers load their teams in one batch and then loop, so an admin edit to this team's
+ replay settings can land before its turn comes up. Both rewrites replace a whole column, so
+ computing one from a stale copy would put the pre-edit column back and publish it to the SDKs.
+
+ Taking the lock here is safe because this is the only row the function locks and the
+ transaction commits before returning, so two calls for different teams cannot deadlock against
+ each other. `relink_teams_on_key_change` defers to `on_commit` so the serializer's lock on the
+ flag row is already released by the time this runs.
+ """
+ with transaction.atomic():
+ # Loads every column rather than deferring: the `post_save` cache receiver reads about
+ # thirty other fields, each its own query when deferred.
+ # `no_key=True` because this writes no key column, so the lock does not block the
+ # `KEY SHARE` that a foreign key check on this Team row takes. Two `FOR NO KEY UPDATE`
+ # locks still conflict, so two calls to this function for one team stay serialized.
+ # The lock does not serialize this against the Team API. That serializer saves the
+ # column the client sent on a row it read without a lock, so a settings edit racing a
+ # rename can still land the pre-rename key. `repair_replay_linked_flag_keys` reports
+ # such a row on its next run.
+ team = Team.objects.select_for_update(no_key=True).filter(pk=team_id).first()
+ if team is None:
return
- if linked_flag.get("key") == new_key:
+
+ rewrite = compute(team)
+ update_fields = []
+ if rewrite.linked_flag is not None:
+ team.session_recording_linked_flag = rewrite.linked_flag
+ update_fields.append("session_recording_linked_flag")
+ if rewrite.trigger_groups is not None:
+ team.session_recording_trigger_groups = rewrite.trigger_groups
+ update_fields.append("session_recording_trigger_groups")
+ if not update_fields:
# 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.
+ # 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. Both columns go in one save because that
+ # refresh is queued per save, not per changed field.
+ team.save(update_fields=update_fields)
+
+
+def relink_teams(feature_flag: FeatureFlag, *, old_key: str) -> None:
+ """Point every team gating replay on this flag at its current key.
+
+ Teams are found by `old_key` rather than the flag's current one, because a trigger group is
+ matched by the key it still holds, which is the one the flag has just stopped having.
+ """
+ try:
+ # Read into a list here rather than iterated straight in the loop below, because a queryset
+ # runs its query on the first step of the loop, where the per-team handler cannot catch it.
+ team_ids = list(teams_gating_replay_on_flag(feature_flag, key=old_key).values_list("pk", flat=True))
+ except Exception:
+ # This read runs after the rename has committed, so a fault here, such as a connection a
+ # failover dropped, must not raise for the same reason a write failure below must not: it
+ # would fail a request that already succeeded. `repair_replay_linked_flag_keys` picks the
+ # linked flag column back up later.
+ logger.exception("replay_relink_lookup_failed", flag_id=feature_flag.pk)
+ capture_exception()
return
- for team in teams_linking_flag(feature_flag):
+ def rewrite(team: Team) -> ReplayGateRewrite:
+ # Read once per team, under that team's row lock, rather than once before the loop. Two
+ # renames of the same flag committed close together fire their `on_commit` callbacks with
+ # no ordering guarantee between them, and a rename can also land partway through this
+ # loop. Every relink holding this team's row lock reads the key at this point, so they
+ # converge on the stored key instead of leaving later teams on the key this callback
+ # started with. A Team API write takes no such lock and is not ordered against them.
+ # `objects_including_soft_deleted` also finds the tombstone that
+ # `_free_key_held_by_soft_deleted_flags` renames.
+ new_key = (
+ FeatureFlag.objects_including_soft_deleted.filter(pk=feature_flag.pk).values_list("key", flat=True).first()
+ )
+ if new_key is None:
+ # The row is gone entirely, not just soft-deleted, so there is no key to point this
+ # team at. `repair_replay_linked_flag_keys` reports it as flag_missing on its next run.
+ return ReplayGateRewrite()
+ trigger_groups = team.session_recording_trigger_groups
+ # Matched by id as well as by key, because `teams_gating_replay_on_flag` also selects a
+ # team whose group names this flag by id while holding a key the flag no longer has. The
+ # rename is the last moment that stored id still resolves to a key.
+ # `repair_replay_linked_flag_keys` does not read trigger groups, so a group skipped here
+ # keeps the stale key for good. A bare string reference carries no id, so it still moves
+ # on its key alone.
+ moving = {
+ ref.group_index: new_key
+ for ref in trigger_group_flag_refs(trigger_groups)
+ if ref.key == old_key or ref.flag_id == feature_flag.pk
+ }
+ return ReplayGateRewrite(
+ linked_flag=rewritten_linked_flag(
+ team.session_recording_linked_flag, flag_id=feature_flag.pk, new_key=new_key
+ ),
+ trigger_groups=rewritten_trigger_groups(trigger_groups, moving),
+ )
+
+ for team_id in team_ids:
try:
- update_linked_flag_key(team, feature_flag.id, current_key)
+ save_replay_gate_rewrites(team_id, rewrite)
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)
+ # already succeeded. `repair_replay_linked_flag_keys` picks the linked flag column back
+ # up later. It does not read trigger groups, so a group left here stays stale.
+ logger.exception("replay_relink_failed", flag_id=feature_flag.pk, team_id=team_id)
capture_exception()
@@ -155,10 +364,8 @@ def capture_replay_link_key_before_save(
update_fields: frozenset[str] | None = None,
**kwargs: Any,
) -> None:
- # Its own snapshot rather than sharing the one `flag_version_sync` takes: relinking must
- # not hinge on which fields another feature happens to watch.
- # objects_including_soft_deleted so the tombstone rename a soft-deleted flag gets when
- # `_free_key_held_by_soft_deleted_flags` frees its key for reuse is captured too.
+ # `objects_including_soft_deleted` so the tombstone rename that
+ # `_free_key_held_by_soft_deleted_flags` does is captured too.
capture_fields_before_save(
instance,
FeatureFlag.objects_including_soft_deleted,
@@ -178,22 +385,23 @@ def relink_teams_on_key_change(
**kwargs: Any,
) -> None:
# Wired to plain model signals rather than to FeatureFlagSerializer so renames from the
- # Django admin, a shell, or a Celery task keep the link intact too, and rather than to
+ # Django admin, a shell, or a Celery task keep the gate intact too, and rather than to
# model_activity_signal because activity logging is tunable in ways recording must not
# inherit: `mute_selected_signals()` and the activity-log `signal_exclusions` can both
- # silently drop that signal, and a skipped relink turns replay off for every linking team.
- # The snapshot is only a change detector; `relink_teams` re-reads the stored key itself.
- if raw or created or snapshot_if_changed(instance, attr=_KEY_BEFORE_SAVE_ATTR) is None:
+ # silently drop that signal, and a skipped relink turns replay off for every gating team.
+ if raw or created:
+ return
+ before = snapshot_if_changed(instance, attr=_KEY_BEFORE_SAVE_ATTR)
+ if before is None:
return
+ old_key = before["key"]
- # Unlike `repair_replay_linked_flag_keys`, this has no `instance.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.
+ # No `instance.deleted` guard, unlike `repair_replay_linked_flag_keys`, so the tombstone rename
+ # `_free_key_held_by_soft_deleted_flags` does when freeing a soft-deleted flag's key relinks
+ # too. Skipping it would leave the team on the now-freed original key, which a new flag could
+ # claim 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(instance))
+ transaction.on_commit(lambda: relink_teams(instance, old_key=old_key))
diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
index 204f21a7d175..74d49ff91e5f 100644
--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
@@ -24,7 +24,7 @@ from products.feature_flags.backend.flag_status import (
)
from products.feature_flags.backend.flag_version_sync import direct_flag_dependency_ids, flags_with_flag_dependencies
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.feature_flags.backend.session_recording_links import replay_linked_flag_ids_for_projects
+from products.feature_flags.backend.session_recording_links import replay_gated_flags_for_projects
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
@@ -170,22 +170,24 @@ def _excluded_flag_ids(candidates: list[FeatureFlag]) -> set[int]:
The bulk-delete guard in ``products/feature_flags/backend/api/feature_flag.py`` blocks
the same references and must stay in step with this list. Where the two differ it is on
purpose, and this list is the stricter one: the guard blocks only running experiments
- where this excludes every non-deleted one, and the guard's ``find_dependent_flags_batch``
- counts only active dependent flags where this also lets disabled dependents block.
+ where this excludes every non-deleted one, the guard's ``find_dependent_flags_batch``
+ counts only active dependent flags where this also lets disabled dependents block, and
+ the guard matches a replay gate only within the flag's own project where this matches a
+ stored id across every project scanned.
A survey's user-created ``linked_flag`` is deliberately not excluded, unlike the
survey flags PostHog generates itself. It is user-managed, bulk delete permits it, and
the remediation tells the investigator to check surveys. A reported flag is evidence
to investigate, not a verdict that removal is safe.
"""
- flag_ids = [flag.id for flag in candidates]
team_ids = {flag.team_id for flag in candidates}
# Product tours, replay links, and flag dependencies are scoped by project, not by team:
# another team in the same project can reference a flag this batch's teams own. A product
# tour stays on the environment that created it, while a flag moves to the project root.
# Surveys stay on team scope: Survey and FeatureFlag both inherit RootTeamMixin, so both
# rows always sit on the project root team and their team ids line up.
- project_ids = set(Team.objects.filter(id__in=team_ids).values_list("project_id", flat=True))
+ team_projects = dict(Team.objects.filter(id__in=team_ids).values_list("id", "project_id"))
+ project_ids = set(team_projects.values())
excluded: set[int] = set()
excluded |= Survey.get_internal_flag_ids(team_ids=team_ids)
@@ -203,7 +205,25 @@ def _excluded_flag_ids(candidates: list[FeatureFlag]) -> set[int]:
)
)
excluded |= _depended_on_flag_ids(project_ids)
- excluded |= replay_linked_flag_ids_for_projects(project_ids, flag_ids)
+ # A trigger group counts here as much as the linked-flag column: both gate recording, so a
+ # flag either one names must not be reported as a cleanup candidate.
+ replay_gates = replay_gated_flags_for_projects(project_ids)
+ # A stored id is matched against every project scanned, because flag ids are globally unique.
+ # Only the stored key reaches an SDK, so a team holding another project's flag id gates no
+ # recording on that flag. The candidate is withheld anyway, because a hard delete leaves that
+ # reference unrepairable. `repair_replay_linked_flag_keys` reports such a row as
+ # `FLAG_IN_OTHER_PROJECT` and has no key it can safely adopt.
+ excluded |= {flag_id for gates in replay_gates.values() for flag_id in gates.flag_ids}
+ # A stored key is matched only within its own project, because a key names one flag only
+ # there, and pooling keys would let a key stored in one project protect a same-keyed flag in
+ # another.
+ excluded |= {
+ flag.id
+ for flag in candidates
+ if (project_id := team_projects.get(flag.team_id)) is not None
+ and (gates := replay_gates.get(project_id)) is not None
+ and flag.key in gates.flag_keys
+ }
return excluded
diff --git a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
index 1ea2535df330..7ced7baae56c 100644
--- a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
@@ -28,6 +28,7 @@ from products.feature_flags.backend.temporal.health_checks.stale_flags import (
EVIDENCE_NOT_CALLED_RECENTLY,
StaleFeatureFlagsCheck,
)
+from products.feature_flags.backend.test.replay_gate_fixtures import trigger_groups
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
@@ -107,6 +108,10 @@ class TestStaleFlagsDetect(BaseTest):
elif link == "replay_link":
# Queryset update instead of save so no Team receivers run in the fixture.
Team.objects.filter(pk=self.team.pk).update(session_recording_linked_flag={"id": flag.id, "key": flag.key})
+ elif link == "replay_trigger_group":
+ Team.objects.filter(pk=self.team.pk).update(
+ session_recording_trigger_groups=trigger_groups({"flag": flag.key})
+ )
else:
raise ValueError(link)
@@ -135,6 +140,9 @@ class TestStaleFlagsDetect(BaseTest):
# Local-evaluation semantics: a disabled dependent still protects its dependency.
("disabled_dependent_still_blocks", stale_by_usage(), "disabled_dependent_flag", False),
("replay_linked", stale_by_config(), "replay_link", False),
+ # A trigger group gates recording just as the linked-flag column does, so the flag it
+ # names is not a cleanup candidate either.
+ ("replay_trigger_group_linked", stale_by_config(), "replay_trigger_group", False),
]
)
def test_detect_inclusion_and_exclusion(
@@ -149,6 +157,30 @@ class TestStaleFlagsDetect(BaseTest):
included = any(result.payload["flag_id"] == flag.id for result in results.get(self.team.id, []))
assert included is expected_included
+ def test_a_gate_stored_in_another_project_still_protects_the_flag(self) -> None:
+ # Flag ids are globally unique, so a team can store a flag another project owns. Matching
+ # ids per project would report that flag as a cleanup candidate. The delete guard is
+ # project-scoped too, so nothing else would stop the delete that follows, and the stored
+ # reference would be left unrepairable.
+ flag = self._create_flag("gated-from-another-project", **stale_by_config())
+ other_project_team = Team.objects.create(organization=self.organization)
+ # The scan covers the projects that own candidate flags, so the other project needs one
+ # of its own before the gate it stores is read at all.
+ their_flag = FeatureFlag.objects.create(
+ team=other_project_team, key="their-own-flag", created_by=self.user, active=True, **stale_by_config()
+ )
+ Team.objects.filter(pk=other_project_team.pk).update(
+ session_recording_linked_flag={"id": flag.id, "key": flag.key}
+ )
+
+ results = self._detect([self.team.id, other_project_team.id])
+
+ assert not any(result.payload["flag_id"] == flag.id for result in results.get(self.team.id, []))
+ # Nothing gates `their_flag`: a linked flag contributes its id to `flag_ids` and never its
+ # key to `flag_keys`. It stays reported, so an exclusion that swallowed the whole batch
+ # would fail here.
+ assert any(result.payload["flag_id"] == their_flag.id for result in results.get(other_project_team.id, []))
+
# (name, flag_kwargs, expected payload subset)
@parameterized.expand(
[
diff --git a/products/feature_flags/backend/test/replay_gate_fixtures.py b/products/feature_flags/backend/test/replay_gate_fixtures.py
new file mode 100644
index 000000000000..f9a9e50c4a07
--- /dev/null
+++ b/products/feature_flags/backend/test/replay_gate_fixtures.py
@@ -0,0 +1,29 @@
+"""Builders for the session replay recording gate a team stores on `Team`.
+
+The shape these emit is the contract the production matchers key off, so every suite that needs a
+gated team builds it here rather than keeping its own copy to drift.
+"""
+
+from typing import Any
+
+from posthog.models import Team
+
+
+def trigger_groups(*conditions: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "version": 2,
+ "groups": [
+ {"id": f"group-{index}", "sampleRate": 1, "conditions": {"matchType": "any", **condition}}
+ for index, condition in enumerate(conditions)
+ ],
+ }
+
+
+def set_trigger_groups(team: Team, *conditions: dict[str, Any]) -> None:
+ team.session_recording_trigger_groups = trigger_groups(*conditions)
+ team.save()
+
+
+def set_linked_flag(team: Team, linked_flag: dict[str, Any] | None) -> None:
+ team.session_recording_linked_flag = linked_flag
+ team.save()
diff --git a/products/feature_flags/backend/test/test_session_recording_links.py b/products/feature_flags/backend/test/test_session_recording_links.py
index b2cd26cf0926..6753fa1aa335 100644
--- a/products/feature_flags/backend/test/test_session_recording_links.py
+++ b/products/feature_flags/backend/test/test_session_recording_links.py
@@ -1,92 +1,297 @@
+from typing import Any
+
from posthog.test.base import BaseTest
from unittest.mock import patch
+from parameterized import parameterized
+
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
+from products.feature_flags.backend.session_recording_links import (
+ ReplayGateRewrite,
+ relink_teams,
+ replay_gated_flags,
+ replay_gated_flags_for_projects,
+ rewritten_linked_flag,
+ rewritten_trigger_groups,
+ save_replay_gate_rewrites,
+ teams_gating_replay_on_flag,
+ trigger_group_flag_refs,
+)
+from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag, set_trigger_groups, trigger_groups
+GATED = True
+NOT_GATED = False
-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"}
+class TestReplayGateMatchersAgree(BaseTest):
+ @parameterized.expand(
+ [
+ ("linked_flag_by_id", lambda gate, other: ({"id": gate.id, "key": "stale"}, None), GATED),
+ (
+ "linked_flag_naming_another_flag",
+ lambda gate, other: ({"id": other.id, "key": gate.key}, None),
+ NOT_GATED,
+ ),
+ ("trigger_group_bare_key", lambda gate, other: (None, [{"flag": gate.key}]), GATED),
+ (
+ "trigger_group_object_key",
+ lambda gate, other: (None, [{"flag": {"id": gate.id, "key": gate.key}}]),
+ GATED,
+ ),
+ ("trigger_group_object_without_id", lambda gate, other: (None, [{"flag": {"key": gate.key}}]), GATED),
+ (
+ "trigger_group_stale_key_live_id",
+ lambda gate, other: (None, [{"flag": {"id": gate.id, "key": "stale"}}]),
+ GATED,
+ ),
+ (
+ "trigger_group_float_id",
+ lambda gate, other: (None, [{"flag": {"id": float(gate.id), "key": "stale"}}]),
+ GATED,
+ ),
+ ("trigger_group_naming_another_flag", lambda gate, other: (None, [{"flag": other.key}]), NOT_GATED),
+ ("trigger_group_key_prefix", lambda gate, other: (None, [{"flag": f"{gate.key}-v2"}]), NOT_GATED),
+ ("trigger_group_key_only_in_events", lambda gate, other: (None, [{"events": [gate.key]}]), NOT_GATED),
+ (
+ "trigger_group_without_a_flag",
+ lambda gate, other: (None, [{"urls": [{"url": "/x", "matching": "regex"}]}]),
+ NOT_GATED,
+ ),
+ ("second_group_matches", lambda gate, other: (None, [{"flag": other.key}, {"flag": gate.key}]), GATED),
+ ("nothing_stored", lambda gate, other: (None, None), NOT_GATED),
+ ("empty_groups", lambda gate, other: (None, []), NOT_GATED),
+ ]
+ )
+ def test_both_matchers_agree(self, _name: str, build_gate: Any, expected: bool) -> None:
+ gate_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="unrelated")
+ linked_flag, group_conditions = build_gate(gate_flag, other_flag)
+
+ self.team.session_recording_linked_flag = linked_flag
+ self.team.session_recording_trigger_groups = (
+ None if group_conditions is None else trigger_groups(*group_conditions)
+ )
self.team.save()
- update_linked_flag_key(stale_team, flag.id, "replay-gate-v2")
+ assert teams_gating_replay_on_flag(gate_flag, key=gate_flag.key).exists() is expected
+ assert replay_gated_flags(self.team.project_id).gates(gate_flag) is expected
+
+ def test_both_matchers_ignore_another_project(self) -> None:
+ gate_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ other_project_team = Team.objects.create(organization=self.organization)
+ other_project_team.session_recording_trigger_groups = trigger_groups({"flag": "replay-gate"})
+ other_project_team.save()
+
+ assert teams_gating_replay_on_flag(gate_flag, key=gate_flag.key).exists() is False
+ assert replay_gated_flags(self.team.project_id).gates(gate_flag) is False
+
+ def test_the_multi_project_scan_keeps_each_projects_keys_to_itself(self) -> None:
+ # A flag key names one flag only within its project, so two projects can hold the same
+ # key. A scan that pooled the keys would report each project's flag as gated by the
+ # other project's trigger group.
+ mine = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ other_team = Team.objects.create(organization=self.organization)
+ theirs = FeatureFlag.objects.create(team=other_team, created_by=self.user, key="replay-gate")
+ other_team.session_recording_trigger_groups = trigger_groups({"flag": "replay-gate"})
+ other_team.save()
+
+ gates = replay_gated_flags_for_projects([self.team.project_id, other_team.project_id])
+
+ assert gates[other_team.project_id].gates(theirs) is True
+ assert self.team.project_id not in gates
+ assert replay_gated_flags(self.team.project_id).gates(mine) is False
+
+
+class TestReplayGateWritesUseTheLockedRow(BaseTest):
+ def test_an_edit_to_the_linked_flag_since_the_caller_looked_survives(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-new")
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-old", "variant": "control"})
+
+ set_linked_flag(Team.objects.get(pk=self.team.pk), {"id": flag.id, "key": "gate-old", "variant": "test"})
+
+ save_replay_gate_rewrites(
+ self.team.pk,
+ lambda team: ReplayGateRewrite(
+ linked_flag=rewritten_linked_flag(
+ team.session_recording_linked_flag, flag_id=flag.id, new_key="gate-new"
+ )
+ ),
+ )
self.team.refresh_from_db()
- assert self.team.session_recording_linked_flag == {
- "id": flag.id,
- "key": "replay-gate-v2",
- "variant": "test",
- }
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-new", "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")
+ def test_skips_the_write_when_the_team_now_gates_on_a_different_flag(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-new")
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)
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-old"})
- # 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()
+ set_linked_flag(Team.objects.get(pk=self.team.pk), {"id": other_flag.id, "key": "other-gate"})
- update_linked_flag_key(stale_team, flag.id, "replay-gate-v2")
+ save_replay_gate_rewrites(
+ self.team.pk,
+ lambda team: ReplayGateRewrite(
+ linked_flag=rewritten_linked_flag(
+ team.session_recording_linked_flag, flag_id=flag.id, new_key="gate-new"
+ )
+ ),
+ )
self.team.refresh_from_db()
assert self.team.session_recording_linked_flag == {"id": other_flag.id, "key": "other-gate"}
+ def test_a_group_added_since_the_caller_looked_survives_and_the_rename_moves_its_own_group(self) -> None:
+ set_trigger_groups(self.team, {"flag": "gate-old"})
+
+ # Prepending shifts the reference the rename is about off index 0, so a rewrite keyed by
+ # indices read earlier would move the wrong group.
+ admin = Team.objects.get(pk=self.team.pk)
+ stored = admin.session_recording_trigger_groups
+ stored["groups"].insert(
+ 0, {"id": "added", "sampleRate": 0.5, "conditions": {"matchType": "any", "events": ["signup"]}}
+ )
+ admin.session_recording_trigger_groups = stored
+ admin.save()
+
+ def rewrite(team: Team) -> ReplayGateRewrite:
+ groups = team.session_recording_trigger_groups
+ moving = {ref.group_index: "gate-new" for ref in trigger_group_flag_refs(groups) if ref.key == "gate-old"}
+ return ReplayGateRewrite(trigger_groups=rewritten_trigger_groups(groups, moving))
+
+ save_replay_gate_rewrites(self.team.pk, rewrite)
-class TestRelinkTeams(BaseTest):
- def test_converges_on_the_current_key_despite_a_stale_signal_snapshot(self) -> None:
+ self.team.refresh_from_db()
+ groups = self.team.session_recording_trigger_groups["groups"]
+ assert [group["id"] for group in groups] == ["added", "group-0"]
+ assert groups[0]["conditions"] == {"matchType": "any", "events": ["signup"]}
+ assert groups[1]["conditions"]["flag"] == "gate-new"
+
+
+class TestRelinkTeamsConvergesOnTheStoredKey(BaseTest):
+ def test_a_stale_callback_does_not_put_back_the_key_it_captured(self) -> None:
+ # Renames serialize on the flag row. Their post-commit callbacks do not, so the callback
+ # for gate-a to gate-b can run after gate-b to gate-c has committed and relinked. Taking
+ # the key from the signal's own instance would move both columns back to gate-b, which no
+ # flag holds, and the SDKs stop recording on a key they cannot resolve.
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()
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-a"})
+ set_trigger_groups(self.team, {"flag": "gate-a"})
- relink_teams(stale_flag)
+ stale = FeatureFlag(pk=flag.pk, team=flag.team, key="gate-b")
+ relink_teams(stale, old_key="gate-a")
self.team.refresh_from_db()
assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}
+ assert self.team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == "gate-c"
+
+ def test_a_rename_landing_mid_loop_does_not_strand_the_teams_after_it(self) -> None:
+ # The loop writes one team at a time, so a rename can commit between two of them. A key
+ # read once before the loop leaves every team after that point on a key no flag holds,
+ # which is the state the SDKs read as "do not record".
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-b")
+ later_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-a"})
+ set_linked_flag(later_team, {"id": flag.id, "key": "gate-a"})
+
+ real_save = save_replay_gate_rewrites
+ renamed: list[int] = []
+ def rename_after_the_first_team(team_id: int, compute: Any) -> None:
+ real_save(team_id, compute)
+ if renamed:
+ return
+ renamed.append(team_id)
+ flag.key = "gate-c"
+ with self.captureOnCommitCallbacks(execute=True):
+ flag.save()
+
+ with patch(
+ "products.feature_flags.backend.session_recording_links.save_replay_gate_rewrites",
+ side_effect=rename_after_the_first_team,
+ ):
+ relink_teams(flag, old_key="gate-a")
+
+ for team in (self.team, later_team):
+ team.refresh_from_db()
+ assert team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}
+
+
+class TestRelinkTeamsMovesEveryReferenceNamingTheFlag(BaseTest):
+ def test_a_group_naming_the_flag_by_id_moves_off_a_key_the_flag_never_held(self) -> None:
+ # The SDK resolves a trigger group by key alone, so a group holding a key no flag holds
+ # turns recording off for the team. Only the stored id still says which flag this group
+ # meant. The rename is the last moment it resolves to a key.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-new")
+ other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="other-gate")
+ set_trigger_groups(
+ self.team,
+ {"flag": {"id": flag.id, "key": "stale"}},
+ {"flag": {"id": other.id, "key": "other-gate"}},
+ )
+
+ relink_teams(flag, old_key="gate-old")
+
+ self.team.refresh_from_db()
+ groups = self.team.session_recording_trigger_groups["groups"]
+ assert groups[0]["conditions"]["flag"] == {"id": flag.id, "key": "gate-new"}
+ assert groups[1]["conditions"]["flag"] == {"id": other.id, "key": "other-gate"}
+
+
+class TestRelinkTeamsIsolatesAWriteFailure(BaseTest):
def test_one_teams_write_failure_does_not_strand_its_siblings(self) -> None:
- # relink_teams wraps each team's update in its own try/except so that one row it can't
- # write (a lock timeout, a constraint violation) doesn't stop the rename from reaching
- # every other team gating replay on the same flag.
flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-old")
other_team = Team.objects.create(organization=self.organization, project=self.team.project)
- self.team.session_recording_linked_flag = {"id": flag.id, "key": "gate-old"}
- self.team.save()
- other_team.session_recording_linked_flag = {"id": flag.id, "key": "gate-old"}
- other_team.save()
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-old"})
+ set_linked_flag(other_team, {"id": flag.id, "key": "gate-old"})
- real_update_linked_flag_key = update_linked_flag_key
+ real_save = save_replay_gate_rewrites
+ failed_for: list[int] = []
- def _raise_for_other_team(team: Team, expected_flag_id: int, new_key: str) -> None:
- if team.pk == other_team.pk:
+ # Fails whichever team comes up first, so the assertions hold whatever order the scan
+ # returns them in.
+ def fail_on_the_first_team(team_id: int, compute: Any) -> None:
+ if not failed_for:
+ failed_for.append(team_id)
raise Exception("simulated write failure")
- real_update_linked_flag_key(team, expected_flag_id, new_key)
+ real_save(team_id, compute)
+
+ flag.key = "gate-new"
+ with patch(
+ "products.feature_flags.backend.session_recording_links.save_replay_gate_rewrites",
+ side_effect=fail_on_the_first_team,
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ flag.save()
+
+ assert len(failed_for) == 1
+ stored = {
+ team.pk: team.session_recording_linked_flag
+ for team in Team.objects.filter(pk__in=[self.team.pk, other_team.pk])
+ }
+ stranded = failed_for[0]
+ relinked = ({self.team.pk, other_team.pk} - {stranded}).pop()
+ assert stored[stranded] == {"id": flag.id, "key": "gate-old"}
+ assert stored[relinked] == {"id": flag.id, "key": "gate-new"}
+
+
+class TestRelinkTeamsAbsorbsALookupFailure(BaseTest):
+ def test_a_failed_team_lookup_does_not_fail_the_committed_rename(self) -> None:
+ # The relink runs after the rename has committed, and its own reads sit outside the
+ # per-team handler. A fault in them would reach the caller, so a rename that already
+ # landed would answer with an error the caller cannot act on.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-old")
+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-old"})
flag.key = "gate-new"
with patch(
- "products.feature_flags.backend.session_recording_links.update_linked_flag_key",
- side_effect=_raise_for_other_team,
+ "products.feature_flags.backend.session_recording_links.teams_gating_replay_on_flag",
+ side_effect=Exception("simulated lookup failure"),
):
with self.captureOnCommitCallbacks(execute=True):
flag.save()
+ assert FeatureFlag.objects.get(pk=flag.pk).key == "gate-new"
self.team.refresh_from_db()
- other_team.refresh_from_db()
- assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-new"}
- assert other_team.session_recording_linked_flag == {"id": flag.id, "key": "gate-old"}
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-old"}
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 8f4ef3f2b25a..efe77a80c3d9 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -618,7 +618,7 @@ export interface FeatureFlagApi {
*/
last_called_at?: string | null
_create_in_folder?: string
- /** Check if this feature flag is used in any team's session recording linked flag setting. */
+ /** Check if any team gates session recording on this flag, by linked flag or trigger group. */
readonly is_used_in_replay_settings: boolean
/** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */
readonly is_eligible_for_experiment: boolean
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index f2eb14db75ee..b0e165438d85 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -1538,7 +1538,8 @@ class TestSurvey(APIBaseTest):
format="json",
).json()
- with self.assertNumQueries(20):
+ # Includes one query for the project's replay gates
+ with self.assertNumQueries(21):
response = self.client.get(f"/api/projects/{self.team.id}/feature_flags")
self.assertEqual(response.status_code, status.HTTP_200_OK)
result = response.json()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dcbc15befdcb..d9df2b0be008 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41717,7 +41717,7 @@ export namespace Schemas {
*/
last_called_at?: string | null;
_create_in_folder?: string;
- /** Check if this feature flag is used in any team's session recording linked flag setting. */
+ /** Check if any team gates session recording on this flag, by linked flag or trigger group. */
readonly is_used_in_replay_settings: boolean;
/** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */
readonly is_eligible_for_experiment: boolean;