:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): cut over django flag matching to use flags service (#62763)
Nick Best9bc0cc52e0e5
diff --git a/.github/workflows/ci-rust-flags-integration.yml b/.github/workflows/ci-rust-flags-integration.ymlindex c7751e6e7436..cc5fa01ccd3d 100644--- a/.github/workflows/ci-rust-flags-integration.yml+++ b/.github/workflows/ci-rust-flags-integration.yml@@ -37,6 +37,9 @@ env:REDIS_URL: 'redis://localhost:6379/'TEST: 1UV_HTTP_TIMEOUT: 300+ # Shared by the Rust flags service and the pytest step — the batch flag evaluation+ # tests (static cohort generation) authenticate with it. Test-only value.+ INTERNAL_REQUEST_TOKEN: 'rust-integration-internal-token'jobs:rust-flags-integration:@@ -205,7 +208,7 @@ jobs:- name: Run integration testsrun: |- pytest posthog/api/test/rust_integration/test_flags.py -v --tb=short+ pytest posthog/api/test/rust_integration/ -v --tb=shortenv:SKIP_RUST_INTEGRATION_TESTS: '0'FEATURE_FLAGS_SERVICE_URL: 'http://127.0.0.1:3001'diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 38d3243749e4..9e8dbd80e4c1 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -1,20 +1,21 @@import csvimport json+import timeimport uuidimport hashlibfrom collections import defaultdictfrom collections.abc import Iteratorfrom typing import Annotated, Any, Literal, Optional, Union, cast-from django.conf import settings-from django.db import DatabaseError-from django.db.models import OuterRef, Prefetch, QuerySet, Subquery, prefetch_related_objects+from django.db.models import OuterRef, QuerySet, Subquery+from django.utils import timezone+import requestsimport structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom loginas.utils import is_impersonated_session-from prometheus_client import Counter+from prometheus_client import Counter, Histogramfrom pydantic import (BaseModel,Field,@@ -36,16 +37,17 @@ from posthog.hogql.property import property_to_exprfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_teamfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.cdp.filters import build_behavioral_event_exprfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.constants import LIMIT, OFFSET, PropertyOperatorType+from posthog.constants import LIMIT, OFFSETfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.metrics import LABEL_TEAM_ID-from posthog.models import Person, User+from posthog.models import Userfrom posthog.models.activity_logging.activity_log import (Change,Detail,@@ -56,13 +58,12 @@ from posthog.models.activity_logging.activity_log import (from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.filters.filter import Filter-from posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctIdfrom posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist-from posthog.models.property.property import Property, PropertyGroup+from posthog.models.property.property import Propertyfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTfrom posthog.queries.actor_base_query import get_serialized_people-from posthog.queries.base import determine_parsed_date_for_property_matching, property_group_to_Q+from posthog.queries.base import determine_parsed_date_for_property_matchingfrom posthog.queries.person_query import PersonQueryfrom posthog.queries.util import get_earliest_timestampfrom posthog.renderers import SafeJSONRenderer@@ -77,16 +78,12 @@ from products.cohorts.backend.models.cohort import (CohortType,)from products.cohorts.backend.models.util import (+ CohortErrorCode,cohort_filters_have_values,get_all_cohort_dependencies,get_friendly_error_message,)from products.cohorts.backend.models.validation import CohortTypeValidationSerializer-from products.feature_flags.backend.flag_matching import (- FeatureFlagMatcher,- FlagsMatcherCache,- get_feature_flag_hash_key_overrides,-)from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insight@@ -1813,166 +1810,199 @@ def will_create_loops(cohort: Cohort) -> bool:return dfs_loop_helper(cohort, set(), set())-def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int, batchsize: int = 1_000):- # :TODO: Find a way to incorporate this into the same code path as feature flag evaluation- project_id = Team.objects.only("project_id").get(pk=team_id).project_id- try:- feature_flag = FeatureFlag.objects.get(team__project_id=project_id, key=flag)- except FeatureFlag.DoesNotExist:- return []+# Number of attempts per page when calling the batch evaluation endpoint, including the+# first try. Only transient failures (connection errors, timeouts, 5xx) are retried.+BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS = 3+BATCH_FLAG_EVALUATION_RETRY_BACKOFF_SECONDS = 2.0- if not feature_flag.active or feature_flag.aggregation_group_type_index is not None:- return []+COHORT_FLAG_GENERATION_COMPLETED_COUNTER = Counter(+ "cohort_flag_generation_completed_total",+ "Cohort generations from a feature flag that finished, by outcome",+ ["outcome"], # "success" or a CohortErrorCode value ("flag_changed", "unknown")+)- cohort = Cohort.objects.get(pk=cohort_id, team__project_id=project_id)- matcher_cache = FlagsMatcherCache(project_id=project_id)- uuids_to_add_to_cohort = []- cohorts_cache: dict[int, CohortOrEmpty] = {}-- if feature_flag.uses_cohorts:- # TODO: Consider disabling flags with cohorts for creating static cohorts- # because this is currently a lot more inefficient for flag matching,- # as we're required to go to the database for each person.- cohorts_cache = {- cohort.pk: cohort for cohort in Cohort.objects.filter(team__project_id=project_id, deleted=False)- }+COHORT_FLAG_GENERATION_DURATION_SECONDS = Histogram(+ "cohort_flag_generation_duration_seconds",+ "Duration of cohort generation from a feature flag in seconds",+ ["outcome"],+ buckets=[1, 5, 10, 30, 60, 120, 300, 600, 1800, 3600, 7200, 14400],+)- default_person_properties = {}- for condition in feature_flag.conditions:- property_list = Filter(data=condition).property_groups.flat- for property in property_list:- default_person_properties.update(get_default_person_property(property, cohorts_cache))+COHORT_FLAG_GENERATION_PAGE_RETRIES_COUNTER = Counter(+ "cohort_flag_generation_page_retries_total",+ "Transient batch flag evaluation page failures that were retried against the flags service",+)- flag_property_conditions = [Filter(data=condition).property_groups for condition in feature_flag.conditions]- flag_property_group = PropertyGroup(type=PropertyOperatorType.OR, values=flag_property_conditions)+COHORT_FLAG_GENERATION_EVAL_ERRORS_COUNTER = Counter(+ "cohort_flag_generation_eval_errors_total",+ "Per-person evaluation errors reported by the flags service during cohort generation",+)- try:- # QuerySet.Iterator() doesn't work with pgbouncer, it will load everything into memory and then stream- # which doesn't work for us, so need a manual chunking here.- # Because of this pgbouncer transaction pooling mode, we can't use server-side cursors.- # We pre-filter all persons to be ones that will match the feature flag, so that we don't have to- # iterate through all persons- queryset = (- Person.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id)- .filter(property_group_to_Q(team_id, flag_property_group, cohorts_cache=cohorts_cache))- .order_by("id")- )- # get batchsize number of people at a time- start = 0- batch_of_persons = queryset[start : start + batchsize]- while batch_of_persons:- # TODO: Check if this subquery bulk fetch limiting is better than just doing a join for all distinct ids- # OR, if row by row getting single distinct id is better- # distinct_id = PersonDistinctId.objects.filter(person=person, team_id=team_id).values_list(- # "distinct_id", flat=True- # )[0]- distinct_id_subquery = Subquery(- PersonDistinctId.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id, person_id=OuterRef("person_id"))- .values_list("id", flat=True)[:3]++def _batch_evaluate_flag_page_with_retries(+ *,+ team_id: int,+ project_id: int,+ flag_key: str,+ expected_version: int,+ cursor: int,+ limit: int,+) -> dict[str, Any]:+ last_error: Exception | None = None+ for attempt in range(BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS):+ if attempt > 0:+ COHORT_FLAG_GENERATION_PAGE_RETRIES_COUNTER.inc()+ time.sleep(BATCH_FLAG_EVALUATION_RETRY_BACKOFF_SECONDS * (2 ** (attempt - 1)))+ try:+ return batch_evaluate_flag_for_team(+ team_id=team_id,+ project_id=project_id,+ flag_key=flag_key,+ expected_version=expected_version,+ cursor=cursor,+ limit=limit,)- prefetch_related_objects(- batch_of_persons,- Prefetch(- "persondistinctid_set",- to_attr="distinct_ids_cache",- queryset=PersonDistinctId.objects.db_manager( # nosemgrep: no-direct-persons-db-orm- READ_DB_FOR_PERSONS- ).filter( # nosemgrep: no-direct-persons-db-orm- id__in=distinct_id_subquery- ),- ),+ except FlagVersionConflictError:+ # Permanent: the flag changed mid-run; retrying the same page cannot help.+ raise+ except requests.RequestException as err:+ if (+ isinstance(err, requests.HTTPError)+ and err.response is not None+ and 400 <= err.response.status_code < 500+ ):+ # Permanent client errors (bad request, missing flag, auth misconfiguration).+ raise+ last_error = err+ logger.warning(+ "cohort_from_feature_flag_page_retry",+ team_id=team_id,+ flag_key=flag_key,+ cursor=cursor,+ attempt=attempt + 1,+ error=str(err),)+ assert last_error is not None+ raise last_error- all_persons = list(batch_of_persons)- if len(all_persons) == 0:- break-- for person in all_persons:- # ignore almost-deleted persons / persons with no distinct ids- if len(person.distinct_ids) == 0:- continue-- distinct_id = person.distinct_ids[0]- person_overrides = {}- if feature_flag.ensure_experience_continuity:- # :TRICKY: This is inefficient because it tries to get the hashkey overrides one by one.- # But reusing functions is better for maintainability. Revisit optimising if this becomes a bottleneck.- person_overrides = get_feature_flag_hash_key_overrides(- team_id,- [distinct_id],- person_id_to_distinct_id_mapping={person.id: distinct_id},- )-- try:- match = FeatureFlagMatcher(- team_id,- project_id,- [feature_flag],- distinct_id,- groups={},- cache=matcher_cache,- hash_key_overrides=person_overrides,- property_value_overrides={- **default_person_properties,- **person.properties,- },- group_property_value_overrides={},- cohorts_cache=cohorts_cache,- ).get_match(feature_flag)- if match.match:- uuids_to_add_to_cohort.append(str(person.uuid))- except (DatabaseError, ValueError, ValidationError):- logger.exception(- "Error evaluating feature flag for person",- person_uuid=str(person.uuid),- team_id=team_id,- )- except Exception as err:- # matching errors are not fatal, so we just log them and move on.- # Capturing error for now just in case there are some unexpected errors- # we did not account for.- capture_exception(err)-- if len(uuids_to_add_to_cohort) >= batchsize:- cohort.insert_users_list_by_uuid(uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id)- uuids_to_add_to_cohort = []-- start += batchsize- batch_of_persons = queryset[start : start + batchsize]- if len(uuids_to_add_to_cohort) > 0:- cohort.insert_users_list_by_uuid(uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id)+def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int, batchsize: int = 1_000) -> None:+ """+ Populate a static cohort with the persons matched by a feature flag.- except Exception as err:- if settings.DEBUG or settings.TEST:- raise- capture_exception(err)+ Evaluation happens in the Rust feature-flags service (the same code path as live+ /flags evaluation) via its internal cursor-paged batch endpoint; this task only+ orchestrates paging and inserts the matched person UUIDs into the cohort.+ """+ # Flag and cohort lookups are deliberately project-scoped (team__project_id), matching+ # how flags resolve everywhere else. Multi-team projects ("environments") are+ # deprecated, so a project has exactly one team and this cannot cross team boundaries.+ project_id = Team.objects.only("project_id").get(pk=team_id).project_id+ cohort = Cohort.objects.get(pk=cohort_id, team__project_id=project_id)+ # The enqueue site set is_calculating=True before dispatching, so every exit has to+ # clear it. On the guard paths there is nothing to evaluate, so finalize as a clean+ # no-op run rather than leaving the cohort stuck "calculating" with no record of why.+ try:+ feature_flag = FeatureFlag.objects.get(team__project_id=project_id, key=flag)+ except FeatureFlag.DoesNotExist:+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)+ return+ if not feature_flag.active or feature_flag.aggregation_group_type_index is not None:+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)+ return-def get_default_person_property(prop: Property, cohorts_cache: dict[int, CohortOrEmpty]):- default_person_properties = {}+ # Pin the flag definition for the whole run: every page sends this version and the+ # service refuses to evaluate under any other, so a run can never mix two+ # definitions of the flag. Nullable versions coerce to 0 on both sides.+ expected_version = feature_flag.version or 0- if prop.operator not in ("is_set", "is_not_set") and prop.type == "person":- default_person_properties[prop.key] = ""- elif prop.type == "cohort" and not isinstance(prop.value, list):- try:- parsed_cohort_id = int(prop.value)- except (ValueError, TypeError):- return None- cohort = cohorts_cache.get(parsed_cohort_id)- if cohort:- return get_default_person_properties_for_cohort(cohort, cohorts_cache)- return default_person_properties+ started_at = timezone.now()+ start_monotonic = time.monotonic()+ eval_errors_count = 0+ try:+ uuids_to_add_to_cohort: list[str] = []+ cursor = 0+ while True:+ page = _batch_evaluate_flag_page_with_retries(+ team_id=team_id,+ project_id=project_id,+ flag_key=feature_flag.key,+ expected_version=expected_version,+ cursor=cursor,+ limit=batchsize,+ )+ uuids_to_add_to_cohort.extend(page["matched_person_uuids"])+ page_errors_count = page.get("errors_count") or 0+ if page_errors_count:+ COHORT_FLAG_GENERATION_EVAL_ERRORS_COUNTER.inc(page_errors_count)+ eval_errors_count += page_errors_count++ if len(uuids_to_add_to_cohort) >= batchsize:+ cohort.insert_users_list_by_uuid(+ uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id, raise_on_error=True+ )+ uuids_to_add_to_cohort = []+ next_cursor = page["next_cursor"]+ if next_cursor is None:+ break+ if next_cursor <= cursor:+ raise RuntimeError(f"Batch flag evaluation cursor did not advance (got {next_cursor} after {cursor})")+ cursor = next_cursor++ # Always flush, even when empty: insert_users_list_by_uuid recomputes the cohort+ # count and clears is_calculating via _safe_save_cohort_state. Re-running after a+ # partial failure is safe because inserts dedupe on (cohort_id, person_id).+ # raise_on_error surfaces an insert failure so the except below records it rather+ # than letting a partial insert be counted as a successful generation.+ cohort.insert_users_list_by_uuid(+ uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id, raise_on_error=True+ )-def get_default_person_properties_for_cohort(cohort: Cohort, cohorts_cache: dict[int, CohortOrEmpty]) -> dict[str, str]:- """- Returns a dictionary of default person properties to use when evaluating a feature flag- """- default_person_properties = {}- for property in cohort.properties.flat:- default_person_properties.update(get_default_person_property(property, cohorts_cache))+ if eval_errors_count:+ logger.warning(+ "cohort_from_feature_flag_eval_errors",+ cohort_id=cohort_id,+ team_id=team_id,+ flag_key=feature_flag.key,+ errors_count=eval_errors_count,+ )- return default_person_properties+ COHORT_FLAG_GENERATION_COMPLETED_COUNTER.labels(outcome="success").inc()+ COHORT_FLAG_GENERATION_DURATION_SECONDS.labels(outcome="success").observe(time.monotonic() - start_monotonic)+ except Exception as err:+ logger.exception(+ "cohort_from_feature_flag_failed",+ cohort_id=cohort_id,+ team_id=team_id,+ flag_key=feature_flag.key,+ error=str(err),+ )+ capture_exception(err, additional_properties={"cohort_id": cohort_id, "team_id": team_id})+ error_code = (+ CohortErrorCode.FLAG_CHANGED if isinstance(err, FlagVersionConflictError) else CohortErrorCode.UNKNOWN+ )+ COHORT_FLAG_GENERATION_COMPLETED_COUNTER.labels(outcome=error_code.value).inc()+ COHORT_FLAG_GENERATION_DURATION_SECONDS.labels(outcome=error_code.value).observe(+ time.monotonic() - start_monotonic+ )+ # Finalize cohort state before writing the history row. _safe_save_cohort_state+ # swallows its own failures, so if the history insert ran first and raised, the+ # cohort would stay is_calculating=True with no Celery retry to recover it+ # (max_retries=0). Worst case in this order is a finalized cohort missing a+ # history row, rather than one stuck calculating forever.+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)+ # The history `error` field is user-visible via the calculation history API, so+ # store the friendly message; raw exception details (internal URLs, instance+ # config) stay in logs and error tracking only.+ CohortCalculationHistory.objects.create(+ team_id=team_id,+ cohort=cohort,+ filters=cohort.filters or {},+ started_at=started_at,+ finished_at=timezone.now(),+ error=get_friendly_error_message(error_code),+ error_code=error_code,+ )+ raisediff --git a/posthog/api/services/flags_service.py b/posthog/api/services/flags_service.pyindex 168d64b7453b..44a593cc4e28 100644--- a/posthog/api/services/flags_service.py+++ b/posthog/api/services/flags_service.py@@ -8,12 +8,22 @@ flags service. This module provides a shared HTTP client and proxy function.from typing import Anyfrom django.conf import settings+from django.core.exceptions import ImproperlyConfiguredfrom posthog.security.outbound_proxy import internal_requests_session# Reusable session for proxying to the flags service with connection pooling_FLAGS_SERVICE_SESSION = internal_requests_session()+# One page of batch evaluation covers up to ~10k persons evaluated sequentially in the+# service, so this sits above the service's own per-request timeout (120s) rather than+# the 3s live-proxy timeout.+BATCH_FLAG_EVALUATION_TIMEOUT_SECONDS = 150+++class FlagVersionConflictError(Exception):+ """The feature flag changed while a static cohort was being generated from it."""+def get_flags_from_service(token: str,@@ -107,3 +117,69 @@ def get_flags_from_service()response.raise_for_status()return response.json()+++def batch_evaluate_flag_for_team(+ *,+ team_id: int,+ project_id: int,+ flag_key: str,+ expected_version: int,+ cursor: int,+ limit: int,+) -> dict[str, Any]:+ """+ Request one page of batch flag evaluation from the Rust flags service.++ The internal endpoint evaluates the flag for a cursor-paged slice of the team's+ persons, exactly like live /flags evaluation (read-only — no continuity override+ writes, no billing or analytics). Used by static cohort generation from a flag.++ Args:+ team_id: The team whose persons are evaluated+ project_id: The project the flag belongs to (informational; flag lookup is team-scoped)+ flag_key: The key of the flag to evaluate+ expected_version: Optimistic-lock pin — the flag `version` read before the run started+ cursor: Exclusive lower bound on person id; 0 for the first page+ limit: Page size; the service rejects (400) any value above its configured+ maximum (BATCH_FLAG_EVAL_MAX_LIMIT, default 10000) rather than clamping it,+ so keep this at or below that maximum++ Returns:+ The page as a dict: {"matched_person_uuids": [...], "next_cursor": int | None, "errors_count": int}++ Raises:+ ImproperlyConfigured: `INTERNAL_REQUEST_TOKEN` is not set+ FlagVersionConflictError: The flag's version no longer matches `expected_version`+ requests.RequestException: If the HTTP request fails (timeout, connection error, etc.)+ requests.HTTPError: If the service returns a non-2xx status code+ """+ flags_service_url = getattr(settings, "FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")++ # The service refuses all internal requests when its token is unset, so an empty+ # token here can only ever produce an opaque 401 — fail fast with the real cause.+ internal_request_token = settings.INTERNAL_REQUEST_TOKEN+ if not internal_request_token or not internal_request_token.strip():+ raise ImproperlyConfigured("INTERNAL_REQUEST_TOKEN must be set for batch flag evaluation")+ headers = {"Authorization": f"Bearer {internal_request_token}"}++ response = _FLAGS_SERVICE_SESSION.post(+ f"{flags_service_url}/internal/batch_flag_evaluation",+ json={+ "team_id": team_id,+ "project_id": project_id,+ "flag_key": flag_key,+ "expected_version": expected_version,+ "cursor": cursor,+ "limit": limit,+ },+ headers=headers,+ timeout=BATCH_FLAG_EVALUATION_TIMEOUT_SECONDS,+ )+ if response.status_code == 409:+ raise FlagVersionConflictError(+ f"Feature flag '{flag_key}' changed while generating the cohort (expected version "+ f"{expected_version}). Re-run cohort generation to use the latest flag definition."+ )+ response.raise_for_status()+ return response.json()diff --git a/posthog/api/test/rust_integration/test_cohort_generation.py b/posthog/api/test/rust_integration/test_cohort_generation.pynew file mode 100644index 000000000000..56f43778bf49--- /dev/null+++ b/posthog/api/test/rust_integration/test_cohort_generation.py@@ -0,0 +1,124 @@+"""+Integration tests for the Rust batch flag evaluation endpoint used by static cohort+generation (`get_cohort_actors_for_feature_flag`).++These cover the Django-client ↔ Rust-endpoint contract: internal-token auth, payload+shape, version pinning, pagination, and matched-person results, using the real+`batch_evaluate_flag_for_team` HTTP client against a live Rust service. The full Celery+task (paging loop, retries, cohort insert) is covered by Django unit tests with this+client mocked — this environment has no ClickHouse, so the task's static-cohort insert+cannot run here.++Requires `INTERNAL_REQUEST_TOKEN` to be set identically for this process and the Rust+service (see ci-rust-flags-integration.yml).+"""++import os+from typing import Any++import pytest++from conftest import DjangoAPI, TestDB, TestEnv # type: ignore[attr-defined,unused-ignore]++pytestmark = [+ pytest.mark.skipif(+ os.environ.get("SKIP_RUST_INTEGRATION_TESTS", "1") == "1",+ reason="Set SKIP_RUST_INTEGRATION_TESTS=0 to run",+ ),+ pytest.mark.skipif(+ not os.environ.get("INTERNAL_REQUEST_TOKEN"),+ reason="INTERNAL_REQUEST_TOKEN must be set (matching the Rust service) for batch evaluation tests",+ ),+]+++def _person_uuid(db: TestDB, person_id: int) -> str:+ with db.persons_conn.cursor() as cur:+ cur.execute("SELECT uuid FROM posthog_person WHERE id = %s", (person_id,))+ row = cur.fetchone()+ assert row is not None, f"Person with id={person_id} not found"+ return str(row[0])+++def _property_flag_filters(key: str, value: str, rollout_percentage: int = 100) -> dict[str, Any]:+ return {+ "groups": [+ {+ "properties": [{"key": key, "type": "person", "value": value, "operator": "exact"}],+ "rollout_percentage": rollout_percentage,+ }+ ]+ }+++def test_batch_evaluation_returns_property_matched_persons(db: TestDB, api: DjangoAPI, env: TestEnv):+ from posthog.api.services.flags_service import batch_evaluate_flag_for_team++ # Property values are unique per test so the exact-match assertions below cannot+ # pick up persons leaked from another test (cleanup hiccup or service-side caching).+ premium = db.create_person(["cohort_gen_user1"], {"plan": "premium_match"})+ db.create_person(["cohort_gen_user2"], {"plan": "free"})++ flag = api.create_flag("cohort-gen-flag", _property_flag_filters("plan", "premium_match"))++ page = batch_evaluate_flag_for_team(+ team_id=env.team_id,+ project_id=env.project_id,+ flag_key="cohort-gen-flag",+ expected_version=flag["version"] or 0,+ cursor=0,+ limit=100,+ )++ assert page["matched_person_uuids"] == [_person_uuid(db, premium)]+ assert page["next_cursor"] is None+ assert page["errors_count"] == 0+++def test_batch_evaluation_paginates_with_cursor(db: TestDB, api: DjangoAPI, env: TestEnv):+ from posthog.api.services.flags_service import batch_evaluate_flag_for_team++ person_ids = [db.create_person([f"cohort_gen_page_user{i}"], {"plan": "premium_paginate"}) for i in range(3)]+ expected_uuids = {_person_uuid(db, pid) for pid in person_ids}++ flag = api.create_flag("cohort-gen-paging-flag", _property_flag_filters("plan", "premium_paginate"))++ matched: set[str] = set()+ cursor = 0+ pages = 0+ while True:+ page = batch_evaluate_flag_for_team(+ team_id=env.team_id,+ project_id=env.project_id,+ flag_key="cohort-gen-paging-flag",+ expected_version=flag["version"] or 0,+ cursor=cursor,+ limit=1,+ )+ matched.update(page["matched_person_uuids"])+ pages += 1+ assert pages <= 10, "pagination should terminate"+ if page["next_cursor"] is None:+ break+ assert page["next_cursor"] > cursor, "cursor must advance"+ cursor = page["next_cursor"]++ assert matched == expected_uuids+ assert pages >= 3+++def test_batch_evaluation_rejects_stale_flag_version(db: TestDB, api: DjangoAPI, env: TestEnv):+ from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_team++ db.create_person(["cohort_gen_version_user"], {"plan": "premium_version"})+ flag = api.create_flag("cohort-gen-version-flag", _property_flag_filters("plan", "premium_version"))++ with pytest.raises(FlagVersionConflictError):+ batch_evaluate_flag_for_team(+ team_id=env.team_id,+ project_id=env.project_id,+ flag_key="cohort-gen-version-flag",+ expected_version=(flag["version"] or 0) + 999,+ cursor=0,+ limit=100,+ )diff --git a/posthog/api/test/test_flags_service.py b/posthog/api/test/test_flags_service.pynew file mode 100644index 000000000000..3d30067e8cb8--- /dev/null+++ b/posthog/api/test/test_flags_service.py@@ -0,0 +1,65 @@+from unittest.mock import MagicMock, patch++from django.core.exceptions import ImproperlyConfigured+from django.test import SimpleTestCase, override_settings++import requests+from parameterized import parameterized++from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_team+++class TestBatchEvaluateFlagForTeam(SimpleTestCase):+ @parameterized.expand([("unset", None), ("empty", ""), ("whitespace", " ")])+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")+ def test_missing_internal_request_token_fails_fast(self, _name, token, mock_post):+ with override_settings(INTERNAL_REQUEST_TOKEN=token):+ with self.assertRaises(ImproperlyConfigured):+ batch_evaluate_flag_for_team(+ team_id=1,+ project_id=1,+ flag_key="my-flag",+ expected_version=0,+ cursor=0,+ limit=100,+ )+ mock_post.assert_not_called()++ @override_settings(INTERNAL_REQUEST_TOKEN="secret")+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")+ def test_409_maps_to_flag_version_conflict_before_raise_for_status(self, mock_post):+ response = MagicMock()+ response.status_code = 409+ mock_post.return_value = response++ with self.assertRaises(FlagVersionConflictError):+ batch_evaluate_flag_for_team(+ team_id=1,+ project_id=1,+ flag_key="my-flag",+ expected_version=7,+ cursor=0,+ limit=100,+ )+ # The 409 branch must short-circuit: a generic HTTPError from raise_for_status+ # would lose the version-conflict semantics the paging loop relies on.+ response.raise_for_status.assert_not_called()+ response.json.assert_not_called()++ @override_settings(INTERNAL_REQUEST_TOKEN="secret")+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")+ def test_5xx_still_raises_for_status(self, mock_post):+ response = MagicMock()+ response.status_code = 503+ response.raise_for_status.side_effect = requests.HTTPError("503 Server Error", response=response)+ mock_post.return_value = response++ with self.assertRaises(requests.HTTPError):+ batch_evaluate_flag_for_team(+ team_id=1,+ project_id=1,+ flag_key="my-flag",+ expected_version=0,+ cursor=0,+ limit=100,+ )diff --git a/posthog/queries/base.py b/posthog/queries/base.pyindex 829520803468..22be6b576bfb 100644--- a/posthog/queries/base.py+++ b/posthog/queries/base.py@@ -310,9 +310,6 @@ def property_to_Q(override_property_values: Optional[dict[str, Any]] = None,cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,using_database: str = "default",- *,- person_id: Optional[int] = None,- team_id: Optional[int] = None,) -> Q:if override_property_values is None:override_property_values = {}@@ -346,30 +343,6 @@ def property_to_Q(return Q(pk__isnull=True)if cohort.is_static:- # When a concrete person is in scope, short-circuit the Exists subquery- # with a direct membership check — routes through personhog when enabled,- # falling back to the persons-DB ORM otherwise. Mirrors the override- # short-circuit below (returning Q(pk__isnull=False|True)).- if person_id is not None and team_id is not None:- from products.cohorts.backend.models.util import is_person_in_cohort-- if is_person_in_cohort(team_id=team_id, person_id=person_id, cohort_id=cohort_id):- return Q(pk__isnull=False)- return Q(pk__isnull=True)-- # When team_id is available, list all member IDs and filter with- # Q(id__in=…) — routes through personhog when the gate is on,- # falling back to the CohortPeople table otherwise. This avoids- # the Exists(CohortPeople) subquery so the persons DB is not- # required on the personhog path.- if team_id is not None:- from products.cohorts.backend.models.util import list_cohort_member_ids-- member_ids = list_cohort_member_ids(team_id=team_id, cohort_id=cohort_id)- if not member_ids:- return Q(pk__isnull=True)- return Q(id__in=member_ids)-return Q(Exists(CohortPeople.objects.db_manager(using_database) # nosemgrep: no-direct-persons-db-orm@@ -390,8 +363,6 @@ def property_to_Q(override_property_values,cohorts_cache,using_database,- person_id=person_id,- team_id=team_id,)# short circuit query if key exists in override_property_values@@ -462,9 +433,6 @@ def property_group_to_Q(override_property_values: Optional[dict[str, Any]] = None,cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,using_database: str = "default",- *,- person_id: Optional[int] = None,- team_id: Optional[int] = None,) -> Q:if override_property_values is None:override_property_values = {}@@ -481,8 +449,6 @@ def property_group_to_Q(override_property_values,cohorts_cache,using_database,- person_id=person_id,- team_id=team_id,)if property_group.type == PropertyOperatorType.OR:filters |= group_filter@@ -497,8 +463,6 @@ def property_group_to_Q(override_property_values,cohorts_cache,using_database,- person_id=person_id,- team_id=team_id,)if property_group.type == PropertyOperatorType.OR:if property.negation:@@ -520,18 +484,10 @@ def properties_to_Q(override_property_values: Optional[dict[str, Any]] = None,cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,using_database: str = "default",- *,- person_id: Optional[int] = None,- team_id: Optional[int] = None,) -> Q:"""Converts a filter to Q, for use in Django ORM .filter()If you're filtering a Person/Group QuerySet, use is_direct_query to avoid doing an unnecessary nested loop-- When ``person_id`` and ``team_id`` are both provided, static-cohort- membership checks short-circuit through ``is_person_in_cohort`` (routed via- personhog when enabled) instead of emitting an ``Exists(CohortPeople)``- subquery — useful for per-person evaluation paths."""if override_property_values is None:override_property_values = {}@@ -546,8 +502,6 @@ def properties_to_Q(override_property_values,cohorts_cache,using_database,- person_id=person_id,- team_id=team_id,)diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 72fd7df45873..0dd3130cd0d6 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -647,11 +647,28 @@ def insert_cohort_from_filters(cohort_id: int, team_id: Optional[int] = None) ->)-@shared_task(ignore_result=True, max_retries=1)+# No task-level retry: transient failures are already retried per page with backoff+# inside get_cohort_actors_for_feature_flag, and by the time an exception propagates+# here the task has recorded final error state (calculation history, errors_calculating,+# is_calculating=False) — a Celery retry after that would contradict the recorded state.+# Runs on the long-running queue (like the sibling cohort tasks) so a large paging run+# can't clog the default workers, with a generous soft limit as a backstop ceiling.+# SoftTimeLimitExceeded subclasses Exception, so get_cohort_actors_for_feature_flag's+# except block records error state and re-raises it like any other failure.+@shared_task(+ ignore_result=True,+ max_retries=0,+ queue=CeleryQueue.LONG_RUNNING.value,+ soft_time_limit=4 * 60 * 60,+)def insert_cohort_from_feature_flag(cohort_id: int, flag_key: str, team_id: int) -> None:from posthog.api.cohort import get_cohort_actors_for_feature_flag- get_cohort_actors_for_feature_flag(cohort_id, flag_key, team_id, batchsize=10_000)+ # batchsize is also the per-page `limit` sent to the flags service, which evaluates a+ # page sequentially under a 120s request timeout. The service's hard cap is 10_000, but+ # paging at the cap risks a deterministic, retry-immune timeout on large or+ # condition-heavy flags, so page well below it.+ get_cohort_actors_for_feature_flag(cohort_id, flag_key, team_id, batchsize=2_000)def _collect_cohort_calculation_metrics(history: CohortCalculationHistory, start_time: datetime) -> None:diff --git a/posthog/utils.py b/posthog/utils.pyindex ed555df4a174..238abd330e78 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -1995,32 +1995,6 @@ def patchable(fn):return inner-def label_for_team_id_to_track(team_id: int) -> str:- """- LEGACY: Only used by flag_matching.py (cohort creation background task).- Returns empty string to avoid tracking specific team IDs in metrics.- """- team_id_as_string = str(team_id)- team_id_filter: list[str] = [] # No longer tracking specific teams-- if "all" in team_id_filter:- return team_id_as_string-- if team_id_as_string in team_id_filter:- return team_id_as_string-- team_id_ranges = [team_id_range for team_id_range in team_id_filter if ":" in team_id_range]- for range in team_id_ranges:- try:- start, end = range.split(":")- if int(start) <= team_id <= int(end):- return team_id_as_string- except Exception:- pass-- return "unknown"--def camel_to_snake_case(name: str) -> str:return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 83275135a118..0d9a48921c52 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -454,6 +454,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):batchsize=DEFAULT_COHORT_INSERT_BATCH_SIZE,*,team_id: int,+ raise_on_error: bool = False,) -> int:"""Insert a list of users identified by their UUID into the cohort, for the given team.@@ -462,13 +463,19 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):items: List of user UUIDs to be inserted into the cohort.batchsize: Number of UUIDs to process in each batch.team_id: The ID of the team to which the cohort belongs.+ raise_on_error: When True, a batch insert failure is re-raised and terminal+ cohort state is left for the caller to finalize, instead of being swallowed+ and recorded on the cohort here. Use when the caller records its own+ success/failure outcome and must not treat a partial insert as success.Returns:The number of batches processed."""batch_iterator = ArrayBatchIterator(items, batch_size=batchsize)- return self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)+ return self._insert_users_list_with_batching(+ batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error+ )def insert_users_by_email(self,@@ -544,6 +551,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):insert_in_clickhouse: bool = False,*,team_id: int,+ raise_on_error: bool = False,) -> int:"""Insert a list of users identified by their UUID into the cohort, for the given team.@@ -623,7 +631,10 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):except Exception as err:processing_error = err- if settings.DEBUG:+ # When the caller owns terminal-state finalization (raise_on_error), surface+ # the failure instead of swallowing it, so a partial insert can't be recorded+ # as success. The finally block below skips its own error save in this mode.+ if settings.DEBUG or raise_on_error:raisecapture_exception(err,@@ -651,7 +662,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):additional_properties={"cohort_id": self.id, "team_id": team_id},)- self._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)+ # In raise_on_error mode the caller finalizes cohort state on failure, so skip+ # the error save here to avoid double-counting errors_calculating. The success+ # path (processing_error is None) still finalizes state as usual.+ if not (raise_on_error and processing_error is not None):+ self._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)return current_batch_index + 1diff --git a/products/cohorts/backend/models/test/test_cohort_personhog.py b/products/cohorts/backend/models/test/test_cohort_personhog.pyindex db4b06245898..847bd06afd11 100644--- a/products/cohorts/backend/models/test/test_cohort_personhog.py+++ b/products/cohorts/backend/models/test/test_cohort_personhog.py@@ -4,8 +4,6 @@ via the ORM and personhog paths."""from posthog.test.base import BaseTestfrom unittest.mock import patch-from django.db.models import Q-from parameterized import parameterized_classfrom posthog.models import Person, Team@@ -337,89 +335,6 @@ class TestCheckCohortMembershipFallback(BaseTest):fake.assert_not_called("check_cohort_membership")-@parameterized_class(("personhog",), [(False,), (True,)])-class TestPropertyToQStaticCohortShortCircuit(PersonhogTestMixin, BaseTest):- """property_to_Q short-circuits the Exists(CohortPeople) subquery when- caller passes person_id + team_id for a static cohort."""-- def _make_cohort_property(self, cohort_id: int):- from posthog.models.property import Property-- return Property(key="id", value=cohort_id, type="cohort")-- def test_returns_match_all_q_when_person_is_member(self):- from posthog.queries.base import property_to_Q-- person = self._seed_person(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(cohort.id),- person_id=person.id,- team_id=self.team.id,- )-- assert q == Q(pk__isnull=False)- self._assert_personhog_called("check_cohort_membership")-- def test_returns_no_match_q_when_person_is_not_member(self):- from posthog.queries.base import property_to_Q-- person = self._seed_person(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(cohort.id),- person_id=person.id,- team_id=self.team.id,- )-- assert q == Q(pk__isnull=True)-- def test_falls_back_to_exists_without_person_id_or_team_id(self):- from posthog.queries.base import property_to_Q-- person = self._seed_person(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- q = property_to_Q(self.team.project_id, self._make_cohort_property(cohort.id))-- # Not a short-circuit Q — it's an Exists() wrapped in Q- assert q != Q(pk__isnull=False)- assert q != Q(pk__isnull=True)- # The Exists subquery path never calls either RPC- self._assert_personhog_not_called("check_cohort_membership")- self._assert_personhog_not_called("list_cohort_member_ids")-- def test_isolates_cohort_by_team_id(self):- """A cohort owned by a different team (even within the same project)- must resolve to Q(pk__isnull=True), regardless of any CohortPeople- rows or fake memberships set up for it."""- from posthog.queries.base import property_to_Q-- other_team = self.organization.teams.create(name="other", project=self.team.project)- person = self._seed_person(team=self.team, distinct_ids=["d1"])- other_team_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- # Plant a CohortPeople row and (in the personhog run) a fake membership- # so that a missing team scope would show up as a false positive.- CohortPeople.objects.create(cohort=other_team_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_team_cohort.id, is_member=True)-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(other_team_cohort.id),- person_id=person.id,- team_id=self.team.id,- )-- assert q == Q(pk__isnull=True)--@parameterized_class(("personhog",), [(False,), (True,)])class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):def test_returns_member_ids(self):@@ -493,71 +408,6 @@ class TestListCohortMemberIdsFallback(BaseTest):fake.assert_not_called("list_cohort_member_ids")-@parameterized_class(("personhog",), [(False,), (True,)])-class TestPropertyToQStaticCohortMemberList(PersonhogTestMixin, BaseTest):- """property_to_Q uses list_cohort_member_ids to produce Q(id__in=…) when- team_id is provided but person_id is not (queryset-wide filtering)."""-- def _make_cohort_property(self, cohort_id: int):- from posthog.models.property import Property-- return Property(key="id", value=cohort_id, type="cohort")-- def test_returns_id_in_q_with_team_id_and_no_person_id(self):- from posthog.queries.base import property_to_Q-- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=p1)- CohortPeople.objects.create(cohort=cohort, person=p2)- self._seed_cohort_membership(person_id=p1.id, cohort_id=cohort.id, is_member=True)- self._seed_cohort_membership(person_id=p2.id, cohort_id=cohort.id, is_member=True)-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(cohort.id),- team_id=self.team.id,- )-- matched = Person.objects.filter(team_id=self.team.id).filter(q)- assert sorted(matched.values_list("id", flat=True)) == sorted([p1.id, p2.id])- self._assert_personhog_called("list_cohort_member_ids")-- def test_returns_no_match_for_empty_cohort(self):- from posthog.queries.base import property_to_Q-- self._seed_person(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(cohort.id),- team_id=self.team.id,- )-- assert q == Q(pk__isnull=True)-- def test_filters_correctly_with_queryset(self):- from posthog.queries.base import property_to_Q-- member = self._seed_person(team=self.team, distinct_ids=["member"])- non_member = self._seed_person(team=self.team, distinct_ids=["outsider"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=member)- self._seed_cohort_membership(person_id=member.id, cohort_id=cohort.id, is_member=True)-- q = property_to_Q(- self.team.project_id,- self._make_cohort_property(cohort.id),- team_id=self.team.id,- )-- matched = set(Person.objects.filter(team_id=self.team.id).filter(q).values_list("id", flat=True))- assert member.id in matched- assert non_member.id not in matched--@parameterized_class(("personhog",), [(False,), (True,)])class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex d9323f15303b..b86a26f5c63d 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -80,6 +80,7 @@ class CohortErrorCode(StrEnum):INVALID_REGEX = "invalid_regex"INCOMPATIBLE_TYPES = "incompatible_types"NO_PROPERTIES = "no_properties"+ FLAG_CHANGED = "flag_changed"UNKNOWN = "unknown"@@ -97,6 +98,7 @@ ERROR_CODE_MESSAGES: dict[str, str] = {CohortErrorCode.NO_PROPERTIES: "This cohort has no matching criteria defined. Please add at least one.",CohortErrorCode.VALIDATION_ERROR: UNEXPECTED_ERROR_MESSAGE,CohortErrorCode.INCOMPATIBLE_TYPES: UNEXPECTED_ERROR_MESSAGE,+ CohortErrorCode.FLAG_CHANGED: "The feature flag changed while this cohort was being calculated. Please run the calculation again.",CohortErrorCode.UNKNOWN: UNEXPECTED_ERROR_MESSAGE,}diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 66c5bfa77122..1b833d69da5b 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -437,1326 +437,6 @@use_hive_partitioning=0'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator- '''- SELECT "posthog_team"."id",- "posthog_team"."project_id"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.1- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature2'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.2- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE ("posthog_cohort"."id" = 99999- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.3- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.4- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.5- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.6- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.7- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.8- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.9- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too- '''- SELECT "posthog_team"."id",- "posthog_team"."project_id"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.1- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature-new'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.2- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE ("posthog_cohort"."id" = 99999- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.3- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (NOT "posthog_cohort"."deleted"- AND "posthog_team"."project_id" = 99999)- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.4- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.5- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.6- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.7- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment- '''- SELECT "posthog_team"."id",- "posthog_team"."project_id"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.1- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature2'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.10- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.11- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.12- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.13- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort2'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.2- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE ("posthog_cohort"."id" = 99999- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.3- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.4- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.5- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.6- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.7- '''- SELECT "posthog_team"."id",- "posthog_team"."project_id"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.8- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature-new'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.9- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE ("posthog_cohort"."id" = 99999- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag- '''- SELECT "posthog_team"."id",- "posthog_team"."project_id"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.1- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature2'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.2- '''- SELECT "posthog_cohort"."id",- "posthog_cohort"."name",- "posthog_cohort"."description",- "posthog_cohort"."team_id",- "posthog_cohort"."deleted",- "posthog_cohort"."filters",- "posthog_cohort"."query",- "posthog_cohort"."version",- "posthog_cohort"."pending_version",- "posthog_cohort"."count",- "posthog_cohort"."created_by_id",- "posthog_cohort"."created_at",- "posthog_cohort"."is_calculating",- "posthog_cohort"."last_calculation",- "posthog_cohort"."last_calculation_duration_ms",- "posthog_cohort"."errors_calculating",- "posthog_cohort"."last_error_at",- "posthog_cohort"."last_backfill_person_properties_at",- "posthog_cohort"."last_realtime_cohort_calculation_at",- "posthog_cohort"."is_static",- "posthog_cohort"."kind",- "posthog_cohort"."cohort_type",- "posthog_cohort"."groups"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE ("posthog_cohort"."id" = 99999- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.3- '''- SELECT 1 AS "a"- FROM "posthog_cohort"- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")- WHERE (("posthog_cohort"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_cohort"."team_id" = 99999))- AND "posthog_cohort"."id" = 99999)- LIMIT 1- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.4- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.5- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.6- '''- SELECT "posthog_filesystemshortcut"."id",- "posthog_filesystemshortcut"."team_id",- "posthog_filesystemshortcut"."user_id",- "posthog_filesystemshortcut"."path",- "posthog_filesystemshortcut"."type",- "posthog_filesystemshortcut"."ref",- "posthog_filesystemshortcut"."href",- "posthog_filesystemshortcut"."order",- "posthog_filesystemshortcut"."created_at",- "posthog_filesystemshortcut"."surface"- FROM "posthog_filesystemshortcut"- WHERE (("posthog_filesystemshortcut"."surface" IS NULL- OR "posthog_filesystemshortcut"."surface" = 'web')- AND "posthog_filesystemshortcut"."ref" = '0001'- AND "posthog_filesystemshortcut"."team_id" = 99999- AND "posthog_filesystemshortcut"."type" = 'cohort'- AND NOT ("posthog_filesystemshortcut"."path" = 'some cohort'- AND "posthog_filesystemshortcut"."href" = '__skipped__'- AND "posthog_filesystemshortcut"."href" IS NOT NULL))- '''-# ---# name: TestFeatureFlag.test_creating_static_cohort'''SELECT "posthog_user"."id",@@ -2061,38 +741,6 @@'''# ---# name: TestFeatureFlag.test_creating_static_cohort.16- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'some-feature'- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestFeatureFlag.test_creating_static_cohort.17'''SELECT "posthog_cohort"."id","posthog_cohort"."name",@@ -2124,6 +772,38 @@LIMIT 21'''# ---+# name: TestFeatureFlag.test_creating_static_cohort.17+ '''+ SELECT "posthog_featureflag"."id",+ "posthog_featureflag"."key",+ "posthog_featureflag"."name",+ "posthog_featureflag"."filters",+ "posthog_featureflag"."team_id",+ "posthog_featureflag"."created_by_id",+ "posthog_featureflag"."created_at",+ "posthog_featureflag"."updated_at",+ "posthog_featureflag"."deleted",+ "posthog_featureflag"."active",+ "posthog_featureflag"."version",+ "posthog_featureflag"."last_modified_by_id",+ "posthog_featureflag"."rollback_conditions",+ "posthog_featureflag"."performed_rollback",+ "posthog_featureflag"."ensure_experience_continuity",+ "posthog_featureflag"."usage_dashboard_id",+ "posthog_featureflag"."has_enriched_analytics",+ "posthog_featureflag"."is_remote_configuration",+ "posthog_featureflag"."has_encrypted_payloads",+ "posthog_featureflag"."evaluation_runtime",+ "posthog_featureflag"."bucketing_identifier",+ "posthog_featureflag"."last_called_at"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'some-feature'+ AND "posthog_team"."project_id" = 99999)+ LIMIT 21+ '''+# ---# name: TestFeatureFlag.test_creating_static_cohort.18'''SELECT 1 AS "a"diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 1b993969d32b..be21b19a7fbe 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -19,12 +19,15 @@ from django.core.cache import cachefrom django.test import override_settingsfrom django.utils.timezone import now+import requestsfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom rest_framework import statusfrom rest_framework.relations import ManyRelatedFieldfrom posthog import redis-from posthog.api.cohort import get_cohort_actors_for_feature_flag+from posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flag+from posthog.api.services.flags_service import FlagVersionConflictErrorfrom posthog.constants import AvailableFeaturefrom posthog.models import GroupTypeMapping, TaggedItem, Userfrom posthog.models.group.group import Group@@ -37,7 +40,9 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.util import CohortErrorCode, get_friendly_error_messagefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment@@ -47,7 +52,6 @@ from products.feature_flags.backend.flag_status import FeatureFlagStatusfrom products.feature_flags.backend.models.feature_flag import (FeatureFlag,FeatureFlagDashboards,- FeatureFlagHashKeyOverride,get_feature_flags_for_team_in_cache,)from products.product_analytics.backend.models.insight import Insight@@ -6309,7 +6313,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@freeze_time("2021-01-01")@snapshot_clickhouse_queries- def test_creating_static_cohort(self):+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_creating_static_cohort(self, mock_batch_evaluate):flag = FeatureFlag.objects.create(team=self.team,filters={@@ -6321,7 +6326,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):created_by=self.user,)- _create_person(+ person1 = _create_person(team=self.team,distinct_ids=[f"person1"],properties={"key": "value"},@@ -6338,6 +6343,12 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):)flush_persons_and_events()+ mock_batch_evaluate.return_value = {+ "matched_person_uuids": [str(person1.uuid)],+ "next_cursor": None,+ "errors_count": 0,+ }+with (snapshot_postgres_queries_context(self),self.settings(@@ -7469,514 +7480,442 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):- def test_creating_static_cohort_with_deleted_flag(self):- FeatureFlag.objects.create(- team=self.team,- filters={+ """+ Orchestration tests for get_cohort_actors_for_feature_flag with the Rust batch+ evaluation HTTP client mocked. Evaluation correctness lives in the Rust service's+ own test suite (rust/feature-flags/tests/test_batch_flag_evaluation.rs).+ """++ def _create_flag(self, key: str = "some-feature", **kwargs) -> FeatureFlag:+ defaults: dict = {+ "team": self.team,+ "filters": {"groups": [{"properties": [{"key": "key", "value": "value", "type": "person"}]}],"multivariate": None,},- name="some feature",- key="some-feature",- created_by=self.user,- deleted=True,- )+ "name": "some feature",+ "key": key,+ "created_by": self.user,+ }+ defaults.update(kwargs)+ return FeatureFlag.objects.create(**defaults)- _create_person(- team=self.team,- distinct_ids=[f"person1"],- properties={"key": "value"},- )- flush_persons_and_events()+ def _create_static_cohort(self) -> Cohort:+ return Cohort.objects.create(team=self.team, is_static=True, name="some cohort")- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ @staticmethod+ def _page(uuids: list[str], next_cursor: int | None = None, errors_count: int = 0) -> dict:+ return {"matched_person_uuids": uuids, "next_cursor": next_cursor, "errors_count": errors_count}- with self.assertNumQueries(2):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)+ @staticmethod+ def _metric(name: str, **labels: str) -> float:+ # Metrics are process-global, so tests assert deltas against a before-value.+ return REGISTRY.get_sample_value(name, labels or None) or 0.0+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_deleted_flag_returns_empty_without_calling_service(self, mock_batch_evaluate):+ self._create_flag(deleted=True)+ cohort = self._create_static_cohort()++ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ mock_batch_evaluate.assert_not_called()cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")# don't even try inserting anything, because invalid flag, so None instead of 0self.assertEqual(cohort.count, None)- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 0, response)+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_inactive_flag_returns_empty_without_calling_service(self, mock_batch_evaluate):+ self._create_flag(active=False)+ cohort = self._create_static_cohort()- def test_creating_static_cohort_with_inactive_flag(self):- FeatureFlag.objects.create(- team=self.team,+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ mock_batch_evaluate.assert_not_called()+ cohort.refresh_from_db()+ self.assertEqual(cohort.count, None)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_group_flag_returns_empty_without_calling_service(self, mock_batch_evaluate):+ self._create_flag(filters={- "groups": [{"properties": [{"key": "key", "value": "value", "type": "person"}]}],+ "groups": [{"properties": [{"key": "key", "value": "value", "type": "group", "group_type_index": 1}]}],"multivariate": None,- },- name="some feature",- key="some-feature2",- created_by=self.user,- active=False,+ "aggregation_group_type_index": 1,+ })+ cohort = self._create_static_cohort()- _create_person(- team=self.team,- distinct_ids=[f"person1"],- properties={"key": "value"},- )- flush_persons_and_events()+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ mock_batch_evaluate.assert_not_called()+ cohort.refresh_from_db()+ self.assertEqual(cohort.count, None)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_non_existing_flag_returns_empty_without_calling_service(self, mock_batch_evaluate):+ cohort = self._create_static_cohort()- with self.assertNumQueries(2):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)+ get_cohort_actors_for_feature_flag(cohort.pk, "does-not-exist", self.team.pk)+ mock_batch_evaluate.assert_not_called()cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- # don't even try inserting anything, because invalid flag, so None instead of 0self.assertEqual(cohort.count, None)- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 0, response)-- @freeze_time("2021-01-01")- def test_creating_static_cohort_with_group_flag(self):- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [- {- "key": "key",- "value": "value",- "type": "group",- "group_type_index": 1,- }- ]+ @parameterized.expand(+ [+ ("inactive_flag", {"active": False}),+ (+ "group_aggregated_flag",+ {+ "filters": {+ "groups": [+ {"properties": [{"key": "key", "value": "value", "type": "group", "group_type_index": 1}]}+ ],+ "multivariate": None,+ "aggregation_group_type_index": 1,}- ],- "multivariate": None,- "aggregation_group_type_index": 1,- },- name="some feature",- key="some-feature3",- created_by=self.user,- )-- _create_person(- team=self.team,- distinct_ids=[f"person1"],- properties={"key": "value"},- )+ },+ ),+ ("missing_flag", None),+ ]+ )+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_guard_paths_clear_is_calculating(self, _name, flag_kwargs, mock_batch_evaluate):+ # The enqueue site sets is_calculating=True before dispatching, so every guard+ # exit must clear it rather than leave the cohort stuck. Each branch has its own+ # _safe_save_cohort_state call: the missing-flag exit (except FeatureFlag.DoesNotExist)+ # is separate from the combined inactive / group-aggregated branch.+ if flag_kwargs is not None:+ self._create_flag(**flag_kwargs)+ cohort = self._create_static_cohort()+ cohort.is_calculating = True+ cohort.save(update_fields=["is_calculating"])++ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ mock_batch_evaluate.assert_not_called()+ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_matched_persons_are_added_to_cohort(self, mock_batch_evaluate):+ self._create_flag()+ p1 = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)+ p2 = _create_person(team=self.team, distinct_ids=["person2"], properties={"key": "value"}, immediate=True)+ _create_person(team=self.team, distinct_ids=["person3"], properties={}, immediate=True)flush_persons_and_events()+ cohort = self._create_static_cohort()- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ mock_batch_evaluate.return_value = self._page([str(p1.uuid), str(p2.uuid)])- with self.assertNumQueries(2):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature3", self.team.pk)+ completed_before = self._metric("cohort_flag_generation_completed_total", outcome="success")+ duration_count_before = self._metric("cohort_flag_generation_duration_seconds_count", outcome="success")+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ self.assertEqual(+ self._metric("cohort_flag_generation_completed_total", outcome="success"), completed_before + 1+ )+ self.assertEqual(+ self._metric("cohort_flag_generation_duration_seconds_count", outcome="success"),+ duration_count_before + 1,+ )+ mock_batch_evaluate.assert_called_once_with(+ team_id=self.team.pk,+ project_id=self.team.project_id,+ flag_key="some-feature",+ expected_version=1,+ cursor=0,+ limit=1_000,+ )cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- # don't even try inserting anything, because invalid flag, so None instead of 0- self.assertEqual(cohort.count, None)+ self.assertEqual(cohort.count, 2)+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 0, response)+ self.assertEqual(len(response.json()["results"]), 2, response)- def test_creating_static_cohort_with_no_person_distinct_ids(self):- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": None,- },- name="some feature",- key="some-feature2",- created_by=self.user,- )+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_flag_matching_nobody_finalizes_empty_cohort(self, mock_batch_evaluate):+ self._create_flag()+ cohort = self._create_static_cohort()- Person.objects.create(team=self.team)+ # The final flush is unconditional precisely so a zero-match run still recomputes+ # count to 0 and clears is_calculating, instead of leaving the cohort stuck.+ mock_batch_evaluate.return_value = self._page([])- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )-- with self.assertNumQueries(6):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)+ mock_batch_evaluate.assert_called_once()cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- # don't even try inserting anything, because invalid flag, so None instead of 0- self.assertEqual(cohort.count, None)+ self.assertEqual(cohort.count, 0)+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_cursor_loop_advances_and_terminates(self, mock_batch_evaluate):+ self._create_flag()+ persons = [+ _create_person(team=self.team, distinct_ids=[f"person{i}"], properties={"key": "value"}, immediate=True)+ for i in range(3)+ ]+ flush_persons_and_events()+ cohort = self._create_static_cohort()- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 0, response)+ mock_batch_evaluate.side_effect = [+ self._page([str(persons[0].uuid)], next_cursor=100),+ self._page([str(persons[1].uuid)], next_cursor=200),+ self._page([str(persons[2].uuid)], next_cursor=None),+ ]- def test_creating_static_cohort_with_non_existing_flag(self):- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk, batchsize=2)- with self.assertNumQueries(2):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)+ self.assertEqual(mock_batch_evaluate.call_count, 3)+ cursors = [call.kwargs["cursor"] for call in mock_batch_evaluate.call_args_list]+ self.assertEqual(cursors, [0, 100, 200])+ limits = {call.kwargs["limit"] for call in mock_batch_evaluate.call_args_list}+ self.assertEqual(limits, {2})cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- # don't even try inserting anything, because invalid flag, so None instead of 0- self.assertEqual(cohort.count, None)+ self.assertEqual(cohort.count, 3)- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 0, response)+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_non_advancing_cursor_fails_instead_of_looping(self, mock_batch_evaluate):+ self._create_flag()+ cohort = self._create_static_cohort()- @patch("products.feature_flags.backend.tasks.update_team_flags_cache")- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_creating_static_cohort_with_experience_continuity_flag(self, mock_on_commit, mock_update_cache):- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [{"key": "key", "value": "value", "type": "person"}],- "rollout_percentage": 50,- }- ],- "multivariate": None,- },- name="some feature",- key="some-feature2",- created_by=self.user,- ensure_experience_continuity=True,- )+ mock_batch_evaluate.return_value = self._page([], next_cursor=0)- p1 = _create_person(- team=self.team,- distinct_ids=[f"person1"],- properties={"key": "value"},- immediate=True,- )- _create_person(- team=self.team,- distinct_ids=[f"person2"],- properties={"key": "value"},- )- _create_person(- team=self.team,- distinct_ids=[f"person3"],- properties={"key": "value"},- )+ with self.assertRaises(RuntimeError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ self.assertEqual(mock_batch_evaluate.call_count, 1)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)+ self.assertEqual(history.error, get_friendly_error_message(CohortErrorCode.UNKNOWN))++ @patch("posthog.api.cohort.time.sleep")+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_transient_errors_retry_then_succeed(self, mock_batch_evaluate, mock_sleep):+ self._create_flag()+ person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)flush_persons_and_events()+ cohort = self._create_static_cohort()- FeatureFlagHashKeyOverride.objects.create(- feature_flag_key="some-feature2",- person=p1,- team=self.team,- hash_key="123",- )+ mock_batch_evaluate.side_effect = [+ requests.ConnectionError("connection refused"),+ self._page([str(person.uuid)]),+ ]- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ retries_before = self._metric("cohort_flag_generation_page_retries_total")- # TODO: Ensure server-side cursors are disabled, since in production we use this with pgbouncer- with snapshot_postgres_queries_context(self), self.assertNumQueries(18):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)+ self.assertEqual(mock_batch_evaluate.call_count, 2)+ self.assertEqual(self._metric("cohort_flag_generation_page_retries_total"), retries_before + 1)cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")self.assertEqual(cohort.count, 1)+ self.assertEqual(cohort.errors_calculating, 0)- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 1, response)+ @patch("posthog.api.cohort.time.sleep")+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_persistent_errors_exhaust_retries_and_propagate(self, mock_batch_evaluate, mock_sleep):+ self._create_flag()+ cohort = self._create_static_cohort()- @patch("products.feature_flags.backend.tasks.update_team_flags_cache")- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_creating_static_cohort_iterator(self, mock_on_commit, mock_update_cache):- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [{"key": "key", "value": "value", "type": "person"}],- "rollout_percentage": 100,- }- ],- "multivariate": None,- },- name="some feature",- key="some-feature2",- created_by=self.user,- )+ mock_batch_evaluate.side_effect = requests.ConnectionError("connection refused")- _create_person(- team=self.team,- distinct_ids=[f"person1"],- properties={"key": "value"},- )- _create_person(- team=self.team,- distinct_ids=[f"person2"],- properties={"key": "value"},- )- _create_person(- team=self.team,- distinct_ids=[f"person3"],- properties={"key": "value"},- )- _create_person(- team=self.team,- distinct_ids=[f"person4"],- properties={"key": "valuu3"},- )- flush_persons_and_events()+ completed_before = self._metric("cohort_flag_generation_completed_total", outcome="unknown")- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",+ with self.assertRaises(requests.ConnectionError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ self.assertEqual(mock_batch_evaluate.call_count, BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS)+ self.assertEqual(+ self._metric("cohort_flag_generation_completed_total", outcome="unknown"), completed_before + 1)- # Extra queries because each batch adds its own queries- with snapshot_postgres_queries_context(self), self.assertNumQueries(25):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk, batchsize=2)+ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)+ # The user-visible error is the friendly message, never the raw exception+ # (which can contain internal service URLs).+ self.assertEqual(history.error, get_friendly_error_message(CohortErrorCode.UNKNOWN))+ assert history.error is not None+ self.assertNotIn("connection refused", history.error)++ @patch("posthog.api.cohort.time.sleep")+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_version_conflict_is_not_retried_and_surfaces_user_facing_error(self, mock_batch_evaluate, mock_sleep):+ self._create_flag()+ cohort = self._create_static_cohort()++ mock_batch_evaluate.side_effect = FlagVersionConflictError("flag changed during cohort generation")++ with self.assertRaises(FlagVersionConflictError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ # Permanent error: no retries+ self.assertEqual(mock_batch_evaluate.call_count, 1)+ mock_sleep.assert_not_called()cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- self.assertEqual(cohort.count, 3)+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.FLAG_CHANGED)+ self.assertEqual(+ get_friendly_error_message(history.error_code),+ "The feature flag changed while this cohort was being calculated. Please run the calculation again.",+ )- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 3, response)+ @patch("posthog.api.cohort.time.sleep")+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_client_errors_are_not_retried(self, mock_batch_evaluate, mock_sleep):+ self._create_flag()+ cohort = self._create_static_cohort()- # if the batch is big enough, it's fewer queries- with self.assertNumQueries(FuzzyInt(14, 17)):- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk, batchsize=10)+ response = requests.Response()+ response.status_code = 400+ mock_batch_evaluate.side_effect = requests.HTTPError(response=response)- cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- self.assertEqual(cohort.count, 3)+ with self.assertRaises(requests.HTTPError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)- response = self.client.get(f"/api/cohort/{cohort.pk}/persons")- self.assertEqual(len(response.json()["results"]), 3, response)+ self.assertEqual(mock_batch_evaluate.call_count, 1)+ mock_sleep.assert_not_called()- @patch("products.feature_flags.backend.tasks.update_team_flags_cache")- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_creating_static_cohort_with_default_person_properties_adjustment(self, mock_on_commit, mock_update_cache):- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [- {- "key": "key",- "value": "value",- "type": "person",- "operator": "icontains",- }- ],- "rollout_percentage": 100,- }- ],- "multivariate": None,- },- name="some feature",- key="some-feature2",- created_by=self.user,- ensure_experience_continuity=False,- )- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [- {- "key": "key",- "value": "value",- "type": "person",- "operator": "is_set",- }- ],- "rollout_percentage": 100,- }- ],- "multivariate": None,- },- name="some feature",- key="some-feature-new",- created_by=self.user,- ensure_experience_continuity=False,- )+ @patch("posthog.api.cohort.time.sleep")+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_server_errors_are_retried(self, mock_batch_evaluate, mock_sleep):+ self._create_flag()+ cohort = self._create_static_cohort()- _create_person(team=self.team, distinct_ids=[f"person1"], properties={"key": "value"})- _create_person(- team=self.team,- distinct_ids=[f"person2"],- properties={"key": "vaalue"},- )- _create_person(- team=self.team,- distinct_ids=[f"person3"],- properties={"key22": "value"},- )+ # A request timeout or overload surfaces as a 5xx HTTPError from raise_for_status,+ # which must fall through the 4xx permanent band and retry, unlike the 400 above.+ response = requests.Response()+ response.status_code = 503+ mock_batch_evaluate.side_effect = requests.HTTPError(response=response)++ with self.assertRaises(requests.HTTPError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ self.assertEqual(mock_batch_evaluate.call_count, BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_rerun_after_failure_is_idempotent(self, mock_batch_evaluate):+ # Re-running after a failure (e.g. the user triggers cohort generation again)+ # re-inserts the same UUIDs; inserts dedupe on (cohort_id, person_id) so the+ # count must not grow.+ self._create_flag()+ person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)flush_persons_and_events()+ cohort = self._create_static_cohort()- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ mock_batch_evaluate.return_value = self._page([str(person.uuid)])- with snapshot_postgres_queries_context(self), self.assertNumQueries(15):- # no queries to evaluate flags, because all evaluated using override properties- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")self.assertEqual(cohort.count, 1)response = self.client.get(f"/api/cohort/{cohort.pk}/persons")self.assertEqual(len(response.json()["results"]), 1, response)- cohort2 = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort2",- )+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_per_person_eval_errors_do_not_fail_the_run(self, mock_batch_evaluate):+ self._create_flag()+ person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)+ flush_persons_and_events()+ cohort = self._create_static_cohort()- with snapshot_postgres_queries_context(self), self.assertNumQueries(FuzzyInt(14, 17)):- # person3 doesn't match filter conditions so is pre-filtered out- get_cohort_actors_for_feature_flag(cohort2.pk, "some-feature-new", self.team.pk)+ mock_batch_evaluate.return_value = self._page([str(person.uuid)], errors_count=5)- cohort2.refresh_from_db()- self.assertEqual(cohort2.name, "some cohort2")- self.assertEqual(cohort2.count, 2)+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)- @patch("products.feature_flags.backend.tasks.update_team_flags_cache")- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too(- self, mock_on_commit, mock_update_cache- ):- cohort_nested = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "does-not-exist",- "value": "none",- "type": "person",- },- ],- }- ],- }- },- )- cohort_static = Cohort.objects.create(- team=self.team,- is_static=True,- )- cohort_existing = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {"key": "group", "value": "none", "type": "person"},- {"key": "group2", "value": [1, 2, 3], "type": "person"},- {- "key": "id",- "value": cohort_static.pk,- "type": "cohort",- },- {- "key": "id",- "value": cohort_nested.pk,- "type": "cohort",- },- ],- }- ],- }- },- name="cohort1",- )- FeatureFlag.objects.create(- team=self.team,- filters={- "groups": [- {- "properties": [{"key": "id", "value": cohort_existing.pk, "type": "cohort"}],- "rollout_percentage": 100,- },- {- "properties": [{"key": "key", "value": "value", "type": "person"}],- "rollout_percentage": 100,- },- ],- "multivariate": None,- },- name="some feature",- key="some-feature-new",- created_by=self.user,- ensure_experience_continuity=False,- )+ cohort.refresh_from_db()+ self.assertEqual(cohort.count, 1)+ self.assertEqual(cohort.errors_calculating, 0)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_insert_batching_flushes_mid_run(self, mock_batch_evaluate):+ # With batchsize=2 and 2 matches on the first of two pages, the buffer flushes+ # mid-run and the final flush still completes the cohort.+ self._create_flag()+ persons = [+ _create_person(team=self.team, distinct_ids=[f"person{i}"], properties={"key": "value"}, immediate=True)+ for i in range(3)+ ]+ flush_persons_and_events()+ cohort = self._create_static_cohort()- _create_person(team=self.team, distinct_ids=[f"person1"], properties={"key": "value"})- _create_person(- team=self.team,- distinct_ids=[f"person2"],- properties={"group": "none"},- )- _create_person(- team=self.team,- distinct_ids=[f"person3"],- properties={"key22": "value", "group2": 2},- )- _create_person(- team=self.team,- distinct_ids=[f"person4"],- properties={},- )+ mock_batch_evaluate.side_effect = [+ self._page([str(persons[0].uuid), str(persons[1].uuid)], next_cursor=50),+ self._page([str(persons[2].uuid)], next_cursor=None),+ ]++ with patch.object(+ Cohort, "insert_users_list_by_uuid", autospec=True, side_effect=Cohort.insert_users_list_by_uuid+ ) as mock_insert:+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk, batchsize=2)++ # One mid-run flush (buffer hit batchsize) + the final flush+ self.assertEqual(mock_insert.call_count, 2)+ cohort.refresh_from_db()+ self.assertEqual(cohort.count, 3)++ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_insert_failure_is_recorded_as_failure_not_success(self, mock_batch_evaluate):+ # A DB/ClickHouse failure while inserting matched persons must surface as a failed+ # generation (the insert runs with raise_on_error=True), not be swallowed and+ # counted as success. DEBUG is forced off so the production swallow path is what+ # would run without raise_on_error.+ self._create_flag()+ person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)flush_persons_and_events()+ cohort = self._create_static_cohort()- cohort_static.insert_users_by_list([f"person4"])+ mock_batch_evaluate.return_value = self._page([str(person.uuid)])- cohort = Cohort.objects.create(- team=self.team,- is_static=True,- name="some cohort",- )+ success_before = self._metric("cohort_flag_generation_completed_total", outcome="success")+ unknown_before = self._metric("cohort_flag_generation_completed_total", outcome="unknown")++ with (+ self.settings(DEBUG=False),+ patch("posthog.personhog_client.gate.use_personhog", return_value=False),+ patch(+ "products.cohorts.backend.models.util.insert_static_cohort",+ side_effect=Exception("clickhouse insert failed"),+ ),+ self.assertRaises(Exception),+ ):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)- with snapshot_postgres_queries_context(self), self.assertNumQueries(32):- # forced to evaluate flags by going to db, because cohorts need db query to evaluate- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature-new", self.team.pk)+ # Recorded as a failure, never as success.+ self.assertEqual(self._metric("cohort_flag_generation_completed_total", outcome="success"), success_before)+ self.assertEqual(self._metric("cohort_flag_generation_completed_total", outcome="unknown"), unknown_before + 1)cohort.refresh_from_db()- self.assertEqual(cohort.name, "some cohort")- self.assertEqual(cohort.count, 4)+ self.assertFalse(cohort.is_calculating)+ # A single error save (the orchestrator's), not double-counted by the insert helper.+ self.assertEqual(cohort.errors_calculating, 1)+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):diff --git a/products/feature_flags/backend/flag_matching.py b/products/feature_flags/backend/flag_matching.pydeleted file mode 100644index 24274f51a228..000000000000--- a/products/feature_flags/backend/flag_matching.py+++ /dev/null@@ -1,760 +0,0 @@-"""-Legacy Python-based feature flag evaluation, used only by the-"create static cohort from feature flag" background task-(posthog/tasks/calculate_cohort.py -> posthog/api/cohort.py:get_cohort_actors_for_feature_flag).--Exported symbols: FeatureFlagMatcher, FlagsMatcherCache, get_feature_flag_hash_key_overrides.--All other flag evaluation uses the Rust flags service.-DO NOT add new callers — if you need flag evaluation, call FEATURE_FLAGS_SERVICE_URL/flags.-"""--import hashlib-from dataclasses import dataclass-from enum import StrEnum-from typing import Literal, Optional, Union, cast--from django.db import DatabaseError-from django.db.models import CharField, Expression, F, Func, Q-from django.db.models.expressions import ExpressionWrapper, RawSQL-from django.db.models.fields import BooleanField-from django.db.models.query import QuerySet--import structlog--from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING-from posthog.models.filters import Filter-from posthog.models.filters.mixins.utils import cached_property-from posthog.models.group import Group-from posthog.models.person import Person, PersonDistinctId-from posthog.models.property import GroupTypeIndex, GroupTypeName-from posthog.models.property.property import Property-from posthog.models.utils import execute_with_timeout-from posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITE-from posthog.queries.base import match_property, properties_to_Q, sanitize_property_key--from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty-from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payload--from .models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride--logger = structlog.get_logger(__name__)--__LONG_SCALE__ = float(0xFFFFFFFFFFFFFFF)--FLAG_MATCHING_QUERY_TIMEOUT_MS = 500 # 500 ms. Any longer and we'll just error out.--ENTITY_EXISTS_PREFIX = "flag_entity_exists_"-PERSON_KEY = "person"--# Use centralized database routing constants-READ_ONLY_DATABASE_FOR_PERSONS = PERSONS_DB_FOR_READ-WRITE_DATABASE_FOR_PERSONS = PERSONS_DB_FOR_WRITE---class FeatureFlagMatchReason(StrEnum):- SUPER_CONDITION_VALUE = "super_condition_value"- HOLDOUT_CONDITION_VALUE = "holdout_condition_value"- CONDITION_MATCH = "condition_match"- NO_CONDITION_MATCH = "no_condition_match"- OUT_OF_ROLLOUT_BOUND = "out_of_rollout_bound"- NO_GROUP_TYPE = "no_group_type"-- def score(self) -> float:- match self:- case FeatureFlagMatchReason.SUPER_CONDITION_VALUE:- return 4- case FeatureFlagMatchReason.HOLDOUT_CONDITION_VALUE:- return 3.5- case FeatureFlagMatchReason.CONDITION_MATCH:- return 3- case FeatureFlagMatchReason.NO_GROUP_TYPE:- return 2- case FeatureFlagMatchReason.OUT_OF_ROLLOUT_BOUND:- return 1- case FeatureFlagMatchReason.NO_CONDITION_MATCH:- return 0- case _:- raise AssertionError("Unreachable - all enum cases are handled")-- def __lt__(self, other):- if self.__class__ is other.__class__:- return self.score() < other.score()-- raise NotImplementedError(f"Cannot compare {self.__class__} and {other.__class__}")---@dataclass(frozen=True)-class FeatureFlagMatch:- match: bool = False- variant: Optional[str] = None- reason: FeatureFlagMatchReason = FeatureFlagMatchReason.NO_CONDITION_MATCH- condition_index: Optional[int] = None- payload: Optional[object] = None---class FlagsMatcherCache:- def __init__(self, project_id: int):- self.project_id = project_id- self.failed_to_fetch_flags = False-- @cached_property- def group_types_to_indexes(self) -> dict[GroupTypeName, GroupTypeIndex]:- if self.failed_to_fetch_flags:- raise DatabaseError("Failed to fetch group type mapping previously, not trying again.")- try:- from posthog.models.group_type_mapping import get_group_types_for_project-- rows = get_group_types_for_project(self.project_id)- return {row["group_type"]: cast(GroupTypeIndex, row["group_type_index"]) for row in rows}- except DatabaseError as e:- logger.exception("group_types_to_indexes database error", error=str(e), exc_info=True)- self.failed_to_fetch_flags = True- raise-- @cached_property- def group_type_index_to_name(self) -> dict[GroupTypeIndex, GroupTypeName]:- return {value: key for key, value in self.group_types_to_indexes.items()}---class FeatureFlagMatcher:- failed_to_fetch_conditions = False-- def __init__(- self,- team_id: int,- project_id: int,- feature_flags: list[FeatureFlag],- distinct_id: str,- groups: Optional[dict[GroupTypeName, str]] = None,- cache: Optional[FlagsMatcherCache] = None,- hash_key_overrides: Optional[dict[str, str]] = None,- property_value_overrides: Optional[dict[str, Union[str, int]]] = None,- group_property_value_overrides: Optional[dict[str, dict[str, Union[str, int]]]] = None,- skip_database_flags: bool = False,- cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,- ):- if group_property_value_overrides is None:- group_property_value_overrides = {}- if property_value_overrides is None:- property_value_overrides = {}- if hash_key_overrides is None:- hash_key_overrides = {}- if groups is None:- groups = {}- self.team_id = team_id- self.project_id = project_id- self.feature_flags = feature_flags- self.distinct_id = distinct_id- self.groups = groups- self.cache = cache or FlagsMatcherCache(project_id)- self.hash_key_overrides = hash_key_overrides- self.property_value_overrides = property_value_overrides- self.group_property_value_overrides = group_property_value_overrides- self.skip_database_flags = skip_database_flags-- if cohorts_cache is None:- self.cohorts_cache = {}- else:- self.cohorts_cache = cohorts_cache-- def get_match(self, feature_flag: FeatureFlag) -> FeatureFlagMatch:- # If aggregating flag by groups and relevant group type is not passed - flag is off!- if self.hashed_identifier(feature_flag) is None:- return FeatureFlagMatch(match=False, reason=FeatureFlagMatchReason.NO_GROUP_TYPE)-- highest_priority_evaluation_reason = FeatureFlagMatchReason.NO_CONDITION_MATCH- highest_priority_index = 0-- # Match for early access feature enrollment first- if feature_flag.has_feature_enrollment:- (- is_match,- enrollment_value,- evaluation_reason,- ) = self.is_feature_enrollment_match(feature_flag)- if is_match:- payload = self.get_matching_payload(enrollment_value, None, feature_flag)- return FeatureFlagMatch(- match=enrollment_value,- reason=evaluation_reason,- condition_index=0,- payload=payload,- )-- # Match for holdout condition- if feature_flag.filters.get("holdout", None):- (- is_match,- holdout_value,- evaluation_reason,- ) = self.is_holdout_condition_match(feature_flag)- if is_match:- payload = self.get_matching_payload(is_match, holdout_value, feature_flag)- return FeatureFlagMatch(- match=is_match,- variant=holdout_value,- reason=evaluation_reason,- condition_index=0,- payload=payload,- )-- # Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are- # evaluated first, and the variant override is applied to the first matching condition.- # :TRICKY: We need to include the enumeration index before the sort so the flag evaluation reason gets the right condition index.- sorted_flag_conditions = sorted(- enumerate(feature_flag.conditions),- key=lambda condition_tuple: 0 if condition_tuple[1].get("variant") else 1,- )- for index, condition in sorted_flag_conditions:- is_match, evaluation_reason = self.is_condition_match(feature_flag, condition, index)- if is_match:- variant_override = condition.get("variant")- if variant_override in [variant["key"] for variant in feature_flag.variants]:- variant = variant_override- else:- variant = self.get_matching_variant(feature_flag)-- payload = self.get_matching_payload(is_match, variant, feature_flag)- return FeatureFlagMatch(- match=True,- variant=variant,- reason=evaluation_reason,- condition_index=index,- payload=payload,- )-- (- highest_priority_evaluation_reason,- highest_priority_index,- ) = self.get_highest_priority_match_evaluation(- highest_priority_evaluation_reason,- highest_priority_index,- evaluation_reason,- index,- )-- return FeatureFlagMatch(- match=False,- reason=highest_priority_evaluation_reason,- condition_index=highest_priority_index,- payload=None,- )-- def get_matching_variant(self, feature_flag: FeatureFlag) -> Optional[str]:- # Calculate hash once outside the loop since it's the same for all variants- variant_hash = self.get_hash(feature_flag, salt="variant")- for variant in self.variant_lookup_table(feature_flag):- if variant_hash >= variant["value_min"] and variant_hash < variant["value_max"]:- return variant["key"]- return None-- def get_matching_payload(- self, is_match: bool, match_variant: Optional[str], feature_flag: FeatureFlag- ) -> Optional[object]:- if is_match:- if match_variant:- return feature_flag.get_payload(match_variant)- else:- return (- feature_flag.get_payload("true")- if not feature_flag.has_encrypted_payloads- else get_decrypted_flag_payload(feature_flag.get_payload("true"), should_decrypt=False)- )- else:- return None-- def is_holdout_condition_match(self, feature_flag: FeatureFlag) -> tuple[bool, str | None, FeatureFlagMatchReason]:- holdout = feature_flag.holdout- if not holdout:- return False, None, FeatureFlagMatchReason.NO_CONDITION_MATCH-- percentage = holdout.get("exclusion_percentage")- if percentage is not None and self.get_holdout_hash(feature_flag) > (percentage / 100):- return False, None, FeatureFlagMatchReason.OUT_OF_ROLLOUT_BOUND-- variant = f"holdout-{holdout['id']}"- return True, variant, FeatureFlagMatchReason.HOLDOUT_CONDITION_VALUE-- def is_feature_enrollment_match(self, feature_flag: FeatureFlag) -> tuple[bool, bool, FeatureFlagMatchReason]:- is_set_key = f"flag_{feature_flag.pk}_enrollment_is_set"- enrollment_is_set = self.query_conditions.get(is_set_key)-- if enrollment_is_set is None:- logger.debug(- "feature_enrollment_query_missing",- flag_id=feature_flag.pk,- flag_key=feature_flag.key,- )- return False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH-- enrollment_matches = self._get_query_condition(f"flag_{feature_flag.pk}_enrollment")- if enrollment_is_set:- return (True, enrollment_matches, FeatureFlagMatchReason.SUPER_CONDITION_VALUE)-- return False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH-- def is_condition_match(- self, feature_flag: FeatureFlag, condition: dict, condition_index: int- ) -> tuple[bool, FeatureFlagMatchReason]:- rollout_percentage = condition.get("rollout_percentage")- properties = condition.get("properties")- if properties and len(properties) > 0:- properties = Filter(data=condition).property_groups.flat- if self.can_compute_locally(properties, feature_flag.aggregation_group_type_index):- # :TRICKY: If overrides are enough to determine if a condition is a match,- # we can skip checking the query.- # This ensures match even if the person hasn't been ingested yet.- target_properties = self.property_value_overrides- if feature_flag.aggregation_group_type_index is not None:- target_properties = self.group_property_value_overrides.get(- self.cache.group_type_index_to_name[feature_flag.aggregation_group_type_index],- {},- )- condition_match = all(match_property(property, target_properties) for property in properties)- else:- match_if_entity_doesnt_exist = check_pure_is_not_operator_condition(condition)- condition_match = self._condition_matches(- feature_flag,- condition_index,- match_if_entity_doesnt_exist,- feature_flag.aggregation_group_type_index,- )-- if not condition_match:- return False, FeatureFlagMatchReason.NO_CONDITION_MATCH- elif rollout_percentage is None:- return True, FeatureFlagMatchReason.CONDITION_MATCH-- if rollout_percentage is not None and self.get_hash(feature_flag) > (rollout_percentage / 100):- return False, FeatureFlagMatchReason.OUT_OF_ROLLOUT_BOUND-- return True, FeatureFlagMatchReason.CONDITION_MATCH-- def _condition_matches(- self,- feature_flag: FeatureFlag,- condition_index: int,- match_if_entity_doesnt_exist: bool = False,- group_type_index: Optional[GroupTypeIndex] = None,- ) -> bool:- return self._get_query_condition(- f"flag_{feature_flag.pk}_condition_{condition_index}", match_if_entity_doesnt_exist, group_type_index- )-- def _get_query_condition(- self, key: str, match_if_entity_doesnt_exist: bool = False, group_type_index: Optional[GroupTypeIndex] = None- ) -> bool:- if self.failed_to_fetch_conditions:- raise DatabaseError("Failed to fetch conditions for feature flag previously, not trying again.")- if self.skip_database_flags:- raise DatabaseError("Database healthcheck failed, not fetching flag conditions.")-- # :TRICKY: Currently this option is only set with the is_not_set operator, but we can shortcircuit the condition check- # if the person doesn't exist. This is important as it allows resolving flags correctly for non-ingested persons.- if match_if_entity_doesnt_exist:- existence_key = f"{ENTITY_EXISTS_PREFIX}{group_type_index if group_type_index is not None else PERSON_KEY}"- entity_doesnt_exist = self.query_conditions.get(existence_key) is False- # :TRICKY: We only return if entity doesn't exist, because if it does, we still need to check the condition properly.- if entity_doesnt_exist:- return True-- return self.query_conditions.get(key, False)-- # Define contiguous sub-domains within [0, 1].- # By looking up a random hash value, you can find the associated variant key.- # e.g. the first of two variants with 50% rollout percentage will have value_max: 0.5- # and the second will have value_min: 0.5 and value_max: 1.0- def variant_lookup_table(self, feature_flag: FeatureFlag):- lookup_table = []- value_min = 0- for variant in feature_flag.variants:- value_max = value_min + variant["rollout_percentage"] / 100- lookup_table.append({"value_min": value_min, "value_max": value_max, "key": variant["key"]})- value_min = value_max- return lookup_table-- @cached_property- def query_conditions(self) -> dict[str, bool]:- try:- with execute_with_timeout(FLAG_MATCHING_QUERY_TIMEOUT_MS * 2, READ_ONLY_DATABASE_FOR_PERSONS):- # Some extra wiggle room here for timeouts because this depends on the number of flags as well,- # and not just the database query.- all_conditions: dict = {}- person_query: QuerySet = Person.objects.db_manager( # nosemgrep: no-direct-persons-db-orm- READ_ONLY_DATABASE_FOR_PERSONS- ).filter( # nosemgrep: no-direct-persons-db-orm- team_id=self.team_id,- persondistinctid__distinct_id=self.distinct_id,- persondistinctid__team_id=self.team_id,- )- basic_group_query: QuerySet = Group.objects.db_manager( # nosemgrep: no-direct-persons-db-orm- READ_ONLY_DATABASE_FOR_PERSONS- ).filter( # nosemgrep: no-direct-persons-db-orm- team_id=self.team_id- )- group_query_per_group_type_mapping: dict[GroupTypeIndex, tuple[QuerySet, list[str]]] = {}- # :TRICKY: Create a queryset for each group type that uniquely identifies a group, based on the groups passed in.- # If no groups for a group type are passed in, we can skip querying for that group type,- # since the result will always be `false`.- for group_type, group_key in self.groups.items():- group_type_index = self.cache.group_types_to_indexes.get(group_type)- if group_type_index is not None:- # a tuple of querySet and field names- group_query_per_group_type_mapping[group_type_index] = (- basic_group_query.filter(group_type_index=group_type_index, group_key=group_key),- [],- )-- person_fields: list[str] = []-- for existence_condition_key in self.has_pure_is_not_conditions:- if existence_condition_key == PERSON_KEY:- person_exists = person_query.exists()- all_conditions[f"{ENTITY_EXISTS_PREFIX}{PERSON_KEY}"] = person_exists- else:- if existence_condition_key not in group_query_per_group_type_mapping:- continue-- group_query, _ = group_query_per_group_type_mapping[- cast(GroupTypeIndex, existence_condition_key)- ]- group_exists = group_query.exists()- all_conditions[f"{ENTITY_EXISTS_PREFIX}{existence_condition_key}"] = group_exists-- def condition_eval(key, condition):- expr = None- annotate_query = True- nonlocal person_query-- property_list = Filter(data=condition).property_groups.flat- properties_with_math_operators = get_all_properties_with_math_operators(- property_list, self.cohorts_cache, self.project_id- )-- if len(condition.get("properties", {})) > 0:- # Feature Flags don't support OR filtering yet- target_properties = self.property_value_overrides- if feature_flag.aggregation_group_type_index is not None:- if feature_flag.aggregation_group_type_index not in self.cache.group_type_index_to_name:- target_properties = {}- else:- target_properties = self.group_property_value_overrides.get(- self.cache.group_type_index_to_name[feature_flag.aggregation_group_type_index],- {},- )-- expr = properties_to_Q(- self.project_id,- property_list,- override_property_values=target_properties,- cohorts_cache=self.cohorts_cache,- using_database=READ_ONLY_DATABASE_FOR_PERSONS,- )-- # TRICKY: Due to property overrides for cohorts, we sometimes shortcircuit the condition check.- # In that case, the expression is either an explicit True or explicit False, or multiple conditions.- # We can skip going to the database in explicit True|False conditions. This is important- # as it allows resolving flags correctly for non-ingested persons.- # However, this doesn't work for the multiple condition case (when expr has multiple Q objects),- # but it's better than nothing.- # TODO: A proper fix would be to handle cohorts with property overrides before we get to this point.- # Unskip test test_complex_cohort_filter_with_override_properties when we fix this.- if expr == Q(pk__isnull=False):- all_conditions[key] = True- annotate_query = False- elif expr == Q(pk__isnull=True):- all_conditions[key] = False- annotate_query = False-- if annotate_query:- if feature_flag.aggregation_group_type_index is None:- # :TRICKY: Flag matching depends on type of property when doing >, <, >=, <= comparisons.- # This requires a generated field to query in Q objects, which sadly don't allow inlining fields,- # hence we need to annotate the query here, even though these annotations are used much deeper,- # in properties_to_q, in empty_or_null_with_value_q- # These need to come in before the expr so they're available to use inside the expr.- # Same holds for the group queries below.- type_property_annotations = _get_property_type_annotations(properties_with_math_operators)- person_query = person_query.annotate(- **type_property_annotations,- **{- key: ExpressionWrapper(- # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (literal "true", no user input)- cast(Expression, expr if expr else RawSQL("true", [])),- output_field=BooleanField(),- ),- },- )- person_fields.append(key)- else:- if feature_flag.aggregation_group_type_index not in group_query_per_group_type_mapping:- # ignore flags that didn't have the right groups passed in- return- (- group_query,- group_fields,- ) = group_query_per_group_type_mapping[feature_flag.aggregation_group_type_index]- type_property_annotations = _get_property_type_annotations(properties_with_math_operators)- group_query = group_query.annotate(- **type_property_annotations,- **{- key: ExpressionWrapper(- # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (literal "true", no user input)- cast(Expression, expr if expr else RawSQL("true", [])),- output_field=BooleanField(),- ),- },- )- group_fields.append(key)- group_query_per_group_type_mapping[feature_flag.aggregation_group_type_index] = (- group_query,- group_fields,- )-- # only fetch all cohorts if not passed in any cached cohorts- if not self.cohorts_cache and any(feature_flag.uses_cohorts for feature_flag in self.feature_flags):- with execute_with_timeout(FLAG_MATCHING_QUERY_TIMEOUT_MS * 2, DATABASE_FOR_FLAG_MATCHING):- all_cohorts = {- cohort.pk: cohort- for cohort in Cohort.objects.db_manager(DATABASE_FOR_FLAG_MATCHING).filter(- team__project_id=self.project_id, deleted=False- )- }- self.cohorts_cache.update(all_cohorts)- # release conditions- for feature_flag in self.feature_flags:- # early access feature enrollment- if feature_flag.has_feature_enrollment:- enrollment_key = f"$feature_enrollment/{feature_flag.key}"- enrollment_condition = {- "properties": [- {- "key": enrollment_key,- "value": ["true"],- "operator": "exact",- "type": "person",- }- ]- }- condition_eval(f"flag_{feature_flag.pk}_enrollment", enrollment_condition)-- is_set_condition = {- "properties": [- {- "key": enrollment_key,- "operator": "is_set",- }- ]- }- condition_eval(f"flag_{feature_flag.pk}_enrollment_is_set", is_set_condition)-- for index, condition in enumerate(feature_flag.conditions):- key = f"flag_{feature_flag.pk}_condition_{index}"- condition_eval(key, condition)-- if len(person_fields) > 0:- person_query = person_query.values(*person_fields)- if len(person_query) > 0:- all_conditions = {**all_conditions, **person_query[0]}- if len(group_query_per_group_type_mapping) > 0:- for (- group_query,- group_fields,- ) in group_query_per_group_type_mapping.values():- # Only query the group if there's a field to query- if len(group_fields) > 0:- group_query = group_query.values(*group_fields)- if len(group_query) > 0:- assert len(group_query) == 1, f"Expected 1 group query result, got {len(group_query)}"- all_conditions = {**all_conditions, **group_query[0]}- return all_conditions- except DatabaseError as e:- logger.exception("query_conditions database error", error=str(e), exc_info=True)- self.failed_to_fetch_conditions = True- raise- except Exception:- # Usually when a user somehow manages to create an invalid filter, usually via API.- # In this case, don't put db down, just skip the flag.- # Covers all cases like invalid JSON, invalid operator, invalid property name, invalid group input format, etc.- raise-- def hashed_identifier(self, feature_flag: FeatureFlag) -> Optional[str]:- """- If aggregating by people, returns distinct_id.-- Otherwise, returns the relevant group_key.-- If relevant group is not passed to the flag, None is returned and handled in get_match.- """- if feature_flag.aggregation_group_type_index is None:- if feature_flag.ensure_experience_continuity:- # TODO: Try a global cache- if feature_flag.key in self.hash_key_overrides:- return self.hash_key_overrides[feature_flag.key]- return self.distinct_id- else:- # TODO: Don't use the cache if self.groups is empty, since that means no groups provided anyway- # :TRICKY: If aggregating by groups- group_type_name = self.cache.group_type_index_to_name.get(feature_flag.aggregation_group_type_index)- if group_type_name is None:- return None- group_key = self.groups.get(group_type_name)- return group_key-- # This function takes a identifier and a feature flag key and returns a float between 0 and 1.- # Given the same identifier and key, it'll always return the same float. These floats are- # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic- # we can do _hash(key, identifier) < 0.2- def get_hash(self, feature_flag: FeatureFlag, salt="") -> float:- return self.calculate_hash(f"{feature_flag.key}.", self.hashed_identifier(feature_flag), salt)-- # This function takes a identifier and a feature flag and returns a float between 0 and 1.- # Given the same identifier and key, it'll always return the same float. These floats are- # uniformly distributed between 0 and 1, and are keyed only on user's distinct id / group key.- # Thus, irrespective of the flag, the same user will always get the same value.- def get_holdout_hash(self, feature_flag: FeatureFlag, salt="") -> float:- return self.calculate_hash("holdout-", self.hashed_identifier(feature_flag), salt)-- @classmethod- def calculate_hash(cls, prefix: str, hash_identifier: str | None, salt="") -> float:- if hash_identifier is None:- # Return a hash value that will make the flag evaluate to false; since we- # can't evaluate a flag without an identifier.- # NB: A flag with 0.0 hash will always evaluate to false- return 0- hash_key = f"{prefix}{hash_identifier}{salt}"- # this hash is for uniform distribution and has no security impact- # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1- hash_val = int(hashlib.sha1(hash_key.encode("utf-8")).hexdigest()[:15], 16)- return hash_val / __LONG_SCALE__-- def can_compute_locally(- self,- properties: list[Property],- group_type_index: Optional[GroupTypeIndex] = None,- ) -> bool:- target_properties = self.property_value_overrides- if group_type_index is not None:- target_properties = self.group_property_value_overrides.get(- self.cache.group_type_index_to_name[group_type_index], {}- )- for property in properties:- # can't locally compute if property is a cohort- # need to atleast fetch the cohort- if property.type == "cohort":- return False- if property.key not in target_properties:- return False- return True-- def get_highest_priority_match_evaluation(- self,- current_match: FeatureFlagMatchReason,- current_index: int,- new_match: FeatureFlagMatchReason,- new_index: int,- ):- if current_match <= new_match:- return new_match, new_index-- return current_match, current_index-- @cached_property- def has_pure_is_not_conditions(self) -> set[Literal["person"] | GroupTypeIndex]:- entity_to_condition_check: set[Literal["person"] | GroupTypeIndex] = set()- for feature_flag in self.feature_flags:- for condition in feature_flag.conditions:- if check_pure_is_not_operator_condition(condition):- if feature_flag.aggregation_group_type_index is not None:- entity_to_condition_check.add(feature_flag.aggregation_group_type_index)- else:- entity_to_condition_check.add("person")-- return entity_to_condition_check---def get_feature_flag_hash_key_overrides(- team_id: int,- distinct_ids: list[str],- using_database: str = WRITE_DATABASE_FOR_PERSONS,- person_id_to_distinct_id_mapping: Optional[dict[int, str]] = None,-) -> dict[str, str]:- feature_flag_to_key_overrides = {}-- # Priority to the first distinctID's values, to keep this function deterministic-- if not person_id_to_distinct_id_mapping:- person_and_distinct_ids = list(- PersonDistinctId.objects.db_manager(using_database) # nosemgrep: no-direct-persons-db-orm- .filter(distinct_id__in=distinct_ids, team_id=team_id)- .values_list("person_id", "distinct_id")- )- person_id_to_distinct_id = dict(person_and_distinct_ids)- else:- person_id_to_distinct_id = person_id_to_distinct_id_mapping-- person_ids = list(person_id_to_distinct_id.keys())-- for feature_flag, override, _ in sorted(- FeatureFlagHashKeyOverride.objects.db_manager(using_database) # nosemgrep: no-direct-persons-db-orm- .filter(person_id__in=person_ids, team_id=team_id)- .values_list("feature_flag_key", "hash_key", "person_id"),- key=lambda x: 1 if person_id_to_distinct_id.get(x[2], "") == distinct_ids[0] else -1,- # We want the highest priority to go last in sort order, so it's the latest update in the dict- ):- feature_flag_to_key_overrides[feature_flag] = override-- return feature_flag_to_key_overrides---def key_and_field_for_property(property: Property) -> tuple[str, str]:- column = "group_properties" if property.type == "group" else "properties"- key = property.key- sanitized_key = sanitize_property_key(key)-- return (- f"{column}_{sanitized_key}_type",- f"{column}__{key}",- )---def get_all_properties_with_math_operators(- properties: list[Property], cohorts_cache: dict[int, CohortOrEmpty], project_id: int-) -> list[tuple[str, str]]:- all_keys_and_fields = []-- for prop in properties:- if prop.type == "cohort":- cohort_id = int(cast(Union[str, int], prop.value))- if cohorts_cache.get(cohort_id) is None:- queried_cohort = (- Cohort.objects.db_manager(DATABASE_FOR_FLAG_MATCHING)- .filter(pk=cohort_id, team__project_id=project_id, deleted=False)- .first()- )- cohorts_cache[cohort_id] = queried_cohort or ""-- cohort = cohorts_cache[cohort_id]- if cohort:- all_keys_and_fields.extend(- get_all_properties_with_math_operators(cohort.properties.flat, cohorts_cache, project_id)- )- elif prop.operator in ["gt", "lt", "gte", "lte"] and prop.type in ("person", "group"):- all_keys_and_fields.append(key_and_field_for_property(prop))-- return all_keys_and_fields---def check_pure_is_not_operator_condition(condition: dict) -> bool:- properties = condition.get("properties", [])- if properties and all(prop.get("operator") in ("is_not_set", "is_not") for prop in properties):- return True- return False---def _get_property_type_annotations(properties_with_math_operators):- return {- prop_key: Func(F(prop_field), function="JSONB_TYPEOF", output_field=CharField())- for prop_key, prop_field in properties_with_math_operators- }diff --git a/products/feature_flags/backend/test/test_flag_matching.py b/products/feature_flags/backend/test/test_flag_matching.pydeleted file mode 100644index adf020b2e955..000000000000--- a/products/feature_flags/backend/test/test_flag_matching.py+++ /dev/null@@ -1,62 +0,0 @@-from unittest.mock import MagicMock, PropertyMock, patch--from django.test import SimpleTestCase--from parameterized import parameterized--from products.feature_flags.backend.flag_matching import FeatureFlagMatcher, FeatureFlagMatchReason---def _make_matcher(query_conditions: dict[str, bool]) -> FeatureFlagMatcher:- matcher = FeatureFlagMatcher(- team_id=1,- project_id=1,- feature_flags=[],- distinct_id="test",- )- return matcher---def _make_flag(pk: int = 42, key: str = "test-flag") -> MagicMock:- flag = MagicMock()- flag.pk = pk- flag.key = key- return flag---class TestIsFeatureEnrollmentMatch(SimpleTestCase):- @parameterized.expand(- [- (- "enrollment_is_set_true_and_matches",- {"flag_42_enrollment_is_set": True, "flag_42_enrollment": True},- (True, True, FeatureFlagMatchReason.SUPER_CONDITION_VALUE),- ),- (- "enrollment_is_set_true_but_not_matching",- {"flag_42_enrollment_is_set": True, "flag_42_enrollment": False},- (True, False, FeatureFlagMatchReason.SUPER_CONDITION_VALUE),- ),- (- "enrollment_is_set_false",- {"flag_42_enrollment_is_set": False, "flag_42_enrollment": False},- (False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH),- ),- (- "enrollment_query_missing",- {},- (False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH),- ),- ],- )- def test_is_feature_enrollment_match(- self,- _name: str,- query_conditions: dict[str, bool],- expected: tuple[bool, bool, FeatureFlagMatchReason],- ):- matcher = _make_matcher(query_conditions)- flag = _make_flag()- with patch.object(type(matcher), "query_conditions", new_callable=PropertyMock, return_value=query_conditions):- result = matcher.is_feature_enrollment_match(flag)- assert result == expected