: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
chore(devex): move cohorts and replay models to product apps (#62112)
Julian Bezf2810fdb75c9
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 15b8c830aded..108e39398fec 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -123,6 +123,7 @@ jobs:- 'ee/clickhouse/**'- 'ee/hogai/**'# --- Only the products that DAGs actually import from ---+ - 'products/cohorts/backend/**/*.py'- 'products/data_modeling/backend/**/*.py'- 'products/data_warehouse/backend/**/*.py'- 'products/error_tracking/backend/**/*.py'diff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.pyindex 3156b66092c9..d39667a5ff20 100644--- a/.semgrep/rules/idor-team-scoped-models.py+++ b/.semgrep/rules/idor-team-scoped-models.py@@ -1,5 +1,6 @@from django.shortcuts import get_object_or_404-from posthog.models import ChangeRequest, Cohort, Notebook+from posthog.models import ChangeRequest, Notebook+from products.cohorts.backend.models.cohort import Cohortfrom products.product_analytics.backend.models.insight import Insightfrom products.actions.backend.models.action import Actionfrom posthog.models.personal_api_key import PersonalAPIKeydiff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.pyindex 51da05dae004..2e32e4bce14d 100644--- a/ee/api/session_summaries.py+++ b/ee/api/session_summaries.py@@ -43,6 +43,15 @@ from posthog.temporal.session_replay.session_summary_group.types import FailedSefrom posthog.temporal.session_replay.session_summary_group.workflow import execute_summarize_session_groupfrom posthog.utils import relative_date_parse+from products.replay.backend.models.session_summaries import SessionGroupSummary, SingleSessionSummary+from products.replay.backend.models.team_session_summaries_config import (+ CUSTOM_TAG_DESCRIPTION_MAX_LENGTH,+ CUSTOM_TAG_NAME_MAX_LENGTH,+ CUSTOM_TAGS_MAX_COUNT,+ PRODUCT_CONTEXT_MAX_LENGTH,+ TeamSessionSummariesConfig,+)+from ee.hogai.session_summaries.session.output_data import SessionSummarySerializerfrom ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContextfrom ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsList@@ -58,14 +67,6 @@ from ee.hogai.session_summaries.tracking import ()from ee.hogai.session_summaries.utils import logging_session_idsfrom ee.hogai.utils.aio import async_to_sync as async_generator_to_sync-from ee.models.session_summaries import SessionGroupSummary, SingleSessionSummary-from ee.models.team_session_summaries_config import (- CUSTOM_TAG_DESCRIPTION_MAX_LENGTH,- CUSTOM_TAG_NAME_MAX_LENGTH,- CUSTOM_TAGS_MAX_COUNT,- PRODUCT_CONTEXT_MAX_LENGTH,- TeamSessionSummariesConfig,-)logger = structlog.get_logger(__name__)diff --git a/ee/api/test/test_single_session_summary_viewset.py b/ee/api/test/test_single_session_summary_viewset.pyindex 628ce86668c6..9fa96124dab0 100644--- a/ee/api/test/test_single_session_summary_viewset.py+++ b/ee/api/test/test_single_session_summary_viewset.py@@ -8,10 +8,11 @@ from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.session_recordings.models.session_recording import SessionRecording+from products.replay.backend.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary+from ee.hogai.session_summaries.session.output_data import SessionSummarySerializerfrom ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_responsefrom ee.models.rbac.access_control import AccessControl-from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummaryclass TestSingleSessionSummaryViewSet(APIBaseTest):diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.pyindex b26eff95e0c3..85134a4d3bc7 100644--- a/ee/benchmarks/benchmarks.py+++ b/ee/benchmarks/benchmarks.py@@ -17,7 +17,8 @@ from posthog.queries.session_recordings.session_recording_list import (SessionRecordingList,)from posthog.queries.util import get_earliest_timestamp-from posthog.models import Cohort, Team, Organization+from posthog.models import Team, Organization+from products.cohorts.backend.models.cohort import Cohortfrom products.actions.backend.models.action import Actionfrom posthog.models.filters.session_recordings_filter import SessionRecordingsFilterfrom posthog.models.filters.filter import Filterdiff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.pyindex e430d6384ba3..6d2d2afa049c 100644--- a/ee/clickhouse/models/test/test_cohort.py+++ b/ee/clickhouse/models/test/test_cohort.py@@ -25,9 +25,6 @@ from posthog.schema import PersonsOnEventsModefrom posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMITfrom posthog.clickhouse.client import sync_execute-from posthog.models.cohort import Cohort-from posthog.models.cohort.sql import GET_COHORTPEOPLE_BY_COHORT_ID-from posthog.models.cohort.util import format_filter_queryfrom posthog.models.filters import Filterfrom posthog.models.organization import Organizationfrom posthog.models.person import Person@@ -38,6 +35,9 @@ from posthog.queries.person_distinct_id_query import get_team_distinct_ids_queryfrom posthog.queries.util import PersonPropertiesModefrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID+from products.cohorts.backend.models.util import format_filter_querydef get_person_ids_by_cohort_id(@@ -571,7 +571,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(len(results), 3)def test_insert_cohort_hogql_query_with_distinct_id(self):- from posthog.models.cohort.util import insert_cohort_query_actors_into_ch+ from products.cohorts.backend.models.util import insert_cohort_query_actors_into_chp1 = Person.objects.create(team_id=self.team.pk, distinct_ids=["user1"])p2 = Person.objects.create(team_id=self.team.pk, distinct_ids=["user2"])diff --git a/ee/clickhouse/models/test/test_filters.py b/ee/clickhouse/models/test/test_filters.pyindex ebdccd2f1100..23f6e406da17 100644--- a/ee/clickhouse/models/test/test_filters.py+++ b/ee/clickhouse/models/test/test_filters.py@@ -6,7 +6,6 @@ from posthog.test.base import ClickhouseTestMixin, _create_event, _create_personfrom posthog.clickhouse.client import query_with_columns, sync_executefrom posthog.constants import FILTER_TEST_ACCOUNTSfrom posthog.models import Element, Organization, Person, Team-from posthog.models.cohort import Cohortfrom posthog.models.event.sql import GET_EVENTS_WITH_PROPERTIESfrom posthog.models.event.util import ClickhouseEventSerializerfrom posthog.models.filters import Filter@@ -19,6 +18,8 @@ from posthog.models.property.util import parse_prop_grouped_clausesfrom posthog.queries.util import PersonPropertiesModefrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+def _filter_events(filter: Filter, team: Team, order_by: Optional[str] = None):prop_filters, prop_filter_params = parse_prop_grouped_clauses(diff --git a/ee/clickhouse/models/test/test_property.py b/ee/clickhouse/models/test/test_property.pyindex fc827a3de035..dc5a4fbd1834 100644--- a/ee/clickhouse/models/test/test_property.py+++ b/ee/clickhouse/models/test/test_property.py@@ -17,7 +17,6 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.clickhouse.client import sync_executefrom posthog.constants import PropertyOperatorType-from posthog.models.cohort import Cohortfrom posthog.models.element import Elementfrom posthog.models.filters import Filterfrom posthog.models.instance_setting import get_instance_setting@@ -36,6 +35,8 @@ from posthog.queries.person_query import PersonQueryfrom posthog.queries.property_optimizer import PropertyOptimizerfrom posthog.queries.util import PersonPropertiesMode+from products.cohorts.backend.models.cohort import Cohort+from ee.clickhouse.materialized_columns.columns import materializediff --git a/ee/clickhouse/queries/funnels/test/test_funnel.py b/ee/clickhouse/queries/funnels/test/test_funnel.pyindex bd736fbc131b..1bae4c40b784 100644--- a/ee/clickhouse/queries/funnels/test/test_funnel.py+++ b/ee/clickhouse/queries/funnels/test/test_funnel.py@@ -3,7 +3,6 @@ from datetime import datetimefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_personfrom posthog.constants import INSIGHT_FUNNELS-from posthog.models.cohort import Cohortfrom posthog.models.filters import Filterfrom posthog.models.group.util import create_groupfrom posthog.queries.funnels.funnel import ClickhouseFunnel@@ -15,6 +14,7 @@ from posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom ee.clickhouse.queries.funnels.test.breakdown_cases import funnel_breakdown_group_test_factorydiff --git a/ee/clickhouse/queries/test/test_breakdown_props.py b/ee/clickhouse/queries/test/test_breakdown_props.pyindex 37c8201b0ab0..8dbdea556225 100644--- a/ee/clickhouse/queries/test/test_breakdown_props.py+++ b/ee/clickhouse/queries/test/test_breakdown_props.py@@ -9,7 +9,6 @@ from posthog.test.base import (snapshot_clickhouse_queries,)-from posthog.models.cohort import Cohortfrom posthog.models.entity import Entityfrom posthog.models.filters import Filterfrom posthog.models.group.util import create_group@@ -21,6 +20,8 @@ from posthog.queries.breakdown_props import (from posthog.queries.trends.util import process_mathfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.cohorts.backend.models.cohort import Cohort+class TestBreakdownProps(ClickhouseTestMixin, APIBaseTest):@also_test_with_materialized_columns(diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.pyindex 78b1b3797d81..f06f85368fa0 100644--- a/ee/clickhouse/queries/test/test_cohort_query.py+++ b/ee/clickhouse/queries/test/test_cohort_query.py@@ -20,10 +20,10 @@ from posthog.schema import PersonsOnEventsModefrom posthog.clickhouse.client import sync_executefrom posthog.hogql_queries.hogql_cohort_query import TestWrapperCohortQuery as CohortQueryfrom posthog.models import Team-from posthog.models.cohort import Cohortfrom posthog.models.filters.filter import Filterfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinitiondiff --git a/ee/clickhouse/queries/test/test_event_query.py b/ee/clickhouse/queries/test/test_event_query.pyindex 78e231e3c035..ebd76b332885 100644--- a/ee/clickhouse/queries/test/test_event_query.py+++ b/ee/clickhouse/queries/test/test_event_query.py@@ -8,7 +8,6 @@ from posthog.test.base import ()from posthog.clickhouse.client import sync_execute-from posthog.models.cohort import Cohortfrom posthog.models.element import Elementfrom posthog.models.entity import Entityfrom posthog.models.filters import Filter@@ -18,6 +17,7 @@ from posthog.queries.trends.trends_event_query import TrendsEventQueryfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom ee.clickhouse.materialized_columns.columns import materializediff --git a/ee/clickhouse/queries/test/test_person_query.py b/ee/clickhouse/queries/test/test_person_query.pyindex e9954402734a..0225582d82c4 100644--- a/ee/clickhouse/queries/test/test_person_query.py+++ b/ee/clickhouse/queries/test/test_person_query.py@@ -2,12 +2,13 @@ import pytestfrom posthog.test.base import _create_person, cleanup_materialized_columnsfrom posthog.clickhouse.client import sync_execute-from posthog.models.cohort import Cohortfrom posthog.models.filters import Filterfrom posthog.models.property import Propertyfrom posthog.models.team import Teamfrom posthog.queries.person_query import PersonQuery+from products.cohorts.backend.models.cohort import Cohort+from ee.clickhouse.materialized_columns.columns import materializediff --git a/ee/clickhouse/queries/test/test_util.py b/ee/clickhouse/queries/test/test_util.pyindex 1c55379ed398..47bbbbd52216 100644--- a/ee/clickhouse/queries/test/test_util.py+++ b/ee/clickhouse/queries/test/test_util.py@@ -5,11 +5,11 @@ from freezegun.api import freeze_timefrom posthog.test.base import _create_eventfrom posthog.clickhouse.client import sync_execute-from posthog.models.cohort import Cohortfrom posthog.queries.breakdown_props import _parse_breakdown_cohortsfrom posthog.queries.util import get_earliest_timestampfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortdef test_get_earliest_timestamp(db, team):diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex faf10e57b628..44e953289151 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -14,12 +14,13 @@ from posthog.api.search import (EntityConfig,search_entities as search_entities_fts,)-from posthog.models import Cohort, Team, User+from posthog.models import Team, Userfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_asyncfrom products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfiguration+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex 844c790fc370..1723d605f2de 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -7,9 +7,8 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models import Cohort-from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/ee/hogai/eval/sandboxed/cohorts/scorers.py b/ee/hogai/eval/sandboxed/cohorts/scorers.pyindex 5a03167745b7..ef4e8b972c27 100644--- a/ee/hogai/eval/sandboxed/cohorts/scorers.py+++ b/ee/hogai/eval/sandboxed/cohorts/scorers.py@@ -36,7 +36,7 @@ COHORTS_UPDATE_TOOL = "cohorts-partial-update"COHORTS_ADD_PERSONS_TOOL = "cohorts-add-persons-to-static-cohort-partial-update"# Column names ``print_cohort_hogql_query`` accepts for actor extraction, in-# priority order — keep in sync with posthog/models/cohort/util.py.+# priority order — keep in sync with products/cohorts/backend/models/util.py.ID_COLUMN_NAMES: tuple[str, ...] = ("person_id", "actor_id", "id", "distinct_id")diff --git a/ee/hogai/session_summaries/session/summarize_session.py b/ee/hogai/session_summaries/session/summarize_session.pyindex 6ed934e91b1a..75fa9e9b8ac3 100644--- a/ee/hogai/session_summaries/session/summarize_session.py+++ b/ee/hogai/session_summaries/session/summarize_session.py@@ -8,6 +8,8 @@ import structlogfrom posthog.session_recordings.models.metadata import RecordingMetadatafrom posthog.sync import database_sync_to_async+from products.replay.backend.models.session_summaries import ExtraSummaryContext+from ee.hogai.session_summaries.session.input_data import (add_context_and_filter_events,get_session_events,@@ -15,7 +17,6 @@ from ee.hogai.session_summaries.session.input_data import ()from ee.hogai.session_summaries.session.prompt_data import SessionSummaryPromptDatafrom ee.hogai.session_summaries.utils import load_custom_template, shorten_url-from ee.models.session_summaries import ExtraSummaryContextlogger = structlog.get_logger(__name__)diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.pyindex ebea882e0565..69256682e7cc 100644--- a/ee/hogai/session_summaries/session_group/patterns.py+++ b/ee/hogai/session_summaries/session_group/patterns.py@@ -10,13 +10,14 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.models.person import Personfrom posthog.models.person.util import get_persons_mapped_by_distinct_id+from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries import SummaryValidationErrorfrom ee.hogai.session_summaries.constants import FAILED_PATTERNS_ENRICHMENT_MIN_RATIOfrom ee.hogai.session_summaries.session.output_data import SessionSummaryIssueTypes, SessionSummarySerializerfrom ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputsfrom ee.hogai.session_summaries.utils import logging_session_idsfrom ee.hogai.utils.yaml import load_yaml_from_raw_llm_content-from ee.models.session_summaries import SingleSessionSummarylogger = structlog.get_logger(__name__)diff --git a/ee/migrations/0050_migrate_replay_models.py b/ee/migrations/0050_migrate_replay_models.pynew file mode 100644index 000000000000..985f01247c4b--- /dev/null+++ b/ee/migrations/0050_migrate_replay_models.py@@ -0,0 +1,71 @@+# Generated by Django 5.2.14 on 2026-06-08 10:07++from django.db import migrations++MODELS_TO_MOVE = ("sessiongroupsummary", "singlesessionsummary", "teamsessionsummariesconfig")+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently.++ If the target (app_label, model) already exists (e.g. Django auto-created it,+ or a prior failed attempt left one behind), merge permissions onto the target+ and delete the source to avoid a unique-constraint violation. Uses the+ migration's own connection alias for multi-DB safety.+ """+ db_alias = schema_editor.connection.alias+ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("auth", "Permission")++ for model_name in MODELS_TO_MOVE:+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()++ if source and target:+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)+ source.delete(using=db_alias)+ elif source:+ source.app_label = to_label+ source.save(using=db_alias)+++def update_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "ee", "replay")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "replay", "ee")+++class Migration(migrations.Migration):+ dependencies = [("ee", "0049_migrate_posthog_ai_models"), ("replay", "0001_migrate_replay_models")]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="singlesessionsummary",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="singlesessionsummary",+ name="team",+ ),+ migrations.RemoveField(+ model_name="teamsessionsummariesconfig",+ name="team",+ ),+ migrations.DeleteModel(+ name="SessionGroupSummary",+ ),+ migrations.DeleteModel(+ name="SingleSessionSummary",+ ),+ migrations.DeleteModel(+ name="TeamSessionSummariesConfig",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex 34dac5f25de8..87a178e93dc0 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0049_migrate_posthog_ai_models+0050_migrate_replay_modelsdiff --git a/ee/models/__init__.py b/ee/models/__init__.pyindex f0df59755ad4..8f967ad4109f 100644--- a/ee/models/__init__.py+++ b/ee/models/__init__.py@@ -6,8 +6,6 @@ from .rbac.access_control import AccessControlfrom .rbac.role import Role, RoleMembershipfrom .scim_provisioned_user import SCIMProvisionedUserfrom .scim_request_log import SCIMRequestLog-from .session_summaries import SingleSessionSummary-from .team_session_summaries_config import TeamSessionSummariesConfig__all__ = ["AccessControl",@@ -19,6 +17,4 @@ __all__ = ["RoleMembership","SCIMProvisionedUser","SCIMRequestLog",- "SingleSessionSummary",- "TeamSessionSummariesConfig",]diff --git a/ee/models/test/test_session_summaries.py b/ee/models/test/test_session_summaries.pyindex 4eb4e608c4e5..aa4fab0686e9 100644--- a/ee/models/test/test_session_summaries.py+++ b/ee/models/test/test_session_summaries.py@@ -5,9 +5,7 @@ from posthog.test.base import BaseTestfrom posthog.models import Organization, Team, User-from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer-from ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_response-from ee.models.session_summaries import (+from products.replay.backend.models.session_summaries import (ExtraSummaryContext,SessionGroupSummary,SessionSummaryPage,@@ -15,6 +13,9 @@ from ee.models.session_summaries import (SingleSessionSummary,)+from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer+from ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_response+class TestSingleSessionSummary(BaseTest):session_id: strdiff --git a/posthog/admin/admins/cohort_admin.py b/posthog/admin/admins/cohort_admin.pyindex 0a53748c4f9f..4687c924b46e 100644--- a/posthog/admin/admins/cohort_admin.py+++ b/posthog/admin/admins/cohort_admin.py@@ -2,7 +2,7 @@ from django.contrib import admin, messagesfrom django.urls import reversefrom django.utils.html import format_html-from posthog.models import Cohort+from products.cohorts.backend.models.cohort import Cohort@admin.register(Cohort)diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex ba10964719f4..1705c99ac8ea 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -56,7 +56,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:"""Returns counts of all bulk-delete models for teams in this organization."""- from posthog.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohort, CohortPeopleteam_ids = list(organization.teams.values_list("id", flat=True))if not team_ids:@@ -106,7 +106,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:{"name": "Cohort People","count": f"Error: {e}",- "model": "posthog.models.cohort.CohortPeople",+ "model": "products.cohorts.backend.models.CohortPeople",})diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex 3bccde880da1..752a8bacfa7f 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -34,7 +34,6 @@ from posthog.admin.inlines.user_product_list_inline import UserProductListInlinefrom posthog.cloud_utils import is_cloudfrom posthog.models import Teamfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity-from posthog.models.exported_recording import ExportedRecordingfrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team.team import DEPRECATED_ATTRSfrom posthog.session_recordings.recordings import recording_s3_client@@ -51,6 +50,8 @@ from posthog.temporal.session_replay.delete_recordings.types import (from posthog.temporal.session_replay.export_recording.types import ExportRecordingInputfrom posthog.temporal.session_replay.import_recording.types import ImportRecordingInput+from products.replay.backend.models.exported_recording import ExportedRecording+logger = get_logger()diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 6c1ad6a5ec57..6a3cdcb2bcd1 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -45,7 +45,7 @@ from posthog.constants import LIMIT, OFFSET, PropertyOperatorTypefrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.metrics import LABEL_TEAM_ID-from posthog.models import Cohort, Person, User+from posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import (Change,Detail,@@ -55,15 +55,6 @@ 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, DeletionType-from posthog.models.cohort import DEFAULT_COHORT_INSERT_BATCH_SIZE, CohortOrEmpty-from posthog.models.cohort.calculation_history import CohortCalculationHistory-from posthog.models.cohort.cohort import REALTIME_COHORT_MAX_PERSON_COUNT, CohortType-from posthog.models.cohort.util import (- cohort_filters_have_values,- get_all_cohort_dependencies,- get_friendly_error_message,-)-from posthog.models.cohort.validation import CohortTypeValidationSerializerfrom posthog.models.filters.filter import Filterfrom posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctIdfrom posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist@@ -77,6 +68,20 @@ from posthog.queries.util import get_earliest_timestampfrom posthog.renderers import SafeJSONRendererfrom posthog.utils import format_query_params_absolute_url, str_to_bool+from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+from products.cohorts.backend.models.cohort import (+ DEFAULT_COHORT_INSERT_BATCH_SIZE,+ REALTIME_COHORT_MAX_PERSON_COUNT,+ Cohort,+ CohortOrEmpty,+ CohortType,+)+from products.cohorts.backend.models.util import (+ cohort_filters_have_values,+ get_all_cohort_dependencies,+ get_friendly_error_message,+)+from products.cohorts.backend.models.validation import CohortTypeValidationSerializerfrom products.feature_flags.backend.flag_matching import (FeatureFlagMatcher,FlagsMatcherCache,diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex 9d1721ca5e88..fe91027b750f 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -448,7 +448,7 @@ def register_core_file_system_types() -> None:register_file_system_type("cohort",- "posthog",+ "cohorts","Cohort",undo_message="Send PATCH /api/projects/@current/cohorts/{id} with deleted=false.",)diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.pyindex c7c27b1483f6..793f116c3d13 100644--- a/posthog/api/file_system/test/test_file_system.py+++ b/posthog/api/file_system/test/test_file_system.py@@ -13,11 +13,11 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMITfrom posthog.models import Project, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystemfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex 03628f67b200..d39c8467700b 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -12,10 +12,11 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ServerTimingsGathered, action-from posthog.models import ActivityLog, Cohort, NotificationViewed, User+from posthog.models import ActivityLog, NotificationViewed, Userfrom posthog.models.comment import Commentfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/api/person.py b/posthog/api/person.pyindex 1de529338c72..811cb1fbf3d2 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -44,11 +44,10 @@ from posthog.constants import INSIGHT_FUNNELS, LIMIT, OFFSET, FunnelVizTypefrom posthog.decorators import cached_by_filtersfrom posthog.event_usage import get_request_analytics_propertiesfrom posthog.metrics import LABEL_TEAM_ID-from posthog.models import Cohort, Filter, Person, Team, User+from posthog.models import Filter, Person, Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.cohort.util import get_all_cohort_ids_by_person_uuidfrom posthog.models.filters.lifecycle_filter import LifecycleFilterfrom posthog.models.filters.path_filter import PathFilterfrom posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter@@ -77,6 +76,8 @@ from posthog.renderers import SafeJSONRendererfrom posthog.tasks.split_person import split_personfrom posthog.utils import format_query_params_absolute_url, is_anonymous_id, refresh_requested_by_client+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuidfrom products.product_analytics.backend.api.insight import capture_legacy_api_calllogger = structlog.get_logger(__name__)diff --git a/posthog/api/search.py b/posthog/api/search.pyindex dfd82a907f63..93c571f07523 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -12,9 +12,10 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.helpers.full_text_search import build_rank, process_query-from posthog.models import Cohort, EventDefinition, PropertyDefinition+from posthog.models import EventDefinition, PropertyDefinitionfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 7d744428cd1c..8e6cd141c7ca 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -33,7 +33,7 @@ from posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_modefrom posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Team+from posthog.models import SessionRecording, SharePassword, SharingConfiguration, Teamfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom posthog.models.user import User@@ -44,6 +44,7 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import get_ip_address, render_templatefrom posthog.views import preflight_check+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.exports.backend.api.exports import ExportedAssetSerializerdiff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 28ba487dd9d8..335ed7b628b5 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -28,8 +28,6 @@ from posthog.clickhouse.client.execute import sync_executefrom posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.async_deletion.async_deletion import AsyncDeletion-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import CohortTypefrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.property import BehavioralPropertyTypefrom posthog.models.team.team import Team@@ -42,6 +40,7 @@ from posthog.tasks.calculate_cohort import ()from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.exports.backend.api.test.test_exports import TestExportMixinfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -127,7 +126,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin"posthog.tasks.calculate_cohort.calculate_cohort_ch.delay",side_effect=calculate_cohort_ch,)- @patch("posthog.models.cohort.util.sync_execute", side_effect=sync_execute)+ @patch("products.cohorts.backend.models.util.sync_execute", side_effect=sync_execute)def test_creating_update_and_calculating(self, patch_sync_execute, patch_calculate_cohort, patch_capture, patch_on_commit):@@ -217,7 +216,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin"posthog.tasks.calculate_cohort.calculate_cohort_ch.delay",side_effect=calculate_cohort_ch,)- @patch("posthog.models.cohort.util.sync_execute", side_effect=sync_execute)+ @patch("products.cohorts.backend.models.util.sync_execute", side_effect=sync_execute)def test_action_persons_on_events(self, patch_sync_execute, patch_calculate_cohort, patch_capture, patch_on_commit):materialize("person", "favorite_number", table_column="properties")self.team.modifiers = {"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS}@@ -4329,9 +4328,10 @@ [email protected],Test that removal succeeds when person exists in ClickHouse but not PostgreSQL.This simulates the CH/PG sync issue where data exists in CH but not PG."""- from posthog.models.cohort.util import insert_static_cohortfrom posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE+ from products.cohorts.backend.models.util import insert_static_cohort+static_cohort = Cohort.objects.create(team=self.team,name="Test Static Cohort",@@ -4402,7 +4402,7 @@ [email protected],assert response.json()["success"] is True@patch("django.db.transaction.on_commit", side_effect=lambda func: func())- @patch("posthog.models.cohort.dependencies._on_cohort_changed")+ @patch("products.cohorts.backend.models.dependencies._on_cohort_changed")@patch("posthog.tasks.calculate_cohort.increment_version_and_enqueue_calculate_cohort")def test_cohort_update_recalculated_after_caching(self,@@ -5132,8 +5132,8 @@ [email protected],def test_cohort_last_error_message_from_calculation_history(self):"""Test that API returns friendly error message from failed calculation"""- from posthog.models.cohort.calculation_history import CohortCalculationHistory- from posthog.models.cohort.util import CohortErrorCode+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.util import CohortErrorCodecohort = Cohort.objects.create(team=self.team,@@ -5160,8 +5160,8 @@ [email protected],def test_cohort_last_error_message_in_list_view(self):"""Test that list view includes last_error_message via annotation"""- from posthog.models.cohort.calculation_history import CohortCalculationHistory- from posthog.models.cohort.util import CohortErrorCode+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.util import CohortErrorCodecohort = Cohort.objects.create(team=self.team,@@ -5189,7 +5189,7 @@ [email protected],def test_cohort_last_error_message_none_when_successful(self):"""Test that successful cohorts return None for last_error_message"""- from posthog.models.cohort.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistorycohort = Cohort.objects.create(team=self.team,@@ -5215,8 +5215,8 @@ [email protected],def test_cohort_last_error_message_uses_most_recent_failure(self):"""Test that only the most recent failed calculation's error is returned"""- from posthog.models.cohort.calculation_history import CohortCalculationHistory- from posthog.models.cohort.util import CohortErrorCode+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.util import CohortErrorCodecohort = Cohort.objects.create(team=self.team,diff --git a/posthog/api/test/test_cohort_bytecode.py b/posthog/api/test/test_cohort_bytecode.pyindex 37bf5bb6481b..2529eb389328 100644--- a/posthog/api/test/test_cohort_bytecode.py+++ b/posthog/api/test/test_cohort_bytecode.py@@ -7,7 +7,7 @@ from common.hogvm.python.operation import HOGQL_BYTECODE_VERSIONclass TestCohortBytecodeScenarios(APIBaseTest):def _create_and_fetch(self, name: str, filters: dict[str, Any]):- from posthog.models.cohort.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortresp = self.client.post(f"/api/projects/{self.team.id}/cohorts/",@@ -19,7 +19,7 @@ class TestCohortBytecodeScenarios(APIBaseTest):return cohortdef _patch_and_fetch(self, cohort_id: int, filters: dict[str, Any]):- from posthog.models.cohort.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortresp = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/",diff --git a/posthog/api/test/test_cohort_personhog.py b/posthog/api/test/test_cohort_personhog.pyindex 3a78d0aa4efe..6004968a7ae5 100644--- a/posthog/api/test/test_cohort_personhog.py+++ b/posthog/api/test/test_cohort_personhog.py@@ -6,11 +6,12 @@ from posthog.test.base import APIBaseTest, BaseTestfrom parameterized import parameterized_classfrom rest_framework import status-from posthog.models import Cohortfrom posthog.models.person import Personfrom posthog.models.person.util import validate_person_uuids_existfrom posthog.personhog_client.test_helpers import PersonhogTestMixin+from products.cohorts.backend.models.cohort import Cohort+@parameterized_class(("personhog",), [(False,), (True,)])class TestValidatePersonUuidsExist(PersonhogTestMixin, BaseTest):diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.pyindex 44097ff01490..072f172ff2f7 100644--- a/posthog/api/test/test_event.py+++ b/posthog/api/test/test_event.py@@ -24,11 +24,11 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Element, Organization, Person, PropertyDefinition, User-from posthog.models.cohort import Cohortfrom posthog.models.event.query_event_list import insight_query_with_columnsfrom posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortclass TestEvents(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.pyindex b48941a20219..143d9a5f0d0a 100644--- a/posthog/api/test/test_file_system.py+++ b/posthog/api/test/test_file_system.py@@ -19,13 +19,13 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.file_system.file_system_logging import log_api_file_system_viewfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex d97274808f4d..0236012f64b7 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -25,12 +25,14 @@ from rest_framework import statusimport posthog.models.person.deletionfrom posthog.clickhouse.client import sync_execute-from posthog.models import Cohort, Organization, Person, PropertyDefinition, Team+from posthog.models import Organization, Person, PropertyDefinition, Teamfrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.person import PersonDistinctIdfrom posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLEfrom posthog.models.person.util import create_person, create_person_distinct_id+from products.cohorts.backend.models.cohort import Cohort+class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def test_legacy_get_person_by_id(self) -> None:diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.pyindex df6e8c7be1bd..a5024c8d111c 100644--- a/posthog/api/test/test_person_personhog.py+++ b/posthog/api/test/test_person_personhog.py@@ -12,10 +12,12 @@ from unittest import mockfrom parameterized import parameterized_classfrom rest_framework import status-from posthog.models import Cohort, Organization, Person, Team+from posthog.models import Organization, Person, Teamfrom posthog.models.person import PersonDistinctIdfrom posthog.personhog_client.test_helpers import PersonhogTestMixin+from products.cohorts.backend.models.cohort import Cohort+UUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"diff --git a/posthog/api/test/test_persons_trends.py b/posthog/api/test/test_persons_trends.pyindex 48f88249b920..f44c743781ee 100644--- a/posthog/api/test/test_persons_trends.py+++ b/posthog/api/test/test_persons_trends.py@@ -13,9 +13,11 @@ from posthog.test.base import ()from posthog.constants import ENTITY_ID, ENTITY_MATH, ENTITY_TYPE, TRENDS_CUMULATIVE-from posthog.models import Cohort, Organization+from posthog.models import Organizationfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from products.cohorts.backend.models.cohort import Cohort+def _create_cohort(**kwargs):team = kwargs.pop("team")diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.pyindex 2c652703e8d1..c00c5440532c 100644--- a/posthog/api/test/test_resource_transfer.py+++ b/posthog/api/test/test_resource_transfer.py@@ -8,12 +8,12 @@ from rest_framework import statusfrom posthog.models import Project, Teamfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.resource_transfer.resource_transfer import ResourceTransferfrom posthog.models.scoping import team_scopefrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.dashboards.backend.models.dashboard_widget import DashboardWidgetdiff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 00f3d820aca8..aac2bbf4378a 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -1386,7 +1386,7 @@ class TestExportCacheKeyFlow(APIBaseTest):class TestSharedCohortInlining(APIBaseTest):@mock_exporter_templatedef test_shared_insight_inlines_referenced_cohort_names(self):- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = Cohort.objects.create(team=self.team, name="Power users")other_cohort = Cohort.objects.create(team=self.team, name="Churned users") # not referenced@@ -1433,8 +1433,7 @@ class TestSharedCohortInlining(APIBaseTest):@mock_exporter_templatedef test_shared_dashboard_collects_cohorts_across_tiles(self):- from posthog.models.cohort import Cohort-+ from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard_tile import DashboardTilecohort_a = Cohort.objects.create(team=self.team, name="Cohort A")diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 645df6daf7bc..55abf35358c1 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -561,12 +561,10 @@ def team_api_test_factory():team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)-- from posthog.models.cohort import Cohort, CohortPeople-# from posthog.models.insight_caching_state import InsightCachingStatefrom posthog.models.person import Person+ from products.cohorts.backend.models.cohort import Cohort, CohortPeoplefrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverridecohort = Cohort.objects.create(team=team, created_by=self.user, name="test")diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.pyindex c10a8942dd4f..47e494a72b7f 100644--- a/posthog/cdp/filters.py+++ b/posthog/cdp/filters.py@@ -8,10 +8,10 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, ast, property_to_exprfrom posthog.hogql.visitor import TraversingVisitor-from posthog.models.cohort.cohort import Cohortfrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import CohortCOHORT_FILTER_TYPES = frozenset({"cohort", "static-cohort", "precalculated-cohort", "dynamic-cohort"})diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.pyindex cbef110963e1..135130f39d4e 100644--- a/posthog/cdp/test/test_filters.py+++ b/posthog/cdp/test/test_filters.py@@ -11,9 +11,9 @@ from posthog.cdp.filters import (compile_filters_bytecode,hog_function_filters_to_expr,)-from posthog.models.cohort.cohort import Cohortfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom common.hogvm.python.execute import execute_bytecodefrom common.hogvm.python.operation import HOGQL_BYTECODE_VERSIONdiff --git a/posthog/cdp/test/test_site_functions.py b/posthog/cdp/test/test_site_functions.pyindex 5434c3ab0ce2..07f671b02e8a 100644--- a/posthog/cdp/test/test_site_functions.py+++ b/posthog/cdp/test/test_site_functions.py@@ -12,7 +12,6 @@ from parameterized import parameterizedfrom posthog.cdp.site_functions import get_transpiled_functionfrom posthog.cdp.templates.helpers import mock_transpile-from posthog.models.cohort import Cohortfrom posthog.models.organization import Organizationfrom posthog.models.project import Projectfrom posthog.models.user import User@@ -21,6 +20,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import TranspilerError+from products.cohorts.backend.models.cohort import Cohort@pytest.mark.usefixtures("unittest_snapshot")diff --git a/posthog/clickhouse/migrations/0010_cohortpeople.py b/posthog/clickhouse/migrations/0010_cohortpeople.pyindex d0de6d0db6c0..2ca3c5ab34fb 100644--- a/posthog/clickhouse/migrations/0010_cohortpeople.py+++ b/posthog/clickhouse/migrations/0010_cohortpeople.py@@ -1,4 +1,5 @@from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions-from posthog.models.cohort.sql import CREATE_COHORTPEOPLE_TABLE_SQL++from products.cohorts.backend.models.sql import CREATE_COHORTPEOPLE_TABLE_SQLoperations = [run_sql_with_exceptions(CREATE_COHORTPEOPLE_TABLE_SQL())]diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex cacf35d13519..f1ecea64899a 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -123,7 +123,6 @@ from posthog.models.channel_type.sql import (CHANNEL_DEFINITION_DICTIONARY_SQL,CHANNEL_DEFINITION_TABLE_SQL,)-from posthog.models.cohort.sql import CREATE_COHORTPEOPLE_TABLE_SQLfrom posthog.models.cohortmembership.sql import (COHORT_MEMBERSHIP_MV_SQL,COHORT_MEMBERSHIP_TABLE_SQL,@@ -259,6 +258,7 @@ from posthog.session_recordings.sql.session_replay_feature_sql import (WRITABLE_SESSION_REPLAY_FEATURES_TABLE_SQL,)+from products.cohorts.backend.models.sql import CREATE_COHORTPEOPLE_TABLE_SQLfrom products.error_tracking.backend.embedding import (DISTRIBUTED_DOCUMENT_EMBEDDINGS_TABLE_SQL,DOCUMENT_EMBEDDINGS_MV_SQL,diff --git a/posthog/conftest.py b/posthog/conftest.pyindex 2bde15d717af..ddd313d2ee38 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -80,7 +80,6 @@ def reset_clickhouse_tables():from posthog.models.ai_events.sql import TRUNCATE_AI_EVENTS_TABLE_SQLfrom posthog.models.app_metrics.sql import TRUNCATE_APP_METRICS_TABLE_SQLfrom posthog.models.channel_type.sql import TRUNCATE_CHANNEL_DEFINITION_TABLE_SQL- from posthog.models.cohort.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQLfrom posthog.models.event.sql import TRUNCATE_EVENTS_RECENT_TABLE_SQL, TRUNCATE_EVENTS_TABLE_SQLfrom posthog.models.exchange_rate.sql import TRUNCATE_EXCHANGE_RATE_TABLE_SQLfrom posthog.models.group.sql import TRUNCATE_GROUPS_TABLE_SQL@@ -96,6 +95,7 @@ def reset_clickhouse_tables():from posthog.models.raw_sessions.sessions_v3 import TRUNCATE_RAW_SESSIONS_TABLE_SQL_V3from posthog.models.sessions.sql import TRUNCATE_SESSIONS_TABLE_SQL+ from products.cohorts.backend.models.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQLfrom products.error_tracking.backend.embedding import TRUNCATE_DOCUMENT_EMBEDDINGS_TABLE_SQLfrom products.error_tracking.backend.sql import (TRUNCATE_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_TABLE_SQL,diff --git a/posthog/dags/backfill_internal_test_users_cohort.py b/posthog/dags/backfill_internal_test_users_cohort.pyindex 92bb854d8eca..f56f4737290b 100644--- a/posthog/dags/backfill_internal_test_users_cohort.py+++ b/posthog/dags/backfill_internal_test_users_cohort.py@@ -2,10 +2,10 @@ import dagsterfrom posthog.dags.common import JobOwnersfrom posthog.dags.common.ops import get_all_team_ids_op-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import INTERNAL_TEST_USERS_COHORT_NAME, CohortKindfrom posthog.models.team import Team+from products.cohorts.backend.models.cohort import INTERNAL_TEST_USERS_COHORT_NAME, Cohort, CohortKind+# Standard filter: matches people with $internal_or_test_user set to true_INTERNAL_TEST_USERS_FILTERS: dict = {"properties": {diff --git a/posthog/demo/matrix/manager.py b/posthog/demo/matrix/manager.pyindex 1e2f6db1e7a5..151254f6562e 100644--- a/posthog/demo/matrix/manager.py+++ b/posthog/demo/matrix/manager.py@@ -12,7 +12,6 @@ from django.db import IntegrityError, transactionfrom posthog.clickhouse.client import query_with_columns, sync_executefrom posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_teamfrom posthog.models import (- Cohort,Group,GroupTypeMapping,Organization,@@ -24,6 +23,8 @@ from posthog.models import ()from posthog.models.utils import UUIDT, generate_random_token_project+from products.cohorts.backend.models.cohort import Cohort+from .matrix import Matrixfrom .models import SimEvent, SimPersondiff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.pyindex d43dd29c9942..51b2aa1703d6 100644--- a/posthog/demo/products/hedgebox/matrix.py+++ b/posthog/demo/products/hedgebox/matrix.py@@ -50,12 +50,12 @@ from posthog.demo.matrix.matrix import Cluster, Matrixfrom posthog.demo.matrix.models import SimEventfrom posthog.demo.matrix.randomization import Industryfrom posthog.exceptions_capture import capture_exception-from posthog.models import Cohortfrom posthog.models.event.util import create_eventfrom posthog.models.oauth import OAuthApplicationfrom posthog.storage import object_storagefrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_tools.backend.models.join import DataWarehouseJoin@@ -290,7 +290,7 @@ class HedgeboxMatrix(Matrix):],)# Create the standard internal/test users cohort (same as non-demo teams get)- from posthog.models.cohort.cohort import get_or_create_internal_test_users_cohort+ from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohorttest_users_cohort = get_or_create_internal_test_users_cohort(team, initiating_user_email=user.email)team.test_account_filters = [diff --git a/posthog/demo/products/spikegpt/matrix.py b/posthog/demo/products/spikegpt/matrix.pyindex 15f6ff7f48b7..b598b210904a 100644--- a/posthog/demo/products/spikegpt/matrix.py+++ b/posthog/demo/products/spikegpt/matrix.py@@ -1,5 +1,6 @@from posthog.demo.matrix.matrix import Cluster, Matrix-from posthog.models import Cohort++from products.cohorts.backend.models.cohort import Cohortfrom .models import SpikeGPTPerson@@ -47,7 +48,7 @@ class SpikeGPTMatrix(Matrix):],)# Create the standard internal/test users cohort (same as non-demo teams get)- from posthog.models.cohort.cohort import get_or_create_internal_test_users_cohort+ from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohorttest_users_cohort = get_or_create_internal_test_users_cohort(team, initiating_user_email=user.email)team.test_account_filters = [diff --git a/posthog/hogql/database/schema/cohort_people.py b/posthog/hogql/database/schema/cohort_people.pyindex 5dbc5a7bc53e..096b0dee5077 100644--- a/posthog/hogql/database/schema/cohort_people.py+++ b/posthog/hogql/database/schema/cohort_people.py@@ -24,7 +24,7 @@ COHORT_PEOPLE_FIELDS: dict[str, FieldOrTable] = {def select_from_cohort_people_table(requested_fields: dict[str, list[str | int]], project_id: int):from posthog.hogql import ast- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort_tuples = list(Cohort.objects.filter(is_static=False, team__project_id=project_id, deleted=False)diff --git a/posthog/hogql/database/schema/test/test_cohort_people.py b/posthog/hogql/database/schema/test/test_cohort_people.pyindex a7557fb098c0..28a785d90482 100644--- a/posthog/hogql/database/schema/test/test_cohort_people.py+++ b/posthog/hogql/database/schema/test/test_cohort_people.py@@ -3,7 +3,9 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models import Cohort, Person+from posthog.models import Person++from products.cohorts.backend.models.cohort import Cohortclass TestCohortPeopleTable(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.pyindex 43722eee914e..a86c45d2b1f1 100644--- a/posthog/hogql/database/schema/test/test_persons.py+++ b/posthog/hogql/database/schema/test/test_persons.py@@ -38,11 +38,12 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.execute import sync_executefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner-from posthog.models import Cohort-from posthog.models.cohort.util import recalculate_cohortpeoplefrom posthog.models.person.util import create_personfrom posthog.models.utils import UUIDT+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import recalculate_cohortpeople+@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True)) # for persons-inner-where-optimizationclass TestPersonOptimization(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 4c022ba8d368..072ba5e877d0 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -12,9 +12,8 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.query import execute_hogql_query-from posthog.models import Cohort, Group, GroupTypeMapping, GroupUsageMetric, Organization, Tag, Team+from posthog.models import Group, GroupTypeMapping, GroupUsageMetric, Organization, Tag, Teamfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort.calculation_history import CohortCalculationHistoryfrom posthog.models.project import Projectfrom posthog.models.scoping import team_scope@@ -27,6 +26,8 @@ from products.annotations.backend.models.annotation import Annotationfrom products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSourcefrom products.business_knowledge.backend.models.constants import SourceStatus, SourceTypefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+from products.cohorts.backend.models.cohort import Cohortfrom products.conversations.backend.models import Ticketfrom products.customer_analytics.backend.models.account import Accountfrom products.dashboards.backend.models.dashboard import Dashboarddiff --git a/posthog/hogql/functions/cohort.py b/posthog/hogql/functions/cohort.pyindex bc23432add5a..a6cc286db937 100644--- a/posthog/hogql/functions/cohort.py+++ b/posthog/hogql/functions/cohort.py@@ -41,7 +41,7 @@ def _is_inline_flag_enabled(context: HogQLContext) -> bool:def _is_cohort_fast_enough_to_inline(cohort_id: int) -> bool:- from posthog.models.cohort.calculation_history import CohortCalculationHistory+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistoryseven_days_ago = timezone.now() - datetime.timedelta(days=7)recent_calcs = list(@@ -72,7 +72,8 @@ def inline_cohort_query(context: HogQLContext,) -> Optional[ast.SelectQuery | ast.SelectSetQuery]:from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery- from posthog.models import Cohort++ from products.cohorts.backend.models.cohort import Cohortif is_static:return None@@ -114,7 +115,7 @@ def cohort_query_node(node: ast.Expr, context: HogQLContext) -> ast.Expr:def cohort(node: ast.Expr, args: list[ast.Expr], context: HogQLContext) -> ast.Expr:- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortarg = args[0]if not isinstance(arg, ast.Constant):diff --git a/posthog/hogql/functions/test/test_cohort.py b/posthog/hogql/functions/test/test_cohort.pyindex 049927958b3f..25dd536978c9 100644--- a/posthog/hogql/functions/test/test_cohort.py+++ b/posthog/hogql/functions/test/test_cohort.py@@ -18,12 +18,13 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_response_in_testsfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import Cohort-from posthog.models.cohort.calculation_history import CohortCalculationHistory-from posthog.models.cohort.util import recalculate_cohortpeoplefrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDT+from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import recalculate_cohortpeople+elements_chain_match = lambda x: parse_expr("match(elements_chain, {regex})", {"regex": ast.Constant(value=str(x))})not_call = lambda x: ast.Call(name="not", args=[x])diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 14c05ba445b9..01802ed507ef 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -57,11 +57,11 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.execute import sync_executefrom posthog.models import PropertyDefinition-from posthog.models.cohort.cohort import Cohortfrom posthog.models.exchange_rate.sql import EXCHANGE_RATE_DICTIONARY_NAMEfrom posthog.models.team.team import WeekStartDayfrom posthog.settings.data_stores import CLICKHOUSE_DATABASE+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyTypefrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex 1ee0bfed2281..8cdf8938837e 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -50,7 +50,7 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_exprfrom posthog.clickhouse.query_tagging import tag_contains_user_hogqlfrom posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS, PropertyOperatorType-from posthog.models import Cohort, Property, PropertyDefinition, Team+from posthog.models import Property, PropertyDefinition, Teamfrom posthog.models.element import Elementfrom posthog.models.event import Selectorfrom posthog.models.property import PropertyGroup, ValueT@@ -58,6 +58,7 @@ from posthog.models.property.util import build_selector_regexfrom posthog.utils import get_from_dict_or_attrfrom products.actions.backend.models.action import Action, ActionStepJSON+from products.cohorts.backend.models.cohort import Cohortfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.event_definitions.backend.models.property_definition import PropertyTypefrom products.warehouse_sources.backend.models.util import get_view_or_table_by_namediff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 14dd490b549b..de6b58393bd5 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -19,8 +19,9 @@ from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERRORfrom posthog.hogql.metadata import get_hogql_metadatafrom posthog.hogql.parser import parse_select-from posthog.models import Cohort, EventDefinition, PropertyDefinition+from posthog.models import EventDefinition, PropertyDefinition+from products.cohorts.backend.models.cohort import Cohortfrom products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemadiff --git a/posthog/hogql/test/test_modifiers.py b/posthog/hogql/test/test_modifiers.pyindex b39d882a26f3..34bfb6bb20a6 100644--- a/posthog/hogql/test/test_modifiers.py+++ b/posthog/hogql/test/test_modifiers.py@@ -10,7 +10,7 @@ from posthog.schema import HogQLQueryModifiers, MaterializationMode, PersonsArgMfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.query import execute_hogql_query-from posthog.models import Cohort+from products.cohorts.backend.models.cohort import Cohortclass TestModifiers(BaseTest):diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex 051d3f6375b1..5c1d94630399 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -35,9 +35,10 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.visitor import clear_locationsfrom posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_EVENTS, PropertyOperatorType-from posthog.models import Cohort, Property, PropertyDefinition, Team+from posthog.models import Property, PropertyDefinition, Teamfrom posthog.models.property import PropertyGroup+from products.cohorts.backend.models.cohort import Cohortfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.event_definitions.backend.models.property_definition import PropertyTypefrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialdiff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 7cd8b520f7a6..286893af47eb 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -36,13 +36,13 @@ from posthog.hogql.test.utils import ()from posthog.errors import InternalCHQueryError-from posthog.models import Cohort-from posthog.models.cohort.util import recalculate_cohortpeoplefrom posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODESfrom posthog.models.utils import UUIDT, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import recalculate_cohortpeoplefrom products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcediff --git a/posthog/hogql/transforms/in_cohort.py b/posthog/hogql/transforms/in_cohort.pyindex 85d17ec8dc2a..e70dfe9f1441 100644--- a/posthog/hogql/transforms/in_cohort.py+++ b/posthog/hogql/transforms/in_cohort.py@@ -97,7 +97,7 @@ class MultipleInCohortResolver(TraversingVisitor):def _resolve_cohorts(self, compare_operations: list[ast.CompareOperation]) -> list[tuple[int, StaticOrDynamic, int]]:- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohorts: list[tuple[int, StaticOrDynamic, int]] = []@@ -310,8 +310,7 @@ class InCohortResolver(TraversingVisitor):arg = node.rightif not isinstance(arg, ast.Constant):raise QueryError("IN COHORT only works with constant arguments", node=arg)-- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortif (isinstance(arg.value, int) or isinstance(arg.value, float)) and not isinstance(arg.value, bool):cohorts = Cohort.objects.filter(diff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.pyindex 64bfe9e4f821..a31c379b517b 100644--- a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py@@ -41,10 +41,11 @@ from posthog.hogql.transforms.events_predicate_pushdown import (from posthog.hogql.transforms.lazy_tables import resolve_lazy_tablesfrom posthog.clickhouse.client import sync_execute-from posthog.models import Cohort, MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition-from posthog.models.cohort.util import recalculate_cohortpeople+from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinitionfrom posthog.models.utils import uuid7+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import recalculate_cohortpeoplefrom products.event_definitions.backend.models.property_definition import PropertyTypediff --git a/posthog/hogql/transforms/test/test_in_cohort.py b/posthog/hogql/transforms/test/test_in_cohort.pyindex a9ac3a70fba2..c71f000986b7 100644--- a/posthog/hogql/transforms/test/test_in_cohort.py+++ b/posthog/hogql/transforms/test/test_in_cohort.py@@ -12,10 +12,11 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_response_in_testsfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import Cohort-from posthog.models.cohort.util import recalculate_cohortpeoplefrom posthog.models.utils import UUIDT+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import recalculate_cohortpeople+elements_chain_match = lambda x: parse_expr("match(elements_chain, {regex})", {"regex": ast.Constant(value=str(x))})not_call = lambda x: ast.Call(name="not", args=[x])diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex a87938c48afe..0d63dd90b85d 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -47,10 +47,12 @@ from posthog.constants import PropertyOperatorTypefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.events_query_runner import EventsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.models import Cohort, Filter, Property, Team+from posthog.models import Filter, Property, Teamfrom posthog.models.property import OperatorInterval, PropertyGroupfrom posthog.types import AnyPropertyFilter+from products.cohorts.backend.models.cohort import Cohort+INTERVAL_TO_SECONDS = {"minute": 60,"hour": 3600,diff --git a/posthog/hogql_queries/insights/funnels/base.py b/posthog/hogql_queries/insights/funnels/base.pyindex 9f3f5229722a..dc3492e68640 100644--- a/posthog/hogql_queries/insights/funnels/base.py+++ b/posthog/hogql_queries/insights/funnels/base.py@@ -25,13 +25,13 @@ from posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQufrom posthog.hogql_queries.insights.funnels.utils import funnel_window_interval_unit_to_sqlfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_IDfrom posthog.hogql_queries.insights.utils.entities import is_equal, is_superset-from posthog.models.cohort.cohort import Cohortfrom posthog.models.property.property import PropertyNamefrom posthog.queries.breakdown_props import get_breakdown_cohort_namefrom posthog.queries.util import correct_result_for_samplingfrom posthog.types import FunnelEntityNodefrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import CohortJOIN_ALGOS = "auto"diff --git a/posthog/hogql_queries/insights/funnels/test/breakdown_cases.py b/posthog/hogql_queries/insights/funnels/test/breakdown_cases.pyindex a9a0b31c5c3b..cf6bb999cc1c 100644--- a/posthog/hogql_queries/insights/funnels/test/breakdown_cases.py+++ b/posthog/hogql_queries/insights/funnels/test/breakdown_cases.py@@ -35,12 +35,12 @@ from posthog.constants import FunnelOrderTypefrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunnerfrom posthog.hogql_queries.insights.funnels.test.test_funnel_persons import get_actorsfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, NOT_IN_COHORT_ID-from posthog.models.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.instance_setting import override_instance_configfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.cohorts.backend.models.cohort import Cohortfrom products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csvTEST_BUCKET = "test_storage_bucket-posthog.hogql_queries.insights.funnels.breakdown_cases"diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel.py b/posthog/hogql_queries/insights/funnels/test/test_funnel.pyindex 66855062857d..bb0b05440b95 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel.py@@ -58,13 +58,13 @@ from posthog.hogql_queries.insights.funnels.test.breakdown_cases import ()from posthog.hogql_queries.insights.funnels.test.conversion_time_cases import funnel_conversion_time_test_factoryfrom posthog.models import Element-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.utils import uuid7from posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinitiondiff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.pyindex cf6925c6723c..6794e7705325 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py@@ -29,13 +29,14 @@ from posthog.schema import ()from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner-from posthog.models import Cohortfrom posthog.models.event.util import bulk_create_eventsfrom posthog.models.person.util import bulk_create_personsfrom posthog.models.team.team import Teamfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+FORMAT_TIME = "%Y-%m-%d 00:00:00"diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.pyindex a075f80151de..15d804fe7c70 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_trends.py@@ -33,9 +33,10 @@ from posthog.hogql import astfrom posthog.constants import FunnelOrderTypefrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunnerfrom posthog.hogql_queries.insights.funnels.test.test_funnel_persons import get_actors-from posthog.models.cohort.cohort import Cohortfrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+FORMAT_TIME = "%Y-%m-%d %H:%M:%S"FORMAT_TIME_DAY_END = "%Y-%m-%d 23:59:59"diff --git a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.pyindex 4ceacb8172f4..743958a32313 100644--- a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py+++ b/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py@@ -32,7 +32,6 @@ from posthog.schema import (from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner-from posthog.models import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team import WeekStartDay@@ -40,6 +39,7 @@ from posthog.models.utils import UUIDTfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortdef create_action(**kwargs):diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.pyindex f3df9547ea96..ac3fdc5c00b6 100644--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py@@ -41,13 +41,13 @@ from posthog.hogql_queries.insights.retention.test.retention_base_query_variant)from posthog.hogql_queries.insights.retention.test.utils import pad, pluckfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABEL-from posthog.models import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.person import Personfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csvdiff --git a/posthog/hogql_queries/insights/trends/test/test_formula.py b/posthog/hogql_queries/insights/trends/test/test_formula.pyindex 693133eaed2f..b94fc01abe33 100644--- a/posthog/hogql_queries/insights/trends/test/test_formula.py+++ b/posthog/hogql_queries/insights/trends/test/test_formula.py@@ -21,11 +21,12 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.constants import TRENDS_BOLD_NUMBER, TRENDS_CUMULATIVE, TRENDS_PIEfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner-from posthog.models import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.utils import uuid7from posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.cohorts.backend.models.cohort import Cohort+@override_settings(IN_UNIT_TESTING=True)class TestFormula(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql_queries/insights/trends/test/test_trends.py b/posthog/hogql_queries/insights/trends/test/test_trends.pyindex 4fc5efb57dc3..98a2b6d99d03 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends.py@@ -33,7 +33,7 @@ from posthog.constants import TREND_FILTER_TYPE_EVENTS, TRENDS_BAR_VALUE, TRENDSfrom posthog.hogql_queries.insights.trends.test.test_trends_persons import get_actorsfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunnerfrom posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query-from posthog.models import Cohort, Entity, Filter, Organization, Person+from posthog.models import Entity, Filter, Organization, Personfrom posthog.models.group.util import create_groupfrom posthog.models.instance_setting import get_instance_setting, override_instance_configfrom posthog.models.person.util import create_person_distinct_id@@ -43,6 +43,7 @@ from posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinitiondiff --git a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py b/posthog/hogql_queries/insights/trends/test/test_trends_persons.pyindex d19c33bb6e54..1e7e4af26d99 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py@@ -37,11 +37,12 @@ from posthog.schema import (from posthog.api.test.test_team import create_teamfrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL-from posthog.models import Cohort, Team+from posthog.models import Teamfrom posthog.models.group.util import create_groupfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyTypediff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.pyindex fd0c7f8c9832..1dcc7f2b9660 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py@@ -69,13 +69,13 @@ from posthog.hogql_queries.insights.utils.breakdowns import (BREAKDOWN_OTHER_DISPLAY,BREAKDOWN_OTHER_STRING_LABEL,)-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.team.team import Team, WeekStartDayfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinitiondiff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.pyindex 8827e9b0817b..ed687cefe433 100644--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py@@ -77,13 +77,13 @@ from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_efrom posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeriesfrom posthog.hogql_queries.validation.validation import QueryValidationRulefrom posthog.models import Team-from posthog.models.cohort.cohort import Cohortfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.user import Userfrom posthog.queries.util import correct_result_for_samplingfrom posthog.utils import multisortfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.property_definition import PropertyDefinitionfrom products.warehouse_sources.backend.models.util import get_view_or_table_by_namediff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex 85c97b1bbd2f..d7012890e3c3 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -2,7 +2,8 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patchfrom posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery, HogQLRealtimeCohortQuery-from posthog.models import Cohort++from products.cohorts.backend.models.cohort import Cohortclass TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql_queries/test/test_sessions_query_runner.py b/posthog/hogql_queries/test/test_sessions_query_runner.pyindex 48738ca0d7a0..1815c725df0e 100644--- a/posthog/hogql_queries/test/test_sessions_query_runner.py+++ b/posthog/hogql_queries/test/test_sessions_query_runner.py@@ -1327,7 +1327,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert len(response.results) == 1def test_filter_test_accounts_with_cohort_filter(self):- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = Cohort.objects.create(team=self.team,diff --git a/posthog/management/commands/backfill_precalculated_events.py b/posthog/management/commands/backfill_precalculated_events.pyindex d7d5b5b7fe69..02e10c18fffb 100644--- a/posthog/management/commands/backfill_precalculated_events.py+++ b/posthog/management/commands/backfill_precalculated_events.py@@ -11,8 +11,6 @@ from django.core.management.base import BaseCommand, CommandErrorimport structlogfrom temporalio.common import WorkflowIDReusePolicy-from posthog.models import Cohort-from posthog.models.cohort.cohort import CohortTypefrom posthog.models.property.property import BehavioralPropertyTypefrom posthog.temporal.common.client import async_connectfrom posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (@@ -21,6 +19,8 @@ from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflfrom posthog.temporal.messaging.filter_storage import store_event_filtersfrom posthog.temporal.messaging.types import BehavioralEventFilter+from products.cohorts.backend.models.cohort import Cohort, CohortType+logger = structlog.get_logger(__name__)diff --git a/posthog/management/commands/backfill_precalculated_person_properties.py b/posthog/management/commands/backfill_precalculated_person_properties.pyindex abc21819954d..9564908f2c1b 100644--- a/posthog/management/commands/backfill_precalculated_person_properties.py+++ b/posthog/management/commands/backfill_precalculated_person_properties.py@@ -8,8 +8,6 @@ from django.core.management.base import BaseCommand, CommandErrorimport structlogfrom temporalio.common import WorkflowIDReusePolicy-from posthog.models import Cohort-from posthog.models.cohort.cohort import CohortTypefrom posthog.temporal.common.client import async_connectfrom posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (BackfillPrecalculatedPersonPropertiesCoordinatorInputs,@@ -17,6 +15,8 @@ from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinfrom posthog.temporal.messaging.filter_storage import store_filtersfrom posthog.temporal.messaging.types import PersonPropertyFilter+from products.cohorts.backend.models.cohort import Cohort, CohortType+logger = structlog.get_logger(__name__)diff --git a/posthog/management/commands/calculate_cohort.py b/posthog/management/commands/calculate_cohort.pyindex 7449584eaee5..59d791c25edd 100644--- a/posthog/management/commands/calculate_cohort.py+++ b/posthog/management/commands/calculate_cohort.py@@ -3,9 +3,10 @@ import tracebackfrom django.core.management.base import BaseCommand-from posthog.models import Cohortfrom posthog.tasks.calculate_cohort import calculate_cohort_ch, increment_version_and_enqueue_calculate_cohort+from products.cohorts.backend.models.cohort import Cohort+logger = logging.getLogger(__name__)diff --git a/posthog/management/commands/fix_cohort_people_unsynced_ch.py b/posthog/management/commands/fix_cohort_people_unsynced_ch.pyindex eec85f4b7552..f6d4a2e13281 100644--- a/posthog/management/commands/fix_cohort_people_unsynced_ch.py+++ b/posthog/management/commands/fix_cohort_people_unsynced_ch.py@@ -4,10 +4,11 @@ from django.db import connectionsimport structlogfrom posthog.clickhouse.client import sync_execute-from posthog.models.cohort.cohort import Cohortfrom posthog.models.person import Personfrom posthog.person_db_router import PERSONS_DB_FOR_READ+from products.cohorts.backend.models.cohort import Cohort+logger = structlog.get_logger(__name__)# Use centralized database routing constantdiff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.pyindex ea752efb86e6..2983936e1e29 100644--- a/posthog/management/commands/resave_cohorts.py+++ b/posthog/management/commands/resave_cohorts.py@@ -7,10 +7,11 @@ from django.core.management.base import BaseCommand, CommandParserimport structlogfrom posthog.api.cohort import validate_filters_and_compute_realtime_support-from posthog.models.cohort.cohort import Cohort-from posthog.models.cohort.util import get_all_cohort_dependencies, sort_cohorts_topologicallyfrom posthog.models.team.team import Team+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically+logger = structlog.get_logger(__name__)diff --git a/posthog/management/commands/test/test_backfill_precalculated_events.py b/posthog/management/commands/test/test_backfill_precalculated_events.pyindex 18156e9bb7dd..aa05d4d565ce 100644--- a/posthog/management/commands/test/test_backfill_precalculated_events.py+++ b/posthog/management/commands/test/test_backfill_precalculated_events.py@@ -17,13 +17,14 @@ from posthog.management.commands.backfill_precalculated_events import (compute_backfill_days,extract_behavioral_filters,)-from posthog.models import Cohort, Team-from posthog.models.cohort.cohort import CohortType+from posthog.models import Teamfrom posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (BackfillPrecalculatedEventsCoordinatorInputs,)from posthog.temporal.messaging.types import BehavioralEventFilter+from products.cohorts.backend.models.cohort import Cohort, CohortType+class TestExtractBehavioralFilters(BaseTest):def test_extracts_performed_event_filter(self):diff --git a/posthog/management/commands/test/test_backfill_precalculated_person_properties.py b/posthog/management/commands/test/test_backfill_precalculated_person_properties.pyindex f2ecf8f3a93a..ffcf10b9d035 100644--- a/posthog/management/commands/test/test_backfill_precalculated_person_properties.py+++ b/posthog/management/commands/test/test_backfill_precalculated_person_properties.py@@ -5,8 +5,7 @@ from unittest.mock import patchfrom django.core.management import call_command-from posthog.models import Cohort-from posthog.models.cohort.cohort import CohortType+from products.cohorts.backend.models.cohort import Cohort, CohortTypeclass BackfillPrecalculatedPersonPropertiesCommandTestCase(BaseTest):diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.pyindex ff48737e34ee..9a994134dc10 100644--- a/posthog/management/commands/test/test_resave_cohorts.py+++ b/posthog/management/commands/test/test_resave_cohorts.py@@ -6,9 +6,10 @@ from posthog.test.base import BaseTestfrom django.core.management import call_command-from posthog.models.cohort.cohort import Cohortfrom posthog.models.team.team import Team+from products.cohorts.backend.models.cohort import Cohort+from common.hogvm.python.operation import HOGQL_BYTECODE_VERSIONdiff --git a/posthog/middleware.py b/posthog/middleware.pyindex 64467d2d83a6..5d48977eb017 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -40,7 +40,7 @@ from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_hfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_sessionfrom posthog.helpers.user_devices import set_known_device_cookie-from posthog.models import Cohort, Team, User+from posthog.models import Team, Userfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_CLIENT_HEADER,ACTIVITY_LOG_CLIENT_MAX_LENGTH,@@ -53,6 +53,7 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import _is_valid_ip_address, get_ip_addressfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookdiff --git a/posthog/migrations/1215_migrate_replay_models.py b/posthog/migrations/1215_migrate_replay_models.pynew file mode 100644index 000000000000..af68edf26af7--- /dev/null+++ b/posthog/migrations/1215_migrate_replay_models.py@@ -0,0 +1,53 @@+# Generated by Django 5.2.14 on 2026-06-08 10:07++from django.db import migrations++MODELS_TO_MOVE = ("exportedrecording",)+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently.++ If the target (app_label, model) already exists (e.g. Django auto-created it,+ or a prior failed attempt left one behind), merge permissions onto the target+ and delete the source to avoid a unique-constraint violation. Uses the+ migration's own connection alias for multi-DB safety.+ """+ db_alias = schema_editor.connection.alias+ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("auth", "Permission")++ for model_name in MODELS_TO_MOVE:+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()++ if source and target:+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)+ source.delete(using=db_alias)+ elif source:+ source.app_label = to_label+ source.save(using=db_alias)+++def update_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "posthog", "replay")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "replay", "posthog")+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1214_oauthapplication_sessions_revoked_at"), ("replay", "0001_migrate_replay_models")]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="ExportedRecording",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/1216_migrate_cohorts_models.py b/posthog/migrations/1216_migrate_cohorts_models.pynew file mode 100644index 000000000000..fdf33d746c6c--- /dev/null+++ b/posthog/migrations/1216_migrate_cohorts_models.py@@ -0,0 +1,80 @@+# Generated by Django 5.2.14 on 2026-06-08 10:30++from django.db import migrations++MODELS_TO_MOVE = ("cohort", "cohortcalculationhistory", "cohortpeople")+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently.++ If the target (app_label, model) already exists (e.g. Django auto-created it,+ or a prior failed attempt left one behind), merge permissions onto the target+ and delete the source to avoid a unique-constraint violation. Uses the+ migration's own connection alias for multi-DB safety.+ """+ db_alias = schema_editor.connection.alias+ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("auth", "Permission")++ for model_name in MODELS_TO_MOVE:+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()++ if source and target:+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)+ source.delete(using=db_alias)+ elif source:+ source.app_label = to_label+ source.save(using=db_alias)+++def update_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "posthog", "cohorts")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "cohorts", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("error_tracking", "0017_migrate_cohorts_models"),+ ("experiments", "0018_migrate_cohorts_models"),+ ("posthog", "1215_migrate_replay_models"),+ ("cohorts", "0001_migrate_cohorts_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="cohortpeople",+ name="cohort",+ ),+ migrations.RemoveField(+ model_name="cohortcalculationhistory",+ name="cohort",+ ),+ migrations.RemoveField(+ model_name="cohortcalculationhistory",+ name="team",+ ),+ migrations.RemoveField(+ model_name="cohortpeople",+ name="person",+ ),+ migrations.DeleteModel(+ name="Cohort",+ ),+ migrations.DeleteModel(+ name="CohortCalculationHistory",+ ),+ migrations.DeleteModel(+ name="CohortPeople",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d49047e386f3..089c457074e5 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1214_oauthapplication_sessions_revoked_at+1216_migrate_cohorts_modelsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex b2d9cf87b3b0..11bbaa4e8c53 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -9,7 +9,6 @@ from .activity_logging.activity_log import ActivityLogfrom .activity_logging.notification_viewed import NotificationViewedfrom .async_deletion import AsyncDeletion, DeletionTypefrom .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus-from .cohort import Cohort, CohortPeople, CohortCalculationHistoryfrom .column_configuration import ColumnConfigurationfrom .comment import Commentfrom .core_event import CoreEvent@@ -27,7 +26,6 @@ from .event_filter_config import EventFilterConfig # noqa: F401from products.event_definitions.backend.models import EventDefinitionfrom products.event_definitions.backend.models import EventPropertyfrom .role_external_reference import RoleExternalReference-from .exported_recording import ExportedRecordingfrom .file_system.file_system import FileSystemfrom .file_system.folder_instructions import FileSystemFolderInstructionsfrom .file_system.file_system_view_log import FileSystemViewLog@@ -94,9 +92,6 @@ __all__ = ["AsyncMigration","AsyncMigrationError","CIMDVerificationToken",- "Cohort",- "CohortPeople",- "CohortCalculationHistory","ColumnConfiguration","CoreEvent","Dashboard",@@ -116,7 +111,6 @@ __all__ = ["EventDefinition","EventProperty","RoleExternalReference",- "ExportedRecording","FileSystem","FileSystemFolderInstructions","FileSystemViewLog",diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.pyindex 5ea0040d96d9..a0fcb376c35a 100644--- a/posthog/models/file_system/unfiled_file_saver.py+++ b/posthog/models/file_system/unfiled_file_saver.py@@ -4,7 +4,6 @@ from typing import Optionalfrom django.utils import timezone-from posthog.models.cohort import Cohortfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system import FileSystem, escape_path, split_pathfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixin@@ -14,6 +13,7 @@ from posthog.session_recordings.models.session_recording_playlist import Sessionfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/posthog/models/filters/mixins/simplify.py b/posthog/models/filters/mixins/simplify.pyindex 8ed976bb6b20..01e49f30a3bf 100644--- a/posthog/models/filters/mixins/simplify.py+++ b/posthog/models/filters/mixins/simplify.py@@ -104,8 +104,8 @@ class SimplifyFilterMixin:def _simplify_property(self, team: "Team", property: "Property", **kwargs) -> "PropertyGroup":if property.type == "cohort":- from posthog.models import Cohort- from posthog.models.cohort.util import simplified_cohort_filter_properties+ from products.cohorts.backend.models.cohort import Cohort+ from products.cohorts.backend.models.util import simplified_cohort_filter_propertiestry:cohort = Cohort.objects.get(pk=cast(str | int, property.value), team__project_id=team.project_id)diff --git a/posthog/models/filters/test/test_filter.py b/posthog/models/filters/test/test_filter.pyindex 97625474bfb4..3ba4e66b6042 100644--- a/posthog/models/filters/test/test_filter.py+++ b/posthog/models/filters/test/test_filter.py@@ -16,10 +16,12 @@ from posthog.test.base import (from django.db.models import CharField, F, Func, Qfrom posthog.constants import FILTER_TEST_ACCOUNTS-from posthog.models import Cohort, Filter, Person, Team+from posthog.models import Filter, Person, Teamfrom posthog.models.property import Propertyfrom posthog.queries.base import properties_to_Q, property_group_to_Q+from products.cohorts.backend.models.cohort import Cohort+class TestFilter(BaseTest):def test_old_style_properties(self):diff --git a/posthog/models/property/util.py b/posthog/models/property/util.pyindex 89c6f875ac77..d895ad96982d 100644--- a/posthog/models/property/util.py+++ b/posthog/models/property/util.py@@ -21,14 +21,6 @@ from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.kafka_engine import trim_quotes_exprfrom posthog.clickhouse.materialized_columns import TableWithProperties, get_materialized_column_for_propertyfrom posthog.constants import PropertyOperatorType-from posthog.models.cohort import Cohort-from posthog.models.cohort.util import (- format_cohort_subquery,- format_filter_query,- format_precalculated_cohort_query,- format_static_cohort_query,- get_count_operator,-)from posthog.models.event import Selectorfrom posthog.models.group.sql import GET_GROUP_IDS_BY_PROPERTY_SQLfrom posthog.models.person.sql import GET_DISTINCT_IDS_BY_PERSON_ID_FILTER, GET_DISTINCT_IDS_BY_PROPERTY_SQL@@ -50,6 +42,14 @@ from posthog.utils import is_json, is_valid_regexfrom products.actions.backend.models.action import Actionfrom products.actions.backend.models.util import get_action_tables_and_properties+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import (+ format_cohort_subquery,+ format_filter_query,+ format_precalculated_cohort_query,+ format_static_cohort_query,+ get_count_operator,+)StringMatching = Literal["selector", "tag_name", "href", "text"]diff --git a/posthog/models/resource_transfer/test/test_visitors.py b/posthog/models/resource_transfer/test/test_visitors.pyindex 7ddcebbe933f..4d774b33bfe9 100644--- a/posthog/models/resource_transfer/test/test_visitors.py+++ b/posthog/models/resource_transfer/test/test_visitors.py@@ -7,7 +7,6 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.models import Cohortfrom posthog.models.resource_transfer.visitors import CohortVisitor, InsightVisitorfrom posthog.models.resource_transfer.visitors.experiment import ExperimentVisitorfrom posthog.models.resource_transfer.visitors.experiment_holdout import ExperimentHoldoutVisitor@@ -24,6 +23,7 @@ from posthog.models.resource_transfer.visitors.feature_flag_filters import (from posthog.models.resource_transfer.visitors.survey import SurveyVisitorfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import ExperimentHoldoutdiff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.pyindex 7263a061fb00..501a1d5838ee 100644--- a/posthog/models/resource_transfer/visitors/cohort.py+++ b/posthog/models/resource_transfer/visitors/cohort.py@@ -30,15 +30,14 @@ class CohortVisitor():@classmethoddef get_model(cls) -> type[models.Model]:- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortreturn Cohort@classmethoddef get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:- from posthog.models import Cohort-from products.actions.backend.models.action import Action+ from products.cohorts.backend.models.cohort import Cohortcohort_ids = cls._extract_cohort_ids(resource.filters)action_ids = cls._extract_action_ids(resource.filters)diff --git a/posthog/models/resource_transfer/visitors/experiment.py b/posthog/models/resource_transfer/visitors/experiment.pyindex d48ca2453a8a..64fe9fa02afc 100644--- a/posthog/models/resource_transfer/visitors/experiment.py+++ b/posthog/models/resource_transfer/visitors/experiment.py@@ -4,7 +4,6 @@ from typing import Anyfrom django.db import models-from posthog.models import Cohortfrom posthog.models.resource_transfer.types import ResourceTransferEdgefrom posthog.models.resource_transfer.visitors.base import ResourceTransferVisitorfrom posthog.models.resource_transfer.visitors.common import build_edges_for_ids@@ -15,6 +14,7 @@ from posthog.models.resource_transfer.visitors.experiment_payload import ()from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortclass ExperimentVisitor(diff --git a/posthog/models/resource_transfer/visitors/experiment_holdout.py b/posthog/models/resource_transfer/visitors/experiment_holdout.pyindex 138d37c10e2f..809d5693d49f 100644--- a/posthog/models/resource_transfer/visitors/experiment_holdout.py+++ b/posthog/models/resource_transfer/visitors/experiment_holdout.py@@ -4,7 +4,6 @@ from typing import Anyfrom django.db import models-from posthog.models import Cohortfrom posthog.models.resource_transfer.types import ResourcePayload, ResourceTransferEdgefrom posthog.models.resource_transfer.visitors.base import ResourceTransferVisitorfrom posthog.models.resource_transfer.visitors.common import (@@ -13,6 +12,8 @@ from posthog.models.resource_transfer.visitors.common import (rewrite_cohort_id_in_properties,)+from products.cohorts.backend.models.cohort import Cohort+class ExperimentHoldoutVisitor(ResourceTransferVisitor,diff --git a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py b/posthog/models/resource_transfer/visitors/experiment_saved_metric.pyindex 78b52cc41fe1..48d27aca75a5 100644--- a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py+++ b/posthog/models/resource_transfer/visitors/experiment_saved_metric.py@@ -4,13 +4,13 @@ from typing import Anyfrom django.db import models-from posthog.models import Cohortfrom posthog.models.resource_transfer.types import ResourcePayload, ResourceTransferEdgefrom posthog.models.resource_transfer.visitors.base import ResourceTransferVisitorfrom posthog.models.resource_transfer.visitors.common import build_edges_for_idsfrom posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortclass ExperimentSavedMetricVisitor(diff --git a/posthog/models/resource_transfer/visitors/feature_flag.py b/posthog/models/resource_transfer/visitors/feature_flag.pyindex dbeb33912df0..f31c7f2d529f 100644--- a/posthog/models/resource_transfer/visitors/feature_flag.py+++ b/posthog/models/resource_transfer/visitors/feature_flag.py@@ -4,7 +4,6 @@ from typing import Anyfrom django.db import models-from posthog.models import Cohortfrom posthog.models.resource_transfer.types import ResourceTransferEdgefrom posthog.models.resource_transfer.visitors.base import ResourceTransferVisitorfrom posthog.models.resource_transfer.visitors.common import build_edges_for_ids, make_json_id_rewriter@@ -18,6 +17,7 @@ from posthog.models.resource_transfer.visitors.feature_flag_filters import ()from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import ExperimentHoldoutdiff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.pyindex a9b85b3451e2..d8c915c62d57 100644--- a/posthog/models/resource_transfer/visitors/insight.py+++ b/posthog/models/resource_transfer/visitors/insight.py@@ -37,9 +37,8 @@ class InsightVisitor(@classmethoddef get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:- from posthog.models import Cohort-from products.actions.backend.models.action import Action+ from products.cohorts.backend.models.cohort import Cohortaction_ids = cls._extract_action_ids(resource.filters, resource.query)cohort_ids = cls._extract_cohort_ids(resource.filters, resource.query)diff --git a/posthog/models/resource_transfer/visitors/survey.py b/posthog/models/resource_transfer/visitors/survey.pyindex 327822c8e644..c10f0cd45f8c 100644--- a/posthog/models/resource_transfer/visitors/survey.py+++ b/posthog/models/resource_transfer/visitors/survey.py@@ -42,7 +42,7 @@ class SurveyVisitor(@classmethoddef get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:- from posthog.models import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort_ids = cls._extract_cohort_ids_from_conditions(resource.conditions)diff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex d1ead27049b2..6b1fdc8679f5 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -89,7 +89,7 @@ class TeamManager(models.Manager):team = cast("Team", self.create(**kwargs))# Create internal/test users cohort and set test_account_filters to exclude it- from posthog.models.cohort.cohort import get_or_create_internal_test_users_cohort+ from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohortinitiating_user_email = initiating_user.email if initiating_user else Nonetest_users_cohort = get_or_create_internal_test_users_cohort(team, initiating_user_email=initiating_user_email)diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 759167cb4b02..4e35075a3c78 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -25,10 +25,9 @@ actions_that_require_current_team = [def delete_bulky_postgres_data(team_ids: list[int]):"Efficiently delete large tables for teams from postgres. Using normal CASCADE delete here can time out"-- from posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system_view_log import FileSystemViewLog+ from products.cohorts.backend.models.cohort import Cohortfrom products.data_modeling.backend.models import Edge, Nodefrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2@@ -222,8 +221,8 @@ def _delete_cohort_members_for_teams(team_ids: list[int], cohort_ids: list[int])Falls back to ORM _raw_delete when personhog is not available.Routes per-team for consistent gate/metrics/fallback behavior."""- from posthog.models.cohort import Cohort- from posthog.models.cohort.util import delete_cohort_members_bulk+ from products.cohorts.backend.models.cohort import Cohort+ from products.cohorts.backend.models.util import delete_cohort_members_bulkfor team_id in team_ids:team_cohort_ids = list(Cohort.objects.filter(team_id=team_id, id__in=cohort_ids).values_list("id", flat=True))diff --git a/posthog/models/test/test_async_deletion_model.py b/posthog/models/test/test_async_deletion_model.pyindex 636a3eb49152..451a25feb2ce 100644--- a/posthog/models/test/test_async_deletion_model.py+++ b/posthog/models/test/test_async_deletion_model.py@@ -14,12 +14,12 @@ from posthog.clickhouse.client import sync_executefrom posthog.models import AsyncDeletion, DeletionType, Team, Userfrom posthog.models.async_deletion.delete_cohorts import AsyncCohortDeletionfrom posthog.models.async_deletion.delete_events import AsyncEventDeletion-from posthog.models.cohort.util import insert_static_cohortfrom posthog.models.group.util import create_groupfrom posthog.models.person.util import create_person, create_person_distinct_idfrom posthog.test.test_plugin_log_entry import create_plugin_log_entryfrom products.cdp.backend.models.plugin import PluginLogEntrySource, PluginLogEntryType+from products.cohorts.backend.models.util import insert_static_cohortuuid = str(UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))uuid2 = str(UUID("7ba7b810-9dad-11d1-80b4-00c04fd430c8"))diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.pyindex 0dfaf7775810..108485e56f21 100644--- a/posthog/models/test/test_hog_function.py+++ b/posthog/models/test/test_hog_function.py@@ -6,7 +6,6 @@ from unittest.mock import Mock, patchfrom django.test import TestCase-from posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -14,6 +13,7 @@ from posthog.models.user import Userfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions+from products.cohorts.backend.models.cohort import Cohortfrom common.hogvm.python.operation import HOGQL_BYTECODE_VERSIONdiff --git a/posthog/person_db_router.py b/posthog/person_db_router.pyindex eecf3b4f490d..4eecd2e3a1f3 100644--- a/posthog/person_db_router.py+++ b/posthog/person_db_router.py@@ -46,7 +46,8 @@ class PersonDBRouter:# Apps whose models can live in the persons DB. FeatureFlagHashKeyOverride# was historically in the `posthog` app; it moved to `feature_flags` when the# FF models were extracted, but the physical table still lives in persons_db.- PERSONS_APP_LABELS = {"posthog", "feature_flags"}+ # Likewise CohortPeople moved to `cohorts`, keeping its posthog_cohortpeople table.+ PERSONS_APP_LABELS = {"posthog", "feature_flags", "cohorts"}def db_for_read(self, model, **hints):"""@@ -94,9 +95,9 @@ class PersonDBRouter:# GroupTypeMapping -> Project: GroupTypeMapping.project has db_constraint=False# GroupTypeMapping -> Dashboard: GroupTypeMapping.detail_dashboard has db_constraint=Falsefrom posthog.models import Person, Project, Team- from posthog.models.cohort import Cohort, CohortPeoplefrom posthog.models.group_type_mapping import GroupTypeMapping+ from products.cohorts.backend.models.cohort import Cohort, CohortPeoplefrom products.dashboards.backend.models.dashboard import Dashboard# Allow any persons_db model -> Team relationdiff --git a/posthog/queries/base.py b/posthog/queries/base.pyindex 4be6ce9e4bea..829520803468 100644--- a/posthog/queries/base.py+++ b/posthog/queries/base.py@@ -12,7 +12,6 @@ from dateutil.relativedelta import relativedeltafrom rest_framework.exceptions import ValidationErrorfrom posthog.constants import PropertyOperatorType-from posthog.models.cohort import Cohort, CohortOrEmpty, CohortPeoplefrom posthog.models.filters.filter import Filterfrom posthog.models.filters.path_filter import PathFilterfrom posthog.models.property import Property, PropertyGroup@@ -21,6 +20,8 @@ from posthog.models.team import Teamfrom posthog.queries.util import convert_to_datetime_awarefrom posthog.utils import get_compare_period_dates, is_valid_regex+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, CohortPeople+FilterType = TypeVar("FilterType", Filter, PathFilter)@@ -350,7 +351,7 @@ def property_to_Q(# 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 posthog.models.cohort.util import is_person_in_cohort+ from products.cohorts.backend.models.util import is_person_in_cohortif is_person_in_cohort(team_id=team_id, person_id=person_id, cohort_id=cohort_id):return Q(pk__isnull=False)@@ -362,7 +363,7 @@ def property_to_Q(# the Exists(CohortPeople) subquery so the persons DB is not# required on the personhog path.if team_id is not None:- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idsmember_ids = list_cohort_member_ids(team_id=team_id, cohort_id=cohort_id)if not member_ids:diff --git a/posthog/queries/breakdown_props.py b/posthog/queries/breakdown_props.pyindex 05be7e31fabe..4c84a761ef49 100644--- a/posthog/queries/breakdown_props.py+++ b/posthog/queries/breakdown_props.py@@ -8,8 +8,6 @@ from posthog.hogql.hogql import HogQLContextfrom posthog.constants import BREAKDOWN_TYPES, MONTHLY_ACTIVE, WEEKLY_ACTIVE, PropertyOperatorTypefrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, NOT_IN_COHORT_ID-from posthog.models.cohort import Cohort-from posthog.models.cohort.util import format_filter_queryfrom posthog.models.entity import Entityfrom posthog.models.entity.util import get_entity_filtering_paramsfrom posthog.models.filters.filter import Filter@@ -32,6 +30,9 @@ from posthog.queries.trends.sql import HISTOGRAM_ELEMENTS_ARRAY_OF_KEY_SQL, TOP_from posthog.queries.util import PersonPropertiesMode, alias_poe_mode_for_legacyfrom posthog.session_recordings.queries.session_query import SessionQuery+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import format_filter_query+def get_breakdown_prop_values(filter: Filter,diff --git a/posthog/queries/event_query/event_query.py b/posthog/queries/event_query/event_query.pyindex f0d662ed06e4..1ed335a9190a 100644--- a/posthog/queries/event_query/event_query.py+++ b/posthog/queries/event_query/event_query.py@@ -6,8 +6,7 @@ from posthog.schema import PersonsOnEventsModefrom posthog.hogql.database.database import Databasefrom posthog.clickhouse.materialized_columns import ColumnName-from posthog.models import Cohort, Filter, Property-from posthog.models.cohort.util import is_precalculated_query+from posthog.models import Filter, Propertyfrom posthog.models.filters import AnyFilterfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.filters.path_filter import PathFilter@@ -25,6 +24,9 @@ from posthog.queries.query_date_range import QueryDateRangefrom posthog.queries.util import PersonPropertiesMode, alias_poe_mode_for_legacyfrom posthog.session_recordings.queries.session_query import SessionQuery+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import is_precalculated_query+class EventQuery(metaclass=ABCMeta):DISTINCT_ID_TABLE_ALIAS = "pdi"diff --git a/posthog/queries/funnels/funnel_trends.py b/posthog/queries/funnels/funnel_trends.pyindex f5ae4956e1f9..3e1430d26cfc 100644--- a/posthog/queries/funnels/funnel_trends.py+++ b/posthog/queries/funnels/funnel_trends.py@@ -2,7 +2,6 @@ from datetime import datetimefrom itertools import groupbyfrom typing import Optional-from posthog.models.cohort import Cohortfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Teamfrom posthog.queries.funnels.base import ClickhouseFunnelBase@@ -14,6 +13,8 @@ from posthog.queries.util import (get_start_of_interval_sql,)+from products.cohorts.backend.models.cohort import Cohort+TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"HUMAN_READABLE_TIMESTAMP_FORMAT = "%-d-%b-%Y"diff --git a/posthog/queries/funnels/test/breakdown_cases.py b/posthog/queries/funnels/test/breakdown_cases.pyindex d23afcdfe49b..d383ab43ae0f 100644--- a/posthog/queries/funnels/test/breakdown_cases.py+++ b/posthog/queries/funnels/test/breakdown_cases.py@@ -7,12 +7,13 @@ from typing import Any, Literal, Optional, Unionfrom posthog.test.base import APIBaseTest, also_test_with_materialized_columns, snapshot_clickhouse_queriesfrom posthog.constants import INSIGHT_FUNNELS-from posthog.models.cohort import Cohortfrom posthog.models.filters import Filterfrom posthog.queries.breakdown_props import ALL_USERS_COHORT_IDfrom posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnorderedfrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+@dataclass(frozen=True)class FunnelStepResult:diff --git a/posthog/queries/funnels/test/test_funnel.py b/posthog/queries/funnels/test/test_funnel.pyindex 1ea9acb57dfc..ed18a217bb97 100644--- a/posthog/queries/funnels/test/test_funnel.py+++ b/posthog/queries/funnels/test/test_funnel.py@@ -21,7 +21,6 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.clickhouse.client import sync_executefrom posthog.constants import FILTER_TEST_ACCOUNTS, INSIGHT_FUNNELSfrom posthog.models import Element-from posthog.models.cohort import Cohortfrom posthog.models.filters import Filterfrom posthog.models.instance_setting import get_instance_settingfrom posthog.queries.funnels import ClickhouseFunnel, ClickhouseFunnelActors@@ -30,6 +29,7 @@ from posthog.queries.funnels.test.conversion_time_cases import funnel_conversionfrom posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortclass TestFunnelBreakdown(diff --git a/posthog/queries/funnels/test/test_funnel_persons.py b/posthog/queries/funnels/test/test_funnel_persons.pyindex b1c7fe0375f1..db549d9bd43f 100644--- a/posthog/queries/funnels/test/test_funnel_persons.py+++ b/posthog/queries/funnels/test/test_funnel_persons.py@@ -14,13 +14,15 @@ from posthog.test.base import (from django.utils import timezonefrom posthog.constants import INSIGHT_FUNNELS-from posthog.models import Cohort, Filter+from posthog.models import Filterfrom posthog.models.event.util import bulk_create_eventsfrom posthog.models.person.util import bulk_create_personsfrom posthog.queries.funnels.funnel_persons import ClickhouseFunnelActorsfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+FORMAT_TIME = "%Y-%m-%d 00:00:00"MAX_STEP_COLUMN = 0COUNT_COLUMN = 1diff --git a/posthog/queries/funnels/test/test_funnel_trends.py b/posthog/queries/funnels/test/test_funnel_trends.pyindex 2367d48f2fb1..135613058b44 100644--- a/posthog/queries/funnels/test/test_funnel_trends.py+++ b/posthog/queries/funnels/test/test_funnel_trends.py@@ -5,12 +5,13 @@ from freezegun.api import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, snapshot_clickhouse_queriesfrom posthog.constants import INSIGHT_FUNNELS, TRENDS_LINEAR, FunnelOrderType-from posthog.models.cohort import Cohortfrom posthog.models.filters import Filterfrom posthog.queries.funnels.funnel_trends import ClickhouseFunnelTrendsfrom posthog.queries.funnels.funnel_trends_persons import ClickhouseFunnelTrendsActorsfrom posthog.test.test_journeys import journeys_for+from products.cohorts.backend.models.cohort import Cohort+FORMAT_TIME = "%Y-%m-%d %H:%M:%S"FORMAT_TIME_DAY_END = "%Y-%m-%d 23:59:59"diff --git a/posthog/queries/person_query.py b/posthog/queries/person_query.pyindex a9503d6104b8..0b0b30b80625 100644--- a/posthog/queries/person_query.py+++ b/posthog/queries/person_query.py@@ -4,9 +4,6 @@ from uuid import UUIDfrom posthog.clickhouse.materialized_columns import ColumnNamefrom posthog.constants import PropertyOperatorTypefrom posthog.models import Filter-from posthog.models.cohort import Cohort-from posthog.models.cohort.sql import GET_COHORTPEOPLE_BY_COHORT_ID, GET_STATIC_COHORTPEOPLE_BY_COHORT_ID-from posthog.models.cohort.util import format_precalculated_cohort_query, format_static_cohort_queryfrom posthog.models.entity import Entityfrom posthog.models.filters.path_filter import PathFilterfrom posthog.models.filters.retention_filter import RetentionFilter@@ -22,6 +19,10 @@ from posthog.queries.person_distinct_id_query import get_team_distinct_ids_queryfrom posthog.queries.trends.util import COUNT_PER_ACTOR_MATH_FUNCTIONSfrom posthog.queries.util import PersonPropertiesMode+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID, GET_STATIC_COHORTPEOPLE_BY_COHORT_ID+from products.cohorts.backend.models.util import format_precalculated_cohort_query, format_static_cohort_query+class PersonQuery:"""diff --git a/posthog/queries/test/test_person_query.py b/posthog/queries/test/test_person_query.pyindex 1970bd52547a..b3a0230ce6e1 100644--- a/posthog/queries/test/test_person_query.py+++ b/posthog/queries/test/test_person_query.py@@ -5,10 +5,11 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person,from posthog.clickhouse.client import sync_executefrom posthog.models import Filter-from posthog.models.cohort import Cohortfrom posthog.queries.column_optimizer.column_optimizer import ColumnOptimizerfrom posthog.queries.person_query import PersonQuery+from products.cohorts.backend.models.cohort import Cohort+class TestPersonQuery(ClickhouseTestMixin, APIBaseTest):@freeze_time("2021-01-01T00:00:00Z")diff --git a/posthog/queries/test/test_trends.py b/posthog/queries/test/test_trends.pyindex fc943f8f874f..a11661b2504c 100644--- a/posthog/queries/test/test_trends.py+++ b/posthog/queries/test/test_trends.py@@ -37,7 +37,7 @@ from posthog.constants import (TRENDS_LINEAR,TRENDS_TABLE,)-from posthog.models import Cohort, Entity, Filter, Organization, Person+from posthog.models import Entity, Filter, Organization, Personfrom posthog.models.group.util import create_groupfrom posthog.models.instance_setting import get_instance_setting, override_instance_config, set_instance_settingfrom posthog.models.person.util import create_person_distinct_id@@ -49,6 +49,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import generate_cache_keyfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortdef breakdown_label(entity: Entity, value: Union[str, int]) -> dict[str, Optional[Union[str, int]]]:diff --git a/posthog/queries/trends/trends_actors.py b/posthog/queries/trends/trends_actors.pyindex 5d344fdb1e2b..abdc221f332a 100644--- a/posthog/queries/trends/trends_actors.py+++ b/posthog/queries/trends/trends_actors.py@@ -4,7 +4,6 @@ from typing import Any, Optional, castfrom posthog.schema import PersonsOnEventsModefrom posthog.constants import PropertyOperatorType-from posthog.models.cohort import Cohortfrom posthog.models.entity import Entityfrom posthog.models.filters import Filterfrom posthog.models.filters.mixins.utils import cached_property@@ -15,6 +14,8 @@ from posthog.queries.actor_base_query import ActorBaseQueryfrom posthog.queries.trends.trends_event_query import TrendsEventQueryfrom posthog.queries.trends.util import PROPERTY_MATH_FUNCTIONS, is_series_group_based, process_math+from products.cohorts.backend.models.cohort import Cohort+class TrendsActors(ActorBaseQuery):ACTOR_VALUES_INCLUDED = Truediff --git a/posthog/session_recordings/queries/sub_queries/cohort_subquery.py b/posthog/session_recordings/queries/sub_queries/cohort_subquery.pyindex 64f70c42c742..a04456819c1e 100644--- a/posthog/session_recordings/queries/sub_queries/cohort_subquery.py+++ b/posthog/session_recordings/queries/sub_queries/cohort_subquery.py@@ -3,10 +3,12 @@ from posthog.schema import CohortPropertyFilter, PropertyOperator, RecordingsQuefrom posthog.hogql import astfrom posthog.hogql.parser import parse_select-from posthog.models import Cohort, Team+from posthog.models import Teamfrom posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQueryfrom posthog.session_recordings.queries.utils import is_anonymous_cohort_fix_enabled, poe_is_active+from products.cohorts.backend.models.cohort import Cohort+class CohortPropertyGroupsSubQuery(SessionRecordingsListingBaseQuery):"""diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.pyindex ba1c32cbd8ed..a935b8c1a671 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py@@ -33,7 +33,6 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQLfrom posthog.models import Person-from posthog.models.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.models.team import Teamfrom posthog.session_recordings.queries.session_recording_list_from_query import (@@ -50,6 +49,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom ee.clickhouse.materialized_columns.columns import get_materialized_columns, materializefrom ee.clickhouse.models.test.test_cohort import get_person_ids_by_cohort_iddiff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.pyindex e18015f09d63..944e5e13f31b 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py@@ -15,7 +15,7 @@ from dateutil.relativedelta import relativedeltafrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import Cohort, Person+from posthog.models import Personfrom posthog.session_recordings.queries.test.listing_recordings.test_utils import (assert_query_matches_session_ids,create_event,@@ -23,6 +23,8 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils imporfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from products.cohorts.backend.models.cohort import Cohort+@freeze_time("2021-01-01T13:46:23")class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex a2720188874d..3dc62df345a2 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -112,6 +112,8 @@ from posthog.temporal.session_replay.session_summary.workflow import (execute_summarize_session_video_stream,)+from products.replay.backend.models.team_session_summaries_config import TeamSessionSummariesConfig+from ee.hogai.session_summaries.llm.call import get_openai_clientfrom ee.hogai.session_summaries.session.output_data import OutcomeSerializerfrom ee.hogai.session_summaries.tracking import (@@ -120,7 +122,6 @@ from ee.hogai.session_summaries.tracking import (generate_tracking_id,)from ee.hogai.session_summaries.utils import serialize_to_sse_event-from ee.models.team_session_summaries_config import TeamSessionSummariesConfigfrom ..models.product_intent.product_intent import ProductIntentfrom .queries.combine_session_ids_for_filtering import combine_session_id_filters@@ -330,7 +331,7 @@ class SessionRecordingSerializer(serializers.ModelSerializer, UserAccessControlSreturn Falsetry:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:return False@@ -1269,7 +1270,7 @@ class SessionRecordingViewSet(if include_outcomes:outcomes: dict[str, dict] = {}try:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:# Distinguishes OSS deploys (expected) from EE refactors that break the import (silent feature# degradation otherwise).@@ -2093,7 +2094,7 @@ def list_recordings_from_query(summary_outcomes: dict[str, dict] = {}if recording_ids_in_list:try:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:default_summary_session_ids = set()else:diff --git a/posthog/session_recordings/synthetic_playlists.py b/posthog/session_recordings/synthetic_playlists.pyindex ad5274cdd51a..f5cc9f826dce 100644--- a/posthog/session_recordings/synthetic_playlists.py+++ b/posthog/session_recordings/synthetic_playlists.py@@ -27,7 +27,7 @@ from posthog.session_recordings.session_recording_api import list_recordings_frofrom products.exports.backend.models.exported_asset import ExportedAssettry:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryHAS_EE = Trueexcept ImportError:diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 606d4f279e12..61dac24d7b34 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -448,7 +448,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)@freeze_time("2023-01-01T12:00:00.000Z")def test_get_session_recordings_list_metadata_includes_has_summary(self):try:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:pytest.skip("EE summary models are not available in this build")@@ -858,7 +858,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)@freeze_time("2023-01-01T12:00:00.000Z")def test_get_single_session_recording_metadata_has_summary_true(self):try:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:pytest.skip("EE summary models are not available in this build")@@ -891,7 +891,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)@freeze_time("2023-01-01T12:00:00.000Z")def test_get_single_session_recording_metadata_has_summary_false_for_contextual_summary(self):try:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryexcept ImportError:pytest.skip("EE summary models are not available in this build")@@ -2159,7 +2159,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_batch_check_exists_with_outcomes_returns_persisted_outcomes(self):"""include_outcomes attaches the persisted session_outcome alongside existence results."""- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryoutcome_session = "outcome_session_1"no_outcome_session = "outcome_session_2"@@ -2206,7 +2206,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_batch_check_exists_with_outcomes_doesnt_leak_teams(self):"""Outcomes from other teams must not be returned even when include_outcomes is set."""- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryother_team = Team.objects.create(organization=self.organization)shared_session_id = "leak_check_session"diff --git a/posthog/session_recordings/test/test_synthetic_playlists.py b/posthog/session_recordings/test/test_synthetic_playlists.pyindex 4619d15ac2a0..4b211582d664 100644--- a/posthog/session_recordings/test/test_synthetic_playlists.py+++ b/posthog/session_recordings/test/test_synthetic_playlists.py@@ -21,7 +21,7 @@ from posthog.session_recordings.synthetic_playlists import (from products.exports.backend.models.exported_asset import ExportedAssettry:- from ee.models.session_summaries import SingleSessionSummary+ from products.replay.backend.models.session_summaries import SingleSessionSummaryHAS_EE = Trueexcept ImportError:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 15570c510270..a6d3d540f950 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -87,6 +87,8 @@ PRODUCTS_APPS = ["products.batch_exports.backend.apps.BatchExportsConfig","products.engineering_analytics.backend.apps.EngineeringAnalyticsConfig","products.managed_migrations.backend.apps.ManagedMigrationsConfig",+ "products.replay.backend.apps.ReplayConfig",+ "products.cohorts.backend.apps.CohortsConfig",]INSTALLED_APPS = [diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex a79bf64d45dc..72fd7df45873 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -18,20 +18,20 @@ from posthog.clickhouse.query_tagging import QueryTags, update_tagsfrom posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorS3Error, CHQueryErrorTooManySimultaneousQueriesfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exception-from posthog.models import Cohort-from posthog.models.cohort import CohortOrEmpty-from posthog.models.cohort.calculation_history import CohortCalculationHistory-from posthog.models.cohort.util import (+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.cohorts.backend.models.util import (COHORT_STATS_COLLECTION_DELAY_SECONDS,get_all_cohort_dependencies,get_all_cohort_dependents,get_clickhouse_query_stats,sort_cohorts_topologically,)-from posthog.models.team.team import Team-from posthog.models.user import User-from posthog.scoping_audit import skip_team_scope_audit-from posthog.tasks.utils import CeleryQueueCOHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge("cohort_recalculations_backlog",@@ -111,7 +111,7 @@ MAX_STUCK_STATIC_COHORTS_TO_SCAN = MAX_STUCK_COHORTS_TO_RESET * 10def static_cohort_has_supported_population_source(cohort: Cohort) -> bool:- from posthog.models.cohort.util import cohort_filters_have_values+ from products.cohorts.backend.models.util import cohort_filters_have_valuesreturn bool(cohort.query or cohort_filters_have_values(cohort.filters))@@ -519,7 +519,7 @@ def insert_cohort_from_query(cohort_id: int, team_id: Optional[int] = None) -> Nteam_id is only optional for backwards compatibility with the old celery task signature.All new tasks should pass team_id explicitly."""- from posthog.models.cohort.util import insert_cohort_people_into_pg, insert_cohort_query_actors_into_ch+ from products.cohorts.backend.models.util import insert_cohort_people_into_pg, insert_cohort_query_actors_into_chcohort = Cohort.objects.get(pk=cohort_id)if team_id is None:@@ -590,7 +590,7 @@ def insert_cohort_from_filters(cohort_id: int, team_id: Optional[int] = None) ->"""One-time population task for static cohorts created from saved cohort criteria."""- from posthog.models.cohort.util import insert_cohort_filter_actors_into_ch, insert_cohort_people_into_pg+ from products.cohorts.backend.models.util import insert_cohort_filter_actors_into_ch, insert_cohort_people_into_pgif team_id is not None:cohort = Cohort.objects.get(pk=cohort_id, team_id=team_id)diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex c19a4ad90794..cb9e5dd8b377 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -9,7 +9,6 @@ from django.utils import timezonefrom dateutil.relativedelta import relativedeltafrom parameterized import parameterized-from posthog.models.cohort import Cohortfrom posthog.models.person import Personfrom posthog.tasks.calculate_cohort import (COHORT_STUCK_COUNT_GAUGE,@@ -26,6 +25,8 @@ from posthog.tasks.calculate_cohort import (update_cohort_metrics,)+from products.cohorts.backend.models.cohort import Cohort+MISSING_COHORT_ID = 12345@@ -1105,7 +1106,7 @@ class TestCohortCalculationTasks(APIBaseTest):)with (- patch("posthog.models.cohort.dependencies._on_cohort_changed") as mock_dep_cache,+ patch("products.cohorts.backend.models.dependencies._on_cohort_changed") as mock_dep_cache,patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_cache,patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions") as mock_hog_refresh,):@@ -1127,8 +1128,8 @@ class TestCohortCalculationTasks(APIBaseTest):)with (- patch("posthog.models.cohort.util.insert_cohort_query_actors_into_ch") as mock_insert_ch,- patch("posthog.models.cohort.util.insert_cohort_people_into_pg") as mock_insert_pg,+ patch("products.cohorts.backend.models.util.insert_cohort_query_actors_into_ch") as mock_insert_ch,+ patch("products.cohorts.backend.models.util.insert_cohort_people_into_pg") as mock_insert_pg,):mock_insert_ch.side_effect = Exception("Simulated query processing error")mock_insert_pg.side_effect = Exception("Simulated pg insert error")@@ -1162,8 +1163,8 @@ class TestCohortCalculationTasks(APIBaseTest):)with (- patch("posthog.models.cohort.util.insert_cohort_filter_actors_into_ch") as mock_insert_ch,- patch("posthog.models.cohort.util.insert_cohort_people_into_pg") as mock_insert_pg,+ patch("products.cohorts.backend.models.util.insert_cohort_filter_actors_into_ch") as mock_insert_ch,+ patch("products.cohorts.backend.models.util.insert_cohort_people_into_pg") as mock_insert_pg,):mock_insert_ch.side_effect = Exception("Simulated filter processing error")mock_insert_pg.side_effect = Exception("Simulated pg insert error")diff --git a/posthog/temporal/ai_observability/trace_summarization/sampling.py b/posthog/temporal/ai_observability/trace_summarization/sampling.pyindex db8f974cbdea..137e6ff31f26 100644--- a/posthog/temporal/ai_observability/trace_summarization/sampling.py+++ b/posthog/temporal/ai_observability/trace_summarization/sampling.py@@ -17,7 +17,6 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.models.cohort import Cohortfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.trace_summarization.constants import (@@ -29,6 +28,8 @@ from posthog.temporal.ai_observability.trace_summarization.models import BatchSufrom posthog.temporal.ai_observability.trace_summarization.utils import format_datetime_for_clickhousefrom posthog.temporal.common.heartbeat import Heartbeater+from products.cohorts.backend.models.cohort import Cohort+logger = structlog.get_logger(__name__)# Filter `type` values that resolve to cohort membership lookups in HogQL.diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.pyindex 7e9f39253b7c..f732170673b5 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_workflow.py@@ -301,7 +301,7 @@ class TestSampleItemsInWindowActivity:async def test_sample_skips_when_cohort_filter_references_soft_deleted_cohort(self, mock_team):from asgiref.sync import sync_to_async- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = await sync_to_async(Cohort.objects.create)(team=mock_team, name="Stale", deleted=True)inputs = BatchSummarizationInputs(@@ -326,7 +326,7 @@ class TestSampleItemsInWindowActivity:async def test_sample_runs_when_cohort_filter_resolves(self, mock_team):from asgiref.sync import sync_to_async- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = await sync_to_async(Cohort.objects.create)(team=mock_team, name="VIPs")inputs = BatchSummarizationInputs(diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.pyindex b3c2d213ff08..0a0e0d0ac44e 100644--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py@@ -20,7 +20,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.hogql_cohort_query import HogQLRealtimeCohortQueryfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_COHORT_MEMBERSHIP_CHANGED-from posthog.models.cohort.cohort import Cohort, CohortTypefrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.clickhouse import get_client@@ -28,6 +27,8 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.messaging.constants import get_percentile_bucket_label+from products.cohorts.backend.models.cohort import Cohort, CohortType+if TYPE_CHECKING:from posthog.kafka_client.client import _KafkaProducerdiff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.pyindex 873aa526293d..41144beb0cd7 100644--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py@@ -14,7 +14,6 @@ import temporalio.activityimport temporalio.workflowfrom temporalio.common import MetricHistogramFloat-from posthog.models.cohort.cohort import Cohort, CohortTypefrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.logger import get_logger@@ -25,6 +24,8 @@ from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (RealtimeCohortCalculationWorkflowInputs,)+from products.cohorts.backend.models.cohort import Cohort, CohortType+LOGGER = get_logger(__name__)diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.pyindex 40ed3b4f12cc..ad843bd35823 100644--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py@@ -1487,10 +1487,11 @@ class TestBatchUpdateCohortMetrics:from asgiref.sync import sync_to_async- from posthog.models.cohort.cohort import Cohort, CohortTypefrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team+ from products.cohorts.backend.models.cohort import Cohort, CohortType+# Create test organization and teamorganization = await sync_to_async(Organization.objects.create)(name="Test Organization")team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)@@ -1558,10 +1559,11 @@ class TestBatchUpdateCohortMetrics:"""Test that first calculation always updates duration regardless of threshold."""from asgiref.sync import sync_to_async- from posthog.models.cohort.cohort import Cohort, CohortTypefrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team+ from products.cohorts.backend.models.cohort import Cohort, CohortType+# Create test organization and teamorganization = await sync_to_async(Organization.objects.create)(name="Test Organization")team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)@@ -1600,10 +1602,11 @@ class TestBatchUpdateCohortMetrics:"""Test that cohorts with zero previous duration always get updated."""from asgiref.sync import sync_to_async- from posthog.models.cohort.cohort import Cohort, CohortTypefrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team+ from products.cohorts.backend.models.cohort import Cohort, CohortType+# Create test organization and teamorganization = await sync_to_async(Organization.objects.create)(name="Test Organization")team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)diff --git a/posthog/temporal/session_replay/export_recording/activities.py b/posthog/temporal/session_replay/export_recording/activities.pyindex c752d832efac..9c61a351eba2 100644--- a/posthog/temporal/session_replay/export_recording/activities.py+++ b/posthog/temporal/session_replay/export_recording/activities.py@@ -12,7 +12,6 @@ import pytzfrom temporalio import activityfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.models.exported_recording import ExportedRecordingfrom posthog.redis import get_async_clientfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.session_recordings.recordings import recording_s3_client@@ -24,6 +23,8 @@ from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_loggerfrom posthog.temporal.session_replay.export_recording.types import ExportContext, ExportRecordingInput, RedisConfig+from products.replay.backend.models.exported_recording import ExportedRecording+LOGGER = get_write_only_logger()diff --git a/posthog/temporal/session_replay/session_summary/activities/check_summary_exists.py b/posthog/temporal/session_replay/session_summary/activities/check_summary_exists.pyindex daaadab1d6bc..244292847493 100644--- a/posthog/temporal/session_replay/session_summary/activities/check_summary_exists.py+++ b/posthog/temporal/session_replay/session_summary/activities/check_summary_exists.py@@ -3,7 +3,7 @@ import temporaliofrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionSummaryInputs-from ee.models.session_summaries import SingleSessionSummary+from products.replay.backend.models.session_summaries import SingleSessionSummary@temporalio.activity.defndiff --git a/posthog/temporal/session_replay/session_summary/activities/event_based/get_llm_single_session_summary.py b/posthog/temporal/session_replay/session_summary/activities/event_based/get_llm_single_session_summary.pyindex 39e3a06d0f81..44a01fc1c24d 100644--- a/posthog/temporal/session_replay/session_summary/activities/event_based/get_llm_single_session_summary.py+++ b/posthog/temporal/session_replay/session_summary/activities/event_based/get_llm_single_session_summary.py@@ -13,10 +13,11 @@ from posthog.temporal.session_replay.session_summary.state import ()from posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionSummaryInputs+from products.replay.backend.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary+from ee.hogai.session_summaries.llm.consume import get_exception_event_ids_from_summary, get_llm_single_session_summaryfrom ee.hogai.session_summaries.session.output_data import SessionSummarySerializerfrom ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputs-from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummarydef _store_final_summary_in_db_from_activity(diff --git a/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py b/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.pyindex 9d317777690e..f2f5f797fcbf 100644--- a/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py+++ b/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py@@ -15,13 +15,13 @@ from posthog.temporal.session_replay.session_summary.types.video import ()from products.exports.backend.models.exported_asset import ExportedAsset+from products.replay.backend.models.session_summaries import SingleSessionSummaryfrom ee.hogai.session_summaries.constants import (EXPIRES_AFTER_DAYS,FULL_VIDEO_EXPORT_FORMAT,MIN_SESSION_DURATION_FOR_VIDEO_SUMMARY_S,)-from ee.models.session_summaries import SingleSessionSummarylogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/session_summary/activities/video_based/a7c_store_video_session_summary.py b/posthog/temporal/session_replay/session_summary/activities/video_based/a7c_store_video_session_summary.pyindex 441a88ee5705..da94d4abe0ee 100644--- a/posthog/temporal/session_replay/session_summary/activities/video_based/a7c_store_video_session_summary.py+++ b/posthog/temporal/session_replay/session_summary/activities/video_based/a7c_store_video_session_summary.py@@ -50,8 +50,9 @@ async def store_video_session_summary_activity(from posthog.models.user import User+ from products.replay.backend.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary+from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer- from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary# Check against duplicate writes (summary already exists). Should not happen, as we should avoid starting the workflow in the first place.summary_exists = await database_sync_to_async(SingleSessionSummary.objects.summaries_exist)(diff --git a/posthog/temporal/session_replay/session_summary/event_capture.py b/posthog/temporal/session_replay/session_summary/event_capture.pyindex 1b9ce6af249c..b47d03b62b24 100644--- a/posthog/temporal/session_replay/session_summary/event_capture.py+++ b/posthog/temporal/session_replay/session_summary/event_capture.py@@ -5,7 +5,7 @@ import structlogfrom posthog.api.capture import capture_internalfrom posthog.temporal.session_replay.session_summary.types.events import SessionSummaryReadyProperties-from ee.models.session_summaries import SingleSessionSummary+from products.replay.backend.models.session_summaries import SingleSessionSummaryEVENT_SOURCE = "session_summary_events"logger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/session_summary/state.py b/posthog/temporal/session_replay/session_summary/state.pyindex 96a997c16026..fd2358545df5 100644--- a/posthog/temporal/session_replay/session_summary/state.py+++ b/posthog/temporal/session_replay/session_summary/state.py@@ -9,8 +9,9 @@ from redis import asyncio as aioredisfrom posthog.redis import get_async_client+from products.replay.backend.models.session_summaries import ExtraSummaryContext, SingleSessionSummary+from ee.hogai.session_summaries.constants import SESSION_SUMMARIES_DB_DATA_REDIS_TTL-from ee.models.session_summaries import ExtraSummaryContext, SingleSessionSummarylogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/session_summary/workflow.py b/posthog/temporal/session_replay/session_summary/workflow.pyindex f406b121b511..b032d0829117 100644--- a/posthog/temporal/session_replay/session_summary/workflow.py+++ b/posthog/temporal/session_replay/session_summary/workflow.py@@ -69,10 +69,11 @@ from posthog.temporal.session_replay.session_summary.types.video import (collect_session_problems,)+from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.constants import DEFAULT_VIDEO_UNDERSTANDING_MODEL, SESSION_SUMMARIES_MODELfrom ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContextfrom ee.hogai.session_summaries.utils import serialize_to_sse_event-from ee.models.session_summaries import SingleSessionSummarylogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/session_summary_group/activities/fetch_session_batch_events.py b/posthog/temporal/session_replay/session_summary_group/activities/fetch_session_batch_events.pyindex 7898e4a61890..e71c5a2ef624 100644--- a/posthog/temporal/session_replay/session_summary_group/activities/fetch_session_batch_events.py+++ b/posthog/temporal/session_replay/session_summary_group/activities/fetch_session_batch_events.py@@ -26,6 +26,8 @@ from posthog.temporal.session_replay.session_summary_group.types import (SessionGroupSummaryInputs,)+from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.constants import MIN_SESSION_DURATION_FOR_SUMMARY_MSfrom ee.hogai.session_summaries.session.input_data import add_context_and_filter_eventsfrom ee.hogai.session_summaries.session.summarize_session import (@@ -34,7 +36,6 @@ from ee.hogai.session_summaries.session.summarize_session import (prepare_single_session_summary_input,)from ee.hogai.session_summaries.utils import logging_session_ids-from ee.models.session_summaries import SingleSessionSummarydef _get_db_events_per_page(diff --git a/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py b/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.pyindex cb57f0153899..ca1b7fec788f 100644--- a/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py+++ b/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py@@ -26,6 +26,8 @@ from posthog.temporal.session_replay.session_summary_group.types import (SessionGroupSummaryPatternsExtractionChunksInputs,)+from products.replay.backend.models.session_summaries import SessionGroupSummary, SessionSummaryRunMeta+from ee.hogai.session_summaries.constants import (PATTERNS_ASSIGNMENT_CHUNK_SIZE,PATTERNS_EXTRACTION_MAX_TOKENS,@@ -55,7 +57,6 @@ from ee.hogai.session_summaries.session_group.summarize_session_group import (remove_excessive_content_from_session_summary_for_llm,)from ee.hogai.session_summaries.utils import estimate_tokens_from_strings, logging_session_ids-from ee.models.session_summaries import SessionGroupSummary, SessionSummaryRunMetalogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/session_summary_group/types.py b/posthog/temporal/session_replay/session_summary_group/types.pyindex dd687de01752..e8f56196e6fb 100644--- a/posthog/temporal/session_replay/session_summary_group/types.py+++ b/posthog/temporal/session_replay/session_summary_group/types.py@@ -4,8 +4,9 @@ from typing import Literal, TypedDictfrom posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionSummaryInputs+from products.replay.backend.models.session_summaries import FailedSessionCategory, FailedSessionInfo+from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContext-from ee.models.session_summaries import FailedSessionCategory, FailedSessionInfo# Re-exported so consumers don't reach into ee.models directly for these.__all__ = [diff --git a/posthog/temporal/session_replay/session_summary_group/workflow.py b/posthog/temporal/session_replay/session_summary_group/workflow.pyindex a65463944b3f..99dd079e168b 100644--- a/posthog/temporal/session_replay/session_summary_group/workflow.py+++ b/posthog/temporal/session_replay/session_summary_group/workflow.py@@ -51,6 +51,8 @@ from posthog.temporal.session_replay.session_summary_group.types import (WorkflowProgress,)+from products.replay.backend.models.session_summaries import SessionGroupSummary+from ee.hogai.session_summaries.constants import (GROUP_SUMMARY_MIN_SUCCESS_FLOOR,GROUP_SUMMARY_MIN_SUCCESS_RATIO,@@ -60,7 +62,6 @@ from ee.hogai.session_summaries.constants import (from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContextfrom ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsListfrom ee.hogai.session_summaries.utils import logging_session_ids-from ee.models.session_summaries import SessionGroupSummarylogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/session_replay/summarization_sweep/activities.py b/posthog/temporal/session_replay/summarization_sweep/activities.pyindex 7b35a51ae86b..a3f68928fb89 100644--- a/posthog/temporal/session_replay/summarization_sweep/activities.py+++ b/posthog/temporal/session_replay/summarization_sweep/activities.py@@ -34,10 +34,9 @@ from posthog.temporal.session_replay.summarization_sweep.types import (UpsertTeamScheduleInput,)+from products.replay.backend.models.session_summaries import SingleSessionSummaryfrom products.signals.backend.models import SignalSourceConfig-from ee.models.session_summaries import SingleSessionSummary-logger = structlog.get_logger(__name__)diff --git a/posthog/temporal/tests/session_replay/export_recording/test_activities.py b/posthog/temporal/tests/session_replay/export_recording/test_activities.pyindex b4da3ac80a46..23840a619b7b 100644--- a/posthog/temporal/tests/session_replay/export_recording/test_activities.py+++ b/posthog/temporal/tests/session_replay/export_recording/test_activities.py@@ -5,7 +5,6 @@ from uuid import UUID, uuid4import pytestfrom unittest.mock import AsyncMock, MagicMock, patch-from posthog.models.exported_recording import ExportedRecordingfrom posthog.session_recordings.recordings.errors import BlockFetchErrorfrom posthog.session_recordings.session_recording_v2_service import RecordingBlockfrom posthog.temporal.session_replay.export_recording.activities import (@@ -21,6 +20,8 @@ from posthog.temporal.session_replay.export_recording.activities import ()from posthog.temporal.session_replay.export_recording.types import ExportContext, ExportRecordingInput, RedisConfig+from products.replay.backend.models.exported_recording import ExportedRecording+TEST_RECORDING_ID = UUID("01938a67-1234-7000-8000-000000000001")TEST_REDIS_CONFIG = RedisConfig(redis_url="redis://test-redis:6379", redis_ttl=3600)diff --git a/posthog/temporal/tests/session_replay/session_summary/conftest.py b/posthog/temporal/tests/session_replay/session_summary/conftest.pyindex 69323df2e398..52374c86184f 100644--- a/posthog/temporal/tests/session_replay/session_summary/conftest.py+++ b/posthog/temporal/tests/session_replay/session_summary/conftest.py@@ -12,11 +12,16 @@ from posthog.temporal.session_replay.session_summary.types.inputs import SingleSfrom posthog.temporal.session_replay.session_summary_group.types import SessionGroupSummaryOfSummariesInputsfrom posthog.temporal.session_replay.session_summary_group.workflow import SessionGroupSummaryInputs+from products.replay.backend.models.session_summaries import (+ ExtraSummaryContext,+ SessionSummaryRunMeta,+ SingleSessionSummary,+)+from ee.hogai.session_summaries.constants import SESSION_SUMMARIES_DB_DATA_REDIS_TTL, SESSION_SUMMARIES_MODELfrom ee.hogai.session_summaries.session.output_data import SessionSummarySerializerfrom ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputsfrom ee.hogai.session_summaries.tests.conftest import * # noqa: F401, F403 # legacy: pytest fixtures inherited from session-summaries conftest-from ee.models.session_summaries import ExtraSummaryContext, SessionSummaryRunMeta, SingleSessionSummary@pytest.fixturediff --git a/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py b/posthog/temporal/tests/session_replay/session_summary/test_event_capture.pyindex ba9ba2cffb1e..0b6af70973d7 100644--- a/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py+++ b/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py@@ -17,7 +17,11 @@ from posthog.temporal.session_replay.session_summary.types.video import (VideoSummarySingleSessionInputs,)-from ee.models.session_summaries import ExtraSummaryContext, SessionSummaryRunMeta, SingleSessionSummary+from products.replay.backend.models.session_summaries import (+ ExtraSummaryContext,+ SessionSummaryRunMeta,+ SingleSessionSummary,+)pytestmark = pytest.mark.django_dbdiff --git a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.pyindex 53d682c22bd0..446a0ab27ea1 100644--- a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py+++ b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py@@ -30,9 +30,10 @@ from posthog.temporal.session_replay.session_summary.workflow import ()from posthog.temporal.tests.session_replay.session_summary.conftest import AsyncRedisTestContext+from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputsfrom ee.hogai.session_summaries.utils import serialize_to_sse_event-from ee.models.session_summaries import SingleSessionSummarypytestmark = pytest.mark.django_dbdiff --git a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.pyindex 1ddce845d3b4..add7c8eea118 100644--- a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py+++ b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py@@ -70,6 +70,8 @@ from posthog.temporal.session_replay.session_summary_group.workflow import ()from posthog.temporal.tests.session_replay.session_summary.conftest import AsyncRedisTestContext+from products.replay.backend.models.session_summaries import SessionGroupSummary, SingleSessionSummary+from ee.hogai.session_summaries.constants import SESSION_SUMMARIES_MODELfrom ee.hogai.session_summaries.session.output_data import SessionSummarySerializerfrom ee.hogai.session_summaries.session.prompt_data import SessionSummaryPromptData@@ -80,7 +82,6 @@ from ee.hogai.session_summaries.session_group.patterns import (EnrichedSessionGroupSummaryPatternStats,RawSessionGroupSummaryPatternsList,)-from ee.models.session_summaries import SessionGroupSummary, SingleSessionSummarypytestmark = pytest.mark.django_db@@ -362,7 +363,7 @@ async def test_assign_events_to_patterns_activity_standalone(# Verify the activity completed successfully - now returns just the summary idassert isinstance(result, str)# Verify the summary was stored in DB- from ee.models.session_summaries import SessionGroupSummary+ from products.replay.backend.models.session_summaries import SessionGroupSummarysession_group_summary = await SessionGroupSummary.objects.aget(id=result)assert session_group_summary is not None@@ -1172,7 +1173,7 @@ class TestSummarizeSessionGroupWorkflow:# Verify the result is of the correct type (now returns just summary_id)assert isinstance(result, str)# Verify the summary was stored in DB and can be fetched- from ee.models.session_summaries import SessionGroupSummary+ from products.replay.backend.models.session_summaries import SessionGroupSummarysession_group_summary = await SessionGroupSummary.objects.aget(id=result)patterns_result = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)@@ -1879,8 +1880,9 @@ async def test_combine_patterns_from_chunks_activity_fails_when_no_chunks(def test_get_persons_for_sessions_from_distinct_ids_maps_session_to_person():+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummaryperson = MagicMock()person.uuid = "person-uuid-1"@@ -1902,8 +1904,9 @@ def test_get_persons_for_sessions_from_distinct_ids_maps_session_to_person():def test_get_persons_for_sessions_from_distinct_ids_handles_multiple_sessions_same_distinct_id():+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummaryperson = MagicMock()person.uuid = "person-uuid-shared"@@ -1927,8 +1930,9 @@ def test_get_persons_for_sessions_from_distinct_ids_handles_multiple_sessions_sadef test_get_persons_for_sessions_from_distinct_ids_excludes_sessions_with_no_distinct_id():+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummaryperson = MagicMock()person.uuid = "person-uuid-1"@@ -1960,8 +1964,9 @@ def test_get_persons_for_sessions_from_distinct_ids_excludes_sessions_with_no_didef test_get_persons_for_sessions_from_distinct_ids_returns_empty_when_all_sessions_lack_distinct_id():+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummarysummary = MagicMock(spec=SingleSessionSummary)summary.distinct_id = None@@ -1980,8 +1985,9 @@ def test_get_persons_for_sessions_from_distinct_ids_returns_empty_when_all_sessidef test_get_persons_for_sessions_from_distinct_ids_deduplicates_distinct_ids_sent_to_rpc():+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummaryperson = MagicMock()summaries: dict[str, SingleSessionSummary] = {}@@ -2007,8 +2013,9 @@ def test_get_persons_for_sessions_from_distinct_ids_deduplicates_distinct_ids_sedef test_get_persons_for_sessions_from_distinct_ids_handles_db_failure():"""Test that get_persons_for_sessions_from_distinct_ids returns empty dict on DB failure."""+ from products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.session_group.patterns import get_persons_for_sessions_from_distinct_ids- from ee.models.session_summaries import SingleSessionSummarymock_summary = MagicMock(spec=SingleSessionSummary)mock_summary.distinct_id = "test-distinct-id"diff --git a/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py b/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.pyindex 84af31735a07..5ecb4c651e31 100644--- a/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py+++ b/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py@@ -69,7 +69,7 @@ async def test_find_sessions_filters_summarized(activity_environment, organizatireturn_value=raw_ids,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value=existing,),patch(@@ -105,7 +105,7 @@ async def test_find_sessions_dispatches_all_unsummarized_candidates(activity_envreturn_value=raw_ids,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value=existing,),patch(@@ -143,7 +143,7 @@ async def test_find_sessions_passes_sample_rate_to_fetch(activity_environment, oside_effect=_fake_fetch,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"only-1": False},),patch(@@ -240,7 +240,7 @@ async def test_find_sessions_prefers_created_by_user(activity_environment, organreturn_value=["s1"],),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"s1": False},),patch(@@ -272,7 +272,7 @@ async def test_find_sessions_falls_back_when_created_by_is_null(activity_environreturn_value=["s1"],),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"s1": False},),patch(@@ -327,7 +327,7 @@ async def test_find_sessions_skips_recordings_with_too_many_failures(activity_enreturn_value=candidate_ids,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={},),patch(@@ -383,7 +383,7 @@ async def test_find_sessions_drops_sessions_without_events(return_value=candidate_ids,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={},),patch(@@ -422,7 +422,7 @@ async def test_find_sessions_skips_events_filter_when_all_summarized(activity_enreturn_value=candidate_ids,),patch(- "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ "products.replay.backend.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"s1": True, "s2": True},),patch(diff --git a/posthog/test/base.py b/posthog/test/base.pyindex ed98947e2657..5e50bf5a8eee 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -86,7 +86,6 @@ from posthog.models.channel_type.sql import (DROP_CHANNEL_DEFINITION_DICTIONARY_SQL,DROP_CHANNEL_DEFINITION_TABLE_SQL,)-from posthog.models.cohort.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQLfrom posthog.models.cohortmembership.sql import (COHORT_MEMBERSHIP_MV_SQL,COHORT_MEMBERSHIP_TABLE_SQL,@@ -198,6 +197,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import (from posthog.test.assert_faster_than import assert_faster_thanfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQLfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.event_definitions.backend.models.property_definition import (diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.pyindex cfe842e12724..cb258227728f 100644--- a/posthog/test/test_cohort_model.py+++ b/posthog/test/test_cohort_model.py@@ -6,9 +6,10 @@ from posthog.test.base import BaseTestfrom parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute-from posthog.models import Cohort, Person, Team-from posthog.models.cohort.sql import GET_COHORTPEOPLE_BY_COHORT_ID+from posthog.models import Person, Team+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_IDfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -451,7 +452,7 @@ class TestCohort(BaseTest):def test_get_static_cohort_size(self):"""Test that get_static_cohort_size works with db_constraint=False on the person foreign key."""- from posthog.models.cohort.util import get_static_cohort_size+ from products.cohorts.backend.models.util import get_static_cohort_size# Create personsperson1 = Person.objects.create(team=self.team, distinct_ids=["person1"])@@ -489,7 +490,7 @@ class TestCohort(BaseTest):def test_calculate_people_ch_clears_realtime_type_when_exceeding_threshold(self):from unittest.mock import patch- from posthog.models.cohort.cohort import REALTIME_COHORT_MAX_PERSON_COUNT+ from products.cohorts.backend.models.cohort import REALTIME_COHORT_MAX_PERSON_COUNT# Create a realtime cohortcohort = Cohort.objects.create(@@ -500,7 +501,7 @@ class TestCohort(BaseTest):)# Mock recalculate_cohortpeople to return a count exceeding the threshold- with patch("posthog.models.cohort.util.recalculate_cohortpeople") as mock_recalc:+ with patch("products.cohorts.backend.models.util.recalculate_cohortpeople") as mock_recalc:mock_recalc.return_value = REALTIME_COHORT_MAX_PERSON_COUNT + 1cohort.calculate_people_ch(pending_version=1)@@ -514,7 +515,7 @@ class TestCohort(BaseTest):def test_calculate_people_ch_keeps_realtime_type_when_at_threshold(self):from unittest.mock import patch- from posthog.models.cohort.cohort import REALTIME_COHORT_MAX_PERSON_COUNT+ from products.cohorts.backend.models.cohort import REALTIME_COHORT_MAX_PERSON_COUNT# Create a realtime cohortcohort = Cohort.objects.create(@@ -525,7 +526,7 @@ class TestCohort(BaseTest):)# Mock recalculate_cohortpeople to return exactly the threshold count- with patch("posthog.models.cohort.util.recalculate_cohortpeople") as mock_recalc:+ with patch("products.cohorts.backend.models.util.recalculate_cohortpeople") as mock_recalc:mock_recalc.return_value = REALTIME_COHORT_MAX_PERSON_COUNTcohort.calculate_people_ch(pending_version=1)@@ -551,7 +552,7 @@ class TestCohort(BaseTest):name="version resilience cohort",)- with patch("posthog.models.cohort.util.recalculate_cohortpeople") as mock_recalc:+ with patch("products.cohorts.backend.models.util.recalculate_cohortpeople") as mock_recalc:mock_recalc.return_value = 42with patch.object(Cohort, method_name, side_effect=Exception(error_message)):diff --git a/posthog/test/test_cohort_validation.py b/posthog/test/test_cohort_validation.pyindex 97bf1a4bfd81..a73dbda12a0b 100644--- a/posthog/test/test_cohort_validation.py+++ b/posthog/test/test_cohort_validation.py@@ -1,9 +1,10 @@from posthog.test.base import BaseTest-from posthog.models import Cohort-from posthog.models.cohort.validation import CohortTypeValidationSerializerfrom posthog.models.property import BehavioralPropertyType, Property, PropertyGroup, PropertyOperatorType+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.validation import CohortTypeValidationSerializer+class TestCohortTypeValidationSerializer(BaseTest):"""Test the CohortTypeValidationSerializer directly"""diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 8ea7ab3f2426..199271795631 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -26,13 +26,13 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.middleware import per_request_logging_context_middleware-from posthog.models import Cohortfrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.settings import SITE_URLfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/test/test_team.py b/posthog/test/test_team.pyindex 797b63e17b7e..78e729545bdf 100644--- a/posthog/test/test_team.py+++ b/posthog/test/test_team.py@@ -8,13 +8,12 @@ from parameterized import parameterizedfrom posthog.schema import PersonsOnEventsModefrom posthog.models import Organization, Team, User-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import INTERNAL_TEST_USERS_COHORT_NAME, CohortKindfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.project import Projectfrom posthog.models.team import get_team_in_cache, utilfrom posthog.models.team.team import SessionRecordingRetentionPeriod+from products.cohorts.backend.models.cohort import INTERNAL_TEST_USERS_COHORT_NAME, Cohort, CohortKindfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilediff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex c6336f0f3cf7..3bee02d175f5 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -28,7 +28,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.constants import TREND_FILTER_TYPE_EVENTSfrom posthog.event_usage import report_user_action-from posthog.models import Cohort, Team+from posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activityfrom posthog.models.event.event import Selectorfrom posthog.models.property.util import build_selector_regex@@ -39,6 +39,7 @@ from posthog.resource_limits import LimitKey, check_count_limitfrom products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experimentfrom products.product_analytics.backend.models.insight import Insightdiff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex 9a087d19572f..bc01c04ebf2c 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -13,10 +13,11 @@ from unittest.mock import ANY, patchfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Cohort, Tag, User+from posthog.models import Tag, Userfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.product_analytics.backend.models.insight import Insightdiff --git a/products/ai_observability/backend/api/clustering_job.py b/products/ai_observability/backend/api/clustering_job.pyindex fa63373c5e03..f07d3e98f472 100644--- a/products/ai_observability/backend/api/clustering_job.py+++ b/products/ai_observability/backend/api/clustering_job.py@@ -10,7 +10,8 @@ from rest_framework.response import Responsefrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_action-from posthog.models.cohort import Cohort++from products.cohorts.backend.models.cohort import Cohortfrom ..models.clustering_job import ClusteringJobfrom .metrics import llma_track_latencydiff --git a/products/ai_observability/backend/api/test/test_clustering_job.py b/products/ai_observability/backend/api/test/test_clustering_job.pyindex 712900998183..a639cb78509e 100644--- a/products/ai_observability/backend/api/test/test_clustering_job.py+++ b/products/ai_observability/backend/api/test/test_clustering_job.py@@ -211,7 +211,7 @@ class TestClusteringJobViewSet(APIBaseTest):return {"key": "id", "value": cohort_id, "type": "cohort"}def test_create_with_valid_cohort_filter(self):- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = Cohort.objects.create(team=self.team, name="VIPs")response = self.client.post(@@ -245,7 +245,7 @@ class TestClusteringJobViewSet(APIBaseTest):self.assertIn("not found or deleted", str(response.json()))def test_create_rejects_soft_deleted_cohort_filter(self):- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortcohort = Cohort.objects.create(team=self.team, name="Stale", deleted=True)response = self.client.post(diff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex f51e8d614178..f041e665e1fe 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -12,7 +12,6 @@ import structlogfrom prometheus_client import Counterfrom posthog.helpers.encrypted_fields import EncryptedJSONStringField-from posthog.models.cohort.cohort import is_cohort_recalculation_only_savefrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation@@ -29,6 +28,7 @@ from posthog.utils import absolute_urifrom products.actions.backend.models.action import Actionfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.plugin import sync_team_inject_web_apps+from products.cohorts.backend.models.cohort import is_cohort_recalculation_only_saveif TYPE_CHECKING:from posthog.models.team import Team@@ -275,7 +275,7 @@ def team_saved(sender, instance: Team, created, **kwargs):refresh_affected_hog_functions.delay(team_id=instance.id)-@receiver(post_save, sender="posthog.Cohort")+@receiver(post_save, sender="cohorts.Cohort")def cohort_saved(sender, instance, **kwargs):if is_cohort_recalculation_only_save(kwargs):returndiff --git a/products/cdp/backend/tasks/hog_functions.py b/products/cdp/backend/tasks/hog_functions.pyindex 41f38f201874..6c3927f812b0 100644--- a/products/cdp/backend/tasks/hog_functions.py+++ b/products/cdp/backend/tasks/hog_functions.py@@ -35,7 +35,7 @@ def refresh_affected_hog_functions(.filter(filters__contains={"actions": [{"id": str(action_id)}]}))elif cohort_id:- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohorttry:cohort = Cohort.objects.select_related("team").get(id=cohort_id)diff --git a/products/cohorts/__init__.py b/products/cohorts/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cohorts/backend/__init__.py b/products/cohorts/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cohorts/backend/apps.py b/products/cohorts/backend/apps.pynew file mode 100644index 000000000000..3e548a85b93c--- /dev/null+++ b/products/cohorts/backend/apps.py@@ -0,0 +1,10 @@+from django.apps import AppConfig+++class CohortsConfig(AppConfig):+ # AutoField (INT4) matches the legacy posthog app default so existing+ # posthog_cohort / posthog_cohortpeople id columns stay compatible with the+ # Rust flags/cohorts services which decode id as i32.+ default_auto_field = "django.db.models.AutoField"+ name = "products.cohorts.backend"+ label = "cohorts"diff --git a/products/cohorts/backend/migrations/0001_migrate_cohorts_models.py b/products/cohorts/backend/migrations/0001_migrate_cohorts_models.pynew file mode 100644index 000000000000..6a3739d32d19--- /dev/null+++ b/products/cohorts/backend/migrations/0001_migrate_cohorts_models.py@@ -0,0 +1,256 @@+# Generated by Django 5.2.14 on 2026-06-08 10:30++import django.utils.timezone+import django.db.models.deletion+import django.contrib.postgres.indexes+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1215_migrate_replay_models"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="CohortPeople",+ fields=[+ ("id", models.BigAutoField(primary_key=True, serialize=False)),+ ("version", models.IntegerField(blank=True, null=True)),+ ],+ options={+ "db_table": "posthog_cohortpeople",+ "managed": False,+ },+ ),+ migrations.CreateModel(+ name="Cohort",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(blank=True, max_length=400, null=True)),+ ("description", models.CharField(blank=True, max_length=1000)),+ ("deleted", models.BooleanField(default=False)),+ (+ "filters",+ models.JSONField(+ blank=True,+ help_text='Filters for the cohort. The `negation` field shown below is specific to\n cohort definitions (the inner sub-filters that build a cohort). Property filters used\n *outside* cohort definitions — e.g. on `team.test_account_filters`, insight filters, or\n feature flag conditions — must use `operator: "in"`/`"not_in"` for cohort exclusion and\n do NOT accept `negation`.\n\n Examples:\n\n # Behavioral filter (performed event)\n {\n "properties": {\n "type": "OR",\n "values": [{\n "type": "OR",\n "values": [{\n "key": "address page viewed",\n "type": "behavioral",\n "value": "performed_event",\n "negation": false,\n "event_type": "events",\n "time_value": "30",\n "time_interval": "day"\n }]\n }]\n }\n }\n\n # Person property filter\n {\n "properties": {\n "type": "OR",\n "values": [{\n "type": "AND",\n "values": [{\n "key": "promoCodes",\n "type": "person",\n "value": ["1234567890"],\n "negation": false,\n "operator": "exact"\n }]\n }]\n }\n }\n\n # Cohort filter (inner — within a cohort definition)\n {\n "properties": {\n "type": "OR",\n "values": [{\n "type": "AND",\n "values": [{\n "key": "id",\n "type": "cohort",\n "value": 8814,\n "negation": false\n }]\n }]\n }\n }',+ null=True,+ ),+ ),+ ("query", models.JSONField(blank=True, null=True)),+ ("version", models.IntegerField(blank=True, null=True)),+ ("pending_version", models.IntegerField(blank=True, null=True)),+ ("count", models.IntegerField(blank=True, null=True)),+ (+ "created_at",+ models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True),+ ),+ ("is_calculating", models.BooleanField(default=False)),+ ("last_calculation", models.DateTimeField(blank=True, null=True)),+ (+ "last_calculation_duration_ms",+ models.IntegerField(blank=True, null=True),+ ),+ ("errors_calculating", models.IntegerField(default=0)),+ ("last_error_at", models.DateTimeField(blank=True, null=True)),+ (+ "last_backfill_person_properties_at",+ models.DateTimeField(blank=True, null=True),+ ),+ (+ "last_realtime_cohort_calculation_at",+ models.DateTimeField(blank=True, null=True),+ ),+ ("is_static", models.BooleanField(default=False)),+ (+ "kind",+ models.CharField(+ blank=True,+ choices=[("internal_test_users", "internal_test_users")],+ help_text="System-defined cohort kind. Null for user-created cohorts.",+ max_length=50,+ null=True,+ ),+ ),+ (+ "cohort_type",+ models.CharField(+ blank=True,+ choices=[+ ("static", "static"),+ ("person_property", "person_property"),+ ("behavioral", "behavioral"),+ ("realtime", "realtime"),+ ("analytical", "analytical"),+ ],+ help_text="Type of cohort based on filter complexity",+ max_length=50,+ null=True,+ ),+ ),+ ("groups", models.JSONField(default=list)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "people",+ models.ManyToManyField(through="cohorts.CohortPeople", to="posthog.person"),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_cohort",+ },+ ),+ migrations.CreateModel(+ name="CohortCalculationHistory",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "filters",+ models.JSONField(help_text="Cohort filters/properties at time of calculation"),+ ),+ (+ "count",+ models.PositiveIntegerField(blank=True, help_text="Number of people in cohort", null=True),+ ),+ (+ "started_at",+ models.DateTimeField(+ default=django.utils.timezone.now,+ help_text="When calculation started",+ ),+ ),+ (+ "finished_at",+ models.DateTimeField(blank=True, help_text="When calculation finished", null=True),+ ),+ (+ "queries",+ models.JSONField(+ blank=True,+ default=None,+ help_text="Array of query information (query, query_id, query_ms, memory_mb, read_rows, written_rows)",+ null=True,+ ),+ ),+ (+ "error",+ models.TextField(+ blank=True,+ help_text="Error message if calculation failed",+ null=True,+ ),+ ),+ (+ "error_code",+ models.CharField(+ blank=True,+ help_text="Error code for categorizing failures (e.g., 'timeout', 'memory_limit'), used for displaying errors to end-users",+ max_length=64,+ null=True,+ ),+ ),+ (+ "cohort",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="cohorts.cohort"),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_cohortcalculationhistory",+ },+ ),+ migrations.AddField(+ model_name="cohortpeople",+ name="cohort",+ field=models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.DO_NOTHING,+ to="cohorts.cohort",+ ),+ ),+ migrations.AddField(+ model_name="cohortpeople",+ name="person",+ field=models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.DO_NOTHING,+ to="posthog.person",+ ),+ ),+ migrations.AddIndex(+ model_name="cohortpeople",+ index=models.Index(fields=["cohort_id", "person_id"], name="posthog_coh_cohort__89c25f_idx"),+ ),+ migrations.AddIndex(+ model_name="cohort",+ index=models.Index(fields=["team", "-created_at"], name="cohort_team_created_idx"),+ ),+ migrations.AddIndex(+ model_name="cohort",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["name"], name="cohort_name_trgm_idx", opclasses=["gin_trgm_ops"]+ ),+ ),+ migrations.AddConstraint(+ model_name="cohort",+ constraint=models.UniqueConstraint(+ condition=models.Q(("deleted", False), ("kind__isnull", False)),+ fields=("team", "kind"),+ name="unique_cohort_kind_per_team",+ ),+ ),+ migrations.AddIndex(+ model_name="cohortcalculationhistory",+ index=models.Index(fields=["team", "cohort"], name="posthog_coh_team_id_0ba00c_idx"),+ ),+ migrations.AddIndex(+ model_name="cohortcalculationhistory",+ index=models.Index(fields=["team", "started_at"], name="posthog_coh_team_id_762cc7_idx"),+ ),+ migrations.AddIndex(+ model_name="cohortcalculationhistory",+ index=models.Index(fields=["cohort", "-started_at"], name="posthog_coh_cohort__cbac1b_idx"),+ ),+ ],+ database_operations=[],+ )+ ]diff --git a/products/cohorts/backend/migrations/__init__.py b/products/cohorts/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..6c080bdd9533--- /dev/null+++ b/products/cohorts/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_cohorts_modelsdiff --git a/posthog/models/cohort/__init__.py b/products/cohorts/backend/models/__init__.pysimilarity index 100%rename from posthog/models/cohort/__init__.pyrename to products/cohorts/backend/models/__init__.pydiff --git a/posthog/models/cohort/calculation_history.py b/products/cohorts/backend/models/calculation_history.pysimilarity index 98%rename from posthog/models/cohort/calculation_history.pyrename to products/cohorts/backend/models/calculation_history.pyindex fe675eb2458e..a30fc44ce3d3 100644--- a/posthog/models/cohort/calculation_history.py+++ b/products/cohorts/backend/models/calculation_history.py@@ -12,7 +12,7 @@ class CohortCalculationHistory(RootTeamMixin, UUIDModel):"""team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)- cohort = models.ForeignKey("posthog.Cohort", on_delete=models.CASCADE)+ cohort = models.ForeignKey("cohorts.Cohort", on_delete=models.CASCADE)# Calculation metadatafilters = models.JSONField(help_text="Cohort filters/properties at time of calculation")diff --git a/posthog/models/cohort/cohort.py b/products/cohorts/backend/models/cohort.pysimilarity index 97%rename from posthog/models/cohort/cohort.pyrename to products/cohorts/backend/models/cohort.pyindex e5001b70c199..705dc1027b30 100644--- a/posthog/models/cohort/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -118,7 +118,7 @@ def is_cohort_recalculation_only_save(kwargs: dict) -> bool:class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):name = models.CharField(max_length=400, null=True, blank=True)description = models.CharField(max_length=1000, blank=True)- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)deleted = models.BooleanField(default=False)filters = models.JSONField(null=True,@@ -184,12 +184,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):}""",)query = models.JSONField(null=True, blank=True)- people = models.ManyToManyField("Person", through="CohortPeople") # type: models.ManyToManyField+ people = models.ManyToManyField("posthog.Person", through="CohortPeople") # type: models.ManyToManyFieldversion = models.IntegerField(blank=True, null=True)pending_version = models.IntegerField(blank=True, null=True)count = models.IntegerField(blank=True, null=True)- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, blank=True, null=True)+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, blank=True, null=True)created_at = models.DateTimeField(default=timezone.now, blank=True, null=True)is_calculating = models.BooleanField(default=False)@@ -236,6 +236,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# Backs `name__icontains` search (the cohort picker's server-side search).GinIndex(fields=["name"], name="cohort_name_trgm_idx", opclasses=["gin_trgm_ops"]),]+ db_table = "posthog_cohort"def __str__(self):return self.name or "Untitled cohort"@@ -351,7 +352,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):)def calculate_people_ch(self, pending_version: int, *, initiating_user_id: Optional[int] = None):- from posthog.models.cohort.util import recalculate_cohortpeople+ from products.cohorts.backend.models.util import recalculate_cohortpeoplelogger.info("cohort_calculation_started",@@ -556,9 +557,10 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Returns:Number of batches processed."""- from posthog.models.cohort.util import count_cohort_members, insert_static_cohortfrom posthog.personhog_client.gate import use_personhog+ from products.cohorts.backend.models.util import count_cohort_members, insert_static_cohort+current_batch_index = -1processing_error = Nonepersonhog = use_personhog()@@ -669,10 +671,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):person_static_cohort table's ORDER BY includes a per-row UUID,preventing ReplacingMergeTree from deduplicating repeated inserts."""- from posthog.models.cohort.util import insert_static_cohortfrom posthog.models.person.sql import PERSON_STATIC_COHORT_TABLEfrom posthog.models.person.util import get_persons_by_uuids+ from products.cohorts.backend.models.util import insert_static_cohort+persons = get_persons_by_uuids(team_id, batch)if not persons:return@@ -687,7 +690,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):if new_uuids:insert_static_cohort(new_uuids, self.pk, team_id=team_id)- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersinsert_cohort_members(team_id, self.pk, person_ids, self.version, _skip_ownership_check=True)@@ -727,7 +730,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Raises:Exception: If removal fails due to database errors."""- from posthog.models.cohort.util import (+ from products.cohorts.backend.models.util import (delete_cohort_member,get_static_cohort_size,is_person_in_cohort,@@ -956,18 +959,19 @@ def get_or_create_internal_test_users_cohort(class CohortPeople(models.Model):id = models.BigAutoField(primary_key=True)cohort = models.ForeignKey("Cohort", on_delete=models.DO_NOTHING, db_constraint=False)- person = models.ForeignKey("Person", on_delete=models.DO_NOTHING, db_constraint=False)+ person = models.ForeignKey("posthog.Person", on_delete=models.DO_NOTHING, db_constraint=False)version = models.IntegerField(blank=True, null=True)class Meta:# migrations managed via rust/persons_migrationsmanaged = Falseindexes = [models.Index(fields=["cohort_id", "person_id"])]+ db_table = "posthog_cohortpeople"@receiver(post_delete, sender=CohortPeople)def cohort_people_changed(sender, instance: "CohortPeople", **kwargs):- from posthog.models.cohort.util import get_static_cohort_size+ from products.cohorts.backend.models.util import get_static_cohort_sizetry:cohort_id = instance.cohort_iddiff --git a/posthog/models/cohort/dependencies.py b/products/cohorts/backend/models/dependencies.pysimilarity index 99%rename from posthog/models/cohort/dependencies.pyrename to products/cohorts/backend/models/dependencies.pyindex 0b85cddc39b9..5a8194c0ed5b 100644--- a/posthog/models/cohort/dependencies.py+++ b/products/cohorts/backend/models/dependencies.py@@ -8,10 +8,11 @@ from prometheus_client import Counterfrom rest_framework.exceptions import ValidationErrorfrom structlog import get_logger-from posthog.models.cohort.cohort import Cohort, CohortType, is_cohort_recalculation_only_savefrom posthog.models.team.team import Teamfrom posthog.redis import get_client as get_redis_client+from products.cohorts.backend.models.cohort import Cohort, CohortType, is_cohort_recalculation_only_save+logger = get_logger(__name__)DEPENDENCY_CACHE_TIMEOUT = 7 * 24 * 60 * 60 # 1 weekCOHORT_BACKFILL_DEBOUNCE_SECONDS = 300 # 5 minutesdiff --git a/posthog/models/cohort/sql.py b/products/cohorts/backend/models/sql.pysimilarity index 100%rename from posthog/models/cohort/sql.pyrename to products/cohorts/backend/models/sql.pydiff --git a/posthog/models/cohort/test/test_cohort_personhog.py b/products/cohorts/backend/models/test/test_cohort_personhog.pysimilarity index 90%rename from posthog/models/cohort/test/test_cohort_personhog.pyrename to products/cohorts/backend/models/test/test_cohort_personhog.pyindex 191eb899203f..db4b06245898 100644--- a/posthog/models/cohort/test/test_cohort_personhog.py+++ b/products/cohorts/backend/models/test/test_cohort_personhog.py@@ -8,11 +8,12 @@ from django.db.models import Qfrom parameterized import parameterized_class-from posthog.models import Cohort, Person, Team-from posthog.models.cohort.cohort import CohortPeople+from posthog.models import Person, Teamfrom posthog.personhog_client.fake_client import fake_personhog_clientfrom posthog.personhog_client.test_helpers import PersonhogTestMixin+from products.cohorts.backend.models.cohort import Cohort, CohortPeople+@parameterized_class(("personhog",), [(False,), (True,)])class TestGetPersonUuidsByDistinctIds(PersonhogTestMixin, BaseTest):@@ -118,8 +119,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):def _create_static_cohort(self) -> Cohort:return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=0)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_removes_existing_cohort_member(self, mock_get_size, mock_remove_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -141,8 +142,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):assert call_args[1]["team_id"] == self.team.idself._assert_personhog_called("check_cohort_membership")- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=0)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_returns_true_for_person_not_in_cohort(self, mock_get_size, mock_remove_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -159,8 +160,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):assert result is False- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=0)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_cross_team_isolation(self, mock_get_size, mock_remove_ch):other_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=other_team, distinct_ids=["d1"])@@ -171,8 +172,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):assert result is Falsemock_remove_ch.assert_not_called()- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=0)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_does_not_delete_when_cohort_belongs_to_other_team(self, mock_get_size, mock_remove_ch):"""Calling remove_user_by_uuid with a team_id that does not own thecohort must not touch CohortPeople rows for that cohort."""@@ -191,8 +192,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):assert CohortPeople.objects.filter(cohort=other_team_cohort, person=person).exists()mock_remove_ch.assert_not_called()- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=5)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=5)def test_updates_cohort_count_after_removal(self, mock_get_size, mock_remove_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -204,8 +205,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):cohort.refresh_from_db()assert cohort.count == 5- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", side_effect=Exception("count failed"))+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", side_effect=Exception("count failed"))def test_count_error_does_not_prevent_removal(self, mock_get_size, mock_remove_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -222,8 +223,8 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()mock_remove_ch.assert_called_once()- @patch("posthog.models.cohort.util.remove_person_from_static_cohort")- @patch("posthog.models.cohort.util.get_static_cohort_size", return_value=0)+ @patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")+ @patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_personhog_resolves_person_for_removal(self, mock_get_size, mock_remove_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -236,7 +237,7 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@parameterized_class(("personhog",), [(False,), (True,)])class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):def test_returns_true_for_member(self):- from posthog.models.cohort.util import check_cohort_membership, is_person_in_cohort+ from products.cohorts.backend.models.util import check_cohort_membership, is_person_in_cohortperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -248,7 +249,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):self._assert_personhog_called("check_cohort_membership")def test_returns_false_for_non_member(self):- from posthog.models.cohort.util import is_person_in_cohort+ from products.cohorts.backend.models.util import is_person_in_cohortperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -256,7 +257,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):assert is_person_in_cohort(team_id=self.team.id, person_id=person.id, cohort_id=cohort.id) is Falsedef test_returns_empty_dict_for_empty_cohort_ids(self):- from posthog.models.cohort.util import check_cohort_membership+ from products.cohorts.backend.models.util import check_cohort_membershipperson = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -264,7 +265,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):self._assert_personhog_not_called("check_cohort_membership")def test_mixed_membership(self):- from posthog.models.cohort.util import check_cohort_membership+ from products.cohorts.backend.models.util import check_cohort_membershipperson = self._seed_person(team=self.team, distinct_ids=["d1"])c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -284,7 +285,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):of which path (personhog vs ORM) runs. Tenant scoping happens in thepublic wrapper before dispatch, so the RPC is never called forout-of-team cohort_ids."""- from posthog.models.cohort.util import check_cohort_membership+ from products.cohorts.backend.models.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -304,7 +305,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):"""When a mix of in-team and out-of-team cohort_ids is passed, only thein-team ones reach downstream; the caller still gets a dict keyed byevery requested id with out-of-team ones reported as non-member."""- from posthog.models.cohort.util import check_cohort_membership+ from products.cohorts.backend.models.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -324,7 +325,7 @@ class TestCheckCohortMembershipFallback(BaseTest):"""Routing test: verifies ORM fallback when the personhog gate is disabled."""def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import is_person_in_cohort+ from products.cohorts.backend.models.util import is_person_in_cohortperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -422,7 +423,7 @@ class TestPropertyToQStaticCohortShortCircuit(PersonhogTestMixin, BaseTest):@parameterized_class(("personhog",), [(False,), (True,)])class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):def test_returns_member_ids(self):- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idsp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -438,7 +439,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):self._assert_personhog_called("list_cohort_member_ids")def test_returns_empty_for_empty_cohort(self):- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idscohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -447,7 +448,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):assert result == []def test_excludes_non_members(self):- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idsp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -463,7 +464,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):assert result == [p1.id]def test_isolates_cross_team_cohort(self):- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idsother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=other_team, distinct_ids=["d1"])@@ -479,7 +480,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):class TestListCohortMemberIdsFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import list_cohort_member_ids+ from products.cohorts.backend.models.util import list_cohort_member_idsperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -565,7 +566,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")def test_inserts_members(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -583,7 +584,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):self._assert_personhog_called("insert_cohort_members")def test_deduplicates_existing_members(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -598,7 +599,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):assert CohortPeople.objects.filter(cohort=cohort).count() == 1def test_returns_zero_for_empty_list(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_memberscohort = self._create_static_cohort()@@ -606,7 +607,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):self._assert_personhog_not_called("insert_cohort_members")def test_rejects_cross_team_cohort(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -619,7 +620,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):self._assert_personhog_not_called("insert_cohort_members")def test_skip_ownership_check_bypasses_team_validation(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -634,7 +635,7 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):class TestInsertCohortMembersFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import insert_cohort_members+ from products.cohorts.backend.models.util import insert_cohort_membersperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -654,7 +655,7 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")def test_deletes_existing_member(self):- from posthog.models.cohort.util import delete_cohort_member+ from products.cohorts.backend.models.util import delete_cohort_memberperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -669,7 +670,7 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):self._assert_personhog_called("delete_cohort_member")def test_returns_false_for_non_member(self):- from posthog.models.cohort.util import delete_cohort_member+ from products.cohorts.backend.models.util import delete_cohort_memberperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()@@ -679,7 +680,7 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):assert result is Falsedef test_rejects_cross_team_cohort(self):- from posthog.models.cohort.util import delete_cohort_member+ from products.cohorts.backend.models.util import delete_cohort_memberother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=other_team, distinct_ids=["d1"])@@ -696,7 +697,7 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):class TestDeleteCohortMemberFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import delete_cohort_member+ from products.cohorts.backend.models.util import delete_cohort_memberperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -715,7 +716,7 @@ class TestDeleteCohortMembersBulk(PersonhogTestMixin, BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef test_deletes_all_members_for_cohorts(self):- from posthog.models.cohort.util import delete_cohort_members_bulk+ from products.cohorts.backend.models.util import delete_cohort_members_bulkp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -734,7 +735,7 @@ class TestDeleteCohortMembersBulk(PersonhogTestMixin, BaseTest):self._assert_personhog_called("delete_cohort_members_bulk")def test_returns_zero_for_empty_list(self):- from posthog.models.cohort.util import delete_cohort_members_bulk+ from products.cohorts.backend.models.util import delete_cohort_members_bulkassert delete_cohort_members_bulk(self.team.id, []) == 0self._assert_personhog_not_called("delete_cohort_members_bulk")@@ -742,7 +743,7 @@ class TestDeleteCohortMembersBulk(PersonhogTestMixin, BaseTest):class TestDeleteCohortMembersBulkFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import delete_cohort_members_bulk+ from products.cohorts.backend.models.util import delete_cohort_members_bulkperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -760,9 +761,10 @@ class TestDeleteCohortMembersBulkMaxIterations(BaseTest):def test_stops_after_max_iterations(self):from unittest.mock import MagicMock- from posthog.models.cohort import util as cohort_utilfrom posthog.personhog_client.proto import DeleteCohortMembersBulkResponse+ from products.cohorts.backend.models import util as cohort_util+mock_client = MagicMock()mock_client.delete_cohort_members_bulk.return_value = DeleteCohortMembersBulkResponse(deleted_count=100)@@ -780,7 +782,7 @@ class TestDeleteCohortMembersBulkMaxIterations(BaseTest):@parameterized_class(("personhog",), [(False,), (True,)])class TestCountCohortMembers(PersonhogTestMixin, BaseTest):def test_returns_count(self):- from posthog.models.cohort.util import count_cohort_members+ from products.cohorts.backend.models.util import count_cohort_membersp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -794,14 +796,14 @@ class TestCountCohortMembers(PersonhogTestMixin, BaseTest):self._assert_personhog_called("count_cohort_members")def test_returns_zero_for_empty_cohort(self):- from posthog.models.cohort.util import count_cohort_members+ from products.cohorts.backend.models.util import count_cohort_memberscohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")assert count_cohort_members(self.team.id, cohort.id) == 0def test_isolates_cross_team_cohort(self):- from posthog.models.cohort.util import count_cohort_members+ from products.cohorts.backend.models.util import count_cohort_membersother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=other_team, distinct_ids=["d1"])@@ -815,7 +817,7 @@ class TestCountCohortMembers(PersonhogTestMixin, BaseTest):class TestCountCohortMembersFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.cohort.util import count_cohort_members+ from products.cohorts.backend.models.util import count_cohort_membersperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -834,7 +836,7 @@ class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):def _create_static_cohort(self) -> Cohort:return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")- @patch("posthog.models.cohort.util.insert_static_cohort")+ @patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_users_by_uuid(self, mock_insert_ch):p1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -847,7 +849,7 @@ class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):else:assert CohortPeople.objects.filter(cohort=cohort).count() == 2- @patch("posthog.models.cohort.util.insert_static_cohort")+ @patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_users_by_distinct_id(self, mock_insert_ch):self._seed_person(team=self.team, distinct_ids=["d1"])self._seed_person(team=self.team, distinct_ids=["d2"])@@ -860,7 +862,7 @@ class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):else:assert CohortPeople.objects.filter(cohort=cohort).count() == 2- @patch("posthog.models.cohort.util.insert_static_cohort")+ @patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_idempotent(self, mock_insert_ch):person = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()diff --git a/posthog/models/cohort/test/test_dependencies.py b/products/cohorts/backend/models/test/test_dependencies.pysimilarity index 98%rename from posthog/models/cohort/test/test_dependencies.pyrename to products/cohorts/backend/models/test/test_dependencies.pyindex 91f7f55f5065..2ce585ccce3e 100644--- a/posthog/models/cohort/test/test_dependencies.py+++ b/products/cohorts/backend/models/test/test_dependencies.py@@ -7,9 +7,8 @@ from django.core.cache import cachefrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError-from posthog.models import Cohort-from posthog.models.cohort.cohort import CohortType-from posthog.models.cohort.dependencies import (+from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.dependencies import (COHORT_BACKFILL_DEBOUNCE_SECONDS,COHORT_DEPENDENCY_CACHE_COUNTER,DEPENDENCY_CACHE_TIMEOUT,@@ -539,7 +538,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):])@mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")- @mock.patch("posthog.models.cohort.dependencies.get_redis_client")+ @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")def test_trigger_cohort_backfill_redis_set(self, _name, redis_set_result, should_schedule, mock_get_redis, mock_task):@@ -558,7 +557,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_task.apply_async.assert_not_called()@mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")- @mock.patch("posthog.models.cohort.dependencies.get_redis_client")+ @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")def test_trigger_cohort_backfill_handles_task_exception(self, mock_get_redis, mock_task):mock_redis = mock.MagicMock()mock_redis.set.return_value = True@@ -573,7 +572,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_redis.delete.assert_called_once_with(f"cohort_backfill_pending:{cohort.pk}")@mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")- @mock.patch("posthog.models.cohort.dependencies.get_redis_client")+ @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")def test_trigger_cohort_backfill_handles_redis_failure(self, mock_get_redis, mock_task):mock_get_redis.side_effect = Exception("Redis unavailable")cohort = self._create_cohort(name="Test Cohort", cohort_type=CohortType.REALTIME)@@ -582,7 +581,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):_trigger_cohort_backfill(cohort)mock_task.apply_async.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True)def test_backfill_signal_triggered_for_realtime_cohorts(self, mock_feature_enabled, mock_trigger_backfill):"""Test that backfill is triggered when a realtime cohort with person properties is saved"""@@ -639,7 +638,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_trigger_backfill.assert_called_once_with(cohort)- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True) # Flag enabled, but cohort type prevents triggerdef test_backfill_signal_not_triggered_for_non_realtime_cohorts(self, mock_feature_enabled, mock_trigger_backfill):"""Test that backfill is not triggered for non-realtime cohorts"""@@ -674,7 +673,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_trigger_backfill.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True) # Flag enabled, but static cohort prevents trigger@@ -712,7 +711,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_trigger_backfill.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True) # Flag enabled, but no person properties prevents trigger@@ -747,7 +746,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_trigger_backfill.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True) # Flag enabled, but recalculation save prevents trigger@@ -787,7 +786,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):mock_trigger_backfill.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=False)def test_backfill_signal_not_triggered_when_feature_flag_disabled(self, mock_feature_enabled, mock_trigger_backfill@@ -855,7 +854,7 @@ class TestCohortBackfillOnConditionsChanged(BaseTest):# Verify backfill was not triggered due to disabled feature flagmock_trigger_backfill.assert_not_called()- @mock.patch("posthog.models.cohort.dependencies._trigger_cohort_backfill")+ @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")@mock.patch("posthoganalytics.feature_enabled", return_value=True)def test_backfill_signal_not_triggered_when_person_properties_unchanged(self, mock_feature_enabled, mock_trigger_backfilldiff --git a/posthog/models/cohort/test/test_util.py b/products/cohorts/backend/models/test/test_util.pysimilarity index 99%rename from posthog/models/cohort/test/test_util.pyrename to products/cohorts/backend/models/test/test_util.pyindex 605068b2e6fa..7f153348e5b9 100644--- a/posthog/models/cohort/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -18,8 +18,9 @@ from posthog.exceptions import (ClickHouseQuerySizeExceeded,ClickHouseQueryTimeOut,)-from posthog.models.cohort import Cohort, CohortOrEmpty-from posthog.models.cohort.util import (++from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.cohorts.backend.models.util import (CohortErrorCode,get_all_cohort_dependencies,get_friendly_error_message,@@ -402,7 +403,7 @@ class TestCohortUtils(BaseTest):def test_get_static_cohort_size_with_strong_consistency(self):cohort = _create_cohort(team=self.team, name="test_cohort", groups=[], is_static=True)- with patch("posthog.models.cohort.util.count_cohort_members", return_value=42) as mock_count:+ with patch("products.cohorts.backend.models.util.count_cohort_members", return_value=42) as mock_count:result = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id, consistency="strong")mock_count.assert_called_once_with(team_id=self.team.id, cohort_id=cohort.id, consistency="strong")@@ -411,7 +412,7 @@ class TestCohortUtils(BaseTest):def test_get_static_cohort_size_defaults_to_eventual_consistency(self):cohort = _create_cohort(team=self.team, name="test_cohort", groups=[], is_static=True)- with patch("posthog.models.cohort.util.count_cohort_members", return_value=10) as mock_count:+ with patch("products.cohorts.backend.models.util.count_cohort_members", return_value=10) as mock_count:result = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id)mock_count.assert_called_once_with(team_id=self.team.id, cohort_id=cohort.id, consistency="eventual")diff --git a/posthog/models/cohort/util.py b/products/cohorts/backend/models/util.pysimilarity index 98%rename from posthog/models/cohort/util.pyrename to products/cohorts/backend/models/util.pyindex 7ad58adab6bc..e8a28f3666d0 100644--- a/posthog/models/cohort/util.py+++ b/products/cohorts/backend/models/util.py@@ -37,16 +37,6 @@ from posthog.exceptions import (ClickHouseQueryTimeOut,)from posthog.models import Filter, Team-from posthog.models.cohort.calculation_history import CohortCalculationHistory-from posthog.models.cohort.cohort import Cohort, CohortOrEmpty-from posthog.models.cohort.dependencies import get_cohort_dependents-from posthog.models.cohort.sql import (- GET_COHORT_SIZE_SQL,- GET_COHORTS_BY_PERSON_UUID,- GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID,- GET_STATIC_COHORTPEOPLE_BY_PERSON_UUID,- RECALCULATE_COHORT_BY_ID,-)from posthog.models.person.sql import (DELETE_PERSON_FROM_STATIC_COHORT,INSERT_COHORT_ALL_PEOPLE_THROUGH_PERSON_ID,@@ -57,6 +47,16 @@ from posthog.models.property import Property, PropertyGroupfrom products.actions.backend.models.action import Actionfrom products.actions.backend.models.util import format_action_filter+from products.cohorts.backend.models.calculation_history import CohortCalculationHistory+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.cohorts.backend.models.dependencies import get_cohort_dependents+from products.cohorts.backend.models.sql import (+ GET_COHORT_SIZE_SQL,+ GET_COHORTS_BY_PERSON_UUID,+ GET_PERSON_ID_BY_PRECALCULATED_COHORT_ID,+ GET_STATIC_COHORTPEOPLE_BY_PERSON_UUID,+ RECALCULATE_COHORT_BY_ID,+)if TYPE_CHECKING:from posthog.personhog_client import ReadConsistency@@ -1176,9 +1176,10 @@ def check_cohort_membership(team_id: int, person_id: int, cohort_ids: list[int])return {}# Local import to avoid circulars (cohort → person via CohortPeople FK).- from posthog.models.cohort.cohort import Cohort, CohortPeoplefrom posthog.models.person.person import READ_DB_FOR_PERSONS+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople+# Scope cohort_ids to the team via Cohort on the default DB before querying# either the personhog RPC or the persons-DB CohortPeople table. Neither# downstream path enforces team ownership (posthog_cohortpeople has no@@ -1244,10 +1245,11 @@ def list_cohort_member_ids(team_id: int, cohort_id: int) -> list[int]:Routes through personhog when the gate is enabled, falling back to a DjangoORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise."""- from posthog.models.cohort.cohort import Cohort, CohortPeoplefrom posthog.models.person.person import READ_DB_FOR_PERSONSfrom posthog.models.person.util import _personhog_routed+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople+# Validate cohort ownership on the default DB before querying the persons DB# or the personhog RPC — neither downstream path enforces team isolation# (posthog_cohortpeople has no team_id column; the proto has no team_id field).@@ -1310,9 +1312,10 @@ def insert_cohort_members(if not person_ids:return 0- from posthog.models.cohort.cohort import Cohort, CohortPeoplefrom posthog.models.person import Person+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople+if not _skip_ownership_check and not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return 0@@ -1362,9 +1365,10 @@ def delete_cohort_member(team_id: int, cohort_id: int, person_id: int) -> bool:ORM DELETE against ``posthog_cohortpeople`` (on the persons DB) otherwise.Returns ``True`` if a row was deleted, ``False`` otherwise."""- from posthog.models.cohort.cohort import Cohort, CohortPeoplefrom posthog.models.person.util import _personhog_routed+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople+if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return False@@ -1423,7 +1427,7 @@ def delete_cohort_members_bulk(team_id: int, cohort_ids: list[int], batch_size:if not cohort_ids:return 0- from posthog.models.cohort.cohort import CohortPeople+ from products.cohorts.backend.models.cohort import CohortPeopledef orm_fn() -> int:from django.db import router@@ -1468,9 +1472,10 @@ def count_cohort_members(team_id: int, cohort_id: int, *, consistency: ReadConsi(e.g. after inserting or deleting cohort members) to avoid stale countsfrom replication lag (ORM) or eventual consistency (personhog)."""- from posthog.models.cohort.cohort import Cohort, CohortPeoplefrom posthog.models.person.util import _personhog_routed+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople+if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():return 0diff --git a/posthog/models/cohort/validation.py b/products/cohorts/backend/models/validation.pysimilarity index 98%rename from posthog/models/cohort/validation.pyrename to products/cohorts/backend/models/validation.pyindex 600b34de893f..8d86f4b06cf8 100644--- a/posthog/models/cohort/validation.py+++ b/products/cohorts/backend/models/validation.py@@ -4,7 +4,7 @@ import structlogfrom rest_framework import serializersfrom rest_framework.exceptions import ValidationError-from posthog.models.cohort.cohort import CohortType+from products.cohorts.backend.models.cohort import CohortTypelogger = structlog.get_logger(__name__)@@ -184,7 +184,7 @@ class CohortTypeValidationSerializer(serializers.Serializer):raise ValidationError("Circular cohort reference detected")# Get the referenced cohort- from posthog.models.cohort.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohorttry:referenced_cohort = Cohort.objects.get(id=cohort_id, team_id=self.team_id)diff --git a/products/cohorts/package.json b/products/cohorts/package.jsonindex 8ad22325a404..4e6e6a4d96d0 100644--- a/products/cohorts/package.json+++ b/products/cohorts/package.json@@ -1,5 +1,8 @@{"name": "@posthog/products-cohorts",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ },"dependencies": {"kea": "catalog:","kea-loaders": "catalog:",diff --git a/products/cohorts/product.yaml b/products/cohorts/product.yamlnew file mode 100644index 000000000000..8dde1811d933--- /dev/null+++ b/products/cohorts/product.yaml@@ -0,0 +1,3 @@+name: Cohorts+owners:+ - team-feature-flagsdiff --git a/products/error_tracking/backend/api/issues.py b/products/error_tracking/backend/api/issues.pyindex be0fbbf3f7c6..80e69430c706 100644--- a/products/error_tracking/backend/api/issues.py+++ b/products/error_tracking/backend/api/issues.py@@ -19,10 +19,10 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response-from posthog.models.cohort.cohort import Cohortfrom posthog.models.organization import OrganizationMembershipfrom posthog.tasks.email import send_error_tracking_issue_assigned+from products.cohorts.backend.models.cohort import Cohortfrom products.error_tracking.backend.facade import api as facade_apifrom products.error_tracking.backend.models import (ErrorTrackingIssue,diff --git a/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.py b/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.pyindex b61651eac971..957fec1d173c 100644--- a/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.py+++ b/products/error_tracking/backend/hogql_queries/test/test_eval_seeders.py@@ -10,8 +10,8 @@ from parameterized import parameterizedfrom posthog.schema import DateRange, ErrorTrackingQueryfrom posthog.clickhouse.client import sync_execute-from posthog.models.cohort.cohort import get_or_create_internal_test_users_cohort+from products.cohorts.backend.models.cohort import get_or_create_internal_test_users_cohortfrom products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunnerfrom ee.hogai.eval.sandboxed.error_tracking.seeders import _EVAL_DISTINCT_IDS, seed_error_tracking_issuesdiff --git a/products/error_tracking/backend/migrations/0017_migrate_cohorts_models.py b/products/error_tracking/backend/migrations/0017_migrate_cohorts_models.pynew file mode 100644index 000000000000..50df0873cbfc--- /dev/null+++ b/products/error_tracking/backend/migrations/0017_migrate_cohorts_models.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.14 on 2026-06-08 10:30++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0001_migrate_cohorts_models"),+ ("error_tracking", "0016_errortrackingrecommendation_status"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="errortrackingissuecohort",+ name="cohort",+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="cohorts.cohort"),+ ),+ ],+ database_operations=[],+ )+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex 02bc169e528e..3be78220c53c 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0016_errortrackingrecommendation_status+0017_migrate_cohorts_modelsdiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 821cf239882c..8bc0587409b4 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -126,7 +126,7 @@ class ErrorTrackingIssueCohort(UUIDTModel):related_name="cohorts",)cohort = models.ForeignKey(- "posthog.Cohort",+ "cohorts.Cohort",on_delete=models.CASCADE,)created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/experiments/backend/admin/experiment_admin.py b/products/experiments/backend/admin/experiment_admin.pyindex 0ea1e482ff17..03d852f2896f 100644--- a/products/experiments/backend/admin/experiment_admin.py+++ b/products/experiments/backend/admin/experiment_admin.py@@ -7,9 +7,9 @@ from django.shortcuts import redirectfrom django.urls import path, reversefrom django.utils.html import format_html-from posthog.models import Cohortfrom posthog.models.utils import convert_legacy_metrics+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import (Experiment,ExperimentHoldout,diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 31519f11763e..47afcd1bd602 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -21,7 +21,6 @@ from posthog.schema import ActionsNode, ExperimentEventExposureConfig, Experimenfrom posthog.api.cohort import CohortSerializerfrom posthog.event_usage import EventSource, report_user_action-from posthog.models.cohort import Cohortfrom posthog.models.filters.filter import Filterfrom posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extension@@ -29,6 +28,7 @@ from posthog.models.team.team import Teamfrom posthog.utils import str_to_boolfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidatorfrom products.experiments.backend.models.experiment import (diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.pyindex 5ca267c5c197..7fdf46424e8d 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py@@ -20,12 +20,12 @@ from posthog.schema import (PropertyOperator,)-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.utils import (diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.pyindex 784460d78a8e..2c4f957ece44 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py@@ -16,10 +16,10 @@ from posthog.schema import ()from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_entity_properties-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestdiff --git a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.pyindex e3470ea4ac48..2e3a5148931c 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py@@ -24,9 +24,9 @@ from posthog.schema import ActorsQuery, EventsNode, ExperimentActorsQuery, Experfrom posthog.hogql.context import HogQLContextfrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunner-from posthog.models.cohort import Cohort-from posthog.models.cohort.util import print_cohort_hogql_query+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import print_cohort_hogql_queryfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestdiff --git a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.pyindex 96b1d20b9f61..e3a534306b4e 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py@@ -31,12 +31,12 @@ from posthog.schema import ()from posthog.constants import ExperimentNoResultsErrorKeys-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group.util import create_groupfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.experiment_trends_query_runner import ExperimentTrendsQueryRunnerfrom products.experiments.backend.hogql_queries.types import ExperimentMetricTypefrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldoutdiff --git a/products/experiments/backend/migrations/0018_migrate_cohorts_models.py b/products/experiments/backend/migrations/0018_migrate_cohorts_models.pynew file mode 100644index 000000000000..67516f20a839--- /dev/null+++ b/products/experiments/backend/migrations/0018_migrate_cohorts_models.py@@ -0,0 +1,29 @@+# Generated by Django 5.2.14 on 2026-06-08 10:30++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0001_migrate_cohorts_models"),+ ("experiments", "0017_experimentmetricsrecalculation"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="experiment",+ name="exposure_cohort",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="cohorts.cohort",+ ),+ ),+ ],+ database_operations=[],+ )+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 8bfa9d1bc80c..15c88b098ed1 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0017_experimentmetricsrecalculation+0018_migrate_cohorts_modelsdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 3b6640a95e1a..ea22c53da8b3 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -47,7 +47,7 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)feature_flag = models.ForeignKey("feature_flags.FeatureFlag", blank=False, on_delete=models.RESTRICT)- exposure_cohort = models.ForeignKey("posthog.Cohort", on_delete=models.SET_NULL, null=True, blank=True)+ exposure_cohort = models.ForeignKey("cohorts.Cohort", on_delete=models.SET_NULL, null=True, blank=True)holdout = models.ForeignKey("ExperimentHoldout", on_delete=models.SET_NULL, null=True, blank=True)start_date = models.DateTimeField(null=True, blank=True)diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 7f7c0827870a..b67a15333c3c 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -18,10 +18,10 @@ from rest_framework.test import APIRequestFactoryfrom posthog.schema import EventsNode, ExperimentMetricfrom posthog.models import Team-from posthog.models.cohort import Cohortfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.models.experiment import (@@ -3004,7 +3004,7 @@ class TestExperimentService(APIBaseTest):assert "does not have a start date" in str(ctx.exception)def test_create_exposure_cohort_duplicate_raises(self):- from posthog.models.cohort import Cohort+ from products.cohorts.backend.models.cohort import Cohortself._create_flag(key="cohort-dup")service = self._service()diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 915474cdbea7..0aae54dab5e4 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -13,12 +13,12 @@ from rest_framework import statusfrom posthog.models import Organization, Teamfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort.cohort import Cohortfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.user import Userfrom posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentSavedMetricfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigdiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 72f40f097247..a8777fc00621 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -57,9 +57,6 @@ from posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.activity_logging.model_activity import ImpersonatedContext, is_impersonated_session-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import CohortType-from posthog.models.cohort.util import get_all_cohort_dependenciesfrom posthog.models.person.point_in_time_properties import (build_person_properties_at_time,get_person_and_distinct_ids_for_identifier,@@ -76,6 +73,8 @@ from posthog.storage.hypercache import HyperCacheDependencyUnavailablefrom posthog.utils import is_valid_regexfrom posthog.views import format_bytes+from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.encrypted_flag_payloads import (diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 3be988bc1f78..249a115acb69 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -13,10 +13,10 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.models import Team-from posthog.models.cohort import Cohort, CohortOrEmptyfrom posthog.models.filters.filter import Filterfrom posthog.user_permissions import UserPermissions+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloadsfrom products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 28d3423a2249..0f6a6d09828c 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -27,8 +27,6 @@ from posthog import redisfrom posthog.api.cohort import get_cohort_actors_for_feature_flagfrom posthog.constants import AvailableFeaturefrom posthog.models import GroupTypeMapping, TaggedItem, User-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import CohortTypefrom posthog.models.group.group import Groupfrom posthog.models.group.util import create_groupfrom posthog.models.organization import Organization, OrganizationMembership@@ -39,6 +37,7 @@ 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.cohort import Cohort, CohortTypefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/products/feature_flags/backend/api/test/test_feature_flag_utils.py b/products/feature_flags/backend/api/test/test_feature_flag_utils.pyindex 55357640cc5f..08a07a66c7b6 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_utils.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_utils.py@@ -1,8 +1,7 @@from posthog.test.base import APIBaseTest-from posthog.models.cohort import Cohort-from posthog.models.cohort.cohort import CohortOrEmpty-from posthog.models.cohort.util import sort_cohorts_topologically+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.cohorts.backend.models.util import sort_cohorts_topologicallyclass TestFeatureFlagUtils(APIBaseTest):diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex de559034677b..cdd209073f0f 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -17,13 +17,13 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.models.cohort import Cohort-from posthog.models.cohort.util import sort_cohorts_topologicallyfrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import sort_cohorts_topologicallyfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentdiff --git a/products/feature_flags/backend/flag_matching.py b/products/feature_flags/backend/flag_matching.pyindex 90e86d0c3683..24274f51a228 100644--- a/products/feature_flags/backend/flag_matching.py+++ b/products/feature_flags/backend/flag_matching.py@@ -23,7 +23,6 @@ from django.db.models.query import QuerySetimport structlogfrom posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING-from posthog.models.cohort import Cohort, CohortOrEmptyfrom posthog.models.filters import Filterfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.group import Group@@ -34,6 +33,7 @@ from posthog.models.utils import execute_with_timeoutfrom posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITEfrom posthog.queries.base import match_property, properties_to_Q, sanitize_property_key+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloadfrom .models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverridediff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 031c63d003f1..5507160f13b3 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -45,8 +45,6 @@ import structlogfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.metrics import TOMBSTONE_COUNTER-from posthog.models.cohort.cohort import Cohort-from posthog.models.cohort.dependencies import extract_cohort_dependenciesfrom posthog.models.team import Teamfrom posthog.storage.cache_expiry_manager import (cleanup_stale_expiry_tracking as cleanup_generic,@@ -59,6 +57,8 @@ from posthog.storage.hypercache_manager import (get_cache_stats as get_cache_stats_generic,)+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.dependencies import extract_cohort_dependenciesfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flagsdiff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex e7c76ac56581..61d763de59f5 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -36,8 +36,6 @@ import structlogfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter-from posthog.models.cohort.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_save-from posthog.models.cohort.util import get_nested_cohort_idsfrom posthog.models.group_type_mapping import (GROUP_TYPES_STALE_CACHE_KEY_PREFIX,GroupTypesUnavailable,@@ -50,6 +48,8 @@ from posthog.storage.hypercache import HYPERCACHE_REBUILD_SKIPPED_COUNTER, Hyperfrom posthog.storage.hypercache_manager import HyperCacheManagementConfigfrom posthog.utils import capture_exception_throttled, get_safe_cache+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_save+from products.cohorts.backend.models.util import get_nested_cohort_idsfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,get_team_ids_with_recently_updated_flags,diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 06849ab49b74..fa29ac372c26 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -18,7 +18,6 @@ from posthog.caching.flags_redis_cache import write_flags_to_cachefrom posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER, PropertyOperatorTypefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.model_activity import ModelActivityMixin-from posthog.models.cohort import Cohort, CohortOrEmptyfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation@@ -27,6 +26,8 @@ from posthog.models.property.property import Property, PropertyGroupfrom posthog.models.signals import mutable_receiverfrom posthog.models.utils import RootTeamManager, RootTeamMixin+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+FIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in secondslogger = structlog.get_logger(__name__)@@ -401,7 +402,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsseen_cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,sort_by_topological_order=False,) -> list[int]:- from posthog.models.cohort.util import get_all_cohort_dependencies, sort_cohorts_topologically+ from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologicallyif seen_cohorts_cache is None:seen_cohorts_cache = {}diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 7b08df337ce8..4753b69ba59b 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -24,8 +24,8 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom posthog.models import Team-from posthog.models.cohort.cohort import Cohort+from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,_compute_flag_dependencies,diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex a52abed878be..56367ae9ed23 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -7,7 +7,6 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.models.cohort.cohort import Cohortfrom posthog.models.group_type_mapping import (GROUP_TYPES_STALE_CACHE_KEY_PREFIX,GroupTypeMapping,@@ -19,6 +18,7 @@ from posthog.models.team.team import Teamfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import safe_cache_delete+from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flagsfrom products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 20ce175255ee..de698bf1c6d4 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -100,7 +100,7 @@ from posthog.hogql_queries.query_runner import (shared_insights_execution_mode,)from posthog.kafka_client.topics import KAFKA_METRICS_TIME_TO_SEE_DATA-from posthog.models import Cohort, Filter, User+from posthog.models import Filter, Userfrom posthog.models.activity_logging.activity_log import (Change,Detail,@@ -138,6 +138,7 @@ from posthog.utils import ()from products.alerts.backend.models.alert import AlertConfiguration+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.api.insight_metadata import generate_insight_metadatadiff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 95d29780b240..9b86211d5677 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -51,10 +51,11 @@ from posthog.caching.insight_cache import update_cachefrom posthog.caching.insight_caching_state import TargetCacheAgefrom posthog.constants import AvailableFeaturefrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Cohort, Filter, OrganizationMembership, Person, SharingConfiguration, Team, User+from posthog.models import Filter, OrganizationMembership, Person, SharingConfiguration, Team, Userfrom posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queries+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Textfrom products.product_analytics.backend.api.insight import _last_refresh_for_shared_gatediff --git a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.pyindex dec6666b3bae..a7edbc6f408e 100644--- a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py@@ -33,11 +33,11 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPrfrom posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeriesfrom posthog.hogql_queries.validation.validation import QueryValidationRulefrom posthog.models import Team-from posthog.models.cohort.util import get_count_operator, get_count_operator_astfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.user import Userfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.util import get_count_operator, get_count_operator_astclass SeriesWithExtras:diff --git a/products/replay/backend/migrations/0001_migrate_replay_models.py b/products/replay/backend/migrations/0001_migrate_replay_models.pynew file mode 100644index 000000000000..90ebc5b6c75e--- /dev/null+++ b/products/replay/backend/migrations/0001_migrate_replay_models.py@@ -0,0 +1,292 @@+# Generated by Django 5.2.14 on 2026-06-08 10:07++import django.db.models.deletion+import django.contrib.postgres.fields+import django.contrib.postgres.indexes+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("posthog", "1213_filesystemfolderinstructions"),+ ("ee", "0049_migrate_posthog_ai_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="TeamSessionSummariesConfig",+ fields=[+ (+ "team",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ primary_key=True,+ serialize=False,+ to="posthog.team",+ ),+ ),+ (+ "product_context",+ models.TextField(+ blank=True,+ default="",+ help_text="Free-form description of the team's product, used to tailor AI-generated session summaries. Injected into the system prompt of every summary generated for this team.",+ max_length=10000,+ ),+ ),+ (+ "custom_tags",+ models.JSONField(+ blank=True,+ default=dict,+ help_text="Team-defined tags layered on top of the fixed taxonomy. Stored as a {name: description} mapping matching the AI_TAGS_FIXED_TAXONOMY shape. Names must be lowercase snake_case. Descriptions tell the LLM when to apply each tag.",+ ),+ ),+ ],+ options={+ "db_table": "ee_teamsessionsummariesconfig",+ },+ ),+ migrations.CreateModel(+ name="ExportedRecording",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("session_id", models.CharField(max_length=200)),+ ("reason", models.TextField()),+ (+ "export_location",+ models.CharField(blank=True, max_length=1000, null=True),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("running", "Running"),+ ("complete", "Complete"),+ ("failed", "Failed"),+ ],+ default="pending",+ max_length=20,+ ),+ ),+ ("error_message", models.TextField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="exported_recordings",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="exported_recordings",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_exportedrecording",+ "ordering": ["-created_at"],+ },+ ),+ migrations.CreateModel(+ name="SessionGroupSummary",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "title",+ models.CharField(+ default="Group summary",+ help_text="Title of the group session summary",+ max_length=2048,+ ),+ ),+ (+ "session_ids",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ help_text="List of session replay IDs included in this group summary",+ size=1000,+ ),+ ),+ (+ "summary",+ models.JSONField(+ help_text="Group summary in JSON format (EnrichedSessionGroupSummaryPatternsList schema)"+ ),+ ),+ (+ "extra_summary_context",+ models.JSONField(+ blank=True,+ help_text="Additional context passed to the summary (ExtraSummaryContext schema)",+ null=True,+ ),+ ),+ (+ "run_metadata",+ models.JSONField(+ blank=True,+ help_text="Summary run metadata (SessionSummaryRunMeta schema)",+ null=True,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "ee_group_session_summary",+ "indexes": [+ models.Index(+ fields=["team", "-created_at"],+ name="ee_group_se_team_id_a105a8_idx",+ ),+ django.contrib.postgres.indexes.GinIndex(+ fields=["title"],+ name="idx_group_summary_title_gin",+ opclasses=["gin_trgm_ops"],+ ),+ ],+ },+ ),+ migrations.CreateModel(+ name="SingleSessionSummary",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "session_id",+ models.CharField(help_text="Session replay ID", max_length=200),+ ),+ (+ "summary",+ models.JSONField(+ help_text="Session summary in JSON format (SessionSummarySerializer schema)"+ ),+ ),+ (+ "exception_event_ids",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ blank=True,+ default=list,+ help_text="List of event IDs where exceptions occurred for searchability",+ size=100,+ ),+ ),+ (+ "extra_summary_context",+ models.JSONField(+ blank=True,+ help_text="Additional context passed to the summary (ExtraSummaryContext schema)",+ null=True,+ ),+ ),+ (+ "run_metadata",+ models.JSONField(+ blank=True,+ help_text="Summary run metadata (SessionSummaryRunMeta schema)",+ null=True,+ ),+ ),+ (+ "session_start_time",+ models.DateTimeField(blank=True, help_text="Session start time", null=True),+ ),+ (+ "session_duration",+ models.IntegerField(blank=True, help_text="Session duration in seconds", null=True),+ ),+ (+ "distinct_id",+ models.CharField(+ blank=True,+ help_text="Distinct ID of the session's user",+ max_length=200,+ null=True,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "ee_single_session_summary",+ "indexes": [+ models.Index(+ fields=["team", "session_id"],+ name="ee_single_s_team_id_5e726a_idx",+ ),+ django.contrib.postgres.indexes.GinIndex(+ fields=["exception_event_ids"],+ name="idx_exception_event_ids_gin",+ ),+ ],+ },+ ),+ ],+ database_operations=[],+ )+ ]diff --git a/products/replay/backend/migrations/__init__.py b/products/replay/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/replay/backend/migrations/max_migration.txt b/products/replay/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..35299ac2ce5b--- /dev/null+++ b/products/replay/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_replay_modelsdiff --git a/products/replay/backend/models/__init__.py b/products/replay/backend/models/__init__.pynew file mode 100644index 000000000000..37eb4c6bea7c--- /dev/null+++ b/products/replay/backend/models/__init__.py@@ -0,0 +1,10 @@+from .exported_recording import ExportedRecording+from .session_summaries import SessionGroupSummary, SingleSessionSummary+from .team_session_summaries_config import TeamSessionSummariesConfig++__all__ = [+ "ExportedRecording",+ "SessionGroupSummary",+ "SingleSessionSummary",+ "TeamSessionSummariesConfig",+]diff --git a/posthog/models/exported_recording.py b/products/replay/backend/models/exported_recording.pysimilarity index 94%rename from posthog/models/exported_recording.pyrename to products/replay/backend/models/exported_recording.pyindex fd2f07430772..73998433da34 100644--- a/posthog/models/exported_recording.py+++ b/products/replay/backend/models/exported_recording.py@@ -31,10 +31,11 @@ class ExportedRecording(UUIDModel):class Meta:ordering = ["-created_at"]+ db_table = "posthog_exportedrecording"@propertydef is_expired(self) -> bool:return self.created_at < timezone.now() - timedelta(days=7)- def __str__(self):+ def __str__(self) -> str:return f"ExportedRecording({self.session_id}, {self.status})"diff --git a/ee/models/session_summaries.py b/products/replay/backend/models/session_summaries.pysimilarity index 98%rename from ee/models/session_summaries.pyrename to products/replay/backend/models/session_summaries.pyindex 293a7db393d4..c20887600bfb 100644--- a/ee/models/session_summaries.py+++ b/products/replay/backend/models/session_summaries.py@@ -7,7 +7,6 @@ from django.contrib.postgres.indexes import GinIndexfrom django.db import modelsfrom posthog.models.activity_logging.model_activity import ModelActivityMixin-from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import CreatedMetaFields, UUIDModel@@ -264,7 +263,7 @@ class SingleSessionSummary(ModelActivityMixin, CreatedMetaFields, UUIDModel):Each summary represents analysis of a single session replay."""- team = models.ForeignKey(Team, on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)session_id = models.CharField(max_length=200, help_text="Session replay ID")# Summary content@@ -308,7 +307,7 @@ class SingleSessionSummary(ModelActivityMixin, CreatedMetaFields, UUIDModel):),]- def __str__(self):+ def __str__(self) -> str:if self.extra_summary_context:return f"Summary for session {self.session_id} with extra context {self.extra_summary_context}"return f"Summary for session {self.session_id}"@@ -320,7 +319,7 @@ class SessionGroupSummary(ModelActivityMixin, CreatedMetaFields, UUIDModel):Each summary represents pattern analysis across multiple sessions."""- team = models.ForeignKey(Team, on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)# User-facing title for the summarytitle = models.CharField(max_length=2048, help_text="Title of the group session summary", default="Group summary")# List of session IDs that were analyzed together in this group@@ -357,6 +356,6 @@ class SessionGroupSummary(ModelActivityMixin, CreatedMetaFields, UUIDModel):# Creating Manager for rare cases of `exact 300 ids + context input match` seems excessive.]- def __str__(self):+ def __str__(self) -> str:session_count = len(self.session_ids) if self.session_ids else 0return f"{self.title} - {session_count} sessions (team {self.team_id})"diff --git a/ee/models/team_session_summaries_config.py b/products/replay/backend/models/team_session_summaries_config.pysimilarity index 87%rename from ee/models/team_session_summaries_config.pyrename to products/replay/backend/models/team_session_summaries_config.pyindex e07d6ba07507..61e342e14e26 100644--- a/ee/models/team_session_summaries_config.py+++ b/products/replay/backend/models/team_session_summaries_config.py@@ -2,7 +2,6 @@ import loggingfrom django.db import models-from posthog.models.team import Teamfrom posthog.models.team.extensions import register_team_extension_signallogger = logging.getLogger(__name__)@@ -15,7 +14,7 @@ CUSTOM_TAG_DESCRIPTION_MAX_LENGTH = 200class TeamSessionSummariesConfig(models.Model):- team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True)+ team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True)product_context = models.TextField(blank=True,@@ -37,5 +36,8 @@ class TeamSessionSummariesConfig(models.Model):),)+ class Meta:+ db_table = "ee_teamsessionsummariesconfig"+register_team_extension_signal(TeamSessionSummariesConfig, logger=logger)diff --git a/products/ruff.toml b/products/ruff.tomlindex afe5a61513ac..31677da02c9d 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -23,6 +23,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"annotations/backend/**" = ["ANN"]"batch_exports/backend/**" = ["ANN"]"cdp/backend/**" = ["ANN"]+"cohorts/backend/**" = ["ANN"]"conversations/backend/**" = ["ANN"]"customer_analytics/backend/**" = ["ANN"]"dashboards/backend/**" = ["ANN"]@@ -62,6 +63,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"batch_exports/**" = ["PLC0415"]"business_knowledge/**" = ["PLC0415"]"cdp/**" = ["PLC0415"]+"cohorts/**" = ["PLC0415"]"conversations/**" = ["PLC0415"]"customer_analytics/**" = ["PLC0415"]"dashboards/**" = ["PLC0415"]diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex 491fdad787e3..bbd6fccaa3ea 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -36,7 +36,6 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort.cohort import Cohortfrom posthog.models.integration import Integrationfrom posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.team.team import Team@@ -44,6 +43,7 @@ from posthog.models.team.team import Teamfrom products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboard# `products.experiments` ships a facade (api.py + contracts.py) but the contract isdiff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pyindex 8210d384fcaa..85a4f2111360 100644--- a/products/signals/backend/test/test_scout_harness_profile.py+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -13,7 +13,6 @@ from posthog.test.base import BaseTestfrom django.utils import timezonefrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.cohort.cohort import Cohortfrom posthog.models.integration import Integrationfrom posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.user import User@@ -21,6 +20,7 @@ from posthog.models.user import Userfrom products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex c540f6a6026e..930879df5dfa 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -25,10 +25,10 @@ from rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeaturefrom posthog.models import Person, Team-from posthog.models.cohort.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembershipfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTourdiff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex f75ec780e0ae..083ba90f14f4 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -28,7 +28,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import ExportRendererAuthenticationfrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.models import Cohort, Team, User+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.rate_limit import (AIBurstRateThrottle,@@ -39,6 +39,7 @@ from posthog.rate_limit import (from posthog.security.url_validation import is_url_allowedfrom posthog.utils import relative_date_parse_with_delta_mapping+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS, MAX_TARGET_WIDTHSfrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmapfrom products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshotdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.pyindex 787759d7411f..8101cd6cf65f 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py@@ -13,10 +13,10 @@ from posthog.schema import (WebStatsTableQuery,)-from posthog.models import Cohortfrom posthog.models.utils import uuid7from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunnerdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.pyindex 5b536a8773da..3f8242267c4e 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py@@ -22,11 +22,12 @@ from posthog.schema import (from posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.clickhouse.client import sync_execute-from posthog.models import Cohort, Element, Person+from posthog.models import Element, Personfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLEfrom posthog.models.utils import uuid7from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunnerdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.pyindex b6c99f87dc9d..51d7e5922ce8 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py@@ -33,11 +33,12 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import Cohort, Element+from posthog.models import Elementfrom posthog.models.utils import uuid7from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_overview_pre_aggregated import (WebOverviewPreAggregatedQueryBuilder,diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.pyindex 3b9c25a2aa98..c364d9997ef5 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py@@ -35,10 +35,11 @@ from posthog.schema import (WebStatsTableQuery,)-from posthog.models import Cohort, Element+from posthog.models import Elementfrom posthog.models.utils import uuid7from products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunnernan_value = float("nan")diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 14ca16de8ee9..9d6aaf119850 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -32,11 +32,12 @@ from posthog.cdp.validation import (generate_template_bytecode,)from posthog.event_usage import EventSource, get_event_source-from posthog.models import Cohort, Team-from posthog.models.cohort.util import get_all_cohort_dependencies+from posthog.models import Teamfrom posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocationfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.feature_flags.backend.user_blast_radius import (PERSON_BATCH_SIZE,get_user_blast_radius,diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex a19976bb26c9..43f6674f3ef0 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -8,11 +8,12 @@ from rest_framework import statusfrom posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.cdp.templates.slack.template_slack import template as template_slack-from posthog.models import Cohort, Organization, Team, User+from posthog.models import Organization, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.cohorts.backend.models.cohort import Cohortfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowwebhook_template = MOCK_NODE_TEMPLATES[0]diff --git a/tach.toml b/tach.tomlindex ef1f13308395..fe537218ece4 100644--- a/tach.toml+++ b/tach.toml@@ -34,6 +34,7 @@ utility = true[[modules]]path = "ee"depends_on = [+ "products.cohorts","posthog","products.actions","products.alerts",@@ -63,6 +64,7 @@ layer = "modules"[[modules]]path = "posthog"depends_on = [+ "products.cohorts","ee","products.access_control","products.analytics_platform",@@ -98,6 +100,7 @@ depends_on = ["products.posthog_ai","products.product_analytics","products.product_tours",+ "products.replay","products.replay_vision","products.revenue_analytics","products.signals",@@ -120,6 +123,7 @@ layer = "modules"[[modules]]path = "products.actions"depends_on = [+ "products.cohorts","posthog","products.cdp","products.experiments",@@ -157,6 +161,7 @@ layer = "modules"[[modules]]path = "products.cdp"depends_on = [+ "products.cohorts","ee","posthog","products.actions",@@ -164,6 +169,15 @@ depends_on = []layer = "modules"+[[modules]]+path = "products.cohorts"+depends_on = [+ "products.actions",+ "ee",+ "posthog",+]+layer = "modules"+[[modules]]path = "products.conversations"depends_on = [@@ -254,6 +268,7 @@ layer = "modules"[[modules]]path = "products.error_tracking"depends_on = [+ "products.cohorts","ee","posthog","products.cdp",@@ -271,6 +286,7 @@ layer = "modules"[[modules]]path = "products.experiments"depends_on = [+ "products.cohorts","ee","posthog","products.actions",@@ -289,6 +305,7 @@ layer = "modules"[[modules]]path = "products.feature_flags"depends_on = [+ "products.cohorts","ee","posthog","products.dashboards",@@ -325,6 +342,7 @@ layer = "modules"[[modules]]path = "products.ai_observability"depends_on = [+ "products.cohorts","ee","posthog","products.dashboards",@@ -444,6 +462,7 @@ layer = "modules"[[modules]]path = "products.product_analytics"depends_on = [+ "products.cohorts","ee","posthog","products.actions",@@ -493,6 +512,7 @@ layer = "modules"[[modules]]path = "products.signals"depends_on = [+ "products.cohorts","posthog","products.actions","products.ai_observability",@@ -525,6 +545,7 @@ layer = "modules"[[modules]]path = "products.surveys"depends_on = [+ "products.cohorts","ee","posthog","products.actions",@@ -607,6 +628,7 @@ layer = "modules"[[modules]]path = "products.web_analytics"depends_on = [+ "products.cohorts","ee","posthog","products.actions",@@ -617,6 +639,7 @@ layer = "modules"[[modules]]path = "products.workflows"depends_on = [+ "products.cohorts","ee","posthog","products.actions",