: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
perf(experiments): Implement properties-free person resolution for faster freeze/unfreeze (#69650)
Marcel Poelker67fb2709ada4
diff --git a/posthog/models/person/test/test_util_personhog.py b/posthog/models/person/test/test_util_personhog.pyindex fa8e0e328cff..e9a46e493b69 100644--- a/posthog/models/person/test/test_util_personhog.py+++ b/posthog/models/person/test/test_util_personhog.py@@ -11,6 +11,7 @@ from posthog.models.person.util import (_fetch_persons_by_uuids_via_personhog,_validate_uuids_via_personhog,get_person_by_pk_or_uuid,+ get_person_ids_and_uuids_by_uuids,get_person_uuids_by_distinct_ids,get_persons_mapped_by_distinct_id,)@@ -335,6 +336,51 @@ class TestValidateUuidsViaPersonhog(SimpleTestCase):assert result == []fake.assert_called("get_persons_by_uuids")+ def test_sends_uuid_only_field_mask(self):+ # Existence checks must never pull full person rows — the mask keeps (potentially+ # huge) person properties out of the RPC payloads.+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])++ _validate_uuids_via_personhog(team_id=1, uuids=["uuid-1"])++ calls = fake.assert_called("get_persons_by_uuids", times=1)+ mask = list(calls[0].request.read_options.field_mask)+ assert "uuid" in mask+ assert "id" in mask+ assert "team_id" in mask+ assert "properties" not in mask+++class TestGetPersonIdsAndUuidsByUuids(SimpleTestCase):+ def test_returns_pairs_for_matching_uuids_and_skips_missing(self):+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])+ fake.add_person(team_id=1, person_id=2, uuid="uuid-2", distinct_ids=["d2"])++ result = get_person_ids_and_uuids_by_uuids(1, ["uuid-1", "uuid-2", "uuid-missing"])++ assert result == [(1, "uuid-1"), (2, "uuid-2")]+ fake.assert_not_called("get_distinct_ids_for_persons")++ def test_returns_empty_list_for_empty_input(self):+ with fake_personhog_client() as fake:+ assert get_person_ids_and_uuids_by_uuids(1, []) == []+ fake.assert_not_called("get_persons_by_uuids")++ def test_sends_uuid_only_field_mask(self):+ with fake_personhog_client() as fake:+ fake.add_person(team_id=1, person_id=1, uuid="uuid-1", distinct_ids=["d1"])++ get_person_ids_and_uuids_by_uuids(1, ["uuid-1"])++ calls = fake.assert_called("get_persons_by_uuids", times=1)+ mask = list(calls[0].request.read_options.field_mask)+ assert "uuid" in mask+ assert "id" in mask+ assert "team_id" in mask+ assert "properties" not in mask+# ── Delegation tests ────────────────────────────────────────────────diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex 6a84dee22260..28c83b71d79a 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -56,12 +56,15 @@ def _batched_get_persons_by_uuids(team_id: int,uuids: list[str],operation: str,+ read_options: ReadOptions | None = None,) -> list[person_pb2.Person]:client = _get_client()valid_persons: list[person_pb2.Person] = []for i in range(0, len(uuids), PERSONHOG_BATCH_SIZE):batch = uuids[i : i + PERSONHOG_BATCH_SIZE]- resp = client.get_persons_by_uuids(GetPersonsByUuidsRequest(team_id=team_id, uuids=batch))+ resp = client.get_persons_by_uuids(+ GetPersonsByUuidsRequest(team_id=team_id, uuids=batch, read_options=read_options)+ )present_persons = [p for p in resp.persons if p.id]batch_valid = [p for p in present_persons if p.team_id == team_id]@@ -466,10 +469,17 @@ def get_person_by_pk_or_uuid(team_id: int, key: str, *, distinct_id_limit: int |return None+_UUID_ONLY_READ_OPTIONS = ReadOptions(field_mask=["uuid", "id", "team_id"])++def _validate_uuids_via_personhog(team_id: int, uuids: list[str]) -> list[str]:# _batched_get_persons_by_uuids also filters out persons with id == 0 (server "not found" sentinel),# which the previous single-RPC implementation did not do. This is intentionally more correct.- valid_persons = _batched_get_persons_by_uuids(team_id, uuids, "validate_person_uuids_exist")+ # Existence only needs uuid/id/team_id — the field mask keeps (potentially huge) person+ # properties out of the RPC payloads.+ valid_persons = _batched_get_persons_by_uuids(+ team_id, uuids, "validate_person_uuids_exist", read_options=_UUID_ONLY_READ_OPTIONS+ )return [p.uuid for p in valid_persons]@@ -480,7 +490,26 @@ def validate_person_uuids_exist(team_id: int, uuids: list[str]) -> list[str]:)-_UUID_ONLY_READ_OPTIONS = ReadOptions(field_mask=["uuid", "id", "team_id"])+def get_person_ids_and_uuids_by_uuids(team_id: int, uuids: list[str]) -> list[tuple[int, str]]:+ """Return (person_id, person_uuid) pairs for the given person UUIDs; unknown UUIDs are omitted.++ Lightweight variant of ``get_persons_by_uuids`` — uses field masking to skip fetching+ properties and other heavy fields, and never fetches distinct IDs. For callers that only+ need to resolve UUIDs to person IDs (e.g. cohort membership writes).+ """+ if not uuids:+ return []++ def personhog_fn() -> list[tuple[int, str]]:+ persons = _batched_get_persons_by_uuids(+ team_id, uuids, "get_person_ids_and_uuids_by_uuids", read_options=_UUID_ONLY_READ_OPTIONS+ )+ return [(p.id, p.uuid) for p in persons]++ return personhog_call(+ "get_person_ids_and_uuids_by_uuids",+ personhog_fn,+ )def get_person_uuids_by_distinct_ids(team_id: int, distinct_ids: list[str]) -> list[str]:diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 1f2ad5c09957..bf026373f487 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -492,6 +492,7 @@'_get_uuids_for_emails_batch_ch','_has_filter_type','_insert_batch_via_personhog',+ '_insert_resolved_batch','_insert_users_list_with_batching','_meta','_safe_reset_calculating_state',@@ -514,6 +515,7 @@'id','insert_users_by_email','insert_users_by_list',+ 'insert_users_list_by_id_uuid_pairs_skip_validation','insert_users_list_by_uuid','insert_users_list_by_uuid_into_pg_only','is_calculating',diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.pyindex 84b916a54920..37a947f99ce8 100644--- a/posthog/test/test_cohort_model.py+++ b/posthog/test/test_cohort_model.py@@ -358,6 +358,23 @@ class TestCohort(BaseTest):member_ids = list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.pk)cohort_person_uuids = {str(_require_person_by_id(self.team.id, pid).uuid) for pid in member_ids}assert cohort_person_uuids == set(uuids)++ def test_insert_users_list_by_id_uuid_pairs_skip_validation(self):+ persons = [create_person(team=self.team) for _ in range(5)]+ pairs = [(person.id, str(person.uuid)) for person in persons]+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)++ cohort.insert_users_list_by_id_uuid_pairs_skip_validation(pairs, team_id=self.team.id)++ cohort.refresh_from_db()+ assert cohort.count == 5+ assert set(list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.pk)) == {p.id for p in persons}+ # The members must also land in the ClickHouse static cohort table, keyed by uuid.+ ch_rows = sync_execute(+ "SELECT person_id FROM person_static_cohort WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s",+ {"team_id": self.team.id, "cohort_id": cohort.pk},+ )+ assert {str(row[0]) for row in ch_rows} == {str(p.uuid) for p in persons}assert cohort.is_calculating is Falsedef test_insert_users_by_list_avoids_duplicates_with_batching(self):diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 8de2a0c60978..2867f70217b7 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -1,8 +1,10 @@import reimport time+from collections.abc import Callablefrom datetime import datetimefrom enum import StrEnumfrom typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast+from uuid import UUIDfrom django.conf import settingsfrom django.contrib.postgres.indexes import GinIndex@@ -26,7 +28,7 @@ from posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentationfrom posthog.models.filters.filter import Filterfrom posthog.models.person import Person-from posthog.models.person.util import get_person_by_uuid+from posthog.models.person.util import get_person_by_uuid, get_person_ids_and_uuids_by_uuidsfrom posthog.models.property import Property, PropertyGroupfrom posthog.models.utils import RootTeamManager, RootTeamMixin, sane_reprfrom posthog.personhog_client.caller_tag import personhog_caller_tag@@ -522,6 +524,42 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error)+ def insert_users_list_by_id_uuid_pairs_skip_validation(+ self,+ items: list[tuple[int, str]],+ *,+ team_id: int,+ raise_on_error: bool = False,+ ) -> int:+ """+ Insert already-resolved (person_id, person_uuid) members into the cohort, for the given team.++ Skips the per-batch UUID → person id resolution that ``insert_users_list_by_uuid``+ performs — for callers that resolved the persons themselves (e.g. a validation pass over+ the same set) and must not pay for a second personhog lookup. Semantics otherwise match+ ``insert_users_list_by_uuid``, including ``raise_on_error``.++ The ``_skip_validation`` suffix is the tenant-isolation contract: pairs MUST come from a+ team-scoped personhog read for this same ``team_id`` (e.g.+ ``get_person_ids_and_uuids_by_uuids``). Nothing downstream re-validates person ownership —+ the InsertCohortMembers RPC is team-blind, and in the UUID path that validation happens+ implicitly in the resolve step this method skips.+ Wrong-team pairs would write inert membership rows (read paths join membership against+ the team's own persons, so foreign ids never match), but they are still a tenant-data+ integrity violation.++ Returns:+ The number of batches processed.+ """+ batch_iterator = ArrayBatchIterator(items, batch_size=DEFAULT_COHORT_INSERT_BATCH_SIZE)+ return self._insert_users_list_with_batching(+ batch_iterator,+ insert_in_clickhouse=True,+ team_id=team_id,+ raise_on_error=raise_on_error,+ insert_batch=lambda batch: self._insert_resolved_batch(batch, insert_in_clickhouse=True, team_id=team_id),+ )+def insert_users_by_email(self,items: list[str],@@ -592,11 +630,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):def _insert_users_list_with_batching(self,- batch_iterator: BatchIterator[str],+ batch_iterator: BatchIterator[Any],insert_in_clickhouse: bool = False,*,team_id: int,raise_on_error: bool = False,+ insert_batch: Callable[[list[Any]], None] | None = None,) -> int:"""Insert a list of users identified by their UUID into the cohort, for the given team.@@ -605,18 +644,27 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):batch_iterator: BatchIterator of user UUIDs to be inserted into the cohort.insert_in_clickhouse: Whether the data should also be inserted into ClickHouse.team_id: The ID of the team to which the cohort belongs.+ insert_batch: Override for the per-batch write. Defaults to resolving each batch of+ UUIDs via personhog and inserting (``_insert_batch_via_personhog``, which honors+ ``insert_in_clickhouse``); callers whose batches are not plain UUID lists supply+ a writer matching their item type.Returns:Number of batches processed."""from products.cohorts.backend.models.util import count_cohort_members+ def _resolve_and_insert_batch(batch: list[Any]) -> None:+ self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)++ insert_batch = insert_batch or _resolve_and_insert_batch+current_batch_index = -1processing_error = Nonetry:for batch_index, batch in batch_iterator:current_batch_index = batch_index- self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)+ insert_batch(batch)except SoftTimeLimitExceeded as err:# Let a Celery soft-time-limit interruption propagate so the task's time limit@@ -676,35 +724,44 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):) -> None:"""Personhog path for inserting a single batch of cohort members.- Resolves UUIDs → person IDs via personhog, then calls the- InsertCohortMembers RPC. ClickHouse inserts (if requested)- exclude persons already in the cohort because the- person_static_cohort table's ORDER BY includes a per-row UUID,+ Resolves UUIDs → person IDs via personhog (field-masked — membership only needs+ id/uuid, not properties or distinct IDs), then writes the resolved batch.+ """+ with personhog_caller_tag("cohorts/static-insert"):+ id_uuid_pairs = get_person_ids_and_uuids_by_uuids(team_id, batch)+ self._insert_resolved_batch(id_uuid_pairs, insert_in_clickhouse=insert_in_clickhouse, team_id=team_id)++ def _insert_resolved_batch(+ self,+ id_uuid_pairs: list[tuple[int, str]],+ *,+ insert_in_clickhouse: bool,+ team_id: int,+ ) -> None:+ """Write a single batch of already-resolved (person_id, person_uuid) cohort members.++ Trusts the pairs — see the tenant-isolation contract on+ ``insert_users_list_by_id_uuid_pairs_skip_validation``. Calls the InsertCohortMembers RPC.+ ClickHouse inserts (if requested) exclude persons already in the cohort+ because the person_static_cohort table's ORDER BY includes a per-row UUID,preventing ReplacingMergeTree from deduplicating repeated inserts."""from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE- from posthog.models.person.util import get_persons_by_uuids- from products.cohorts.backend.models.util import insert_static_cohort+ from products.cohorts.backend.models.util import insert_cohort_members, insert_static_cohort- # Cohort membership only needs id/uuid, so skip the unbounded per-person distinct-id fetch.- with personhog_caller_tag("cohorts/static-insert"):- persons = get_persons_by_uuids(team_id, batch, distinct_id_limit=0)- if not persons:+ if not id_uuid_pairs:return- person_ids = [p.id for p in persons]- person_uuids = [p.uuid for p in persons]+ person_ids = [person_id for person_id, _ in id_uuid_pairs]+ person_uuids = [person_uuid for _, person_uuid in id_uuid_pairs]if insert_in_clickhouse:- uuid_strs = [str(u) for u in person_uuids]- existing_uuids = self._get_existing_ch_member_uuids(uuid_strs, team_id, PERSON_STATIC_COHORT_TABLE)- new_uuids = [u for u in person_uuids if str(u) not in existing_uuids]+ existing_uuids = self._get_existing_ch_member_uuids(person_uuids, team_id, PERSON_STATIC_COHORT_TABLE)+ new_uuids = [UUID(u) for u in person_uuids if u not in existing_uuids]if new_uuids:insert_static_cohort(new_uuids, self.pk, team_id=team_id)- from products.cohorts.backend.models.util import insert_cohort_members-insert_cohort_members(team_id, self.pk, person_ids, self.version, _skip_ownership_check=True)def _get_existing_ch_member_uuids(diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 50b77940ac91..d571bb5aec54 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -1,5 +1,6 @@"""Experiment service — single source of truth for experiment business logic."""+import timefrom collections import defaultdictfrom collections.abc import Iterable, Mappingfrom copy import deepcopy@@ -42,7 +43,7 @@ from posthog.exceptions import ()from posthog.models.activity_logging.utils import get_changed_fields_localfrom posthog.models.filters.filter import Filter-from posthog.models.person.util import validate_person_uuids_exist+from posthog.models.person.util import get_person_ids_and_uuids_by_uuidsfrom posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Team@@ -1820,7 +1821,7 @@ class ExperimentService:persons, so a person cohort cannot freeze the exposed set. Experiments whoseexposed set contains a material share of anonymous (personless) users arerejected too, since cohort membership is person-keyed and freezing would drop- those users' variants (see _assert_exposed_persons_resolvable).+ those users' variants (see _resolve_exposed_persons).Runs in two phases because the snapshot build can take tens of seconds — plenty oftime for a concurrent freeze, pause, end, or flag edit to land. Phase 1 (unlocked)@@ -1834,11 +1835,20 @@ class ExperimentService:``request`` is required because FeatureFlagSerializer needs a real requestwith authentication and session context to persist the flag change."""+ # Phase timings are logged at the end: the freeze spans several backends (ClickHouse scan,+ # personhog RPCs, cohort build with its cache side effects, flag save) whose relative cost+ # can't be reconstructed from any single backend's logs — see experiment_freeze_exposure_timing.+ freeze_started_at = time.monotonic()+# Phase 1 — unlocked: fail obviously-invalid requests before the expensive snapshot build.self._validate_freeze_exposure_state(experiment)+ # Separate checkpoint so scan_ms measures only the ClickHouse scan — the guard above can+ # lazy-load the flag row, and folding that into scan_ms would misattribute it.+ scan_started_at = time.monotonic()# 1. Snapshot the actually-exposed set (bounded by time + count; raises if too large to freeze in-request).exposed_person_uuids = self._fetch_exposed_person_uuids(experiment)+ scan_done_at = time.monotonic()if not exposed_person_uuids:# An empty snapshot cohort ANDed into every release group would un-enroll every user.raise ValidationError(@@ -1846,12 +1856,16 @@ class ExperimentService:"Wait until the experiment has recorded exposures.")- # 2. Fail closed if a material share of the exposed set has no person profile: cohort- # membership is person-keyed, so those users would silently lose their variant.- self._assert_exposed_persons_resolvable(exposed_person_uuids)+ # 2. Resolve the exposed set to person ids, failing closed if a material share has no+ # person profile: cohort membership is person-keyed, so those users would silently lose+ # their variant. The resolved pairs feed the snapshot insert directly, so the persons+ # aren't fetched from personhog a second time.+ resolved_person_pairs = self._resolve_exposed_persons(exposed_person_uuids)+ resolve_done_at = time.monotonic()# 3. Materialize it into a static cohort synchronously, so the flag never points at an unpopulated cohort.- exposure_snapshot = self._create_exposure_snapshot_cohort(experiment, exposed_person_uuids)+ exposure_snapshot = self._create_exposure_snapshot_cohort(experiment, resolved_person_pairs)+ cohort_build_done_at = time.monotonic()# Phase 2 — locked: any failure here drops the snapshot cohort, which is referenced only by# the flag change attempted below — a failed freeze should leave nothing behind.@@ -1916,11 +1930,27 @@ class ExperimentService:# Refresh so the experiment's nested flag reflects the narrowed filters when serialized.locked_flag.refresh_from_db()experiment.feature_flag = locked_flag+ flag_save_done_at = time.monotonic()# end_date intentionally left null — metrics keep flowing.self._report_lifecycle_event(experiment, "experiment exposure frozen", request=request)+ # flag_save_ms includes the transaction commit, so it carries the on-commit flag cache+ # rebuilds; cohort_build_ms carries the cohort dependency cache warm-up triggered by the+ # snapshot cohort's creation.+ logger.info(+ "experiment_freeze_exposure_timing",+ team_id=self.team.pk,+ experiment_id=experiment.pk,+ exposed_count=len(exposed_person_uuids),+ scan_ms=round((scan_done_at - scan_started_at) * 1000),+ resolve_ms=round((resolve_done_at - scan_done_at) * 1000),+ cohort_build_ms=round((cohort_build_done_at - resolve_done_at) * 1000),+ flag_save_ms=round((flag_save_done_at - cohort_build_done_at) * 1000),+ total_ms=round((time.monotonic() - freeze_started_at) * 1000),+ )+return experimentdef _validate_freeze_exposure_state(self, experiment: Experiment) -> None:@@ -2051,23 +2081,30 @@ class ExperimentService:return [str(row[0]) for row in response.results]- def _assert_exposed_persons_resolvable(self, person_uuids: list[str]) -> None:- """Fail closed when a material share of the exposed set has no person profile.+ def _resolve_exposed_persons(self, person_uuids: list[str]) -> list[tuple[int, str]]:+ """Resolve exposed person UUIDs to (person_id, uuid) pairs, failing closed when a+ material share of the exposed set has no person profile.Cohort membership is person-keyed, and flag evaluation resolves distinct_id to personbefore checking it, so an exposed user without a person row (anonymous "personless"- traffic, or a since-deleted person) can never match the snapshot cohort. The cohort- insert silently skips such users, and post-freeze the narrowed flag stops serving them:- freezing would break "everyone already enrolled keeps their variant" for exactly that- share of the population. Typical for experiments exposed on logged-out surfaces, where- the share can be the majority. A small unresolved share is tolerated as deletion/merge- noise; beyond FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE the freeze is rejected, before any- cohort is created.+ traffic, or a since-deleted person) can never match the snapshot cohort. Post-freeze the+ narrowed flag would stop serving such users: freezing would break "everyone already+ enrolled keeps their variant" for exactly that share of the population. Typical for+ experiments exposed on logged-out surfaces, where the share can be the majority. A small+ unresolved share is tolerated as deletion/merge noise; beyond+ FREEZE_EXPOSURE_MAX_UNRESOLVED_SHARE the freeze is rejected, before any cohort is created.++ The returned pairs are what the snapshot cohort is built from — resolution and insert+ share one (field-masked) personhog pass instead of fetching the persons twice. Membership+ is therefore snapshotted at resolve time: a person deleted or merged in the moments before+ the insert is written as an inert row rather than skipped. The user-facing outcome is+ unchanged from insert-time resolution (their distinct_id no longer resolves to a cohort+ member either way), and the cohort stays consistent with the count this guard approved."""- resolved_count = len(validate_person_uuids_exist(self.team.id, person_uuids))- unresolved_count = len(person_uuids) - resolved_count+ resolved_person_pairs = get_person_ids_and_uuids_by_uuids(self.team.id, person_uuids)+ unresolved_count = len(person_uuids) - len(resolved_person_pairs)if unresolved_count == 0:- return+ return resolved_person_pairsunresolved_share = unresolved_count / len(person_uuids)logger.warning("experiment_freeze_exposure_unresolved_persons",@@ -2082,12 +2119,14 @@ class ExperimentService:"cannot be held in a cohort. Freezing would remove their variant. Freezing exposure ""requires an experiment whose exposed users are identified.")+ return resolved_person_pairs- def _create_exposure_snapshot_cohort(self, experiment: Experiment, person_uuids: list[str]) -> Cohort:+ def _create_exposure_snapshot_cohort(self, experiment: Experiment, id_uuid_pairs: list[tuple[int, str]]) -> Cohort:"""Create a static cohort frozen to the given already-exposed persons (synchronous, no Celery).Static is required — behavioral cohorts are rejected by feature-flag validation, and a static- snapshot is exactly what freezes enrollment.+ snapshot is exactly what freezes enrollment. Takes the (person_id, uuid) pairs resolved by+ _resolve_exposed_persons so the insert doesn't re-fetch the persons from personhog."""cohort = Cohort.objects.create(team=self.team,@@ -2098,7 +2137,9 @@ class ExperimentService:try:# raise_on_error: the batching helper otherwise swallows mid-batch failures and returns# normally, and a partially populated snapshot would evict every user missing from it.- cohort.insert_users_list_by_uuid(person_uuids, team_id=self.team.id, raise_on_error=True)+ cohort.insert_users_list_by_id_uuid_pairs_skip_validation(+ id_uuid_pairs, team_id=self.team.id, raise_on_error=True+ )except Exception:# The cohort row exists but isn't referenced by anything yet — drop it so a failed# population doesn't leave an empty static cohort behind.@@ -2220,6 +2261,8 @@ class ExperimentService:this path (see Experiment.is_exposure_frozen). The snapshot cohort is soft-deleted afterthe flag save so it doesn't accumulate as clutter."""+ unfreeze_started_at = time.monotonic()+if experiment.is_draft:raise ValidationError("Experiment has not been launched yet.")if experiment.is_stopped:@@ -2246,12 +2289,25 @@ class ExperimentService:# Refresh so the experiment's nested flag reflects the restored filters when serialized.flag.refresh_from_db()experiment.feature_flag = flag+ flag_save_done_at = time.monotonic()# Only after the flag no longer references them: soft-delete the now-orphaned snapshots.self._delete_orphaned_snapshot_cohorts(cohort_ids)+ cohort_cleanup_done_at = time.monotonic()self._report_lifecycle_event(experiment, "experiment exposure unfrozen", request=request)+ # flag_save_ms carries the on-commit flag cache rebuilds; cohort_cleanup_ms carries the+ # orphan check plus the cohort-delete cache side effects (dependency cache warm-up).+ logger.info(+ "experiment_unfreeze_exposure_timing",+ team_id=self.team.pk,+ experiment_id=experiment.pk,+ flag_save_ms=round((flag_save_done_at - unfreeze_started_at) * 1000),+ cohort_cleanup_ms=round((cohort_cleanup_done_at - flag_save_done_at) * 1000),+ total_ms=round((time.monotonic() - unfreeze_started_at) * 1000),+ )+return experiment# ------------------------------------------------------------------diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 08bf9fad04b8..634d11b7eef7 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -3223,11 +3223,12 @@ class TestExperimentService(APIBaseTest):# The stubbed uuids have no real persons behind them; treat them all as resolvable so# the personless guard doesn't reject these unrelated scenarios.patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],),patch(- "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,) as mock_insert,):yield mock_insert@@ -3271,10 +3272,14 @@ class TestExperimentService(APIBaseTest):frozen.feature_flag.refresh_from_db()- # A static snapshot cohort was created and populated synchronously from the exposed set.+ # A static snapshot cohort was created and populated synchronously from the exposed set,+ # fed the (person_id, uuid) pairs already resolved by the personless guard — the freeze+ # must not fetch the persons from personhog a second time.cohort = Cohort.objects.get(team=self.team, name='Exposure snapshot for experiment "Freeze Exposure"')assert cohort.is_static is True- mock_insert.assert_called_once()+ mock_insert.assert_called_once_with(+ [(1, "00000000-0000-0000-0000-000000000001")], team_id=self.team.id, raise_on_error=True+ )# The cohort condition + freeze key + marker note were AND'd into every release group.groups = frozen.feature_flag.filters["groups"]@@ -3554,10 +3559,15 @@ class TestExperimentService(APIBaseTest):with (patch.object(ExperimentService, "_fetch_exposed_person_uuids", return_value=uuids),patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, batch: batch[unresolved:],+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, batch: [+ (index + 1, person_uuid) for index, person_uuid in enumerate(batch[unresolved:])+ ],+ ),+ patch(+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,),- patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),):if expect_rejection:with self.assertRaises(ValidationError) as ctx:@@ -3586,11 +3596,11 @@ class TestExperimentService(APIBaseTest):return_value=["00000000-0000-0000-0000-000000000001"],),patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],),patch(- "products.cohorts.backend.models.cohort.Cohort._insert_batch_via_personhog",+ "products.cohorts.backend.models.cohort.Cohort._insert_resolved_batch",side_effect=RuntimeError("clickhouse insert failed"),),):@@ -3700,10 +3710,13 @@ class TestExperimentService(APIBaseTest):with (patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_change_then_return),patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],+ ),+ patch(+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,),- patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),):with self.assertRaises(ValidationError) as ctx:self._service().freeze_exposure(experiment, request=self._make_request())@@ -3735,10 +3748,13 @@ class TestExperimentService(APIBaseTest):with (patch.object(ExperimentService, "_fetch_exposed_person_uuids", side_effect=concurrent_edit_then_return),patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],+ ),+ patch(+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,),- patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0),):frozen = self._service().freeze_exposure(experiment, request=self._make_request())diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex edaadd8451f5..3489b19e1f93 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -5519,10 +5519,13 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):)self.assertEqual(pause_response.status_code, status.HTTP_400_BAD_REQUEST)- @patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0)@patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,+ )+ @patch(+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],)@patch("products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",@@ -5548,10 +5551,13 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(get_response.status_code, status.HTTP_200_OK)self.assertEqual(get_response.json()["status"], "exposure_frozen")- @patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0)@patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,+ )+ @patch(+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],)@patch("products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",@@ -5568,10 +5574,13 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):)self.assertEqual(second_freeze.status_code, status.HTTP_400_BAD_REQUEST)- @patch("products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_uuid", return_value=0)@patch(- "products.experiments.backend.experiment_service.validate_person_uuids_exist",- new=lambda team_id, uuids: uuids,+ "products.cohorts.backend.models.cohort.Cohort.insert_users_list_by_id_uuid_pairs_skip_validation",+ return_value=0,+ )+ @patch(+ "products.experiments.backend.experiment_service.get_person_ids_and_uuids_by_uuids",+ new=lambda team_id, uuids: [(index + 1, person_uuid) for index, person_uuid in enumerate(uuids)],)@patch("products.experiments.backend.experiment_service.ExperimentService._fetch_exposed_person_uuids",