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.

feat(cohorts): report IDs that matched no person on static cohort import (#75780)

posthog[bot]135f740b9f0f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ff411f27e338..edaed6688bbc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7185,13 +7185,13 @@ snapshots:
scenes-app-oauth-authorize--with-required-scopes--light:
hash: v1.k794b7964.e951fac95b4bfb2628774621d6ac6f479abf8e8d10efb58cbcfad998c62a96be.-ZMfxl773NvFryFdUT6AJlVnUiwplGzEUPhvBD6kSWw
scenes-app-people-cohorts--cohort-edit-dynamic--dark:
- hash: v1.k794b7964.e31408a5ef822c097935dc6ce7b08957ed8df063ec55d50a505fca1ad48389f0.PhHWfr9lECOQQ6thPGblR5uayOXvpLGngJFZ9fZrBRs
+ hash: v1.k794b7964.64bc82476828e61d420a9fc2ef3c550d45acf9c24f8d0bec694f803ecd147df7.eqlptg68mBa-l30eKEMGIEqcHeTSh2GAlhd0ybVid-k
scenes-app-people-cohorts--cohort-edit-dynamic--light:
- hash: v1.k794b7964.af17394f32809d5fb7e65e8f3298be02447f4481ff41645350514a7f16ac8545.f1AXZKpaB9lZ6zPTIYL6gMPVqdUbN_T7QdgB-doywX8
+ hash: v1.k794b7964.16bae00697363fb140788023823ca272a1f57bf2b9cc4984f62f6b39e098b87a.sga7qTbJWVb7MG-E8DSdsDVlcJm9nBZzZAY6TxrBIUw
scenes-app-people-cohorts--cohort-edit-static--dark:
- hash: v1.k794b7964.02d0747e4c10c736c348f8ec64e6c40f7613e9b3c750802c707e807f8d513199.uayJO_46qM2XEfrPzVhPHBxuAi1bH7wTaAc41c-PngY
+ hash: v1.k794b7964.9a7ecdb86d86a13d5ea9c1723b11d6ee9e712851ce610a1f22087f17e4a13c2e.PFmgqeNOFUte6e2WGILBNqWzV9SGyXqGATqt9qX8UcQ
scenes-app-people-cohorts--cohort-edit-static--light:
- hash: v1.k794b7964.ccfdd12041c23093f9dfdea3d74a8be8672f017b838ca9171c9713eb49418899.NFNZNNezQtqlEbBSbXoGbIKJQllVOfqNMGJgCYdKRGc
+ hash: v1.k794b7964.26110785e678568b3be042baeba86b30387e473843b8a65aa48b11edfdd24af7.5Z104Qke5HLoSoHtuKjQoVVoTGvswRtlNGWgu5Y6lL8
scenes-app-people-cohorts--cohort-new--dark:
hash: v1.k794b7964.0c0b9da85f85dac4c299d0527725f192c0c07d204e28462a64736552aaba735b.aX2s9DQu-pQIZHJDYBeZXL9lyni7w6PSMh3u3b_cvhA
scenes-app-people-cohorts--cohort-new--light:
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
index 677a615bd8ff..3f31f8ed918e 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
@@ -493,6 +493,59 @@ describe('cohortEditLogic', () => {
)
})
+ describe('import warning', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('stays hidden after an import that matched every ID', async () => {
+ const cohortId = 5
+ const cohortName = 'Clean import cohort'
+ useMocks({
+ get: {
+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {
+ ...mockCohort,
+ id: cohortId,
+ name: cohortName,
+ is_static: true,
+ last_import_total_count: 5,
+ last_import_unmatched_count: 0,
+ },
+ },
+ })
+
+ render(<CohortEdit id={cohortId} />)
+
+ await screen.findAllByText(cohortName)
+ expect(screen.queryByText("Some IDs in the last import didn't match a person")).not.toBeInTheDocument()
+ })
+
+ it('shows the unmatched and total ID counts after a partial import', async () => {
+ const cohortId = 6
+ const cohortName = 'Partial import cohort'
+ useMocks({
+ get: {
+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {
+ ...mockCohort,
+ id: cohortId,
+ name: cohortName,
+ is_static: true,
+ last_import_total_count: 7,
+ last_import_unmatched_count: 2,
+ },
+ },
+ })
+
+ render(<CohortEdit id={cohortId} />)
+
+ await screen.findAllByText(cohortName)
+ const heading = screen.getByText("Some IDs in the last import didn't match a person")
+ expect(heading).toBeInTheDocument()
+ expect(heading.closest('[aria-live="polite"]')).toBeInTheDocument()
+ expect(screen.getByText(/2 of 7 IDs weren't added to this cohort/)).toBeInTheDocument()
+ })
+ })
+
describe('criteria row type switching', () => {
afterEach(() => {
cleanup()
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index aab4b6a86e00..21547a8ba53e 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -118,6 +118,24 @@ function UsedInBanner({ usedIn }: { usedIn: CohortUsedInResponseApi }): JSX.Elem
)
}
+function UnmatchedImportBanner({ cohort }: { cohort: CohortType }): JSX.Element | null {
+ const unmatched = cohort.last_import_unmatched_count
+ const total = cohort.last_import_total_count
+ if (!unmatched || !total) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="warning">
+ <h4 className="font-semibold mb-1">Some IDs in the last import didn't match a person</h4>
+ <p className="mb-0">
+ {unmatched.toLocaleString()} of {total.toLocaleString()} IDs weren't added to this cohort because they
+ don't match a person in this project. Check that the IDs are correct and come from this project.
+ </p>
+ </LemonBanner>
+ )
+}
+
export interface CohortEditProps {
id?: CohortType['id']
attachTo?: BuiltLogic<Logic> | LogicWrapper<Logic>
@@ -526,6 +544,11 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</div>
</div>
</SceneSection>
+ {!isNewCohort && (
+ <div aria-live="polite">
+ <UnmatchedImportBanner cohort={cohort} />
+ </div>
+ )}
{!isNewCohort && usedIn && <UsedInBanner usedIn={usedIn} />}
{cohort.is_static && staticCohortMode === 'criteria' ? (
<>
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 9dfe509c07b3..66f7e64bfffa 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -171,6 +171,26 @@ describe('cohortEditLogic', () => {
})
})
+ describe('calculation polling', () => {
+ it('refreshes import counts when calculation finishes', async () => {
+ await initCohortLogic({ id: 1 })
+
+ await expectLogic(logic, () => {
+ logic.actions.checkIfFinishedCalculating({
+ ...mockCohort,
+ is_calculating: false,
+ last_import_total_count: 5,
+ last_import_unmatched_count: 3,
+ })
+ }).toMatchValues({
+ cohort: partial({
+ last_import_total_count: 5,
+ last_import_unmatched_count: 3,
+ }),
+ })
+ })
+ })
+
it('delete cohort', async () => {
await initCohortLogic({ id: 1 })
await expectLogic(logic, async () => {
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 5e10dd4af8fd..e29d4cc65867 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -434,6 +434,8 @@ export interface cohortEditLogicActions {
is_static?: boolean | undefined
last_calculation?: string | undefined
last_error_message?: string | null | undefined
+ last_import_total_count?: number | null | undefined
+ last_import_unmatched_count?: number | null | undefined
name?: string | undefined
pending_version?: number | null | undefined
version?: number | null | undefined
@@ -463,6 +465,8 @@ export interface cohortEditLogicActions {
is_static?: boolean | undefined
last_calculation?: string | undefined
last_error_message?: string | null | undefined
+ last_import_total_count?: number | null | undefined
+ last_import_unmatched_count?: number | null | undefined
name?: string | undefined
pending_version?: number | null | undefined
version?: number | null | undefined
@@ -1147,6 +1151,8 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
errors_calculating: cohort.errors_calculating,
last_calculation: cohort.last_calculation,
count: cohort.count,
+ last_import_total_count: cohort.last_import_total_count,
+ last_import_unmatched_count: cohort.last_import_unmatched_count,
version: cohort.version,
pending_version: cohort.pending_version,
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3d5fa46f32b4..e5b6a54e4fc7 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1853,6 +1853,10 @@ export interface CohortType {
errors_calculating?: number
last_calculation?: string
last_error_message?: string | null
+ /** Number of IDs supplied by the most recent static cohort import. */
+ last_import_total_count?: number | null
+ /** How many of those IDs matched no person, and so were left out of the cohort. */
+ last_import_unmatched_count?: number | null
is_static?: boolean
name?: string
csv?: File
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 7a67d8c54cfc..2827faf2ea10 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -648,6 +648,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"errors_calculating",
"last_error_message",
"count",
+ "last_import_total_count",
+ "last_import_unmatched_count",
"is_static",
"cohort_type",
"condition_type",
@@ -668,6 +670,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"errors_calculating",
"last_error_message",
"count",
+ "last_import_total_count",
+ "last_import_unmatched_count",
"experiment_set",
"condition_type",
]
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index d7902753111c..cd1405304b01 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -6825,7 +6825,7 @@ [email protected]
with patch.object(
Cohort,
"_get_uuids_for_emails_batch_ch",
- return_value=[str(person1.uuid), str(person2.uuid)],
+ return_value=([str(person1.uuid), str(person2.uuid)], {"[email protected]", "[email protected]"}),
):
response = self.client.post(
f"/api/projects/{self.team.id}/cohorts/",
@@ -6969,7 +6969,7 @@ Jane Smith,user456,[email protected]
with patch.object(
Cohort,
"_get_uuids_for_emails_batch_ch",
- return_value=[str(person.uuid)],
+ return_value=([str(person.uuid)], {"[email protected]"}),
) as ch_mock:
response = self.client.post(
f"/api/projects/{self.team.id}/cohorts/",
@@ -6985,7 +6985,7 @@ Jane Smith,user456,[email protected]
def test_insert_users_by_email_always_uses_clickhouse(self):
cohort = Cohort.objects.create(team=self.team, name="ch-only", is_static=True)
- with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=[]) as ch_mock:
+ with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=([], set())) as ch_mock:
cohort.insert_users_by_email(["[email protected]"], team_id=self.team.id)
ch_mock.assert_called_once()
@@ -6999,7 +6999,7 @@ Jane Smith,user456,[email protected]
)
def test_email_property_key_is_accepted_and_always_routes_to_clickhouse(self, _name, email_property_key):
cohort = Cohort.objects.create(team=self.team, name="key-compat", is_static=True)
- with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=[]) as ch_mock:
+ with patch.object(Cohort, "_get_uuids_for_emails_batch_ch", return_value=([], set())) as ch_mock:
cohort.insert_users_by_email(["[email protected]"], team_id=self.team.id, email_property_key=email_property_key)
ch_mock.assert_called_once()
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 3ea3ed61efd3..17fa67726215 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -579,20 +579,43 @@ def get_person_ids_and_uuids_by_uuids(team_id: int, uuids: list[str], *, concurr
def get_person_uuids_by_distinct_ids(team_id: int, distinct_ids: list[str]) -> list[str]:
"""Return person UUIDs for the given distinct IDs.
+ Lightweight UUID-only variant — uses field masking to skip fetching
+ properties and other heavy fields from personhog.
+ """
+ uuids, _ = get_person_uuids_and_matched_distinct_ids(team_id, distinct_ids)
+ return uuids
+
+
+def get_person_uuids_and_matched_distinct_ids(team_id: int, distinct_ids: list[str]) -> tuple[list[str], set[str]]:
+ """Return person UUIDs for the given distinct IDs, plus the distinct IDs that resolved.
+
+ The second element lets callers tell "this distinct ID has no person row" apart from
+ "several distinct IDs collapsed onto one person", which a bare UUID list can't express.
+
Lightweight UUID-only variant — uses field masking to skip fetching
properties and other heavy fields from personhog.
"""
if not distinct_ids:
- return []
+ return [], set()
- def personhog_fn() -> list[str]:
+ def personhog_fn() -> tuple[list[str], set[str]]:
results = _batched_get_persons_by_distinct_ids(
team_id,
distinct_ids,
"get_person_uuids_by_distinct_ids",
+ # Keep every match so the caller sees which distinct IDs resolved; dedupe by person below.
+ deduplicate_by_person=False,
read_options=_UUID_ONLY_READ_OPTIONS,
)
- return [r.person.uuid for r in results]
+ matched: set[str] = set()
+ seen_person_ids: set[int] = set()
+ uuids: list[str] = []
+ for r in results:
+ matched.add(r.distinct_id)
+ if r.person.id not in seen_person_ids:
+ seen_person_ids.add(r.person.id)
+ uuids.append(r.person.uuid)
+ return uuids, matched
return personhog_call(
"get_person_uuids_by_distinct_ids",
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index c4aad78ba18f..d270c8e141df 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -160,6 +160,8 @@
'is_static',
'kind',
'last_calculation_duration_ms',
+ 'last_import_total_count',
+ 'last_import_unmatched_count',
'name',
'query',
])
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index daec83b0b700..e15381f51dff 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -33,7 +33,7 @@ from products.cohorts.backend.backfill.runs import (
)
from products.cohorts.backend.models.backfill import CohortBackfillKind
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
-from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
+from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, ImportResolution
from products.cohorts.backend.models.util import (
COHORT_STATS_COLLECTION_DELAY_SECONDS,
get_all_cohort_dependencies,
@@ -542,6 +542,7 @@ def calculate_cohort_from_list(
if team_id is None:
team_id = cohort.team_id
+ import_resolution = ImportResolution()
if id_type not in ("distinct_id", "person_id", "email"):
raise ValueError(f"Unsupported id_type: {id_type}")
@@ -551,12 +552,32 @@ def calculate_cohort_from_list(
# InsertCohortMembers RPC dedupes on person id), so re-running the whole list adds no duplicates.
try:
if id_type == "distinct_id":
- batch_count = cohort.insert_users_by_list(items, team_id=team_id, raise_on_error=True)
+ batch_count = cohort.insert_users_by_list(
+ items, team_id=team_id, raise_on_error=True, import_resolution=import_resolution
+ )
elif id_type == "person_id":
- batch_count = cohort.insert_users_list_by_uuid(items, team_id=team_id, raise_on_error=True)
+ batch_count = cohort.insert_users_list_by_uuid(
+ items, team_id=team_id, raise_on_error=True, import_resolution=import_resolution
+ )
else:
batch_count = cohort.insert_users_by_email(
- items, team_id=team_id, email_property_key=email_property_key, raise_on_error=True
+ items,
+ team_id=team_id,
+ email_property_key=email_property_key,
+ raise_on_error=True,
+ import_resolution=import_resolution,
+ )
+
+ cohort.last_import_total_count = import_resolution.total
+ cohort.last_import_unmatched_count = import_resolution.unmatched
+ cohort.save(update_fields=["last_import_total_count", "last_import_unmatched_count"])
+ if import_resolution.unmatched:
+ logger.warning(
+ "cohort_import_unmatched_ids",
+ cohort_id=cohort.id,
+ team_id=team_id,
+ total=import_resolution.total,
+ unmatched=import_resolution.unmatched,
)
except Exception as err:
# raise_on_error also hands terminal-state finalization to us, so record the failure, but
@@ -565,7 +586,6 @@ def calculate_cohort_from_list(
if _is_final_attempt(self, err):
cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)
raise
-
logger.warn(
"Cohort {}: {:,} items in {} batches from CSV completed in {:.2f}s".format(
cohort.pk, len(items), batch_count, (time.time() - start_time)
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index a8adb16076a7..c776bba7d3c9 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -1456,6 +1456,33 @@ class TestCalculateCohortFromListRetries(APIBaseTest):
finally:
task.pop_request()
+ def test_failed_import_keeps_previous_resolution_counts(self) -> None:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ is_static=True,
+ last_import_total_count=10,
+ last_import_unmatched_count=2,
+ )
+ task = calculate_cohort_from_list
+ task.push_request(retries=0, called_directly=True, is_eager=True)
+ try:
+ with (
+ patch.object(Cohort, "insert_users_by_email", side_effect=RuntimeError("lookup failed")),
+ self.assertRaisesRegex(RuntimeError, "lookup failed"),
+ ):
+ task.run(
+ cohort.id,
+ team_id=self.team.id,
+ id_type="email",
+ )
+ finally:
+ task.pop_request()
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.last_import_total_count, 10)
+ self.assertEqual(cohort.last_import_unmatched_count, 2)
+
@parameterized.expand(
[
("retries_exhausted", ClickHouseAtCapacity, calculate_cohort_from_list.max_retries, False),
diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.py
index 5625a3c93021..9119ce8abcb7 100644
--- a/posthog/test/test_cohort_model.py
+++ b/posthog/test/test_cohort_model.py
@@ -3,6 +3,7 @@ from datetime import UTC, datetime
import pytest
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
@@ -13,9 +14,10 @@ from posthog.clickhouse.client import sync_execute
from posthog.helpers.batch_iterators import FunctionBatchIterator
from posthog.models import Person, Team
from posthog.models.person.util import get_person_by_id
+from posthog.tasks.calculate_cohort import calculate_cohort_from_list
from posthog.test.persons import add_cohort_members, create_person
-from products.cohorts.backend.models.cohort import Cohort, CohortConditionFlags, CohortType
+from products.cohorts.backend.models.cohort import Cohort, CohortConditionFlags, CohortType, ImportResolution
from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID
from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
@@ -76,6 +78,101 @@ class TestCohort(BaseTest):
self.assertEqual(count_cohort_members(self.team.id, cohort.pk), 11)
self.assertEqual(cohort.is_calculating, False)
+ def test_csv_import_records_unmatched_distinct_ids(self):
+ create_person(team=self.team, distinct_ids=["000"])
+ create_person(team=self.team, distinct_ids=["123"])
+
+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)
+ with patch("posthog.tasks.calculate_cohort.logger.warning") as warning:
+ calculate_cohort_from_list(
+ cohort.id,
+ ["123", "000", "anonymous-1", "anonymous-2", "anonymous-3"],
+ team_id=self.team.id,
+ )
+ cohort.refresh_from_db()
+
+ self.assertEqual(cohort.count, 2)
+ self.assertEqual(cohort.last_import_total_count, 5)
+ self.assertEqual(cohort.last_import_unmatched_count, 3)
+ warning.assert_called_once_with(
+ "cohort_import_unmatched_ids",
+ cohort_id=cohort.id,
+ team_id=self.team.id,
+ total=5,
+ unmatched=3,
+ )
+
+ def test_distinct_id_resolution_accumulates_across_batches(self):
+ create_person(team=self.team, distinct_ids=["000"])
+ create_person(team=self.team, distinct_ids=["123"])
+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)
+ resolution = ImportResolution()
+
+ cohort.insert_users_by_list(
+ ["123", "000", "anonymous-1", "anonymous-2", "anonymous-3"],
+ team_id=self.team.id,
+ batch_size=2,
+ import_resolution=resolution,
+ )
+
+ self.assertEqual(resolution.total, 5)
+ self.assertEqual(resolution.unmatched, 3)
+
+ def test_csv_import_records_unmatched_emails(self):
+ person1 = create_person(team=self.team, distinct_ids=["person-1"])
+ person2 = create_person(team=self.team, distinct_ids=["person-2"])
+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)
+
+ with patch.object(
+ Cohort,
+ "_get_uuids_for_emails_batch_ch",
+ return_value=([str(person1.uuid), str(person2.uuid)], {"[email protected]", "[email protected]"}),
+ ):
+ calculate_cohort_from_list(
+ cohort.id,
+ team_id=self.team.id,
+ id_type="email",
+ )
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.count, 2)
+ self.assertEqual(cohort.last_import_total_count, 3)
+ self.assertEqual(cohort.last_import_unmatched_count, 1)
+
+ def test_csv_import_records_unmatched_person_uuids(self):
+ person1 = create_person(team=self.team, distinct_ids=["person-1"])
+ person2 = create_person(team=self.team, distinct_ids=["person-2"])
+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)
+
+ calculate_cohort_from_list(
+ cohort.id,
+ [str(person1.uuid), str(person2.uuid), str(uuid.uuid4())],
+ team_id=self.team.id,
+ id_type="person_id",
+ )
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.count, 2)
+ self.assertEqual(cohort.last_import_total_count, 3)
+ self.assertEqual(cohort.last_import_unmatched_count, 1)
+
+ def test_membership_addition_does_not_replace_import_counts(self):
+ person = create_person(team=self.team, distinct_ids=["002"])
+ cohort = Cohort.objects.create(
+ team=self.team,
+ groups=[],
+ is_static=True,
+ last_import_total_count=5,
+ last_import_unmatched_count=3,
+ )
+ cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)
+ cohort.refresh_from_db()
+
+ self.assertEqual(cohort.count, 1)
+ self.assertEqual(cohort.last_import_total_count, 5)
+ self.assertEqual(cohort.last_import_unmatched_count, 3)
+
@pytest.mark.ee
def test_calculating_cohort_clickhouse(self):
cohort = Cohort.objects.create(
@@ -877,6 +974,16 @@ class TestCohortComputeConditionType(SimpleTestCase):
self.assertEqual(Cohort.compute_condition_type(filters), expected)
+class TestImportResolution(SimpleTestCase):
+ def test_deduplicates_inputs_across_batches(self) -> None:
+ resolution = ImportResolution()
+ resolution.record(["matched", "duplicate"], {"matched"})
+ resolution.record(["duplicate", "unmatched"], {"duplicate"})
+
+ self.assertEqual(resolution.total, 3)
+ self.assertEqual(resolution.unmatched, 1)
+
+
class TestCohortConditionTypeDerivedOnSave(BaseTest):
CLASS_DATA_LEVEL_SETUP = False
diff --git a/products/cohorts/backend/migrations/0011_cohort_import_resolution_counts.py b/products/cohorts/backend/migrations/0011_cohort_import_resolution_counts.py
new file mode 100644
index 000000000000..4a3965548ec7
--- /dev/null
+++ b/products/cohorts/backend/migrations/0011_cohort_import_resolution_counts.py
@@ -0,0 +1,28 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("cohorts", "0010_alter_cohortbackfillrun_marker_watch"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="cohort",
+ name="last_import_total_count",
+ field=models.IntegerField(
+ blank=True,
+ null=True,
+ help_text="Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.",
+ ),
+ ),
+ migrations.AddField(
+ model_name="cohort",
+ name="last_import_unmatched_count",
+ field=models.IntegerField(
+ blank=True,
+ null=True,
+ help_text="How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.",
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
index 11eac0a4a9bf..a58f93c81a99 100644
--- a/products/cohorts/backend/migrations/max_migration.txt
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0010_alter_cohortbackfillrun_marker_watch
+0011_cohort_import_resolution_counts
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 85267ce12d29..b04b548197b6 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -139,10 +139,42 @@ class CohortManager(RootTeamManager):
# in _safe_save_cohort_state must remain subsets of this set, otherwise the
# is_cohort_recalculation_only_save guard will incorrectly allow signal handlers to fire.
COHORT_RECALCULATION_FIELDS = frozenset(
- {"is_calculating", "last_calculation", "errors_calculating", "last_error_at", "count"}
+ {
+ "is_calculating",
+ "last_calculation",
+ "errors_calculating",
+ "last_error_at",
+ "count",
+ "last_import_total_count",
+ "last_import_unmatched_count",
+ }
)
+class ImportResolution:
+ """Accumulates matched and unmatched import IDs, deduplicated across batches."""
+
+ def __init__(self) -> None:
+ self.inputs: set[str] = set()
+ self.matched_inputs: set[str] = set()
+
+ def record(self, inputs: list[str], matched_inputs: set[str]) -> None:
+ self.inputs.update(inputs)
+ self.matched_inputs.update(matched_inputs)
+
+ @property
+ def total(self) -> int:
+ return len(self.inputs)
+
+ @property
+ def unmatched(self) -> int:
+ return len(self.inputs - self.matched_inputs)
+
+
+def _normalize_uuid(value: Any) -> str:
+ return str(UUID(str(value)))
+
+
def is_cohort_recalculation_only_save(kwargs: dict) -> bool:
"""Return True when a post_save signal was triggered only by recalculation bookkeeping fields."""
update_fields = kwargs.get("update_fields")
@@ -238,6 +270,17 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
person_filters_shape_hash = models.CharField(max_length=64, null=True, blank=True)
last_realtime_cohort_calculation_at = models.DateTimeField(blank=True, null=True)
+ last_import_total_count = models.IntegerField(
+ blank=True,
+ null=True,
+ help_text="Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.",
+ )
+ last_import_unmatched_count = models.IntegerField(
+ blank=True,
+ null=True,
+ help_text="How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.",
+ )
+
is_static = models.BooleanField(default=False)
kind = models.CharField(
max_length=50,
@@ -704,6 +747,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
team_id: Optional[int] = None,
batch_size: int = DEFAULT_COHORT_INSERT_BATCH_SIZE,
raise_on_error: bool = False,
+ import_resolution: ImportResolution | None = None,
) -> int:
"""
Insert a list of users identified by their distinct ID into the cohort, for the given team.
@@ -716,6 +760,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
state is left for the caller to finalize, instead of being swallowed and
recorded on the cohort here. Use when the caller must not treat a partial
insert as success.
+ import_resolution: Optional accumulator for deduplicated matched and unmatched IDs.
"""
if team_id is None:
team_id = self.team_id
@@ -727,12 +772,16 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
flush_persons_and_events()
def create_uuid_batch(batch_index: int, batch_size: int) -> list[str]:
- from posthog.models.person.util import get_person_uuids_by_distinct_ids
+ from posthog.models.person.util import get_person_uuids_and_matched_distinct_ids
start_idx = batch_index * batch_size
end_idx = start_idx + batch_size
+ batch_items = items[start_idx:end_idx]
with personhog_caller_tag("cohorts/uuid-batch"):
- return get_person_uuids_by_distinct_ids(team_id, items[start_idx:end_idx])
+ uuids, matched = get_person_uuids_and_matched_distinct_ids(team_id, batch_items)
+ if import_resolution is not None:
+ import_resolution.record(batch_items, matched)
+ return uuids
batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))
return self._insert_users_list_with_batching(
@@ -746,6 +795,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
*,
team_id: int,
raise_on_error: bool = False,
+ import_resolution: ImportResolution | None = None,
) -> int:
"""
Insert a list of users identified by their UUID into the cohort, for the given team.
@@ -758,14 +808,24 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
cohort state is left for the caller to finalize, instead of being swallowed
and recorded on the cohort here. Use when the caller records its own
success/failure outcome and must not treat a partial insert as success.
+ import_resolution: Optional accumulator for deduplicated matched and unmatched UUIDs.
Returns:
The number of batches processed.
"""
+ def insert_batch(batch: list[str]) -> None:
+ matched = self._insert_batch_via_personhog(batch, True, team_id=team_id)
+ if import_resolution is not None:
+ import_resolution.record([_normalize_uuid(item) for item in batch], matched)
+
batch_iterator = ArrayBatchIterator(items, batch_size=batchsize)
return self._insert_users_list_with_batching(
- batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error
+ batch_iterator,
+ insert_in_clickhouse=True,
+ team_id=team_id,
+ raise_on_error=raise_on_error,
+ insert_batch=insert_batch,
)
def insert_users_list_by_id_uuid_pairs_skip_validation(
@@ -812,6 +872,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
batch_size: int = DEFAULT_COHORT_INSERT_BATCH_SIZE,
email_property_key: str | None = None,
raise_on_error: bool = False,
+ import_resolution: ImportResolution | None = None,
) -> int:
"""
Insert a list of users identified by their email address into the cohort, for the given team.
@@ -825,6 +886,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
state is left for the caller to finalize, instead of being swallowed and
recorded on the cohort here. Use when the caller must not treat a partial
insert as success.
+ import_resolution: Optional accumulator for deduplicated matched and unmatched emails.
"""
if team_id is None:
team_id = self.team_id
@@ -838,19 +900,23 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
def create_uuid_batch(batch_index: int, batch_size: int) -> list[str]:
start_idx = batch_index * batch_size
end_idx = start_idx + batch_size
- return self._get_uuids_for_emails_batch_ch(items[start_idx:end_idx], team_id)
+ batch_items = items[start_idx:end_idx]
+ uuids, matched = self._get_uuids_for_emails_batch_ch(batch_items, team_id)
+ if import_resolution is not None:
+ import_resolution.record([email.strip().lower() for email in batch_items], matched)
+ return uuids
batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))
return self._insert_users_list_with_batching(
batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error
)
- def _get_uuids_for_emails_batch_ch(self, emails: list[str], team_id: int) -> list[str]:
+ def _get_uuids_for_emails_batch_ch(self, emails: list[str], team_id: int) -> tuple[list[str], set[str]]:
if not emails:
- return []
+ return [], set()
query = """
- SELECT person.id
+ SELECT person.id, argMax(person.pmat_email, person.version)
FROM person
WHERE person.team_id = %(team_id)s
AND person.pmat_email IN %(emails)s
@@ -861,7 +927,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
result = sync_execute(query, {"team_id": team_id, "emails": emails})
- return [str(row[0]) for row in result]
+ return [str(row[0]) for row in result], {str(row[1]).strip().lower() for row in result}
def insert_users_list_by_uuid_into_pg_only(
self,
@@ -972,15 +1038,18 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
insert_in_clickhouse: bool,
*,
team_id: int,
- ) -> None:
+ ) -> set[str]:
"""Personhog path for inserting a single batch of cohort members.
Resolves UUIDs → person IDs via personhog (field-masked — membership only needs
id/uuid, not properties or distinct IDs), then writes the resolved batch.
+
+ Returns the UUIDs that resolved to people in the team.
"""
with personhog_caller_tag("cohorts/static-insert"):
id_uuid_pairs = get_person_ids_and_uuids_by_uuids(team_id, batch)
self._insert_resolved_batch(id_uuid_pairs, insert_in_clickhouse=insert_in_clickhouse, team_id=team_id)
+ return {_normalize_uuid(person_uuid) for _, person_uuid in id_uuid_pairs}
def _insert_resolved_batch(
self,
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 910de2a80622..369c82be51c1 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -338,6 +338,16 @@ export interface CohortApi {
readonly last_error_message: string | null
/** @nullable */
readonly count: number | null
+ /**
+ * Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.
+ * @nullable
+ */
+ readonly last_import_total_count: number | null
+ /**
+ * How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.
+ * @nullable
+ */
+ readonly last_import_unmatched_count: number | null
is_static?: boolean
/** Type of cohort based on filter complexity
*
@@ -395,6 +405,16 @@ export interface PatchedCohortApi {
readonly last_error_message?: string | null
/** @nullable */
readonly count?: number | null
+ /**
+ * Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.
+ * @nullable
+ */
+ readonly last_import_total_count?: number | null
+ /**
+ * How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.
+ * @nullable
+ */
+ readonly last_import_unmatched_count?: number | null
is_static?: boolean
/** Type of cohort based on filter complexity
*
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 1347d8c4bac2..008e2c709915 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -794,6 +794,8 @@
"posthog_cohort"."behavioral_filters_shape_hash",
"posthog_cohort"."person_filters_shape_hash",
"posthog_cohort"."last_realtime_cohort_calculation_at",
+ "posthog_cohort"."last_import_total_count",
+ "posthog_cohort"."last_import_unmatched_count",
"posthog_cohort"."is_static",
"posthog_cohort"."kind",
"posthog_cohort"."cohort_type",
@@ -1169,6 +1171,8 @@
"posthog_cohort"."behavioral_filters_shape_hash",
"posthog_cohort"."person_filters_shape_hash",
"posthog_cohort"."last_realtime_cohort_calculation_at",
+ "posthog_cohort"."last_import_total_count",
+ "posthog_cohort"."last_import_unmatched_count",
"posthog_cohort"."is_static",
"posthog_cohort"."kind",
"posthog_cohort"."cohort_type",
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 75a97e8ba1db..ddec0e2fa983 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -130,6 +130,8 @@ _COHORT_RECALCULATION_FIELDS = frozenset(
"last_calculation_duration_ms",
"errors_calculating",
"last_error_at",
+ "last_import_total_count",
+ "last_import_unmatched_count",
# NOTE: `groups` is the legacy cohort-condition field (deprecated in favour of
# `filters`). calculate_people_ch() always saves it in update_fields even when
# unchanged (see cohort.py:347). Real definition changes go through a full save
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index 266a62c7d456..38b2ce77cf0d 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -3986,6 +3986,8 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):
("is_calculating", "is_calculating", True),
("count", "count", 100),
("version", "version", 2),
+ ("last_import_total_count", "last_import_total_count", 5),
+ ("last_import_unmatched_count", "last_import_unmatched_count", 3),
]
)
@patch("django.db.transaction.on_commit", lambda fn: fn())
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1e394a8510c9..4496e530e403 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17523,6 +17523,16 @@ export namespace Schemas {
readonly last_error_message: string | null;
/** @nullable */
readonly count: number | null;
+ /**
+ * Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.
+ * @nullable
+ */
+ readonly last_import_total_count: number | null;
+ /**
+ * How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.
+ * @nullable
+ */
+ readonly last_import_unmatched_count: number | null;
is_static?: boolean;
/** Type of cohort based on filter complexity
*
@@ -57339,6 +57349,16 @@ export namespace Schemas {
readonly last_error_message?: string | null;
/** @nullable */
readonly count?: number | null;
+ /**
+ * Number of IDs supplied by the most recent static cohort import. Null if the cohort was never populated from a list of IDs.
+ * @nullable
+ */
+ readonly last_import_total_count?: number | null;
+ /**
+ * How many of the IDs in the most recent static cohort import matched no person, and so were not added to the cohort.
+ * @nullable
+ */
+ readonly last_import_unmatched_count?: number | null;
is_static?: boolean;
/** Type of cohort based on filter complexity
*