Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

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.yml
index 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.py
index 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 Cohort
from products.product_analytics.backend.models.insight import Insight
from products.actions.backend.models.action import Action
from posthog.models.personal_api_key import PersonalAPIKey
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 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 FailedSe
from posthog.temporal.session_replay.session_summary_group.workflow import execute_summarize_session_group
from 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 SessionSummarySerializer
from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContext
from 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_ids
from 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.py
index 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 AvailableFeature
from posthog.models import Organization, OrganizationMembership, Team, User
from 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 SessionSummarySerializer
from ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_response
from ee.models.rbac.access_control import AccessControl
-from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary
class TestSingleSessionSummaryViewSet(APIBaseTest):
diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.py
index 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 Cohort
from products.actions.backend.models.action import Action
from posthog.models.filters.session_recordings_filter import SessionRecordingsFilter
from posthog.models.filters.filter import Filter
diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.py
index 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 PersonsOnEventsMode
from posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMIT
from 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_query
from posthog.models.filters import Filter
from posthog.models.organization import Organization
from posthog.models.person import Person
@@ -38,6 +35,9 @@ from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
from posthog.queries.util import PersonPropertiesMode
from 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_query
def 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_ch
p1 = 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.py
index 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_person
from posthog.clickhouse.client import query_with_columns, sync_execute
from posthog.constants import FILTER_TEST_ACCOUNTS
from posthog.models import Element, Organization, Person, Team
-from posthog.models.cohort import Cohort
from posthog.models.event.sql import GET_EVENTS_WITH_PROPERTIES
from posthog.models.event.util import ClickhouseEventSerializer
from posthog.models.filters import Filter
@@ -19,6 +18,8 @@ from posthog.models.property.util import parse_prop_grouped_clauses
from posthog.queries.util import PersonPropertiesMode
from 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.py
index 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 ValidationError
from posthog.clickhouse.client import sync_execute
from posthog.constants import PropertyOperatorType
-from posthog.models.cohort import Cohort
from posthog.models.element import Element
from posthog.models.filters import Filter
from posthog.models.instance_setting import get_instance_setting
@@ -36,6 +35,8 @@ from posthog.queries.person_query import PersonQuery
from posthog.queries.property_optimizer import PropertyOptimizer
from posthog.queries.util import PersonPropertiesMode
+from products.cohorts.backend.models.cohort import Cohort
+
from ee.clickhouse.materialized_columns.columns import materialize
diff --git a/ee/clickhouse/queries/funnels/test/test_funnel.py b/ee/clickhouse/queries/funnels/test/test_funnel.py
index 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 datetime
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.models.group.util import create_group
from posthog.queries.funnels.funnel import ClickhouseFunnel
@@ -15,6 +14,7 @@ from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from ee.clickhouse.queries.funnels.test.breakdown_cases import funnel_breakdown_group_test_factory
diff --git a/ee/clickhouse/queries/test/test_breakdown_props.py b/ee/clickhouse/queries/test/test_breakdown_props.py
index 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 Cohort
from posthog.models.entity import Entity
from posthog.models.filters import Filter
from posthog.models.group.util import create_group
@@ -21,6 +20,8 @@ from posthog.queries.breakdown_props import (
from posthog.queries.trends.util import process_math
from 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.py
index 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 PersonsOnEventsMode
from posthog.clickhouse.client import sync_execute
from posthog.hogql_queries.hogql_cohort_query import TestWrapperCohortQuery as CohortQuery
from posthog.models import Team
-from posthog.models.cohort import Cohort
from posthog.models.filters.filter import Filter
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/ee/clickhouse/queries/test/test_event_query.py b/ee/clickhouse/queries/test/test_event_query.py
index 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 Cohort
from posthog.models.element import Element
from posthog.models.entity import Entity
from posthog.models.filters import Filter
@@ -18,6 +17,7 @@ from posthog.queries.trends.trends_event_query import TrendsEventQuery
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from ee.clickhouse.materialized_columns.columns import materialize
diff --git a/ee/clickhouse/queries/test/test_person_query.py b/ee/clickhouse/queries/test/test_person_query.py
index 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 pytest
from posthog.test.base import _create_person, cleanup_materialized_columns
from posthog.clickhouse.client import sync_execute
-from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.models.property import Property
from posthog.models.team import Team
from posthog.queries.person_query import PersonQuery
+from products.cohorts.backend.models.cohort import Cohort
+
from ee.clickhouse.materialized_columns.columns import materialize
diff --git a/ee/clickhouse/queries/test/test_util.py b/ee/clickhouse/queries/test/test_util.py
index 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_time
from posthog.test.base import _create_event
from posthog.clickhouse.client import sync_execute
-from posthog.models.cohort import Cohort
from posthog.queries.breakdown_props import _parse_breakdown_cohorts
from posthog.queries.util import get_earliest_timestamp
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
def test_get_earliest_timestamp(db, team):
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 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, User
from posthog.rbac.user_access_control import UserAccessControl
from posthog.sync import database_sync_to_async
from products.actions.backend.models.action import Action
from products.alerts.backend.models.alert import AlertConfiguration
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 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 timezone
from parameterized import parameterized
-from posthog.models import Cohort
-
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
diff --git a/ee/hogai/eval/sandboxed/cohorts/scorers.py b/ee/hogai/eval/sandboxed/cohorts/scorers.py
index 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.py
index 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 structlog
from posthog.session_recordings.models.metadata import RecordingMetadata
from 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 SessionSummaryPromptData
from ee.hogai.session_summaries.utils import load_custom_template, shorten_url
-from ee.models.session_summaries import ExtraSummaryContext
logger = structlog.get_logger(__name__)
diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.py
index 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 ApplicationError
from posthog.models.person import Person
from 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 SummaryValidationError
from ee.hogai.session_summaries.constants import FAILED_PATTERNS_ENRICHMENT_MIN_RATIO
from ee.hogai.session_summaries.session.output_data import SessionSummaryIssueTypes, SessionSummarySerializer
from ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputs
from ee.hogai.session_summaries.utils import logging_session_ids
from ee.hogai.utils.yaml import load_yaml_from_raw_llm_content
-from ee.models.session_summaries import SingleSessionSummary
logger = structlog.get_logger(__name__)
diff --git a/ee/migrations/0050_migrate_replay_models.py b/ee/migrations/0050_migrate_replay_models.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/ee/models/__init__.py b/ee/models/__init__.py
index f0df59755ad4..8f967ad4109f 100644
--- a/ee/models/__init__.py
+++ b/ee/models/__init__.py
@@ -6,8 +6,6 @@ from .rbac.access_control import AccessControl
from .rbac.role import Role, RoleMembership
from .scim_provisioned_user import SCIMProvisionedUser
from .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.py
index 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 BaseTest
from 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: str
diff --git a/posthog/admin/admins/cohort_admin.py b/posthog/admin/admins/cohort_admin.py
index 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, messages
from django.urls import reverse
from 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.py
index 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, CohortPeople
team_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.py
index 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 UserProductListInline
from posthog.cloud_utils import is_cloud
from posthog.models import Team
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity
-from posthog.models.exported_recording import ExportedRecording
from posthog.models.remote_config import RemoteConfig
from posthog.models.team.team import DEPRECATED_ATTRS
from 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 ExportRecordingInput
from 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.py
index 6c1ad6a5ec57..6a3cdcb2bcd1 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -45,7 +45,7 @@ from posthog.constants import LIMIT, OFFSET, PropertyOperatorType
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.metrics import LABEL_TEAM_ID
-from posthog.models import Cohort, Person, User
+from posthog.models import Person, User
from 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_response
from 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 CohortTypeValidationSerializer
from posthog.models.filters.filter import Filter
from posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctId
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
@@ -77,6 +68,20 @@ from posthog.queries.util import get_earliest_timestamp
from posthog.renderers import SafeJSONRenderer
from 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 CohortTypeValidationSerializer
from products.feature_flags.backend.flag_matching import (
FeatureFlagMatcher,
FlagsMatcherCache,
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index 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.py
index 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 APIRequestFactory
from posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT
from posthog.models import Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.py
index 03628f67b200..d39c8467700b 100644
--- a/posthog/api/my_notifications.py
+++ b/posthog/api/my_notifications.py
@@ -12,10 +12,11 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import ServerTimingsGathered, action
-from posthog.models import ActivityLog, Cohort, NotificationViewed, User
+from posthog.models import ActivityLog, NotificationViewed, User
from posthog.models.comment import Comment
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 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, FunnelVizType
from posthog.decorators import cached_by_filters
from posthog.event_usage import get_request_analytics_properties
from posthog.metrics import LABEL_TEAM_ID
-from posthog.models import Cohort, Filter, Person, Team, User
+from posthog.models import Filter, Person, Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.async_deletion import AsyncDeletion, DeletionType
-from posthog.models.cohort.util import get_all_cohort_ids_by_person_uuid
from posthog.models.filters.lifecycle_filter import LifecycleFilter
from posthog.models.filters.path_filter import PathFilter
from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter
@@ -77,6 +76,8 @@ from posthog.renderers import SafeJSONRenderer
from posthog.tasks.split_person import split_person
from 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_uuid
from products.product_analytics.backend.api.insight import capture_legacy_api_call
logger = structlog.get_logger(__name__)
diff --git a/posthog/api/search.py b/posthog/api/search.py
index dfd82a907f63..93c571f07523 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -12,9 +12,10 @@ from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.helpers.full_text_search import build_rank, process_query
-from posthog.models import Cohort, EventDefinition, PropertyDefinition
+from posthog.models import EventDefinition, PropertyDefinition
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 7d744428cd1c..8e6cd141c7ca 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -33,7 +33,7 @@ from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_mode
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Team
+from posthog.models import SessionRecording, SharePassword, SharingConfiguration, Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.resource_transfer.visitors.insight import InsightVisitor
from posthog.models.user import User
@@ -44,6 +44,7 @@ from posthog.user_permissions import UserPermissions
from posthog.utils import get_ip_address, render_template
from posthog.views import preflight_check
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.api.dashboard import DashboardSerializer
from products.dashboards.backend.models.dashboard import Dashboard
from products.exports.backend.api.exports import ExportedAssetSerializer
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 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_execute
from posthog.models import Person, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.async_deletion.async_deletion import AsyncDeletion
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.cohort import CohortType
from posthog.models.file_system.file_system import FileSystem
from posthog.models.property import BehavioralPropertyType
from 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, CohortType
from products.exports.backend.api.test.test_exports import TestExportMixin
from 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_cohort
from 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 CohortErrorCode
cohort = 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 CohortErrorCode
cohort = 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 CohortCalculationHistory
cohort = 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 CohortErrorCode
cohort = Cohort.objects.create(
team=self.team,
diff --git a/posthog/api/test/test_cohort_bytecode.py b/posthog/api/test/test_cohort_bytecode.py
index 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_VERSION
class 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 Cohort
resp = self.client.post(
f"/api/projects/{self.team.id}/cohorts/",
@@ -19,7 +19,7 @@ class TestCohortBytecodeScenarios(APIBaseTest):
return cohort
def _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 Cohort
resp = 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.py
index 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, BaseTest
from parameterized import parameterized_class
from rest_framework import status
-from posthog.models import Cohort
from posthog.models.person import Person
from posthog.models.person.util import validate_person_uuids_exist
from 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.py
index 44097ff01490..072f172ff2f7 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -24,11 +24,11 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import Element, Organization, Person, PropertyDefinition, User
-from posthog.models.cohort import Cohort
from posthog.models.event.query_event_list import insight_query_with_columns
from posthog.test.test_journeys import journeys_for
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
class TestEvents(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index 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 APIRequestFactory
from posthog.api.file_system.file_system_logging import log_api_file_system_view
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 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 status
import posthog.models.person.deletion
from posthog.clickhouse.client import sync_execute
-from posthog.models import Cohort, Organization, Person, PropertyDefinition, Team
+from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import PersonDistinctId
from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE
from 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.py
index 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 mock
from parameterized import parameterized_class
from rest_framework import status
-from posthog.models import Cohort, Organization, Person, Team
+from posthog.models import Organization, Person, Team
from posthog.models.person import PersonDistinctId
from 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.py
index 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 Organization
from 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.py
index 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 status
from posthog.models import Project, Team
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
from posthog.models.scoping import team_scope
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 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_template
def test_shared_insight_inlines_referenced_cohort_names(self):
- from posthog.models.cohort import Cohort
+ from products.cohorts.backend.models.cohort import Cohort
cohort = 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_template
def test_shared_dashboard_collects_cohorts_across_tiles(self):
- from posthog.models.cohort import Cohort
-
+ from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard_tile import DashboardTile
cohort_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.py
index 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 InsightCachingState
from posthog.models.person import Person
+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople
from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride
cohort = Cohort.objects.create(team=team, created_by=self.user, name="test")
diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.py
index c10a8942dd4f..47e494a72b7f 100644
--- a/posthog/cdp/filters.py
+++ b/posthog/cdp/filters.py
@@ -8,10 +8,10 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.property import action_to_expr, ast, property_to_expr
from posthog.hogql.visitor import TraversingVisitor
-from posthog.models.cohort.cohort import Cohort
from posthog.models.team.team import Team
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
COHORT_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.py
index 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 Cohort
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
diff --git a/posthog/cdp/test/test_site_functions.py b/posthog/cdp/test/test_site_functions.py
index 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 parameterized
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.templates.helpers import mock_transpile
-from posthog.models.cohort import Cohort
from posthog.models.organization import Organization
from posthog.models.project import Project
from posthog.models.user import User
@@ -21,6 +20,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from 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.py
index 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_SQL
operations = [run_sql_with_exceptions(CREATE_COHORTPEOPLE_TABLE_SQL())]
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 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_SQL
from 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_SQL
from products.error_tracking.backend.embedding import (
DISTRIBUTED_DOCUMENT_EMBEDDINGS_TABLE_SQL,
DOCUMENT_EMBEDDINGS_MV_SQL,
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 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_SQL
from posthog.models.app_metrics.sql import TRUNCATE_APP_METRICS_TABLE_SQL
from posthog.models.channel_type.sql import TRUNCATE_CHANNEL_DEFINITION_TABLE_SQL
- from posthog.models.cohort.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQL
from posthog.models.event.sql import TRUNCATE_EVENTS_RECENT_TABLE_SQL, TRUNCATE_EVENTS_TABLE_SQL
from posthog.models.exchange_rate.sql import TRUNCATE_EXCHANGE_RATE_TABLE_SQL
from 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_V3
from posthog.models.sessions.sql import TRUNCATE_SESSIONS_TABLE_SQL
+ from products.cohorts.backend.models.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQL
from products.error_tracking.backend.embedding import TRUNCATE_DOCUMENT_EMBEDDINGS_TABLE_SQL
from 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.py
index 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 dagster
from posthog.dags.common import JobOwners
from 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, CohortKind
from 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.py
index 1e2f6db1e7a5..151254f6562e 100644
--- a/posthog/demo/matrix/manager.py
+++ b/posthog/demo/matrix/manager.py
@@ -12,7 +12,6 @@ from django.db import IntegrityError, transaction
from posthog.clickhouse.client import query_with_columns, sync_execute
from posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team
from 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 Matrix
from .models import SimEvent, SimPerson
diff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.py
index 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, Matrix
from posthog.demo.matrix.models import SimEvent
from posthog.demo.matrix.randomization import Industry
from posthog.exceptions_capture import capture_exception
-from posthog.models import Cohort
from posthog.models.event.util import create_event
from posthog.models.oauth import OAuthApplication
from posthog.storage import object_storage
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from 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_cohort
test_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.py
index 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 Cohort
from .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_cohort
test_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.py
index 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 Cohort
cohort_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.py
index 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, ClickhouseTestMixin
from posthog.hogql.parser import parse_select
from 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 Cohort
class TestCohortPeopleTable(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.py
index 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_query
from posthog.clickhouse.client.execute import sync_execute
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
-from posthog.models import Cohort
-from posthog.models.cohort.util import recalculate_cohortpeople
from posthog.models.person.util import create_person
from 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-optimization
class TestPersonOptimization(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 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_select
from posthog.hogql.printer import prepare_and_print_ast
from 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, Team
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort.calculation_history import CohortCalculationHistory
from posthog.models.project import Project
from posthog.models.scoping import team_scope
@@ -27,6 +26,8 @@ from products.annotations.backend.models.annotation import Annotation
from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource
from products.business_knowledge.backend.models.constants import SourceStatus, SourceType
from 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 Cohort
from products.conversations.backend.models import Ticket
from products.customer_analytics.backend.models.account import Account
from products.dashboards.backend.models.dashboard import Dashboard
diff --git a/posthog/hogql/functions/cohort.py b/posthog/hogql/functions/cohort.py
index 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 CohortCalculationHistory
seven_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 Cohort
if 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 Cohort
arg = 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.py
index 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_query
from posthog.hogql.test.utils import pretty_print_response_in_tests
from 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_cohortpeople
from posthog.models.team.team import Team
from 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.py
index 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_query
from posthog.clickhouse.client.execute import sync_execute
from posthog.models import PropertyDefinition
-from posthog.models.cohort.cohort import Cohort
from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DICTIONARY_NAME
from posthog.models.team.team import WeekStartDay
from posthog.settings.data_stores import CLICKHOUSE_DATABASE
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyType
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index 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_expr
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
from posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS, PropertyOperatorType
-from posthog.models import Cohort, Property, PropertyDefinition, Team
+from posthog.models import Property, PropertyDefinition, Team
from posthog.models.element import Element
from posthog.models.event import Selector
from posthog.models.property import PropertyGroup, ValueT
@@ -58,6 +58,7 @@ from posthog.models.property.util import build_selector_regex
from posthog.utils import get_from_dict_or_attr
from products.actions.backend.models.action import Action, ActionStepJSON
+from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.event_definitions.backend.models.property_definition import PropertyType
from products.warehouse_sources.backend.models.util import get_view_or_table_by_name
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.py
index 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_ERROR
from posthog.hogql.metadata import get_hogql_metadata
from 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 Cohort
from products.data_warehouse.backend.types import ExternalDataSourceType
from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
diff --git a/posthog/hogql/test/test_modifiers.py b/posthog/hogql/test/test_modifiers.py
index 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, PersonsArgM
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.query import execute_hogql_query
-from posthog.models import Cohort
+from products.cohorts.backend.models.cohort import Cohort
class TestModifiers(BaseTest):
diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.py
index 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_query
from posthog.hogql.visitor import clear_locations
from 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, Team
from posthog.models.property import PropertyGroup
+from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.event_definitions.backend.models.property_definition import PropertyType
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 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_cohortpeople
from posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODES
from posthog.models.utils import UUIDT, uuid7
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
+from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.util import recalculate_cohortpeople
from products.data_warehouse.backend.types import ExternalDataSourceType
from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
diff --git a/posthog/hogql/transforms/in_cohort.py b/posthog/hogql/transforms/in_cohort.py
index 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 Cohort
cohorts: list[tuple[int, StaticOrDynamic, int]] = []
@@ -310,8 +310,7 @@ class InCohortResolver(TraversingVisitor):
arg = node.right
if 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 Cohort
if (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.py
index 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_tables
from 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, PropertyDefinition
from posthog.models.utils import uuid7
+from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.util import recalculate_cohortpeople
from products.event_definitions.backend.models.property_definition import PropertyType
diff --git a/posthog/hogql/transforms/test/test_in_cohort.py b/posthog/hogql/transforms/test/test_in_cohort.py
index 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_query
from posthog.hogql.test.utils import pretty_print_response_in_tests
from posthog.clickhouse.client.execute import sync_execute
-from posthog.models import Cohort
-from posthog.models.cohort.util import recalculate_cohortpeople
from 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.py
index 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 PropertyOperatorType
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.events_query_runner import EventsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models import Cohort, Filter, Property, Team
+from posthog.models import Filter, Property, Team
from posthog.models.property import OperatorInterval, PropertyGroup
from 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.py
index 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 FunnelQu
from posthog.hogql_queries.insights.funnels.utils import funnel_window_interval_unit_to_sql
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID
from posthog.hogql_queries.insights.utils.entities import is_equal, is_superset
-from posthog.models.cohort.cohort import Cohort
from posthog.models.property.property import PropertyName
from posthog.queries.breakdown_props import get_breakdown_cohort_name
from posthog.queries.util import correct_result_for_sampling
from posthog.types import FunnelEntityNode
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
JOIN_ALGOS = "auto"
diff --git a/posthog/hogql_queries/insights/funnels/test/breakdown_cases.py b/posthog/hogql_queries/insights/funnels/test/breakdown_cases.py
index 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 FunnelOrderType
from posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunner
from posthog.hogql_queries.insights.funnels.test.test_funnel_persons import get_actors
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, NOT_IN_COHORT_ID
-from posthog.models.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.models.instance_setting import override_instance_config
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.cohorts.backend.models.cohort import Cohort
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
TEST_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.py
index 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_factory
from posthog.models import Element
-from posthog.models.cohort.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.models.utils import uuid7
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py
index 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 Cohort
from posthog.models.event.util import bulk_create_events
from posthog.models.person.util import bulk_create_persons
from posthog.models.team.team import Team
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from 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.py
index 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 ast
from posthog.constants import FunnelOrderType
from posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunner
from posthog.hogql_queries.insights.funnels.test.test_funnel_persons import get_actors
-from posthog.models.cohort.cohort import Cohort
from 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.py
index 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_query
from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
-from posthog.models import Cohort
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting
from posthog.models.team import WeekStartDay
@@ -40,6 +39,7 @@ from posthog.models.utils import UUIDT
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
def 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.py
index 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, pluck
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABEL
-from posthog.models import Cohort
from posthog.models.group.util import create_group
from posthog.models.person import Person
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
diff --git a/posthog/hogql_queries/insights/trends/test/test_formula.py b/posthog/hogql_queries/insights/trends/test/test_formula.py
index 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 ExposedHogQLError
from posthog.constants import TRENDS_BOLD_NUMBER, TRENDS_CUMULATIVE, TRENDS_PIE
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
-from posthog.models import Cohort
from posthog.models.group.util import create_group
from posthog.models.utils import uuid7
from 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.py
index 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, TRENDS
from posthog.hogql_queries.insights.trends.test.test_trends_persons import get_actors
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from 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, Person
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting, override_instance_config
from posthog.models.person.util import create_person_distinct_id
@@ -43,6 +43,7 @@ from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
index 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_team
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from 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 Team
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
index 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 Cohort
from posthog.models.group.util import create_group
from posthog.models.team.team import Team, WeekStartDay
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index 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_e
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
-from posthog.models.cohort.cohort import Cohort
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.user import User
from posthog.queries.util import correct_result_for_sampling
from posthog.utils import multisort
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.warehouse_sources.backend.models.util import get_view_or_table_by_name
diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.py
index 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, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery, HogQLRealtimeCohortQuery
-from posthog.models import Cohort
+
+from products.cohorts.backend.models.cohort import Cohort
class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/test/test_sessions_query_runner.py b/posthog/hogql_queries/test/test_sessions_query_runner.py
index 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) == 1
def test_filter_test_accounts_with_cohort_filter(self):
- from posthog.models import Cohort
+ from products.cohorts.backend.models.cohort import Cohort
cohort = Cohort.objects.create(
team=self.team,
diff --git a/posthog/management/commands/backfill_precalculated_events.py b/posthog/management/commands/backfill_precalculated_events.py
index 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, CommandError
import structlog
from temporalio.common import WorkflowIDReusePolicy
-from posthog.models import Cohort
-from posthog.models.cohort.cohort import CohortType
from posthog.models.property.property import BehavioralPropertyType
from posthog.temporal.common.client import async_connect
from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (
@@ -21,6 +19,8 @@ from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workfl
from posthog.temporal.messaging.filter_storage import store_event_filters
from 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.py
index 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, CommandError
import structlog
from temporalio.common import WorkflowIDReusePolicy
-from posthog.models import Cohort
-from posthog.models.cohort.cohort import CohortType
from posthog.temporal.common.client import async_connect
from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (
BackfillPrecalculatedPersonPropertiesCoordinatorInputs,
@@ -17,6 +15,8 @@ from posthog.temporal.messaging.backfill_precalculated_person_properties_coordin
from posthog.temporal.messaging.filter_storage import store_filters
from 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.py
index 7449584eaee5..59d791c25edd 100644
--- a/posthog/management/commands/calculate_cohort.py
+++ b/posthog/management/commands/calculate_cohort.py
@@ -3,9 +3,10 @@ import traceback
from django.core.management.base import BaseCommand
-from posthog.models import Cohort
from 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.py
index 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 connections
import structlog
from posthog.clickhouse.client import sync_execute
-from posthog.models.cohort.cohort import Cohort
from posthog.models.person import Person
from 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 constant
diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.py
index 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, CommandParser
import structlog
from 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_topologically
from 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.py
index 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 Team
from 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.py
index 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 patch
from 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, CohortType
class BackfillPrecalculatedPersonPropertiesCommandTestCase(BaseTest):
diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.py
index 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 BaseTest
from django.core.management import call_command
-from posthog.models.cohort.cohort import Cohort
from posthog.models.team.team import Team
+from products.cohorts.backend.models.cohort import Cohort
+
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 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_h
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.user_devices import set_known_device_cookie
-from posthog.models import Cohort, Team, User
+from posthog.models import Team, User
from posthog.models.activity_logging.utils import (
ACTIVITY_LOG_CLIENT_HEADER,
ACTIVITY_LOG_CLIENT_MAX_LENGTH,
@@ -53,6 +53,7 @@ from posthog.user_permissions import UserPermissions
from posthog.utils import _is_valid_ip_address, get_ip_address
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
diff --git a/posthog/migrations/1215_migrate_replay_models.py b/posthog/migrations/1215_migrate_replay_models.py
new file mode 100644
index 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.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index b2d9cf87b3b0..11bbaa4e8c53 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -9,7 +9,6 @@ from .activity_logging.activity_log import ActivityLog
from .activity_logging.notification_viewed import NotificationViewed
from .async_deletion import AsyncDeletion, DeletionType
from .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus
-from .cohort import Cohort, CohortPeople, CohortCalculationHistory
from .column_configuration import ColumnConfiguration
from .comment import Comment
from .core_event import CoreEvent
@@ -27,7 +26,6 @@ from .event_filter_config import EventFilterConfig # noqa: F401
from products.event_definitions.backend.models import EventDefinition
from products.event_definitions.backend.models import EventProperty
from .role_external_reference import RoleExternalReference
-from .exported_recording import ExportedRecording
from .file_system.file_system import FileSystem
from .file_system.folder_instructions import FileSystemFolderInstructions
from .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.py
index 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 Optional
from django.utils import timezone
-from posthog.models.cohort import Cohort
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system import FileSystem, escape_path, split_path
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
@@ -14,6 +13,7 @@ from posthog.session_recordings.models.session_recording_playlist import Session
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/models/filters/mixins/simplify.py b/posthog/models/filters/mixins/simplify.py
index 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_properties
try:
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.py
index 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, Q
from posthog.constants import FILTER_TEST_ACCOUNTS
-from posthog.models import Cohort, Filter, Person, Team
+from posthog.models import Filter, Person, Team
from posthog.models.property import Property
from 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.py
index 89c6f875ac77..d895ad96982d 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -21,14 +21,6 @@ from posthog.hogql.visitor import TraversingVisitor
from posthog.clickhouse.kafka_engine import trim_quotes_expr
from posthog.clickhouse.materialized_columns import TableWithProperties, get_materialized_column_for_property
from 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 Selector
from posthog.models.group.sql import GET_GROUP_IDS_BY_PROPERTY_SQL
from 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_regex
from products.actions.backend.models.action import Action
from 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.py
index 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 SimpleTestCase
from parameterized import parameterized
-from posthog.models import Cohort
from posthog.models.resource_transfer.visitors import CohortVisitor, InsightVisitor
from posthog.models.resource_transfer.visitors.experiment import ExperimentVisitor
from 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 SurveyVisitor
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import ExperimentHoldout
diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.py
index 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(
):
@classmethod
def get_model(cls) -> type[models.Model]:
- from posthog.models import Cohort
+ from products.cohorts.backend.models.cohort import Cohort
return Cohort
@classmethod
def 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 Cohort
cohort_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.py
index 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 Any
from django.db import models
-from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from 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 Cohort
class ExperimentVisitor(
diff --git a/posthog/models/resource_transfer/visitors/experiment_holdout.py b/posthog/models/resource_transfer/visitors/experiment_holdout.py
index 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 Any
from django.db import models
-from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourcePayload, ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from 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.py
index 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 Any
from django.db import models
-from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourcePayload, ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from posthog.models.resource_transfer.visitors.common import build_edges_for_ids
from posthog.models.resource_transfer.visitors.insight import InsightVisitor
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
class ExperimentSavedMetricVisitor(
diff --git a/posthog/models/resource_transfer/visitors/feature_flag.py b/posthog/models/resource_transfer/visitors/feature_flag.py
index 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 Any
from django.db import models
-from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from 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 Cohort
from products.experiments.backend.models.experiment import ExperimentHoldout
diff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.py
index 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(
@classmethod
def 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 Cohort
action_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.py
index 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(
@classmethod
def get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:
- from posthog.models import Cohort
+ from products.cohorts.backend.models.cohort import Cohort
cohort_ids = cls._extract_cohort_ids_from_conditions(resource.conditions)
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 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_cohort
initiating_user_email = initiating_user.email if initiating_user else None
test_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.py
index 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 Cohort
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
+ from products.cohorts.backend.models.cohort import Cohort
from products.data_modeling.backend.models import Edge, Node
from products.early_access_features.backend.models import EarlyAccessFeature
from 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_bulk
for 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.py
index 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_execute
from posthog.models import AsyncDeletion, DeletionType, Team, User
from posthog.models.async_deletion.delete_cohorts import AsyncCohortDeletion
from posthog.models.async_deletion.delete_events import AsyncEventDeletion
-from posthog.models.cohort.util import insert_static_cohort
from posthog.models.group.util import create_group
from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.test.test_plugin_log_entry import create_plugin_log_entry
from products.cdp.backend.models.plugin import PluginLogEntrySource, PluginLogEntryType
+from products.cohorts.backend.models.util import insert_static_cohort
uuid = 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.py
index 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, patch
from django.test import TestCase
-from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -14,6 +13,7 @@ from posthog.models.user import User
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
+from products.cohorts.backend.models.cohort import Cohort
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
diff --git a/posthog/person_db_router.py b/posthog/person_db_router.py
index 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=False
from posthog.models import Person, Project, Team
- from posthog.models.cohort import Cohort, CohortPeople
from posthog.models.group_type_mapping import GroupTypeMapping
+ from products.cohorts.backend.models.cohort import Cohort, CohortPeople
from products.dashboards.backend.models.dashboard import Dashboard
# Allow any persons_db model -> Team relation
diff --git a/posthog/queries/base.py b/posthog/queries/base.py
index 4be6ce9e4bea..829520803468 100644
--- a/posthog/queries/base.py
+++ b/posthog/queries/base.py
@@ -12,7 +12,6 @@ from dateutil.relativedelta import relativedelta
from rest_framework.exceptions import ValidationError
from posthog.constants import PropertyOperatorType
-from posthog.models.cohort import Cohort, CohortOrEmpty, CohortPeople
from posthog.models.filters.filter import Filter
from posthog.models.filters.path_filter import PathFilter
from posthog.models.property import Property, PropertyGroup
@@ -21,6 +20,8 @@ from posthog.models.team import Team
from posthog.queries.util import convert_to_datetime_aware
from 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_cohort
if 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_ids
member_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.py
index 05be7e31fabe..4c84a761ef49 100644
--- a/posthog/queries/breakdown_props.py
+++ b/posthog/queries/breakdown_props.py
@@ -8,8 +8,6 @@ from posthog.hogql.hogql import HogQLContext
from posthog.constants import BREAKDOWN_TYPES, MONTHLY_ACTIVE, WEEKLY_ACTIVE, PropertyOperatorType
from 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_query
from posthog.models.entity import Entity
from posthog.models.entity.util import get_entity_filtering_params
from 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_legacy
from 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.py
index 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 PersonsOnEventsMode
from posthog.hogql.database.database import Database
from 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, Property
from posthog.models.filters import AnyFilter
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.filters.path_filter import PathFilter
@@ -25,6 +24,9 @@ from posthog.queries.query_date_range import QueryDateRange
from posthog.queries.util import PersonPropertiesMode, alias_poe_mode_for_legacy
from 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.py
index f5ae4956e1f9..3e1430d26cfc 100644
--- a/posthog/queries/funnels/funnel_trends.py
+++ b/posthog/queries/funnels/funnel_trends.py
@@ -2,7 +2,6 @@ from datetime import datetime
from itertools import groupby
from typing import Optional
-from posthog.models.cohort import Cohort
from posthog.models.filters.filter import Filter
from posthog.models.team import Team
from 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.py
index 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, Union
from posthog.test.base import APIBaseTest, also_test_with_materialized_columns, snapshot_clickhouse_queries
from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.queries.breakdown_props import ALL_USERS_COHORT_ID
from posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnordered
from 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.py
index 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 ValidationError
from posthog.clickhouse.client import sync_execute
from posthog.constants import FILTER_TEST_ACCOUNTS, INSIGHT_FUNNELS
from posthog.models import Element
-from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.models.instance_setting import get_instance_setting
from posthog.queries.funnels import ClickhouseFunnel, ClickhouseFunnelActors
@@ -30,6 +29,7 @@ from posthog.queries.funnels.test.conversion_time_cases import funnel_conversion
from posthog.test.test_journeys import journeys_for
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
class TestFunnelBreakdown(
diff --git a/posthog/queries/funnels/test/test_funnel_persons.py b/posthog/queries/funnels/test/test_funnel_persons.py
index 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 timezone
from posthog.constants import INSIGHT_FUNNELS
-from posthog.models import Cohort, Filter
+from posthog.models import Filter
from posthog.models.event.util import bulk_create_events
from posthog.models.person.util import bulk_create_persons
from posthog.queries.funnels.funnel_persons import ClickhouseFunnelActors
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from 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 = 0
COUNT_COLUMN = 1
diff --git a/posthog/queries/funnels/test/test_funnel_trends.py b/posthog/queries/funnels/test/test_funnel_trends.py
index 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_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, snapshot_clickhouse_queries
from posthog.constants import INSIGHT_FUNNELS, TRENDS_LINEAR, FunnelOrderType
-from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.queries.funnels.funnel_trends import ClickhouseFunnelTrends
from posthog.queries.funnels.funnel_trends_persons import ClickhouseFunnelTrendsActors
from 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.py
index a9503d6104b8..0b0b30b80625 100644
--- a/posthog/queries/person_query.py
+++ b/posthog/queries/person_query.py
@@ -4,9 +4,6 @@ from uuid import UUID
from posthog.clickhouse.materialized_columns import ColumnName
from posthog.constants import PropertyOperatorType
from 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_query
from posthog.models.entity import Entity
from posthog.models.filters.path_filter import PathFilter
from posthog.models.filters.retention_filter import RetentionFilter
@@ -22,6 +19,10 @@ from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
from posthog.queries.trends.util import COUNT_PER_ACTOR_MATH_FUNCTIONS
from 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.py
index 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_execute
from posthog.models import Filter
-from posthog.models.cohort import Cohort
from posthog.queries.column_optimizer.column_optimizer import ColumnOptimizer
from 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.py
index 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, Person
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting, override_instance_config, set_instance_setting
from 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_at
from posthog.utils import generate_cache_key
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
def 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.py
index 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, cast
from posthog.schema import PersonsOnEventsMode
from posthog.constants import PropertyOperatorType
-from posthog.models.cohort import Cohort
from posthog.models.entity import Entity
from posthog.models.filters import Filter
from posthog.models.filters.mixins.utils import cached_property
@@ -15,6 +14,8 @@ from posthog.queries.actor_base_query import ActorBaseQuery
from posthog.queries.trends.trends_event_query import TrendsEventQuery
from 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 = True
diff --git a/posthog/session_recordings/queries/sub_queries/cohort_subquery.py b/posthog/session_recordings/queries/sub_queries/cohort_subquery.py
index 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, RecordingsQue
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
-from posthog.models import Cohort, Team
+from posthog.models import Team
from posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQuery
from 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.py
index 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_ast
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
from posthog.models import Person
-from posthog.models.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.models.team import Team
from 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_SES
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from ee.clickhouse.materialized_columns.columns import get_materialized_columns, materialize
from ee.clickhouse.models.test.test_cohort import get_person_ids_by_cohort_id
diff --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.py
index 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 relativedelta
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
-from posthog.models import Cohort, Person
+from posthog.models import Person
from 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 impor
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from 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.py
index 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_client
from ee.hogai.session_summaries.session.output_data import OutcomeSerializer
from 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 TeamSessionSummariesConfig
from ..models.product_intent.product_intent import ProductIntent
from .queries.combine_session_ids_for_filtering import combine_session_id_filters
@@ -330,7 +331,7 @@ class SessionRecordingSerializer(serializers.ModelSerializer, UserAccessControlS
return False
try:
- from ee.models.session_summaries import SingleSessionSummary
+ from products.replay.backend.models.session_summaries import SingleSessionSummary
except 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 SingleSessionSummary
except 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 SingleSessionSummary
except ImportError:
default_summary_session_ids = set()
else:
diff --git a/posthog/session_recordings/synthetic_playlists.py b/posthog/session_recordings/synthetic_playlists.py
index 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_fro
from products.exports.backend.models.exported_asset import ExportedAsset
try:
- from ee.models.session_summaries import SingleSessionSummary
+ from products.replay.backend.models.session_summaries import SingleSessionSummary
HAS_EE = True
except ImportError:
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index 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 SingleSessionSummary
except 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 SingleSessionSummary
except 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 SingleSessionSummary
except 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 SingleSessionSummary
outcome_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 SingleSessionSummary
other_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.py
index 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 ExportedAsset
try:
- from ee.models.session_summaries import SingleSessionSummary
+ from products.replay.backend.models.session_summaries import SingleSessionSummary
HAS_EE = True
except ImportError:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 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.py
index 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_tags
from posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorS3Error, CHQueryErrorTooManySimultaneousQueries
from posthog.exceptions import ClickHouseAtCapacity
from 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 CeleryQueue
COHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge(
"cohort_recalculations_backlog",
@@ -111,7 +111,7 @@ MAX_STUCK_STATIC_COHORTS_TO_SCAN = MAX_STUCK_COHORTS_TO_RESET * 10
def 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_values
return 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) -> N
team_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_ch
cohort = 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_pg
if 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.py
index 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 timezone
from dateutil.relativedelta import relativedelta
from parameterized import parameterized
-from posthog.models.cohort import Cohort
from posthog.models.person import Person
from 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.py
index 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_expr
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.models.cohort import Cohort
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.trace_summarization.constants import (
@@ -29,6 +28,8 @@ from posthog.temporal.ai_observability.trace_summarization.models import BatchSu
from posthog.temporal.ai_observability.trace_summarization.utils import format_datetime_for_clickhouse
from 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.py
index 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 Cohort
cohort = 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 Cohort
cohort = 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.py
index 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_context
from posthog.hogql_queries.hogql_cohort_query import HogQLRealtimeCohortQuery
from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_COHORT_MEMBERSHIP_CHANGED
-from posthog.models.cohort.cohort import Cohort, CohortType
from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.clickhouse import get_client
@@ -28,6 +27,8 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from 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 _KafkaProducer
diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py
index 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.activity
import temporalio.workflow
from temporalio.common import MetricHistogramFloat
-from posthog.models.cohort.cohort import Cohort, CohortType
from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
from 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.py
index 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, CohortType
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+ from products.cohorts.backend.models.cohort import Cohort, CohortType
+
# Create test organization and team
organization = 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, CohortType
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+ from products.cohorts.backend.models.cohort import Cohort, CohortType
+
# Create test organization and team
organization = 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, CohortType
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+ from products.cohorts.backend.models.cohort import Cohort, CohortType
+
# Create test organization and team
organization = 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.py
index 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 pytz
from temporalio import activity
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.models.exported_recording import ExportedRecording
from posthog.redis import get_async_client
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.session_recordings.recordings import recording_s3_client
@@ -24,6 +23,8 @@ from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.logger import get_write_only_logger
from 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.py
index 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 temporalio
from posthog.sync import database_sync_to_async
from 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.defn
diff --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.py
index 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_summary
from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer
from ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputs
-from ee.models.session_summaries import SessionSummaryRunMeta, SingleSessionSummary
def _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.py
index 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 SingleSessionSummary
from 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 SingleSessionSummary
logger = 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.py
index 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.py
index 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 structlog
from posthog.api.capture import capture_internal
from 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 SingleSessionSummary
EVENT_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.py
index 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 aioredis
from 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, SingleSessionSummary
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/session_replay/session_summary/workflow.py b/posthog/temporal/session_replay/session_summary/workflow.py
index 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_MODEL
from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContext
from ee.hogai.session_summaries.utils import serialize_to_sse_event
-from ee.models.session_summaries import SingleSessionSummary
logger = 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.py
index 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_MS
from ee.hogai.session_summaries.session.input_data import add_context_and_filter_events
from 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 SingleSessionSummary
def _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.py
index 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, SessionSummaryRunMeta
logger = 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.py
index 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, TypedDict
from 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.py
index 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 ExtraSummaryContext
from ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsList
from ee.hogai.session_summaries.utils import logging_session_ids
-from ee.models.session_summaries import SessionGroupSummary
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/session_replay/summarization_sweep/activities.py b/posthog/temporal/session_replay/summarization_sweep/activities.py
index 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 SingleSessionSummary
from 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.py
index 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, uuid4
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from posthog.models.exported_recording import ExportedRecording
from posthog.session_recordings.recordings.errors import BlockFetchError
from posthog.session_recordings.session_recording_v2_service import RecordingBlock
from 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.py
index 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 SingleS
from posthog.temporal.session_replay.session_summary_group.types import SessionGroupSummaryOfSummariesInputs
from 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_MODEL
from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer
from ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputs
from 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.fixture
diff --git a/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py b/posthog/temporal/tests/session_replay/session_summary/test_event_capture.py
index 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_db
diff --git a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py
index 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 SingleSessionSummaryLlmInputs
from ee.hogai.session_summaries.utils import serialize_to_sse_event
-from ee.models.session_summaries import SingleSessionSummary
pytestmark = pytest.mark.django_db
diff --git a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
index 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_MODEL
from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer
from 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, SingleSessionSummary
pytestmark = 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 id
assert 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 SessionGroupSummary
session_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 SessionGroupSummary
session_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 SingleSessionSummary
person = 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 SingleSessionSummary
person = MagicMock()
person.uuid = "person-uuid-shared"
@@ -1927,8 +1930,9 @@ def test_get_persons_for_sessions_from_distinct_ids_handles_multiple_sessions_sa
def 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 SingleSessionSummary
person = MagicMock()
person.uuid = "person-uuid-1"
@@ -1960,8 +1964,9 @@ def test_get_persons_for_sessions_from_distinct_ids_excludes_sessions_with_no_di
def 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 SingleSessionSummary
summary = MagicMock(spec=SingleSessionSummary)
summary.distinct_id = None
@@ -1980,8 +1985,9 @@ def test_get_persons_for_sessions_from_distinct_ids_returns_empty_when_all_sessi
def 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 SingleSessionSummary
person = MagicMock()
summaries: dict[str, SingleSessionSummary] = {}
@@ -2007,8 +2013,9 @@ def test_get_persons_for_sessions_from_distinct_ids_deduplicates_distinct_ids_se
def 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 SingleSessionSummary
mock_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.py
index 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, organizati
return_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_env
return_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, o
side_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, organ
return_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_environ
return_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_en
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(
@@ -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_en
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={"s1": True, "s2": True},
),
patch(
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 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_SQL
from 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_than
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQL
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.event_definitions.backend.models.property_definition import (
diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.py
index 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 BaseTest
from parameterized import parameterized
from 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_ID
from 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 persons
person1 = 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 cohort
cohort = 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 + 1
cohort.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 cohort
cohort = 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_COUNT
cohort.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 = 42
with 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.py
index 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 CohortTypeValidationSerializer
from 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.py
index 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, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.middleware import per_request_logging_context_middleware
-from posthog.models import Cohort
from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import SITE_URL
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
diff --git a/posthog/test/test_team.py b/posthog/test/test_team.py
index 797b63e17b7e..78e729545bdf 100644
--- a/posthog/test/test_team.py
+++ b/posthog/test/test_team.py
@@ -8,13 +8,12 @@ from parameterized import parameterized
from posthog.schema import PersonsOnEventsMode
from posthog.models import Organization, Team, User
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.cohort import INTERNAL_TEST_USERS_COHORT_NAME, CohortKind
from posthog.models.instance_setting import override_instance_config
from posthog.models.project import Project
from posthog.models.team import get_team_in_cache, util
from posthog.models.team.team import SessionRecordingRetentionPeriod
+from products.cohorts.backend.models.cohort import INTERNAL_TEST_USERS_COHORT_NAME, Cohort, CohortKind
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index 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 UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.constants import TREND_FILTER_TYPE_EVENTS
from posthog.event_usage import report_user_action
-from posthog.models import Cohort, Team
+from posthog.models import Team
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
from posthog.models.event.event import Selector
from posthog.models.property.util import build_selector_regex
@@ -39,6 +39,7 @@ from posthog.resource_limits import LimitKey, check_count_limit
from products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
from products.product_analytics.backend.models.insight import Insight
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index 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, patch
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Cohort, Tag, User
+from posthog.models import Tag, User
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.models.insight import Insight
diff --git a/products/ai_observability/backend/api/clustering_job.py b/products/ai_observability/backend/api/clustering_job.py
index 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 Response
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.event_usage import report_user_action
-from posthog.models.cohort import Cohort
+
+from products.cohorts.backend.models.cohort import Cohort
from ..models.clustering_job import ClusteringJob
from .metrics import llma_track_latency
diff --git a/products/ai_observability/backend/api/test/test_clustering_job.py b/products/ai_observability/backend/api/test/test_clustering_job.py
index 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 Cohort
cohort = 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 Cohort
cohort = 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.py
index 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 structlog
from prometheus_client import Counter
from posthog.helpers.encrypted_fields import EncryptedJSONStringField
-from posthog.models.cohort.cohort import is_cohort_recalculation_only_save
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
@@ -29,6 +28,7 @@ from posthog.utils import absolute_uri
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.plugin import sync_team_inject_web_apps
+from products.cohorts.backend.models.cohort import is_cohort_recalculation_only_save
if 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):
return
diff --git a/products/cdp/backend/tasks/hog_functions.py b/products/cdp/backend/tasks/hog_functions.py
index 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 Cohort
try:
cohort = Cohort.objects.select_related("team").get(id=cohort_id)
diff --git a/products/cohorts/__init__.py b/products/cohorts/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cohorts/backend/__init__.py b/products/cohorts/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cohorts/backend/apps.py b/products/cohorts/backend/apps.py
new file mode 100644
index 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.py
new file mode 100644
index 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__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..6c080bdd9533
--- /dev/null
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_cohorts_models
diff --git a/posthog/models/cohort/__init__.py b/products/cohorts/backend/models/__init__.py
similarity index 100%
rename from posthog/models/cohort/__init__.py
rename to products/cohorts/backend/models/__init__.py
diff --git a/posthog/models/cohort/calculation_history.py b/products/cohorts/backend/models/calculation_history.py
similarity index 98%
rename from posthog/models/cohort/calculation_history.py
rename to products/cohorts/backend/models/calculation_history.py
index 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 metadata
filters = 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.py
similarity index 97%
rename from posthog/models/cohort/cohort.py
rename to products/cohorts/backend/models/cohort.py
index 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.ManyToManyField
version = 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_cohortpeople
logger.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_cohort
from posthog.personhog_client.gate import use_personhog
+ from products.cohorts.backend.models.util import count_cohort_members, insert_static_cohort
+
current_batch_index = -1
processing_error = None
personhog = 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_cohort
from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE
from posthog.models.person.util import get_persons_by_uuids
+ from products.cohorts.backend.models.util import insert_static_cohort
+
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_members
insert_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_migrations
managed = False
indexes = [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_size
try:
cohort_id = instance.cohort_id
diff --git a/posthog/models/cohort/dependencies.py b/products/cohorts/backend/models/dependencies.py
similarity index 99%
rename from posthog/models/cohort/dependencies.py
rename to products/cohorts/backend/models/dependencies.py
index 0b85cddc39b9..5a8194c0ed5b 100644
--- a/posthog/models/cohort/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -8,10 +8,11 @@ from prometheus_client import Counter
from rest_framework.exceptions import ValidationError
from structlog import get_logger
-from posthog.models.cohort.cohort import Cohort, CohortType, is_cohort_recalculation_only_save
from posthog.models.team.team import Team
from 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 week
COHORT_BACKFILL_DEBOUNCE_SECONDS = 300 # 5 minutes
diff --git a/posthog/models/cohort/sql.py b/products/cohorts/backend/models/sql.py
similarity index 100%
rename from posthog/models/cohort/sql.py
rename to products/cohorts/backend/models/sql.py
diff --git a/posthog/models/cohort/test/test_cohort_personhog.py b/products/cohorts/backend/models/test/test_cohort_personhog.py
similarity index 90%
rename from posthog/models/cohort/test/test_cohort_personhog.py
rename to products/cohorts/backend/models/test/test_cohort_personhog.py
index 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 Q
from parameterized import parameterized_class
-from posthog.models import Cohort, Person, Team
-from posthog.models.cohort.cohort import CohortPeople
+from posthog.models import Person, Team
from posthog.personhog_client.fake_client import fake_personhog_client
from 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.id
self._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 False
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=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 the
cohort 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_cohort
person = 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_cohort
person = 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 False
def 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_membership
person = 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_membership
person = 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 the
public wrapper before dispatch, so the RPC is never called for
out-of-team cohort_ids."""
- from posthog.models.cohort.util import check_cohort_membership
+ from products.cohorts.backend.models.util import check_cohort_membership
other_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 the
in-team ones reach downstream; the caller still gets a dict keyed by
every 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_membership
other_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_cohort
person = 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_ids
p1 = 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_ids
cohort = 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_ids
p1 = 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_ids
other_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_ids
person = 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_members
p1 = 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_members
person = 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() == 1
def 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_members
cohort = 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_members
other_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_members
other_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_members
person = 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_member
person = 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_member
person = 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 False
def test_rejects_cross_team_cohort(self):
- from posthog.models.cohort.util import delete_cohort_member
+ from products.cohorts.backend.models.util import delete_cohort_member
other_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_member
person = 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 = False
def 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_bulk
p1 = 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_bulk
assert delete_cohort_members_bulk(self.team.id, []) == 0
self._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_bulk
person = 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_util
from 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_members
p1 = 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_members
cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")
assert count_cohort_members(self.team.id, cohort.id) == 0
def test_isolates_cross_team_cohort(self):
- from posthog.models.cohort.util import count_cohort_members
+ from products.cohorts.backend.models.util import count_cohort_members
other_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_members
person = 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.py
similarity index 98%
rename from posthog/models/cohort/test/test_dependencies.py
rename to products/cohorts/backend/models/test/test_dependencies.py
index 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 cache
from parameterized import parameterized
from 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 trigger
def 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 flag
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)
def test_backfill_signal_not_triggered_when_person_properties_unchanged(
self, mock_feature_enabled, mock_trigger_backfill
diff --git a/posthog/models/cohort/test/test_util.py b/products/cohorts/backend/models/test/test_util.py
similarity index 99%
rename from posthog/models/cohort/test/test_util.py
rename to products/cohorts/backend/models/test/test_util.py
index 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.py
similarity index 98%
rename from posthog/models/cohort/util.py
rename to products/cohorts/backend/models/util.py
index 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, PropertyGroup
from products.actions.backend.models.action import Action
from 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, CohortPeople
from 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 Django
ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.
"""
- from posthog.models.cohort.cohort import Cohort, CohortPeople
from posthog.models.person.person import READ_DB_FOR_PERSONS
from 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, CohortPeople
from 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, CohortPeople
from 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 CohortPeople
def 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 counts
from replication lag (ORM) or eventual consistency (personhog).
"""
- from posthog.models.cohort.cohort import Cohort, CohortPeople
from 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 0
diff --git a/posthog/models/cohort/validation.py b/products/cohorts/backend/models/validation.py
similarity index 98%
rename from posthog/models/cohort/validation.py
rename to products/cohorts/backend/models/validation.py
index 600b34de893f..8d86f4b06cf8 100644
--- a/posthog/models/cohort/validation.py
+++ b/products/cohorts/backend/models/validation.py
@@ -4,7 +4,7 @@ import structlog
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
-from posthog.models.cohort.cohort import CohortType
+from products.cohorts.backend.models.cohort import CohortType
logger = 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 Cohort
try:
referenced_cohort = Cohort.objects.get(id=cohort_id, team_id=self.team_id)
diff --git a/products/cohorts/package.json b/products/cohorts/package.json
index 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.yaml
new file mode 100644
index 000000000000..8dde1811d933
--- /dev/null
+++ b/products/cohorts/product.yaml
@@ -0,0 +1,3 @@
+name: Cohorts
+owners:
+ - team-feature-flags
diff --git a/products/error_tracking/backend/api/issues.py b/products/error_tracking/backend/api/issues.py
index 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 TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response
-from posthog.models.cohort.cohort import Cohort
from posthog.models.organization import OrganizationMembership
from posthog.tasks.email import send_error_tracking_issue_assigned
+from products.cohorts.backend.models.cohort import Cohort
from products.error_tracking.backend.facade import api as facade_api
from 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.py
index 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 parameterized
from posthog.schema import DateRange, ErrorTrackingQuery
from 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_cohort
from products.error_tracking.backend.hogql_queries.error_tracking_query_runner import ErrorTrackingQueryRunner
from ee.hogai.eval.sandboxed.error_tracking.seeders import _EVAL_DISTINCT_IDS, seed_error_tracking_issues
diff --git a/products/error_tracking/backend/migrations/0017_migrate_cohorts_models.py b/products/error_tracking/backend/migrations/0017_migrate_cohorts_models.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.py
index 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.py
index 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 redirect
from django.urls import path, reverse
from django.utils.html import format_html
-from posthog.models import Cohort
from posthog.models.utils import convert_legacy_metrics
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentHoldout,
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 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, Experimen
from posthog.api.cohort import CohortSerializer
from posthog.event_usage import EventSource, report_user_action
-from posthog.models.cohort import Cohort
from posthog.models.filters.filter import Filter
from posthog.models.signals import mute_selected_signals
from posthog.models.team.extensions import get_or_create_team_extension
@@ -29,6 +28,7 @@ from posthog.models.team.team import Team
from posthog.utils import str_to_bool
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
from 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.py
index 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 Cohort
from posthog.models.group.util import create_group
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
from 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.py
index 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 Cohort
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
index 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, Exper
from posthog.hogql.context import HogQLContext
from 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_query
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
diff --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.py
index 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 Cohort
from posthog.models.group.util import create_group
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.experiment_trends_query_runner import ExperimentTrendsQueryRunner
from products.experiments.backend.hogql_queries.types import ExperimentMetricType
from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout
diff --git a/products/experiments/backend/migrations/0018_migrate_cohorts_models.py b/products/experiments/backend/migrations/0018_migrate_cohorts_models.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 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.py
index 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 APIRequestFactory
from posthog.schema import EventsNode, ExperimentMetric
from posthog.models import Team
-from posthog.models.cohort import Cohort
from posthog.models.team.extensions import get_or_create_team_extension
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.experiment_service import ExperimentService
from 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 Cohort
self._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.py
index 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 status
from posthog.models import Organization, Team
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort.cohort import Cohort
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.user import User
from posthog.test.test_journeys import journeys_for
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentSavedMetric
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 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 Team
from posthog.models.activity_logging.activity_log import Detail, changes_between, load_activity, log_activity
from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response
from 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_dependencies
from 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 HyperCacheDependencyUnavailable
from posthog.utils import is_valid_regex
from posthog.views import format_bytes
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.util import get_all_cohort_dependencies
from products.dashboards.backend.api.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from 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.py
index 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 TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.models import Team
-from posthog.models.cohort import Cohort, CohortOrEmpty
from posthog.models.filters.filter import Filter
from posthog.user_permissions import UserPermissions
+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloads
from products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_team
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 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 redis
from posthog.api.cohort import get_cohort_actors_for_feature_flag
from posthog.constants import AvailableFeature
from posthog.models import GroupTypeMapping, TaggedItem, User
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.cohort import CohortType
from posthog.models.group.group import Group
from posthog.models.group.util import create_group
from posthog.models.organization import Organization, OrganizationMembership
@@ -39,6 +37,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_utils.py b/products/feature_flags/backend/api/test/test_feature_flag_utils.py
index 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_topologically
class 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.py
index 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 timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.models.cohort import Cohort
-from posthog.models.cohort.util import sort_cohorts_topologically
from posthog.models.organization import Organization
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
from 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_topologically
from products.dashboards.backend.api.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/products/feature_flags/backend/flag_matching.py b/products/feature_flags/backend/flag_matching.py
index 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 QuerySet
import structlog
from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING
-from posthog.models.cohort import Cohort, CohortOrEmpty
from posthog.models.filters import Filter
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.group import Group
@@ -34,6 +33,7 @@ from posthog.models.utils import execute_with_timeout
from posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITE
from posthog.queries.base import match_property, properties_to_Q, sanitize_property_key
+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payload
from .models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 031c63d003f1..5507160f13b3 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -45,8 +45,6 @@ import structlog
from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.metrics import TOMBSTONE_COUNTER
-from posthog.models.cohort.cohort import Cohort
-from posthog.models.cohort.dependencies import extract_cohort_dependencies
from posthog.models.team import Team
from 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_dependencies
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index e7c76ac56581..61d763de59f5 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -36,8 +36,6 @@ import structlog
from posthoganalytics import capture_exception
from 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_ids
from 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, Hyper
from posthog.storage.hypercache_manager import HyperCacheManagementConfig
from 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_ids
from 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.py
index 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_cache
from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER, PropertyOperatorType
from posthog.exceptions_capture import capture_exception
from posthog.models.activity_logging.model_activity import ModelActivityMixin
-from posthog.models.cohort import Cohort, CohortOrEmpty
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
@@ -27,6 +26,8 @@ from posthog.models.property.property import Property, PropertyGroup
from posthog.models.signals import mutable_receiver
from posthog.models.utils import RootTeamManager, RootTeamMixin
+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
+
FIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in seconds
logger = structlog.get_logger(__name__)
@@ -401,7 +402,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
seen_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_topologically
if 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.py
index 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_settings
from parameterized import parameterized
from posthog.models import Team
-from posthog.models.cohort.cohort import Cohort
+from products.cohorts.backend.models.cohort import Cohort
from 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.py
index 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_settings
from parameterized import parameterized
-from posthog.models.cohort.cohort import Cohort
from posthog.models.group_type_mapping import (
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
GroupTypeMapping,
@@ -19,6 +18,7 @@ from posthog.models.team.team import Team
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.utils import safe_cache_delete
+from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flags
from 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.py
index 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, User
from 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 Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.api.insight_metadata import generate_insight_metadata
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 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_cache
from posthog.caching.insight_caching_state import TargetCacheAge
from posthog.constants import AvailableFeature
from 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, User
from posthog.models.project import Project
from posthog.test.db_context_capturing import capture_db_queries
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
from products.product_analytics.backend.api.insight import _last_refresh_for_shared_gate
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
index 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 QueryPr
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
-from posthog.models.cohort.util import get_count_operator, get_count_operator_ast
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.user import User
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.util import get_count_operator, get_count_operator_ast
class SeriesWithExtras:
diff --git a/products/replay/backend/migrations/0001_migrate_replay_models.py b/products/replay/backend/migrations/0001_migrate_replay_models.py
new file mode 100644
index 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__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/replay/backend/migrations/max_migration.txt b/products/replay/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..35299ac2ce5b
--- /dev/null
+++ b/products/replay/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_replay_models
diff --git a/products/replay/backend/models/__init__.py b/products/replay/backend/models/__init__.py
new file mode 100644
index 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.py
similarity index 94%
rename from posthog/models/exported_recording.py
rename to products/replay/backend/models/exported_recording.py
index 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"
@property
def 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.py
similarity index 98%
rename from ee/models/session_summaries.py
rename to products/replay/backend/models/session_summaries.py
index 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 GinIndex
from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin
-from posthog.models.team import Team
from posthog.models.user import User
from 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 summary
title = 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 0
return 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.py
similarity index 87%
rename from ee/models/team_session_summaries_config.py
rename to products/replay/backend/models/team_session_summaries_config.py
index 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 logging
from django.db import models
-from posthog.models.team import Team
from posthog.models.team.extensions import register_team_extension_signal
logger = logging.getLogger(__name__)
@@ -15,7 +14,7 @@ CUSTOM_TAG_DESCRIPTION_MAX_LENGTH = 200
class 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.toml
index 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.py
index 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_select
from posthog.hogql.query import execute_hogql_query
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort.cohort import Cohort
from posthog.models.integration import Integration
from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.team.team import Team
@@ -44,6 +43,7 @@ from posthog.models.team.team import Team
from products.actions.backend.models.action import Action
from products.alerts.backend.models.alert import AlertConfiguration
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
# `products.experiments` ships a facade (api.py + contracts.py) but the contract is
diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.py
index 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 BaseTest
from django.utils import timezone
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.cohort.cohort import Cohort
from posthog.models.integration import Integration
from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.user import User
@@ -21,6 +20,7 @@ from posthog.models.user import User
from products.actions.backend.models.action import Action
from products.alerts.backend.models.alert import AlertConfiguration
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 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 status
from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest
from posthog.constants import AvailableFeature
from posthog.models import Person, Team
-from posthog.models.cohort.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
from products.product_tours.backend.models import ProductTour
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index 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 UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import ExportRendererAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
-from posthog.models import Cohort, Team, User
+from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Detail, log_activity
from posthog.rate_limit import (
AIBurstRateThrottle,
@@ -39,6 +39,7 @@ from posthog.rate_limit import (
from posthog.security.url_validation import is_url_allowed
from posthog.utils import relative_date_parse_with_delta_mapping
+from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS, MAX_TARGET_WIDTHS
from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
from products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot
diff --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.py
index 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 Cohort
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
index 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_tests
from posthog.clickhouse.client import sync_execute
-from posthog.models import Cohort, Element, Person
+from posthog.models import Element, Person
from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 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 HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client.execute import sync_execute
-from posthog.models import Cohort, Element
+from posthog.models import Element
from posthog.models.utils import uuid7
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
from 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.py
index 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 Element
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
nan_value = float("nan")
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 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 Team
from posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation
from 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_dependencies
from 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.py
index 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 status
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from 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, User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.cohorts.backend.models.cohort import Cohort
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
webhook_template = MOCK_NODE_TEMPLATES[0]
diff --git a/tach.toml b/tach.toml
index 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",