:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): extend the replay key repair to trigger groups (#89733)
Phil Haackd4fdcf13262c
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.pyindex 149dc211ade0..275e98c18231 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@@ -1,25 +1,29 @@-"""Repair `Team.session_recording_linked_flag` rows whose stored key no longer matches the flag.--Renaming a feature flag used to leave the stored key behind, and the SDKs read the key rather-than the id, so those teams stopped recording sessions entirely. `relink_teams_on_key_change` in-`session_recording_links` now keeps the key in step for every rename that goes through-`FeatureFlag.save()`; this command fixes the rows that were already stale when it was wired up,-plus any left by a writer that bypasses `save()`, such as the `bulk_update` in `bulk_delete`.--Only rows whose stored id resolves to a live flag in the team's own project are rewritten. Rows-pointing at a soft-deleted flag or at a flag in another project are counted and reported but-left alone, because neither has a safe new key to adopt: a human has to decide whether the team-still wants a recording gate at all. 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.+"""Repair a team's session replay recording gate when its stored flag key no longer resolves.++A team can gate recording 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` can store a+`conditions.flag` that holds either a bare key or an object carrying one. The SDKs resolve both by+key, so a stored key that no longer matches its flag silently stops the team recording.+`relink_teams_on_key_change` in `session_recording_links` covers every rename that goes through+`FeatureFlag.save()`. This command repairs the references that predate that receiver, plus any that+a writer bypassing `save()` left behind, such as the `bulk_update` in `bulk_delete`.++The command rewrites only a reference whose stored id resolves to a live flag in the team's own+project. It reports a reference to a soft-deleted flag or to a flag in another project and leaves it+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. A flag soft-deleted between the scan and the write is the one+exception. The write reads each key under the team's row lock, so that team follows the flag onto+its current key. That key is the tombstone key when the soft delete freed the original for a new+flag to claim. The command also reports a bare key that names no live flag and leaves it alone,+because with no id stored beside it, nothing records which flag it meant."""import jsonfrom collections import Counterfrom collections.abc import Iterator-from enum import StrEnum-from typing import Any+from dataclasses import asdict, replace+from enum import Enum, StrEnum, auto+from typing import Any, TypedDict, assert_neverfrom django.core.management.base import BaseCommand, CommandError, CommandParserfrom django.db.models import QuerySet@@ -29,27 +33,38 @@ from posthog.models import Teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.session_recording_links import (+ STORES_A_REPLAY_GATE,ReplayGateRewrite,+ TriggerGroupFlagRef,+ current_flag_keys,rewritten_linked_flag,+ rewritten_trigger_groups,save_replay_gate_rewrites,stored_flag_id,+ trigger_group_flag_refs,+ trigger_groups_readable,)class Outcome(StrEnum):REPAIRED = "repaired"ALREADY_CORRECT = "already_correct"+ # The stored reference moved between the scan and the locked write, so this run neither+ # repaired it nor checked what now stands in its place.+ CHANGED_MID_SCAN = "changed_mid_scan"FLAG_SOFT_DELETED = "flag_soft_deleted"FLAG_IN_OTHER_PROJECT = "flag_in_other_project"FLAG_MISSING = "flag_missing"TEAM_MISSING = "team_missing"+ KEY_UNRESOLVABLE = "key_unresolvable"MALFORMED = "malformed"-@frozen-class _ReplayLinkWrite:- outcome: Outcome- written_key: str | None = None+class Location(StrEnum):+ LINKED_FLAG = "linked_flag"+ # One group's reference, versus a whole trigger groups column too malformed to read one out of.+ TRIGGER_GROUP = "trigger_group"+ TRIGGER_GROUPS_COLUMN = "trigger_groups_column"@frozen@@ -59,10 +74,77 @@ class _FlagRow:project_id: int+@frozen+class _FlagIndex:+ by_id: dict[int, _FlagRow]+ live_keys: set[tuple[int, str]]++ def resolves(self, project_id: int, key: str) -> bool:+ return (project_id, key) in self.live_keys+++class _Unset(Enum):+ """Distinguishes "this field does not apply here" from a stored `None`.++ A group that really has no `id` still has to report `group_id: null` rather than drop the key,+ since that is how a human locates the group. An `Enum` member rather than a bare `object()` so+ the fields it defaults can keep their real types.+ """++ TOKEN = auto()+++_UNSET = _Unset.TOKEN+++@frozen+class _Finding:+ """One reference the scan looked at, and what it found. Serialized straight into the report."""++ outcome: Outcome+ location: Location+ team_id: int+ project_id: int+ stored_flag: Any+ group_index: int | _Unset = _UNSET+ group_id: Any | _Unset = _UNSET+ flag_id: int | _Unset = _UNSET+ old_key: str | None | _Unset = _UNSET+ new_key: str | _Unset = _UNSET++ def written(self, outcome: Outcome, new_key: str | _Unset = _UNSET) -> "_Finding":+ """This finding as the locked write left it, carrying only a key that write really stored."""+ return replace(self, outcome=outcome, new_key=new_key)++ def as_report_row(self) -> dict[str, Any]:+ return {name: value for name, value in asdict(self).items() if value is not _UNSET}++ def describe(self) -> str:+ match self.location:+ case Location.LINKED_FLAG:+ where = "linked flag"+ case Location.TRIGGER_GROUPS_COLUMN:+ where = "trigger groups column"+ case Location.TRIGGER_GROUP:+ where = f"trigger group {self.group_index} (id {self.group_id!r})"+ case _:+ assert_never(self.location)+ return f"team {self.team_id} (project {self.project_id}) {where}"+++class _Resolution(TypedDict, total=False):+ flag_id: int+ old_key: str | None+ new_key: str++def _iter_team_chunks(queryset: QuerySet[Team], chunk_size: int) -> Iterator[list[Team]]:+ # `Team` is a wide model with several large JSONFields. The scan reads only four columns.+ base = queryset.only(+ "id", "project_id", "session_recording_linked_flag", "session_recording_trigger_groups"+ ).order_by("id")# Keyset pagination instead of .iterator(): prod runs behind PgBouncer with server-side# cursors disabled, so .iterator() buffers the whole result set client-side on execute.- base = queryset.order_by("id")last_id = 0while True:chunk = list(base.filter(id__gt=last_id)[:chunk_size])@@ -73,7 +155,7 @@ def _iter_team_chunks(queryset: QuerySet[Team], chunk_size: int) -> Iterator[lisclass Command(BaseCommand):- help = "Rewrite stale flag keys in teams' session replay linked flag settings"+ help = "Rewrite stale flag keys in teams' session replay recording settings"def add_arguments(self, parser: CommandParser) -> None:parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")@@ -93,143 +175,350 @@ class Command(BaseCommand):# looked at nothing.raise CommandError("--chunk-size must be at least 1")- queryset = Team.objects.exclude(session_recording_linked_flag__isnull=True)+ queryset = Team.objects.filter(STORES_A_REPLAY_GATE)if options["team_id"]:queryset = queryset.filter(id__in=options["team_id"])- scanned = 0- # Every row except already_correct, which needs no follow-up and would dwarf the rest.- details: list[dict[str, Any]] = []+ outcomes: Counter[Outcome] = Counter()+ repairs: list[_Finding] = []+ unrepairable: list[_Finding] = []+ scanned_teams = 0for teams in _iter_team_chunks(queryset, chunk_size):- flags_by_id = self._load_flags(teams)+ flags = self._load_flags(teams)for team in teams:- scanned += 1- outcome, detail = self._repair_team(team, flags_by_id, dry_run=dry_run)- if outcome != Outcome.ALREADY_CORRECT:- details.append({"outcome": outcome, **detail})-- outcomes: Counter[Outcome] = Counter(row["outcome"] for row in details)- if already_correct := scanned - len(details):- outcomes[Outcome.ALREADY_CORRECT] = already_correct+ scanned_teams += 1+ for finding in self._scan_team(team, flags, dry_run=dry_run):+ outcomes[finding.outcome] += 1+ if finding.outcome == Outcome.REPAIRED:+ repairs.append(finding)+ elif finding.outcome != Outcome.ALREADY_CORRECT:+ # already_correct rows need no follow-up and would dwarf the report, so+ # the report keeps only their count.+ unrepairable.append(finding)+report = {"dry_run": dry_run,- "scanned": scanned,+ "scanned_teams": scanned_teams,+ "scanned_references": outcomes.total(),"outcomes": dict(outcomes),- "repairs": [row for row in details if row["outcome"] == Outcome.REPAIRED],- "unrepairable": [row for row in details if row["outcome"] != Outcome.REPAIRED],+ "repairs": repairs,+ "unrepairable": unrepairable,}self._report(report, as_json=as_json)- def _load_flags(self, teams: list[Team]) -> dict[int, _FlagRow]:- flag_ids = {- flag_id for team in teams if (flag_id := stored_flag_id(team.session_recording_linked_flag)) is not None- }- if not flag_ids:- return {}- rows = FeatureFlag.objects_including_soft_deleted.filter(id__in=flag_ids).values_list(- "id", "key", "deleted", "team__project_id"- )- return {- flag_id: _FlagRow(key=key, deleted=deleted, project_id=project_id)- for flag_id, key, deleted, project_id in rows- }+ def _load_flags(self, teams: list[Team]) -> _FlagIndex:+ flag_ids: set[int] = set()+ keys: set[str] = set()+ project_ids: set[int] = set()+ for team in teams:+ if (flag_id := stored_flag_id(team.session_recording_linked_flag)) is not None:+ flag_ids.add(flag_id)+ refs = trigger_group_flag_refs(team.session_recording_trigger_groups)+ if refs:+ # Only trigger group references are checked by key. A team adds its project to the+ # live-key query below only when it stores one.+ project_ids.add(team.project_id)+ for ref in refs:+ if ref.flag_id is not None:+ flag_ids.add(ref.flag_id)+ if ref.key is not None:+ keys.add(ref.key)++ by_id: dict[int, _FlagRow] = {}+ if flag_ids:+ # The query includes soft-deleted flags, so the report names a reference to one as+ # soft-deleted rather than as a dangling id.+ rows = FeatureFlag.objects_including_soft_deleted.filter(id__in=flag_ids).values_list(+ "id", "key", "deleted", "team__project_id"+ )+ by_id = {+ flag_id: _FlagRow(key=key, deleted=deleted, project_id=project_id)+ for flag_id, key, deleted, project_id in rows+ }++ live_keys: set[tuple[int, str]] = set()+ if keys:+ # The query asks only for the keys this chunk names. Asking for every live key in these+ # projects would pull tens of thousands of rows for a chunk spanning many of them.+ live_keys = set(+ FeatureFlag.objects.filter(team__project_id__in=project_ids, key__in=keys).values_list(+ "team__project_id", "key"+ )+ )+ return _FlagIndex(by_id=by_id, live_keys=live_keys)++ def _scan_team(self, team: Team, flags: _FlagIndex, *, dry_run: bool) -> list[_Finding]:+ findings = [*self._scan_linked_flag(team, flags), *self._scan_trigger_groups(team, flags)]+ if dry_run:+ # The keys here are the ones the chunk read, not ones this run will write.+ return findings+ return self._write_repairs(team.pk, findings, scanned_trigger_groups=team.session_recording_trigger_groups)++ def _blocked_by(self, *, flag_id: int, project_id: int, flags: _FlagIndex) -> Outcome | None:+ """What stops a stored id resolving to a flag this team can adopt a key from, or None."""+ flag = flags.by_id.get(flag_id)+ if flag is None:+ return Outcome.FLAG_MISSING+ if flag.project_id != project_id:+ return Outcome.FLAG_IN_OTHER_PROJECT+ if flag.deleted:+ return Outcome.FLAG_SOFT_DELETED+ return None- def _repair_team(- self, team: Team, flags_by_id: dict[int, _FlagRow], *, dry_run: bool- ) -> tuple[Outcome, dict[str, Any]]:+ def _scan_linked_flag(self, team: Team, flags: _FlagIndex) -> list[_Finding]:linked_flag = team.session_recording_linked_flag- detail: dict[str, Any] = {"team_id": team.id, "project_id": team.project_id, "linked_flag": linked_flag}+ if linked_flag is None:+ return []++ outcome, resolved = self._classify_linked_flag(linked_flag, team.project_id, flags)+ return [+ _Finding(+ outcome=outcome,+ location=Location.LINKED_FLAG,+ team_id=team.id,+ project_id=team.project_id,+ stored_flag=linked_flag,+ **resolved,+ )+ ]+ def _classify_linked_flag(+ self, linked_flag: Any, project_id: int, flags: _FlagIndex+ ) -> tuple[Outcome, _Resolution]:+ # This column always stores an id, so the classification starts from it. The id names the+ # flag the team meant even after the key has moved on.stored_id = stored_flag_id(linked_flag)if stored_id is None:- return Outcome.MALFORMED, detail+ return Outcome.MALFORMED, {}- detail["flag_id"] = stored_id- flag = flags_by_id.get(stored_id)- if flag is None:- return Outcome.FLAG_MISSING, detail- if flag.project_id != team.project_id:- return Outcome.FLAG_IN_OTHER_PROJECT, detail- if flag.deleted:- return Outcome.FLAG_SOFT_DELETED, detail- if linked_flag.get("key") == flag.key:- return Outcome.ALREADY_CORRECT, detail+ resolved: _Resolution = {"flag_id": stored_id}+ if (blocked := self._blocked_by(flag_id=stored_id, project_id=project_id, flags=flags)) is not None:+ return blocked, resolved- detail["old_key"] = linked_flag.get("key")- 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.+ flag = flags.by_id[stored_id]+ if linked_flag.get("key") == flag.key:+ return Outcome.ALREADY_CORRECT, resolved+ return Outcome.REPAIRED, {**resolved, "old_key": linked_flag.get("key"), "new_key": flag.key}++ def _scan_trigger_groups(self, team: Team, flags: _FlagIndex) -> list[_Finding]:+ trigger_groups = team.session_recording_trigger_groups+ if not trigger_groups:+ # RemoteConfig ignores a falsy column and falls back to the V1 fields, so an empty one+ # gates nothing. Reporting it would only lengthen the list a human has to work through.+ return []++ if not trigger_groups_readable(trigger_groups):+ return [+ _Finding(+ outcome=Outcome.MALFORMED,+ location=Location.TRIGGER_GROUPS_COLUMN,+ team_id=team.id,+ project_id=team.project_id,+ stored_flag=trigger_groups,+ )+ ]++ # `trigger_group_flag_refs` skips an entry that is not an object, so the scan reports it here.+ # The command still repairs the readable groups beside it.+ findings = [+ _Finding(+ outcome=Outcome.MALFORMED,+ location=Location.TRIGGER_GROUP,+ team_id=team.id,+ project_id=team.project_id,+ stored_flag=group,+ group_index=index,+ group_id=None,+ )+ for index, group in enumerate(trigger_groups["groups"])+ if not isinstance(group, dict)+ ]+ for ref in trigger_group_flag_refs(trigger_groups):+ outcome, resolved = self._classify_trigger_group_ref(ref, team.project_id, flags)+ findings.append(+ _Finding(+ outcome=outcome,+ location=Location.TRIGGER_GROUP,+ team_id=team.id,+ project_id=team.project_id,+ stored_flag=ref.stored_flag,+ group_index=ref.group_index,+ group_id=ref.group_id,+ **resolved,+ )+ )+ return findings++ def _classify_trigger_group_ref(+ self, ref: TriggerGroupFlagRef, project_id: int, flags: _FlagIndex+ ) -> tuple[Outcome, _Resolution]:+ resolved: _Resolution = {"flag_id": ref.flag_id} if ref.flag_id is not None else {}++ if ref.key is None:+ return Outcome.MALFORMED, resolved+ key_resolves = flags.resolves(project_id, ref.key)+ if ref.flag_id is None:+ if isinstance(ref.stored_flag, dict) and ref.stored_flag.get("id") is not None:+ # The stored id names a flag, but the scan cannot read it. A match on the key alone+ # would accept whichever flag holds that key now.+ return Outcome.MALFORMED, resolved+ return (Outcome.ALREADY_CORRECT if key_resolves else Outcome.KEY_UNRESOLVABLE), resolved+ if (blocked := self._blocked_by(flag_id=ref.flag_id, project_id=project_id, flags=flags)) is not None:+ # A group copied from another project keeps that project's flag id beside a key that+ # resolves here. A deleted flag's key that resolves belongs to a flag the group never named.+ if blocked is Outcome.FLAG_IN_OTHER_PROJECT and key_resolves:+ return Outcome.ALREADY_CORRECT, resolved+ return blocked, resolved++ new_key = flags.by_id[ref.flag_id].key+ if ref.key == new_key:+ return Outcome.ALREADY_CORRECT, resolved+ # Adopting the id's key moves the gate onto whatever that flag is called now, which can be+ # a different flag than the stale key names today. The id is the stronger reference. The+ # old_key and new_key fields below make the move visible in the report.+ return Outcome.REPAIRED, {**resolved, "old_key": ref.key, "new_key": new_key}++ def _locked_linked_flag_outcome(self, locked_linked_flag: Any, *, flag_id: int, current_key: str) -> Outcome:+ if stored_flag_id(locked_linked_flag) != flag_id:+ return Outcome.CHANGED_MID_SCAN+ if locked_linked_flag.get("key") == current_key:+ # A relink wrote the current key before this run took the lock.+ return Outcome.ALREADY_CORRECT+ return Outcome.REPAIRED++ def _locked_trigger_group_outcome(+ self,+ finding: _Finding,+ ref: TriggerGroupFlagRef | None,+ *,+ flag_id: int,+ current_key: str,+ column_changed: bool,+ ) -> Outcome:+ """What the locked write does with a trigger group reference the scan classed as repairable.++ The match checks the group id and the stored reference as well as the index, so a group+ added, removed or reordered since the scan cannot shift a rewrite onto its neighbour.+ Neither field is enough alone, because a group can store no id and two groups can hold the+ same reference. A group with no id and an identical copy beside it passes both checks, so+ the write repairs a group with no id only while the whole column still matches the scan.+ """+ if ref is None or ref.group_id != finding.group_id or ref.flag_id != flag_id:+ return Outcome.CHANGED_MID_SCAN+ if ref.key == current_key:+ # A relink rewrites the stored reference, so this check runs before the comparison below.+ return Outcome.ALREADY_CORRECT+ if ref.stored_flag != finding.stored_flag:+ return Outcome.CHANGED_MID_SCAN+ if ref.group_id is None and column_changed:+ return Outcome.CHANGED_MID_SCAN+ return Outcome.REPAIRED++ def _write_repairs(self, team_id: int, findings: list[_Finding], *, scanned_trigger_groups: Any) -> list[_Finding]:+ """Rewrite the references the scan classed as repairable, and report what the write did.++ The write reads both the stored reference and the key it should adopt again inside the+ team's row lock, because `_load_flags` reads each key once per chunk and the command can+ write a whole page of teams after that read. A rename that lands in that window has already+ relinked this team. Writing the key the chunk read would then put back a key no flag holds,+ which is the failure this command exists to repair. Reading inside the lock converges on+ the value `relink_teams` writes, because that relink takes this same row lock.++ When an admin edited a reference after the scan, the write skips it and leaves it for the+ next run. The scan classified the finding from a copy that the column no longer holds, so+ rewriting it would put the pre-edit reference back and publish it to the SDKs. The report+ files it as `changed_mid_scan` rather than counting it correct, because this run has+ checked the newly stored reference against no flag key. That reference can be as stale as+ the one the scan classified."""- # `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)+ repairs = [+ (index, finding, finding.flag_id)+ for index, finding in enumerate(findings)+ # Every repairable reference resolved an id to take its new key from, so this narrows+ # the type without dropping any of them.+ if finding.outcome == Outcome.REPAIRED and isinstance(finding.flag_id, int)+ ]+ if not repairs:+ return findings++ # `save_replay_gate_rewrites` skips `rewrite` when the team row is gone, so these+ # team_missing entries remain unless `rewrite` runs and replaces them.+ written = {index: finding.written(Outcome.TEAM_MISSING) for index, finding, _ in repairs}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+ current_keys = current_flag_keys(flag_id for _, _, flag_id in repairs)+ locked_refs = {+ ref.group_index: ref for ref in trigger_group_flag_refs(locked.session_recording_trigger_groups)+ }+ column_changed = locked.session_recording_trigger_groups != scanned_trigger_groups+ linked_flag: dict[str, Any] | None = None+ renames: dict[int, str] = {}++ for index, finding, flag_id in repairs:+ current_key = current_keys.get(flag_id)+ if current_key is None:+ # A hard delete landed in this window and left no key to adopt. Writing the one+ # the chunk read would store a gate the SDKs cannot resolve.+ written[index] = finding.written(Outcome.FLAG_MISSING)+ continue++ # The scan classifies only these two locations as repairable. It reports a whole+ # malformed trigger groups column and never rewrites it.+ if finding.location is Location.LINKED_FLAG:+ locked_linked_flag = locked.session_recording_linked_flag+ outcome = self._locked_linked_flag_outcome(+ locked_linked_flag, flag_id=flag_id, current_key=current_key+ )+ if outcome is Outcome.REPAIRED:+ linked_flag = rewritten_linked_flag(locked_linked_flag, flag_id=flag_id, new_key=current_key)+ else:+ ref = locked_refs.get(finding.group_index) if isinstance(finding.group_index, int) else None+ outcome = self._locked_trigger_group_outcome(+ finding, ref, flag_id=flag_id, current_key=current_key, column_changed=column_changed+ )+ if outcome is Outcome.REPAIRED and ref is not None:+ renames[ref.group_index] = current_key++ written[index] = finding.written(+ outcome, new_key=current_key if outcome is Outcome.REPAIRED else _UNSET+ )++ return ReplayGateRewrite(+ linked_flag=linked_flag,+ trigger_groups=rewritten_trigger_groups(locked.session_recording_trigger_groups, renames),)- 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+ return [written.get(index, finding) for index, finding in enumerate(findings)]def _report(self, report: dict[str, Any], *, as_json: bool) -> None:+ repairs: list[_Finding] = report["repairs"]+ unrepairable: list[_Finding] = report["unrepairable"]+if as_json:- self.stdout.write(json.dumps(report, indent=2, default=str))+ rows = {+ **report,+ "repairs": [finding.as_report_row() for finding in repairs],+ "unrepairable": [finding.as_report_row() for finding in unrepairable],+ }+ self.stdout.write(json.dumps(rows, indent=2, default=str))returnverb = "Would repair" if report["dry_run"] else "Repaired"- self.stdout.write(f"Scanned {report['scanned']} team(s) with a session replay linked flag.")- self.stdout.write(f"{verb} {len(report['repairs'])} team(s):")- for repair in report["repairs"]:- self.stdout.write(- f" team {repair['team_id']} (project {repair['project_id']}): "- f"flag {repair['flag_id']} {repair['old_key']!r} -> {repair['new_key']!r}"- )+ self.stdout.write(+ f"Scanned {report['scanned_teams']} team(s) with session replay gate settings, "+ f"{report['scanned_references']} reference(s)."+ )+ self.stdout.write(f"{verb} {len(repairs)} reference(s):")+ for repair in repairs:+ self.stdout.write(f" {repair.describe()}: flag {repair.flag_id} {repair.old_key!r} -> {repair.new_key!r}")for outcome, count in sorted(report["outcomes"].items()):- if outcome != Outcome.REPAIRED and count:+ if outcome != Outcome.REPAIRED:self.stdout.write(f"{outcome}: {count}")- if report["unrepairable"]:+ if unrepairable:self.stdout.write("Not repaired:")- for row in report["unrepairable"]:- self.stdout.write(- f" team {row['team_id']} (project {row['project_id']}) [{row['outcome']}]: {row['linked_flag']!r}"- )+ for row in unrepairable:+ self.stdout.write(f" {row.describe()} [{row.outcome}]: {row.stored_flag!r}")diff --git a/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py b/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.pyindex c156ae6cdc57..09ecddf2f731 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@@ -1,4 +1,5 @@import json+from collections.abc import Callablefrom io import StringIOfrom typing import Any@@ -14,7 +15,7 @@ from posthog.models import Teamfrom products.feature_flags.backend.management.commands import repair_replay_linked_flag_keys as repair_commandfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag+from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag, set_trigger_groupsclass TestRepairReplayLinkedFlagKeys(BaseTest):@@ -32,6 +33,36 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):)return json.loads(out.getvalue())+ def _run_live_with_edit_before_write(self, edit: Callable[[], object]) -> dict[str, Any]:+ # The edit runs after the chunk read and before the team row lock. A concurrent rename or+ # admin edit can land in that window.+ real_save = repair_command.save_replay_gate_rewrites++ def edit_then_save(team_id: int, compute: Any) -> None:+ edit()+ real_save(team_id, compute)++ with patch.object(repair_command, "save_replay_gate_rewrites", side_effect=edit_then_save):+ return self._run("--live-run", teams=[self.team])++ def _create_unusable_flag(self, outcome: str) -> FeatureFlag:+ if outcome == "flag_soft_deleted":+ return FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2", deleted=True)+ other_project_team = Team.objects.create(organization=self.organization)+ return FeatureFlag.objects.create(team=other_project_team, created_by=self.user, key="replay-gate-v2")++ def _store_gate(self, team: Team, location: str, reference: dict[str, Any]) -> None:+ if location == "linked_flag":+ set_linked_flag(team, reference)+ else:+ set_trigger_groups(team, {"flag": reference})++ def _stored_gate(self, location: str) -> Any:+ self.team.refresh_from_db()+ if location == "linked_flag":+ return self.team.session_recording_linked_flag+ return self.team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"]+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")set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate", "variant": "control"})@@ -42,9 +73,10 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):assert report["repairs"] == [{"outcome": "repaired",+ "location": "linked_flag","team_id": self.team.id,"project_id": self.team.project_id,- "linked_flag": {"id": flag.id, "key": "replay-gate", "variant": "control"},+ "stored_flag": {"id": flag.id, "key": "replay-gate", "variant": "control"},"flag_id": flag.id,"old_key": "replay-gate","new_key": "replay-gate-v2",@@ -57,11 +89,10 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):"variant": "control",}- assert self._run("--live-run", teams=[self.team])["outcomes"] == {"already_correct": 1}+ # A dry run, because a live run's locked write relabels the finding whatever the scan said.+ assert self._run(teams=[self.team])["outcomes"] == {"already_correct": 1}def test_reports_the_repair_without_writing_unless_asked(self) -> None:- # Writing has to be opted into: a bare run rewrites every team's replay config and- # enqueues a RemoteConfig rebuild per row.flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate"})@@ -72,40 +103,9 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):self.team.refresh_from_db()assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate"}- @parameterized.expand(- [- ("flag_soft_deleted", "flag_soft_deleted"),- ("flag_in_other_project", "flag_in_other_project"),- ("flag_missing", "flag_missing"),- ("missing_id", "malformed"),- ("bool_id", "malformed"),- ("non_numeric_id", "malformed"),- ]- )- def test_leaves_links_it_cannot_safely_repair_alone(self, case: str, outcome: str) -> None:+ def _assert_link_survives(self, linked_flag: dict[str, Any], outcome: str) -> None:# Clearing an unrepairable link would remove the recording gate, taking a team from- # recording a filtered subset to recording every session. `bool` subclasses `int`, so- # without the explicit guard `{"id": true}` would repair the team against flag 1.- linked_flag: dict[str, Any]- if case == "flag_missing":- linked_flag = {"id": 987654321, "key": "replay-gate"}- elif case == "missing_id":- linked_flag = {"key": "replay-gate"}- elif case == "bool_id":- linked_flag = {"id": True, "key": "replay-gate"}- elif case == "non_numeric_id":- linked_flag = {"id": "abc", "key": "replay-gate"}- else:- flag_team = (- self.team if case == "flag_soft_deleted" else Team.objects.create(organization=self.organization)- )- flag = FeatureFlag.objects.create(- team=flag_team,- created_by=self.user,- key="replay-gate-v2",- deleted=case == "flag_soft_deleted",- )- linked_flag = {"id": flag.id, "key": "replay-gate"}+ # recording a filtered subset to recording every session.set_linked_flag(self.team, linked_flag)# `--live-run` so the row surviving proves the command declined to rewrite it, rather than@@ -117,6 +117,25 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):self.team.refresh_from_db()assert self.team.session_recording_linked_flag == linked_flag+ @parameterized.expand(+ [+ ("missing_id", {"key": "replay-gate"}, "malformed"),+ # `bool` subclasses `int`, so without the explicit guard this would repair against flag 1.+ ("bool_id", {"id": True, "key": "replay-gate"}, "malformed"),+ ("non_numeric_id", {"id": "abc", "key": "replay-gate"}, "malformed"),+ ("flag_missing", {"id": 987654321, "key": "replay-gate"}, "flag_missing"),+ ]+ )+ def test_leaves_malformed_or_dangling_links_alone(+ self, _name: str, linked_flag: dict[str, Any], outcome: str+ ) -> None:+ self._assert_link_survives(linked_flag, outcome)++ @parameterized.expand([("flag_soft_deleted",), ("flag_in_other_project",)])+ def test_leaves_links_to_unusable_flags_alone(self, outcome: str) -> None:+ flag = self._create_unusable_flag(outcome)+ self._assert_link_survives({"id": flag.id, "key": "replay-gate"}, outcome)+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")@@ -128,53 +147,56 @@ 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:+ @parameterized.expand([("linked_flag",), ("trigger_group",)])+ def test_a_rename_landing_mid_scan_is_not_written_back(self, location: str) -> 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"})+ self._store_gate(self.team, location, {"id": flag.id, "key": "gate-a"})- real_save = repair_command.save_replay_gate_rewrites-- def rename_then_save(team_id: int, compute: Any) -> None:+ def rename() -> 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])+ report = self._run_live_with_edit_before_write(rename)- self.team.refresh_from_db()- assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}+ assert self._stored_gate(location) == {"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:+ @parameterized.expand(+ [+ ("linked_flag_to_a_current_key", "linked_flag", "other-current"),+ ("linked_flag_to_a_stale_key", "linked_flag", "other-stale"),+ ("trigger_group_to_a_current_key", "trigger_group", "other-current"),+ ]+ )+ def test_a_repoint_mid_scan_is_reported_as_changed_rather_than_repaired(+ self, _name: str, location: str, repointed_key: str+ ) -> 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.+ # That edit is not this command's to touch. Reporting a repair here would name a key the+ # team does not hold, on a flag it no longer points at. The report still lists the team.+ # Whether the key that lands happens to be current makes no difference, because this run+ # checked it against no flag. Counting it correct would hide a team that is still not+ # recording.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+ self._store_gate(self.team, location, {"id": stale_flag.id, "key": "gate-stale"})+ repointed = {"id": other_flag.id, "key": repointed_key}- 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])+ report = self._run_live_with_edit_before_write(+ lambda: self._store_gate(Team.objects.get(pk=self.team.pk), location, repointed)+ )- self.team.refresh_from_db()- assert self.team.session_recording_linked_flag == {"id": other_flag.id, "key": "other-current"}+ assert self._stored_gate(location) == repointedassert report["repairs"] == []+ assert report["outcomes"] == {"changed_mid_scan": 1}+ assert report["unrepairable"][0]["location"] == locationdef 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@@ -183,14 +205,9 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):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])+ report = self._run_live_with_edit_before_write(+ lambda: FeatureFlag.objects_including_soft_deleted.filter(pk=flag.id).delete()+ )self.team.refresh_from_db()assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-stale"}@@ -202,11 +219,17 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):# 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")+ set_linked_flag(self.team, {"id": flag.id, "key": "gate-stale"})+ command = repair_command.Command()+ findings = command._scan_linked_flag(self.team, command._load_flags([self.team]))- write = repair_command.Command()._write_current_key(team_id=self.team.pk + 10_000_000, flag_id=flag.id)+ written = command._write_repairs(+ self.team.pk + 10_000_000, findings, scanned_trigger_groups=self.team.session_recording_trigger_groups+ )- assert write.outcome == repair_command.Outcome.TEAM_MISSING- assert write.written_key is None+ assert [finding.outcome for finding in written] == [repair_command.Outcome.TEAM_MISSING]+ # A key it never wrote has no place in the report.+ assert "new_key" not in written[0].as_report_row()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@@ -230,3 +253,309 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):# zero teams instead of failing loudly.with self.assertRaises(CommandError):self._run("--live-run", "--chunk-size", "0", teams=[self.team])++ @parameterized.expand([("old_key_free", False), ("old_key_claimed_by_another_flag", True)])+ def test_repairs_a_trigger_group_key_and_names_the_group_it_fixed(self, _name: str, old_key_claimed: bool) -> None:+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ if old_key_claimed:+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")+ set_trigger_groups(+ self.team,+ {"events": ["$pageview"]},+ {"flag": {"id": flag.id, "key": "replay-gate", "variant": "control"}},+ )++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"repaired": 1}+ assert report["repairs"] == [+ {+ "outcome": "repaired",+ "location": "trigger_group",+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "group_index": 1,+ "group_id": "group-1",+ "stored_flag": {"id": flag.id, "key": "replay-gate", "variant": "control"},+ "flag_id": flag.id,+ "old_key": "replay-gate",+ "new_key": "replay-gate-v2",+ }+ ]+ self.team.refresh_from_db()+ assert self.team.session_recording_trigger_groups["groups"][1]["conditions"]["flag"] == {+ "id": flag.id,+ "key": "replay-gate-v2",+ "variant": "control",+ }++ # A dry run, because a live run's locked write relabels the finding whatever the scan said.+ assert self._run(teams=[self.team])["outcomes"] == {"already_correct": 1}++ def test_reports_a_group_that_stores_no_id_of_its_own(self) -> None:+ # `group_index: 0` and `group_id: null` are how a human finds the group in a team with+ # several. One is falsy and the other is None, so both have to survive into the row.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ self.team.session_recording_trigger_groups = {+ "version": 2,+ "groups": [{"sampleRate": 1, "conditions": {"flag": {"id": flag.id, "key": "replay-gate"}}}],+ }+ self.team.save()++ report = self._run("--live-run", teams=[self.team])++ assert report["repairs"] == [+ {+ "outcome": "repaired",+ "location": "trigger_group",+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "group_index": 0,+ "group_id": None,+ "stored_flag": {"id": flag.id, "key": "replay-gate"},+ "flag_id": flag.id,+ "old_key": "replay-gate",+ "new_key": "replay-gate-v2",+ }+ ]++ def test_reports_an_unreadable_trigger_groups_column_without_touching_it(self) -> None:+ # The column is schemaless, so a row predating the validator can hold anything. Indexing+ # into it would abort a fleet-wide sweep part way, after it had already written.+ stored = {"version": 2, "groups": "not-a-list"}+ self.team.session_recording_trigger_groups = stored+ self.team.save()++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"malformed": 1}+ assert report["unrepairable"] == [+ {+ "outcome": "malformed",+ "location": "trigger_groups_column",+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "stored_flag": stored,+ }+ ]+ self.team.refresh_from_db()+ assert self.team.session_recording_trigger_groups == stored++ def test_reports_a_group_entry_that_is_not_an_object_and_repairs_its_siblings(self) -> None:+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ readable_group = {"id": "group-1", "conditions": {"flag": {"id": flag.id, "key": "replay-gate"}}}+ self.team.session_recording_trigger_groups = {"version": 2, "groups": ["not-a-group", readable_group]}+ self.team.save()++ prose = StringIO()+ call_command("repair_replay_linked_flag_keys", "--team-id", str(self.team.id), stdout=prose)+ assert f"trigger group 1 (id 'group-1'): flag {flag.id} 'replay-gate' -> 'replay-gate-v2'" in prose.getvalue()+ assert "trigger group 0 (id None) [malformed]: 'not-a-group'" in prose.getvalue()++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"malformed": 1, "repaired": 1}+ assert report["unrepairable"] == [+ {+ "outcome": "malformed",+ "location": "trigger_group",+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "group_index": 0,+ "group_id": None,+ "stored_flag": "not-a-group",+ }+ ]+ self.team.refresh_from_db()+ groups = self.team.session_recording_trigger_groups["groups"]+ assert groups[0] == "not-a-group"+ assert groups[1]["conditions"]["flag"] == {"id": flag.id, "key": "replay-gate-v2"}++ @parameterized.expand(+ [+ # The key is what the SDK resolves, so a reference without one gates nothing. These+ # cases pin that the scan gives up here and does not fall back to the stored id.+ ("object_with_no_key", {"id": 1}, "malformed"),+ ("empty_key", "", "malformed"),+ ("string_id", {"id": "123", "key": "live-gate"}, "malformed"),+ # A bare key stores no id, so nothing records which flag it meant. Guessing a rewrite+ # would move the gate onto an unrelated flag. Clearing it would record every session.+ ("bare_key_naming_no_live_flag", "replay-gate", "key_unresolvable"),+ ]+ )+ def test_reports_a_trigger_group_reference_it_cannot_resolve_without_touching_it(+ self, _name: str, stored_flag: Any, outcome: str+ ) -> None:+ # A plain soft delete keeps the key. The SDKs cannot resolve a deleted flag.+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate", deleted=True)+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="live-gate")+ set_trigger_groups(self.team, {"flag": stored_flag})+ stored_before = self.team.session_recording_trigger_groups++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {outcome: 1}+ assert report["unrepairable"][0]["location"] == "trigger_group"+ assert report["unrepairable"][0]["stored_flag"] == stored_flag+ self.team.refresh_from_db()+ assert self.team.session_recording_trigger_groups == stored_before++ @parameterized.expand(+ [+ ("bare_key_resolves", {"flag": "replay-gate"}, {"already_correct": 1}),+ # Most groups gate on events or URLs. Counting those as references would hide the ones+ # that actually need a human.+ ("group_gates_on_no_flag", {"events": ["$pageview"]}, {}),+ ]+ )+ def test_stays_quiet_about_healthy_trigger_groups(+ self, _name: str, conditions: dict[str, Any], expected_outcomes: dict[str, int]+ ) -> None:+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")+ set_trigger_groups(self.team, conditions)++ assert self._run("--live-run", teams=[self.team])["outcomes"] == expected_outcomes++ def test_a_key_live_in_another_project_does_not_resolve_this_projects_group(self) -> None:+ # One run scans both teams, so the key probe returns the other project's flag too.+ other_project_team = Team.objects.create(organization=self.organization)+ FeatureFlag.objects.create(team=other_project_team, created_by=self.user, key="replay-gate")+ set_trigger_groups(self.team, {"flag": "replay-gate"})+ set_trigger_groups(other_project_team, {"flag": "replay-gate"})++ report = self._run(teams=[self.team, other_project_team])++ assert report["outcomes"] == {"already_correct": 1, "key_unresolvable": 1}+ assert [row["team_id"] for row in report["unrepairable"]] == [self.team.id]++ def test_repairs_one_group_without_moving_a_sibling_it_could_not_resolve(self) -> None:+ # Both groups name the same stale key, but only one stores an id to repair from. Moving the+ # other would rewrite a reference the report hands to a human as untouched.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ set_trigger_groups(+ self.team,+ {"flag": {"id": flag.id, "key": "replay-gate"}},+ {"flag": "replay-gate"},+ )++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"repaired": 1, "key_unresolvable": 1}+ self.team.refresh_from_db()+ groups = self.team.session_recording_trigger_groups["groups"]+ assert groups[0]["conditions"]["flag"] == {"id": flag.id, "key": "replay-gate-v2"}+ assert groups[1]["conditions"]["flag"] == "replay-gate"++ def test_repairs_groups_sharing_a_stale_key_to_their_own_flags(self) -> None:+ # The groups' ids name different flags. Resolving the stale key once per team would point+ # both gates at whichever flag the command looked up first and silently retarget the other.+ alpha = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="alpha-now")+ beta = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="beta-now")+ set_trigger_groups(+ self.team,+ {"flag": {"id": alpha.id, "key": "shared-stale"}},+ {"flag": {"id": beta.id, "key": "shared-stale"}},+ )++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"repaired": 2}+ assert [repair["new_key"] for repair in report["repairs"]] == ["alpha-now", "beta-now"]+ self.team.refresh_from_db()+ groups = self.team.session_recording_trigger_groups["groups"]+ assert groups[0]["conditions"]["flag"] == {"id": alpha.id, "key": "alpha-now"}+ assert groups[1]["conditions"]["flag"] == {"id": beta.id, "key": "beta-now"}++ @parameterized.expand(+ [+ ("soft_deleted", "flag_soft_deleted", False, "flag_soft_deleted"),+ ("in_other_project", "flag_in_other_project", False, "flag_in_other_project"),+ ("soft_deleted_key_now_live", "flag_soft_deleted", True, "flag_soft_deleted"),+ ("other_project_key_live_here", "flag_in_other_project", True, "already_correct"),+ ]+ )+ def test_leaves_trigger_groups_naming_unusable_flags_alone(+ self, _name: str, unusable: str, live_flag_holds_key: bool, outcome: str+ ) -> None:+ # The group stores the key that the unusable flag held. A check that compared keys before it+ # checked the flag would miss the block.+ flag = self._create_unusable_flag(unusable)+ if live_flag_holds_key:+ # The API renames a soft-deleted flag before another flag takes its key. A queryset+ # update skips the relink that rename runs, which is the failure this case covers.+ FeatureFlag.objects_including_soft_deleted.filter(pk=flag.pk).update(key=flag.tombstoned_key())+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ set_trigger_groups(self.team, {"flag": {"id": flag.id, "key": "replay-gate-v2"}})+ stored_before = self.team.session_recording_trigger_groups++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {outcome: 1}+ self.team.refresh_from_db()+ assert self.team.session_recording_trigger_groups == stored_before++ @parameterized.expand(+ [+ ("gates_on_events", False, True),+ ("holds_the_same_reference", True, True),+ ("holds_the_same_reference_with_null_group_ids", True, False),+ ]+ )+ def test_a_group_added_mid_scan_does_not_shift_the_repair_onto_its_neighbour(+ self, _name: str, inserted_group_duplicates_the_reference: bool, groups_store_ids: bool+ ) -> None:+ # The command rewrites groups by index. An admin can add a group ahead of the repaired one+ # between the chunk read and the lock. Writing the scanned index then would move the gate+ # of a group this run never looked at. A sibling that holds the same reference would take+ # the rewrite while the report still names the scanned group, which stays stale.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ stored_flag = {"id": flag.id, "key": "replay-gate"}+ set_trigger_groups(self.team, {"flag": stored_flag})+ if not groups_store_ids:+ for group in self.team.session_recording_trigger_groups["groups"]:+ group["id"] = None+ self.team.save()+ scanned_groups = self.team.session_recording_trigger_groups["groups"]+ inserted_conditions: dict[str, Any] = (+ {"flag": stored_flag} if inserted_group_duplicates_the_reference else {"events": ["$pageview"]}+ )+ # This builds the groups by hand rather than through the fixture, because an admin who+ # inserts a group does not renumber the ids of the groups after it.+ after_insert = [+ {+ "id": "group-inserted" if groups_store_ids else None,+ "sampleRate": 1,+ "conditions": {"matchType": "any", **inserted_conditions},+ },+ *scanned_groups,+ ]++ def prepend_group() -> None:+ admin = Team.objects.get(pk=self.team.pk)+ admin.session_recording_trigger_groups = {"version": 2, "groups": after_insert}+ admin.save()++ report = self._run_live_with_edit_before_write(prepend_group)++ assert report["repairs"] == []+ assert report["outcomes"] == {"changed_mid_scan": 1}+ self.team.refresh_from_db()+ # Every group keeps its stale key, and the report marks the scanned group as untouched.+ # The next run repairs each group where it now sits.+ assert self.team.session_recording_trigger_groups["groups"] == after_insert++ def test_repairs_both_kinds_of_reference_in_one_pass(self) -> None:+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")+ set_linked_flag(self.team, {"id": flag.id, "key": "replay-gate"})+ set_trigger_groups(self.team, {"flag": {"id": flag.id, "key": "replay-gate"}})++ report = self._run("--live-run", teams=[self.team])++ assert report["outcomes"] == {"repaired": 2}+ assert {finding["location"] for finding in report["repairs"]} == {"linked_flag", "trigger_group"}+ self.team.refresh_from_db()+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}+ assert self.team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == {+ "id": flag.id,+ "key": "replay-gate-v2",+ }diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.pyindex 55d67f10a281..e9ca40e4b7ef 100644--- a/products/feature_flags/backend/session_recording_links.py+++ b/products/feature_flags/backend/session_recording_links.py@@ -14,7 +14,7 @@ matcher here is project-scoped."""from collections import defaultdict-from collections.abc import Callable, Collection, Mapping+from collections.abc import Callable, Collection, Iterable, Mappingfrom typing import Anyfrom django.db import transaction@@ -37,12 +37,19 @@ REPLAY_GATE_DELETE_ERROR = ("This feature flag is used in session replay settings. Please remove it from replay settings before deleting.")+# Matches a team that stores a recording gate in either column. The repair command and+# `replay_gated_flags_for_projects` share it, so both always visit the same teams.+STORES_A_REPLAY_GATE = Q(session_recording_linked_flag__isnull=False) | Q(+ session_recording_trigger_groups__isnull=False+)+@frozenclass TriggerGroupFlagRef:"""One trigger group's reference to a feature flag, and where in the stored config it sits."""group_index: int+ group_id: Anystored_flag: Anykey: str | Noneflag_id: int | None@@ -107,13 +114,20 @@ def _trigger_group_flag_key(stored_flag: Any) -> str | None:return None+def trigger_groups_readable(trigger_groups: Any) -> bool:+ """Whether a stored trigger groups column is shaped well enough to read references out of."""+ return isinstance(trigger_groups, dict) and isinstance(trigger_groups.get("groups"), list)++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.+ a reference to act on. `trigger_groups_readable` tells those two apart for the one caller that+ reports on the stored shape. A group with no `conditions.flag` yields nothing. Most groups gate+ on events or URLs instead. Counting them would hide the references that need attention."""- if not isinstance(trigger_groups, dict) or not isinstance(trigger_groups.get("groups"), list):+ if not trigger_groups_readable(trigger_groups):return []groups = trigger_groups["groups"]@@ -126,6 +140,7 @@ def trigger_group_flag_refs(trigger_groups: Any) -> list[TriggerGroupFlagRef]:refs.append(TriggerGroupFlagRef(group_index=index,+ group_id=group.get("id"),stored_flag=stored_flag,key=_trigger_group_flag_key(stored_flag),flag_id=stored_flag_id(stored_flag),@@ -178,10 +193,9 @@ def replay_gated_flags_for_projects(project_ids: Collection[int]) -> Mapping[intin one project match a same-keyed flag in another. A project that gates on nothing is absentfrom the result rather than present and empty."""- stored = Team.objects.filter(- Q(session_recording_linked_flag__isnull=False) | Q(session_recording_trigger_groups__isnull=False),- project_id__in=project_ids,- ).values_list("project_id", "session_recording_linked_flag", "session_recording_trigger_groups")+ stored = Team.objects.filter(STORES_A_REPLAY_GATE, project_id__in=project_ids).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)@@ -213,6 +227,17 @@ def rewritten_linked_flag(linked_flag: Any, *, flag_id: int, new_key: str) -> direturn {**linked_flag, "key": new_key}+def current_flag_keys(flag_ids: Iterable[int]) -> dict[int, str]:+ """Each flag's key as it stands right now. A flag absent from the result has been hard-deleted.++ The query includes soft-deleted flags, so a team follows a soft delete onto 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. A team left on the original key would gate recording on a flag it+ never linked.+ """+ return dict(FeatureFlag.objects_including_soft_deleted.filter(pk__in=set(flag_ids)).values_list("pk", "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.@@ -301,8 +326,8 @@ def relink_teams(feature_flag: FeatureFlag, *, old_key: str) -> None: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.+ # would fail a request that already succeeded. `repair_replay_linked_flag_keys` repairs+ # the linked flag column and every trigger group that stores an id on its next run.logger.exception("replay_relink_lookup_failed", flag_id=feature_flag.pk)capture_exception()return@@ -314,22 +339,17 @@ def relink_teams(feature_flag: FeatureFlag, *, old_key: str) -> None:# 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()- )+ new_key = current_flag_keys([feature_flag.pk]).get(feature_flag.pk)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.+ # team whose group names this flag by id while holding a key the flag no longer has. A+ # bare string reference carries no id, so it moves on its key alone. A bare key skipped+ # here keeps the stale key for good, because `repair_replay_linked_flag_keys` repairs only+ # a group that stores an id.moving = {ref.group_index: new_keyfor ref in trigger_group_flag_refs(trigger_groups)@@ -347,8 +367,9 @@ def relink_teams(feature_flag: FeatureFlag, *, old_key: str) -> None: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. `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.+ # already succeeded. `repair_replay_linked_flag_keys` repairs the linked flag column+ # and every trigger group that stores an id on its next run. A bare key left here+ # stays stale.logger.exception("replay_relink_failed", flag_id=feature_flag.pk, team_id=team_id)capture_exception()