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(workflows): import people from an uploaded list into a cohort (#113268)

Harley Alexander84e4b1ef835a
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 4afb3859815e..bcd83b487f24 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -161,6 +161,23 @@ class AudiencePage:
has_more: bool
+class PeopleImportInvalid(Exception):
+ """The upload cannot be used. The message is shown to the person who sent it."""
+
+
+@frozen
+class PeopleImportSummary:
+ """What an uploaded people list kept, and how many rows it dropped and why."""
+
+ cohort_id: int
+ row_count: int
+ new_people: int
+ columns: list[str]
+ dropped_invalid_email: int
+ dropped_duplicate_email: int
+ dropped_too_large: int
+
+
@frozen
class EmailSendingTierLimits:
"""What a trust tier allows: two send-rate caps and a maximum batch audience."""
diff --git a/products/workflows/backend/facade/people_import.py b/products/workflows/backend/facade/people_import.py
new file mode 100644
index 000000000000..cd335a39d557
--- /dev/null
+++ b/products/workflows/backend/facade/people_import.py
@@ -0,0 +1,6 @@
+"""Uploaded people lists: each row creates or updates a person, and the people form a static cohort."""
+
+from products.workflows.backend.facade.contracts import PeopleImportInvalid
+from products.workflows.backend.services.people_import import MAX_PEOPLE_IMPORT_ROWS, start_people_import
+
+__all__ = ["MAX_PEOPLE_IMPORT_ROWS", "PeopleImportInvalid", "start_people_import"]
diff --git a/products/workflows/backend/presentation/views/people_imports.py b/products/workflows/backend/presentation/views/people_imports.py
new file mode 100644
index 000000000000..9c5b20aecfc6
--- /dev/null
+++ b/products/workflows/backend/presentation/views/people_imports.py
@@ -0,0 +1,70 @@
+from typing import Any, cast
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import exceptions, serializers, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.user import User
+
+from products.workflows.backend.facade.people_import import (
+ MAX_PEOPLE_IMPORT_ROWS,
+ PeopleImportInvalid,
+ start_people_import,
+)
+
+
+class PeopleImportCreateSerializer(serializers.Serializer):
+ name = serializers.CharField(max_length=400, help_text="Name of the static cohort that holds the imported people.")
+ rows = serializers.ListField(
+ child=serializers.DictField(child=serializers.CharField(allow_blank=True)),
+ max_length=MAX_PEOPLE_IMPORT_ROWS,
+ help_text=(
+ 'One object per person. Each needs "email". An optional "distinct_id" picks the person to update or '
+ 'create, and an "id" column counts as the distinct_id when there is no "distinct_id" column. Without '
+ "either, the row updates the person with that email, or creates one keyed by the email. "
+ "Every other key is set as a person property."
+ ),
+ )
+
+
+class PeopleImportSerializer(serializers.Serializer):
+ cohort_id = serializers.IntegerField(help_text="The static cohort that fills with the imported people.")
+ row_count = serializers.IntegerField(help_text="People created or updated.")
+ new_people = serializers.IntegerField(help_text="Rows that create a person who isn't in PostHog yet.")
+ columns = serializers.ListField(child=serializers.CharField(), help_text="Person properties the rows set.")
+ dropped_invalid_email = serializers.IntegerField(help_text="Rows dropped for a missing or invalid email.")
+ dropped_duplicate_email = serializers.IntegerField(
+ help_text="Rows dropped because an earlier row had the email or distinct ID."
+ )
+ dropped_too_large = serializers.IntegerField(help_text="Rows dropped for holding more than 4KB of data.")
+
+
+class WorkflowPeopleImportViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ # The import creates a cohort and sets person properties, so it needs both write scopes.
+ scope_object = "cohort"
+ required_scopes = ["cohort:write", "person:write"]
+ serializer_class = PeopleImportCreateSerializer
+
+ @extend_schema(
+ request=PeopleImportCreateSerializer,
+ responses={201: PeopleImportSerializer},
+ summary="Create or update people from rows and add them to a new static cohort",
+ )
+ def create(self, request: Request, **kwargs: Any) -> Response:
+ # Session users skip API scopes, and access control checks only the cohort scope_object.
+ if not self.user_access_control.check_access_level_for_resource("person", "editor"):
+ raise exceptions.PermissionDenied("You need edit access to persons to import people.")
+ serializer = PeopleImportCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ summary = start_people_import(
+ team=self.team,
+ user=cast(User, request.user),
+ name=serializer.validated_data["name"],
+ rows=serializer.validated_data["rows"],
+ )
+ except PeopleImportInvalid as error:
+ raise exceptions.ValidationError(str(error))
+ return Response(PeopleImportSerializer(summary).data, status=201)
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index efffd88aca4c..438ae2c2698d 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -9,6 +9,7 @@ from products.workflows.backend.presentation.views import (
email_drafts,
hog_flow,
hog_flow_template,
+ people_imports,
workflow_classifications,
workflow_scout_runs,
workflow_tasks,
@@ -47,6 +48,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_classifications",
["team_id"],
)
+ routers.projects.register(
+ r"workflow_people_imports",
+ people_imports.WorkflowPeopleImportViewSet,
+ "project_workflow_people_imports",
+ ["team_id"],
+ )
routers.projects.register(
r"hog_flow_templates",
hog_flow_template.HogFlowTemplateViewSet,
diff --git a/products/workflows/backend/services/people_import.py b/products/workflows/backend/services/people_import.py
new file mode 100644
index 000000000000..9070644725dc
--- /dev/null
+++ b/products/workflows/backend/services/people_import.py
@@ -0,0 +1,340 @@
+"""Uploaded people lists: each row creates or updates a person, and the people form a static cohort."""
+
+import re
+import json
+import uuid
+from datetime import timedelta
+from typing import TypedDict
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.core.validators import validate_email
+from django.db.models import F
+from django.utils import timezone
+
+from structlog import get_logger
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models import PropertyDefinition
+from posthog.models.person.util import (
+ get_distinct_ids_for_persons,
+ get_person_ids_and_uuids_by_uuids,
+ get_person_uuids_and_matched_distinct_ids,
+)
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.storage import object_storage
+
+from products.access_control.backend.property_access_control import get_non_writable_property_names
+from products.cohorts.backend.models.cohort import Cohort
+from products.workflows.backend.facade.contracts import PeopleImportInvalid, PeopleImportSummary
+
+logger = get_logger(__name__)
+
+MAX_PEOPLE_IMPORT_ROWS = 50_000
+# Person properties are stored per person, so one row must not grow a profile without bound.
+MAX_PEOPLE_IMPORT_ROW_BYTES = 4096
+# Bounds each HogQL email lookup, so a full file takes five queries.
+EMAIL_LOOKUP_CHUNK_SIZE = 10_000
+# Bounds each personhog lookup of distinct IDs.
+PERSON_LOOKUP_CHUNK_SIZE = 1000
+
+# An import finishes in under 30 minutes, including the waits for ingestion and the capture retries.
+STALLED_IMPORT_AFTER = timedelta(hours=1)
+
+# Capture rejects longer distinct IDs (CAPTURE_V1_DISTINCT_ID_MAX_SIZE in rust/capture).
+MAX_DISTINCT_ID_BYTES = 200
+# Capture turns off person processing for these (ILLEGAL_DISTINCT_IDS in rust/capture), so no person would exist.
+ILLEGAL_DISTINCT_IDS = frozenset(
+ {
+ "0",
+ "00000000-0000-0000-0000-000000000000",
+ "[object object]",
+ "anonymous",
+ "anonymous-user",
+ "backend",
+ "distinct_id",
+ "distinctid",
+ "email",
+ "false",
+ "guest",
+ "id",
+ "nan",
+ "none",
+ "not_authenticated",
+ "null",
+ "system",
+ "true",
+ "undefined",
+ "user",
+ }
+)
+# Only these headers are matched loosely. Every other header is a person property name, kept as written.
+_IDENTITY_HEADERS = ("email", "distinct_id")
+# Customer.io exports name the person's ID "id", so it names the distinct ID when the file has no distinct_id column.
+_ID_HEADER = "id"
+
+_STORAGE_FOLDER = "workflows_people_imports"
+_HEADER_SEPARATORS = re.compile(r"[^a-z0-9]+")
+
+
+class StagedPerson(TypedDict):
+ """One person as the import stores it for the capture task."""
+
+ distinct_id: str
+ properties: dict[str, str]
+
+
+@frozen
+class _CleanedRows:
+ rows: list[dict[str, str]]
+ columns: list[str]
+ dropped_invalid_email: int
+ dropped_duplicate_email: int
+ dropped_too_large: int
+
+
+def start_people_import(*, team: Team, user: User | None, name: str, rows: list[dict[str, str]]) -> PeopleImportSummary:
+ if len(rows) > MAX_PEOPLE_IMPORT_ROWS:
+ raise PeopleImportInvalid(
+ f"This file has {len(rows):,} rows. A file can have up to {MAX_PEOPLE_IMPORT_ROWS:,}."
+ )
+
+ cleaned = _clean_rows(rows)
+ if not cleaned.rows:
+ raise PeopleImportInvalid("No row has a valid email address.")
+ _check_writable_columns(team, user, cleaned.columns)
+
+ distinct_ids = _resolve_distinct_ids(team, user, cleaned.rows)
+ people: list[StagedPerson] = []
+ seen_distinct_ids: set[str] = set()
+ dropped_duplicate_distinct_id = 0
+ for row, distinct_id in zip(cleaned.rows, distinct_ids):
+ # A row with no person yet becomes one, keyed by the CSV's distinct_id or else its email.
+ resolved = distinct_id or row["email"]
+ if resolved in seen_distinct_ids:
+ dropped_duplicate_distinct_id += 1
+ continue
+ seen_distinct_ids.add(resolved)
+ people.append({"distinct_id": resolved, "properties": row})
+
+ existing = existing_distinct_ids(team.id, [person["distinct_id"] for person in people])
+ cohort = Cohort.objects.create(team_id=team.id, name=name, is_static=True, is_calculating=True, created_by=user)
+ storage_key = f"{_STORAGE_FOLDER}/team-{team.id}/{cohort.pk}-{uuid.uuid4()}.json"
+
+ # The task module imports this one, so a module-level import would be circular.
+ from products.workflows.backend.tasks.people_import import ( # noqa: PLC0415
+ capture_people_import,
+ fail_people_import_if_stalled,
+ )
+
+ try:
+ object_storage.write(storage_key, json.dumps(people))
+ capture_people_import.delay(team_id=team.id, cohort_id=cohort.pk, storage_key=storage_key)
+ # A worker that dies mid-task, or a task that can't schedule the next one, leaves the cohort calculating.
+ # The stuck-cohort sweep skips uploaded cohorts, so this check ends the import instead.
+ fail_people_import_if_stalled.apply_async(
+ kwargs={"team_id": team.id, "cohort_id": cohort.pk, "storage_key": storage_key},
+ countdown=int(STALLED_IMPORT_AFTER.total_seconds()),
+ )
+ except Exception:
+ # No task would finish this cohort, and the stuck-cohort sweep skips uploads.
+ fail_people_import(team.id, cohort.pk, storage_key)
+ raise
+
+ return PeopleImportSummary(
+ cohort_id=cohort.pk,
+ row_count=len(people),
+ new_people=sum(1 for person in people if person["distinct_id"] not in existing),
+ columns=cleaned.columns,
+ dropped_invalid_email=cleaned.dropped_invalid_email,
+ dropped_duplicate_email=cleaned.dropped_duplicate_email + dropped_duplicate_distinct_id,
+ dropped_too_large=cleaned.dropped_too_large,
+ )
+
+
+def read_people(storage_key: str) -> list[StagedPerson]:
+ content = object_storage.read(storage_key, missing_ok=True)
+ return json.loads(content) if content else []
+
+
+def delete_people(storage_key: str) -> None:
+ object_storage.delete(storage_key)
+
+
+def fail_people_import(team_id: int, cohort_id: int, storage_key: str) -> None:
+ """Ends an import that can't finish: the cohort stops calculating and shows an error."""
+ Cohort.objects.filter(pk=cohort_id, team_id=team_id).update(
+ is_calculating=False, errors_calculating=F("errors_calculating") + 1, last_error_at=timezone.now()
+ )
+ try:
+ delete_people(storage_key)
+ except Exception:
+ logger.exception("people_import_cleanup_failed", team_id=team_id, cohort_id=cohort_id)
+
+
+def fail_stalled_people_import(team_id: int, cohort_id: int, storage_key: str) -> bool:
+ if not Cohort.objects.filter(pk=cohort_id, team_id=team_id, is_calculating=True).exists():
+ return False
+ fail_people_import(team_id, cohort_id, storage_key)
+ return True
+
+
+def existing_distinct_ids(team_id: int, distinct_ids: list[str]) -> set[str]:
+ found: set[str] = set()
+ for start in range(0, len(distinct_ids), PERSON_LOOKUP_CHUNK_SIZE):
+ _, matched = get_person_uuids_and_matched_distinct_ids(
+ team_id, distinct_ids[start : start + PERSON_LOOKUP_CHUNK_SIZE]
+ )
+ found.update(matched)
+ return found
+
+
+def _clean_rows(rows: list[dict[str, str]]) -> _CleanedRows:
+ id_names_distinct_id = "distinct_id" not in {_loose_header(header) for raw in rows for header in raw}
+ kept: list[dict[str, str]] = []
+ columns: dict[str, None] = {}
+ seen_emails: set[str] = set()
+ has_email_column = False
+ dropped_invalid_email = dropped_duplicate_email = dropped_too_large = 0
+ for line, raw in enumerate(rows, start=2):
+ row: dict[str, str] = {}
+ row_keys: set[str] = set()
+ for header, value in raw.items():
+ key = _column_key(header, id_names_distinct_id)
+ if not key:
+ # Skipping a column that holds data would lose that data without saying so.
+ if str(value).strip():
+ raise PeopleImportInvalid("A column with data in it has no name. Name it and try again.")
+ continue
+ if key in row_keys:
+ # Keeping either value would set the wrong property without saying so.
+ raise PeopleImportInvalid(f'Two columns are both named "{key}". Rename one and try again.')
+ row_keys.add(key)
+ cell = str(value).strip()
+ # A blank cell would $set "" and wipe the value the person already has.
+ if cell:
+ row[key] = cell
+ has_email_column = has_email_column or "email" in row_keys
+ _check_distinct_id(row.get("distinct_id", ""), line)
+ email = row.get("email", "")
+ try:
+ validate_email(email)
+ except DjangoValidationError:
+ dropped_invalid_email += 1
+ continue
+ if not row.get("distinct_id") and len(email.encode()) > MAX_DISTINCT_ID_BYTES:
+ # A row without a distinct_id may become a person keyed by its email, which capture would refuse.
+ dropped_invalid_email += 1
+ continue
+ if email.lower() in seen_emails:
+ dropped_duplicate_email += 1
+ continue
+ if len(json.dumps(row).encode()) > MAX_PEOPLE_IMPORT_ROW_BYTES:
+ dropped_too_large += 1
+ continue
+ seen_emails.add(email.lower())
+ columns.update(dict.fromkeys(key for key in row if key != "distinct_id"))
+ kept.append(row)
+ if not has_email_column:
+ raise PeopleImportInvalid('Add a column named "email" with each person\'s address.')
+ return _CleanedRows(
+ rows=kept,
+ columns=list(columns),
+ dropped_invalid_email=dropped_invalid_email,
+ dropped_duplicate_email=dropped_duplicate_email,
+ dropped_too_large=dropped_too_large,
+ )
+
+
+def _check_distinct_id(distinct_id: str, line: int) -> None:
+ if not distinct_id:
+ return
+ if len(distinct_id.encode()) > MAX_DISTINCT_ID_BYTES:
+ raise PeopleImportInvalid(
+ f"The distinct_id on row {line} is longer than {MAX_DISTINCT_ID_BYTES} bytes. Shorten it and try again."
+ )
+ if distinct_id.lower() in ILLEGAL_DISTINCT_IDS:
+ raise PeopleImportInvalid(
+ f'Row {line} has the distinct_id "{distinct_id}", which PostHog can\'t use for a person. '
+ "Use the person's ID from your app, or leave it empty to match by email."
+ )
+
+
+def _check_writable_columns(team: Team, user: User | None, columns: list[str]) -> None:
+ non_writable = get_non_writable_property_names(
+ team_id=team.id, user=user, property_type=PropertyDefinition.Type.PERSON
+ )
+ blocked = sorted(set(columns) & non_writable)
+ if blocked:
+ raise PeopleImportInvalid(
+ f"You can't change these person properties: {', '.join(blocked)}. Remove those columns and try again."
+ )
+
+
+def _resolve_distinct_ids(team: Team, user: User | None, rows: list[dict[str, str]]) -> list[str | None]:
+ """The distinct ID each row writes to: its own column first, then an existing person with the email."""
+ emails = [row["email"].lower() for row in rows if not row.get("distinct_id")]
+ by_email: dict[str, str] = {}
+ for start in range(0, len(emails), EMAIL_LOOKUP_CHUNK_SIZE):
+ by_email.update(_distinct_ids_by_email(team, user, emails[start : start + EMAIL_LOOKUP_CHUNK_SIZE]))
+ resolved: list[str | None] = []
+ for row in rows:
+ distinct_id = row.pop("distinct_id", "")
+ resolved.append(distinct_id or by_email.get(row["email"].lower()))
+ return resolved
+
+
+def _distinct_ids_by_email(team: Team, user: User | None, emails: list[str]) -> dict[str, str]:
+ if not emails:
+ return {}
+ # Querying persons directly lets HogQL filter people by email before it groups their versions.
+ # The lowest person ID per email is the same person the email dedupe of a filtered audience picks.
+ query = parse_select(
+ """
+ SELECT lower(trim(toString(properties.email))) AS normalized_email, min(id) AS person_uuid
+ FROM persons
+ WHERE lower(trim(toString(properties.email))) IN {emails}
+ GROUP BY normalized_email
+ LIMIT {limit}
+ """,
+ # Without a limit HogQL returns 100 rows, which is fewer than one chunk of emails.
+ placeholders={"emails": ast.Constant(value=emails), "limit": ast.Constant(value=len(emails))},
+ )
+ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)
+ # With the user, property access rules that hide email from the team default still let this user match.
+ response = execute_hogql_query(query=query, team=team, user=user, workload=Workload.OFFLINE)
+ uuid_by_email = {email: uuid.UUID(str(person_uuid)) for email, person_uuid in response.results}
+ id_by_uuid = {
+ uuid.UUID(str(person_uuid)): person_id
+ for person_id, person_uuid in get_person_ids_and_uuids_by_uuids(
+ team.id, [str(person_uuid) for person_uuid in set(uuid_by_email.values())]
+ )
+ }
+ # Any of the person's distinct IDs will do: the row writes its properties to the person behind it.
+ distinct_ids = get_distinct_ids_for_persons(team.id, list(id_by_uuid.values()), limit_per_person=1)
+ matched: dict[str, str] = {}
+ for email, person_uuid in uuid_by_email.items():
+ person_id = id_by_uuid.get(person_uuid)
+ if person_id is not None and distinct_ids.get(person_id):
+ matched[email] = distinct_ids[person_id][0]
+ return matched
+
+
+def _loose_header(header: object) -> str:
+ return _HEADER_SEPARATORS.sub("_", str(header).strip().lower()).strip("_")
+
+
+def _column_key(header: object, id_names_distinct_id: bool) -> str:
+ """The identity column a header names, or else the header itself as the person property name."""
+ loose = _loose_header(header)
+ if loose in _IDENTITY_HEADERS:
+ return loose
+ if loose == _ID_HEADER and id_names_distinct_id:
+ return "distinct_id"
+ return str(header).strip()
diff --git a/products/workflows/backend/tasks/__init__.py b/products/workflows/backend/tasks/__init__.py
index 90f47c6d753f..047db797750b 100644
--- a/products/workflows/backend/tasks/__init__.py
+++ b/products/workflows/backend/tasks/__init__.py
@@ -1,3 +1,3 @@
-from . import email_sending_tiers, hog_flows, ses_account_reputation
+from . import email_sending_tiers, hog_flows, people_import, ses_account_reputation
-__all__ = ["email_sending_tiers", "hog_flows", "ses_account_reputation"]
+__all__ = ["email_sending_tiers", "hog_flows", "people_import", "ses_account_reputation"]
diff --git a/products/workflows/backend/tasks/people_import.py b/products/workflows/backend/tasks/people_import.py
new file mode 100644
index 000000000000..e164e593b0bc
--- /dev/null
+++ b/products/workflows/backend/tasks/people_import.py
@@ -0,0 +1,140 @@
+import uuid
+
+from celery import Task, shared_task
+from structlog import get_logger
+
+from posthog.api.capture import capture_batch_internal
+from posthog.models.team.team import Team
+from posthog.scoping_audit import skip_team_scope_audit
+from posthog.tasks.calculate_cohort import calculate_cohort_from_list
+from posthog.tasks.utils import CeleryQueue
+
+from products.workflows.backend.services.people_import import (
+ StagedPerson,
+ delete_people,
+ existing_distinct_ids,
+ fail_people_import,
+ fail_stalled_people_import,
+ read_people,
+)
+
+logger = get_logger(__name__)
+
+EVENT_SOURCE = "workflows_people_import"
+CAPTURE_MAX_RETRIES = 3
+# Ingestion usually creates the people within seconds. The waits add up to about 25 minutes.
+WAIT_MAX_ATTEMPTS = 8
+WAIT_FIRST_DELAY_SECONDS = 15
+WAIT_MAX_DELAY_SECONDS = 300
+
+
+@shared_task(bind=True, ignore_result=True, queue=CeleryQueue.DEFAULT.value, max_retries=CAPTURE_MAX_RETRIES)
+@skip_team_scope_audit
+def capture_people_import(
+ self, *, team_id: int, cohort_id: int, storage_key: str, pending_distinct_ids: list[str] | None = None
+) -> None:
+ """Sends one $set event per row, so ingestion creates or updates each person with the row's columns."""
+ try:
+ people = read_people(storage_key)
+ if pending_distinct_ids is not None:
+ pending = set(pending_distinct_ids)
+ people = [person for person in people if person["distinct_id"] in pending]
+ team = Team.objects.get(id=team_id)
+ events = _set_events(people, storage_key)
+ result = capture_batch_internal(
+ events=events, token=team.api_token, event_source=EVENT_SOURCE, process_person_profile=True
+ )
+ except Exception as error:
+ logger.warning("people_import_capture_failed", team_id=team_id, cohort_id=cohort_id, error=str(error))
+ _retry_or_fail(self, team_id, cohort_id, storage_key, pending_distinct_ids)
+ return
+ if not result.succeeded():
+ logger.warning(
+ "people_import_capture_partial",
+ team_id=team_id,
+ cohort_id=cohort_id,
+ dropped=len(result.dropped),
+ retried=len(result.retried),
+ unaccounted=len(result.unaccounted),
+ error=result.error,
+ )
+ # Capture can ack part of a batch, and it ingests a resent acked event twice, so a retry sends only the rest.
+ unacknowledged = {*result.retried, *result.unaccounted}
+ if unacknowledged:
+ retry = [str(event["distinct_id"]) for event in events if event["event_uuid"] in unacknowledged]
+ everything_again = pending_distinct_ids is None and len(retry) == len(events)
+ _retry_or_fail(self, team_id, cohort_id, storage_key, None if everything_again else retry)
+ return
+ # A retry can't deliver a dropped event. The cohort import reports those people as unmatched.
+ _schedule_fill(team_id, cohort_id, storage_key, attempt=0)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+@skip_team_scope_audit
+def fill_people_import_cohort(*, team_id: int, cohort_id: int, storage_key: str, attempt: int) -> None:
+ """Waits until ingestion has created every person, then adds them all to the cohort."""
+ last_attempt = attempt + 1 >= WAIT_MAX_ATTEMPTS
+ try:
+ distinct_ids = [person["distinct_id"] for person in read_people(storage_key)]
+ found = existing_distinct_ids(team_id, distinct_ids)
+ except Exception as error:
+ logger.warning("people_import_lookup_failed", team_id=team_id, cohort_id=cohort_id, error=str(error))
+ if last_attempt:
+ fail_people_import(team_id, cohort_id, storage_key)
+ else:
+ _schedule_fill(team_id, cohort_id, storage_key, attempt=attempt + 1)
+ return
+ missing = len(distinct_ids) - len(found)
+ if missing and not last_attempt:
+ _schedule_fill(team_id, cohort_id, storage_key, attempt=attempt + 1)
+ return
+ if missing:
+ # The cohort import records the people it can't find, so the cohort shows the shortfall.
+ logger.warning("people_import_people_missing", team_id=team_id, cohort_id=cohort_id, missing=missing)
+ calculate_cohort_from_list.delay(cohort_id, distinct_ids, team_id=team_id, id_type="distinct_id")
+ delete_people(storage_key)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+@skip_team_scope_audit
+def fail_people_import_if_stalled(*, team_id: int, cohort_id: int, storage_key: str) -> None:
+ """Ends an import whose cohort is still calculating long after it should have finished."""
+ if fail_stalled_people_import(team_id, cohort_id, storage_key):
+ logger.warning("people_import_stalled", team_id=team_id, cohort_id=cohort_id)
+
+
+def _set_events(people: list[StagedPerson], storage_key: str) -> list[dict[str, object]]:
+ return [
+ {
+ "event": "$set",
+ "distinct_id": person["distinct_id"],
+ # The server's IP says nothing about where the person is.
+ "properties": {"$set": person["properties"], "$geoip_disable": True},
+ # A stable uuid per person lets a retry find which events capture didn't acknowledge.
+ "event_uuid": str(uuid.uuid5(uuid.NAMESPACE_URL, f"{storage_key}/{person['distinct_id']}")),
+ }
+ for person in people
+ ]
+
+
+def _schedule_fill(team_id: int, cohort_id: int, storage_key: str, *, attempt: int) -> None:
+ fill_people_import_cohort.apply_async(
+ kwargs={"team_id": team_id, "cohort_id": cohort_id, "storage_key": storage_key, "attempt": attempt},
+ countdown=min(WAIT_FIRST_DELAY_SECONDS * 2**attempt, WAIT_MAX_DELAY_SECONDS),
+ )
+
+
+def _retry_or_fail(
+ task: Task, team_id: int, cohort_id: int, storage_key: str, pending_distinct_ids: list[str] | None
+) -> None:
+ if task.request.retries < CAPTURE_MAX_RETRIES:
+ raise task.retry(
+ kwargs={
+ "team_id": team_id,
+ "cohort_id": cohort_id,
+ "storage_key": storage_key,
+ "pending_distinct_ids": pending_distinct_ids,
+ },
+ countdown=30 * (task.request.retries + 1),
+ )
+ fail_people_import(team_id, cohort_id, storage_key)
diff --git a/products/workflows/backend/test/test_people_import.py b/products/workflows/backend/test/test_people_import.py
new file mode 100644
index 000000000000..25fc870c791d
--- /dev/null
+++ b/products/workflows/backend/test/test_people_import.py
@@ -0,0 +1,368 @@
+import json
+from typing import Any
+
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events
+from unittest.mock import MagicMock, patch
+
+from celery.exceptions import Retry
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.capture import CaptureInternalResult
+from posthog.constants import AvailableFeature
+from posthog.models import PersonalAPIKey, PropertyDefinition
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
+from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.cohorts.backend.models.cohort import Cohort
+from products.workflows.backend.facade.contracts import PeopleImportInvalid
+from products.workflows.backend.services import people_import
+from products.workflows.backend.services.people_import import start_people_import
+from products.workflows.backend.tasks import people_import as people_import_tasks
+from products.workflows.backend.tasks.people_import import (
+ capture_people_import,
+ fail_people_import_if_stalled,
+ fill_people_import_cohort,
+)
+
+
+class _MemoryStorage:
+ def __init__(self) -> None:
+ self.objects: dict[str, str] = {}
+
+ def write(self, key: str, content: str) -> None:
+ self.objects[key] = content
+
+ def read(self, key: str, *, missing_ok: bool = False) -> str | None:
+ return self.objects.get(key)
+
+ def delete(self, key: str) -> None:
+ self.objects.pop(key, None)
+
+
+class _StorageMixin:
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ self.storage = _MemoryStorage()
+ patcher = patch.object(people_import, "object_storage", self.storage)
+ patcher.start()
+ self.addCleanup(patcher.stop) # type: ignore[attr-defined]
+ dispatch = patch("products.workflows.backend.tasks.people_import.capture_people_import.delay")
+ self.dispatch = dispatch.start()
+ self.addCleanup(dispatch.stop) # type: ignore[attr-defined]
+ stall_check = patch("products.workflows.backend.tasks.people_import.fail_people_import_if_stalled.apply_async")
+ self.stall_check = stall_check.start()
+ self.addCleanup(stall_check.stop) # type: ignore[attr-defined]
+
+ def stored_people(self) -> list[dict[str, Any]]:
+ [content] = self.storage.objects.values()
+ return json.loads(content)
+
+
+class TestPeopleImport(_StorageMixin, ClickhouseTestMixin, BaseTest):
+ def test_each_row_writes_to_the_right_person(self) -> None:
+ _create_person(team=self.team, distinct_ids=["user-1"], properties={"email": "[email protected]"})
+ _create_person(team=self.team, distinct_ids=["b-newer"], properties={"email": "[email protected]"})
+ flush_persons_and_events()
+ rows: list[dict[str, str]] = [
+ {"Email": "[email protected]", "Distinct ID": "user-1", "subscriptionPlan": "Pro", "company": " ", " ": ""},
+ {"Email": "[email protected]", "subscriptionPlan": "Free"},
+ {"Email": "[email protected]", "Distinct ID": "user-9", "subscriptionPlan": "Team"},
+ {"Email": "[email protected]", "subscriptionPlan": "Trial"},
+ {"Email": "not-an-email", "subscriptionPlan": "Free"},
+ {"Email": "[email protected]", "subscriptionPlan": "Duplicate"},
+ {"Email": "[email protected]", "subscriptionPlan": "x" * 5000},
+ {"Email": "[email protected]", "Distinct ID": "user-1", "subscriptionPlan": "Same person twice"},
+ ]
+
+ summary = start_people_import(team=self.team, user=self.user, name="Spring sale", rows=rows)
+
+ assert [(p["distinct_id"], p["properties"]) for p in self.stored_people()] == [
+ ("user-1", {"email": "[email protected]", "subscriptionPlan": "Pro"}),
+ ("b-newer", {"email": "[email protected]", "subscriptionPlan": "Free"}),
+ ("user-9", {"email": "[email protected]", "subscriptionPlan": "Team"}),
+ ("[email protected]", {"email": "[email protected]", "subscriptionPlan": "Trial"}),
+ ]
+ assert (summary.row_count, summary.new_people, summary.columns) == (4, 2, ["email", "subscriptionPlan"])
+ assert (summary.dropped_invalid_email, summary.dropped_duplicate_email, summary.dropped_too_large) == (1, 2, 1)
+ cohort = Cohort.objects.get(pk=summary.cohort_id)
+ assert (cohort.team_id, cohort.name, cohort.is_static, cohort.is_calculating) == (
+ self.team.id,
+ "Spring sale",
+ True,
+ True,
+ )
+ self.dispatch.assert_called_once()
+ assert self.stall_check.call_args.kwargs["countdown"] == 3600
+
+ @parameterized.expand(
+ [
+ ("id_names_the_person", {"email": "[email protected]", "ID": "user-7"}, ("user-7", {"email": "[email protected]"})),
+ (
+ "distinct_id_column_wins",
+ {"email": "[email protected]", "distinct_id": "user-7", "id": "cio-1"},
+ ("user-7", {"email": "[email protected]", "id": "cio-1"}),
+ ),
+ ]
+ )
+ def test_id_column_names_the_person_without_a_distinct_id_column(
+ self, _name: str, row: dict[str, str], expected: tuple[str, dict[str, str]]
+ ) -> None:
+ start_people_import(team=self.team, user=self.user, name="List", rows=[row])
+
+ assert [(p["distinct_id"], p["properties"]) for p in self.stored_people()] == [expected]
+
+ @parameterized.expand(
+ [
+ ("no_email_column", [{"name": "Ada"}], 'column named "email"', None),
+ ("no_valid_email", [{"email": "nope"}], "No row has a valid email", None),
+ (
+ "illegal_distinct_id",
+ [{"email": "[email protected]", "distinct_id": "Anonymous"}],
+ 'Row 2 has the distinct_id "Anonymous"',
+ None,
+ ),
+ ("long_distinct_id", [{"email": "[email protected]", "distinct_id": "x" * 201}], "longer than 200 bytes", None),
+ ("blank_header_with_data", [{"email": "[email protected]", " ": "Hedgebox"}], "has no name", None),
+ (
+ "two_columns_with_one_name",
+ [{"email": "[email protected]", "Email ": "[email protected]"}],
+ 'both named "email"',
+ None,
+ ),
+ ("read_only_property", [{"email": "[email protected]", "plan": "Pro"}], "can't change these", "plan"),
+ ]
+ )
+ def test_rejects_unusable_files(
+ self, _name: str, rows: list[dict[str, str]], message: str, read_only_property: str | None
+ ) -> None:
+ if read_only_property:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=PropertyDefinition.objects.create(
+ team=self.team, name=read_only_property, property_type="String", type=PropertyDefinition.Type.PERSON
+ ),
+ access_level=PropertyAccessLevel.READ.value,
+ )
+ with self.assertRaises(PeopleImportInvalid) as error:
+ start_people_import(team=self.team, user=self.user, name="List", rows=rows)
+ assert message in str(error.exception)
+ assert not Cohort.objects.filter(team_id=self.team.id).exists()
+
+ def test_matches_by_email_with_the_importing_users_property_access(self) -> None:
+ _create_person(team=self.team, distinct_ids=["user-1"], properties={"email": "[email protected]"})
+ flush_persons_and_events()
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ email = PropertyDefinition.objects.create(
+ team=self.team, name="email", property_type="String", type=PropertyDefinition.Type.PERSON
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=email, access_level=PropertyAccessLevel.NONE.value
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=email,
+ organization_member=self.organization_membership,
+ access_level=PropertyAccessLevel.READ_WRITE.value,
+ )
+
+ start_people_import(team=self.team, user=self.user, name="List", rows=[{"email": "[email protected]"}])
+
+ assert [person["distinct_id"] for person in self.stored_people()] == ["user-1"]
+
+ def test_ends_the_import_when_staging_fails(self) -> None:
+ with patch.object(self.storage, "write", side_effect=ConnectionError("storage is down")):
+ with self.assertRaises(ConnectionError):
+ start_people_import(team=self.team, user=self.user, name="List", rows=[{"email": "[email protected]"}])
+
+ cohort = Cohort.objects.get(team_id=self.team.id)
+ assert (cohort.is_calculating, cohort.errors_calculating) == (False, 1)
+ self.dispatch.assert_not_called()
+
+
+class TestPeopleImportTasks(_StorageMixin, BaseTest):
+ def _stage(self, distinct_ids: tuple[str, ...] = ("user-1",)) -> tuple[int, str]:
+ cohort = Cohort.objects.create(team=self.team, name="List", is_static=True, is_calculating=True)
+ key = f"workflows_people_imports/team-{self.team.id}/{cohort.pk}.json"
+ people = [{"distinct_id": d, "properties": {"email": f"{d}@example.com"}} for d in distinct_ids]
+ self.storage.write(key, json.dumps(people))
+ return cohort.pk, key
+
+ @patch("products.workflows.backend.tasks.people_import.fill_people_import_cohort.apply_async")
+ @patch("products.workflows.backend.tasks.people_import.capture_batch_internal")
+ def test_capture_sets_each_row_on_its_person(self, capture: MagicMock, fill: MagicMock) -> None:
+ cohort_id, key = self._stage()
+ capture.return_value.succeeded.return_value = True
+
+ capture_people_import(team_id=self.team.id, cohort_id=cohort_id, storage_key=key)
+
+ [event] = capture.call_args.kwargs["events"]
+ assert (event["event"], event["distinct_id"], event["properties"]) == (
+ "$set",
+ "user-1",
+ {"$set": {"email": "[email protected]"}, "$geoip_disable": True},
+ )
+ assert capture.call_args.kwargs["process_person_profile"] is True
+ fill.assert_called_once()
+
+ @parameterized.expand([("capture_raises", ConnectionError("capture is down")), ("capture_acks_nothing", None)])
+ @patch("products.workflows.backend.tasks.people_import.fill_people_import_cohort.apply_async")
+ @patch("products.workflows.backend.tasks.people_import.capture_batch_internal")
+ def test_capture_closes_the_import_after_the_last_retry(
+ self, _name: str, error: Exception | None, capture: MagicMock, fill: MagicMock
+ ) -> None:
+ cohort_id, key = self._stage()
+ capture.side_effect = error or (
+ lambda events, **_: CaptureInternalResult(status_code=503, unaccounted=[e["event_uuid"] for e in events])
+ )
+
+ capture_people_import.apply(
+ kwargs={"team_id": self.team.id, "cohort_id": cohort_id, "storage_key": key},
+ retries=people_import_tasks.CAPTURE_MAX_RETRIES,
+ )
+
+ cohort = Cohort.objects.get(pk=cohort_id)
+ assert (cohort.is_calculating, cohort.errors_calculating) == (False, 1)
+ assert key not in self.storage.objects
+ fill.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("partial_ack", None, {"ok": ["user-1"], "retried": ["user-2"]}, ["user-1", "user-2"], ["user-2"]),
+ ("dropped_only", None, {"ok": ["user-1"], "dropped": ["user-2"]}, ["user-1", "user-2"], None),
+ ("retry_of_a_subset", ["user-2"], {"ok": ["user-2"]}, ["user-2"], None),
+ ]
+ )
+ @patch("products.workflows.backend.tasks.people_import.fill_people_import_cohort.apply_async")
+ @patch("products.workflows.backend.tasks.people_import.capture_batch_internal")
+ def test_capture_resends_only_unacknowledged_events(
+ self,
+ _name: str,
+ pending: list[str] | None,
+ buckets: dict[str, list[str]],
+ sent: list[str],
+ retried: list[str] | None,
+ capture: MagicMock,
+ fill: MagicMock,
+ ) -> None:
+ cohort_id, key = self._stage(("user-1", "user-2"))
+
+ def submit(events: list[dict], **_: object) -> CaptureInternalResult:
+ uuid_of = {event["distinct_id"]: event["event_uuid"] for event in events}
+
+ def uuids(bucket: str) -> list[str]:
+ return [uuid_of[distinct_id] for distinct_id in buckets.get(bucket, [])]
+
+ return CaptureInternalResult(
+ status_code=200, ok=uuids("ok"), dropped=uuids("dropped"), retried=uuids("retried")
+ )
+
+ capture.side_effect = submit
+ with patch.object(capture_people_import, "retry", return_value=Retry()) as retry:
+ try:
+ capture_people_import(
+ team_id=self.team.id, cohort_id=cohort_id, storage_key=key, pending_distinct_ids=pending
+ )
+ except Retry:
+ pass
+
+ assert [event["distinct_id"] for event in capture.call_args.kwargs["events"]] == sent
+ retried_ids = retry.call_args.kwargs["kwargs"]["pending_distinct_ids"] if retry.called else None
+ assert (retried_ids, fill.called) == (retried, retried is None)
+
+ @parameterized.expand(
+ [
+ ("still_missing", ([], set()), 0, "waits"),
+ ("all_found", ([], {"user-1"}), 0, "fills"),
+ ("lookup_fails", ConnectionError("personhog is down"), 0, "waits"),
+ ("lookup_fails_on_the_last_attempt", ConnectionError("personhog is down"), 7, "fails"),
+ ]
+ )
+ @patch("products.workflows.backend.tasks.people_import.calculate_cohort_from_list.delay")
+ @patch("products.workflows.backend.tasks.people_import.fill_people_import_cohort.apply_async")
+ def test_fill_waits_for_ingestion(
+ self,
+ _name: str,
+ lookup: tuple[list[str], set[str]] | Exception,
+ attempt: int,
+ outcome: str,
+ reschedule: MagicMock,
+ calculate: MagicMock,
+ ) -> None:
+ cohort_id, key = self._stage()
+
+ with patch.object(people_import, "get_person_uuids_and_matched_distinct_ids", side_effect=[lookup]):
+ fill_people_import_cohort(team_id=self.team.id, cohort_id=cohort_id, storage_key=key, attempt=attempt)
+
+ cohort = Cohort.objects.get(pk=cohort_id)
+ assert reschedule.called is (outcome == "waits")
+ assert calculate.called is (outcome == "fills")
+ assert (key in self.storage.objects) is (outcome == "waits")
+ assert cohort.is_calculating is (outcome != "fails")
+
+ @parameterized.expand([("still_calculating", True, True), ("finished", False, False)])
+ def test_stall_check_ends_an_import_that_never_finished(self, _name: str, calculating: bool, ended: bool) -> None:
+ cohort_id, key = self._stage()
+ Cohort.objects.filter(pk=cohort_id).update(is_calculating=calculating)
+
+ fail_people_import_if_stalled(team_id=self.team.id, cohort_id=cohort_id, storage_key=key)
+
+ cohort = Cohort.objects.get(pk=cohort_id)
+ assert (cohort.errors_calculating, key in self.storage.objects) == ((1, False) if ended else (0, True))
+
+
+class TestPeopleImportAPI(_StorageMixin, ClickhouseTestMixin, APIBaseTest):
+ def test_import_returns_its_cohort_and_rejects_an_unusable_file(self) -> None:
+ url = f"/api/projects/{self.team.id}/workflow_people_imports/"
+
+ created = self.client.post(
+ url, {"name": "List", "rows": [{"email": "[email protected]", "org": "Acme"}]}, format="json"
+ )
+ rejected = self.client.post(url, {"name": "List", "rows": [{"name": "Ada"}]}, format="json")
+
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ assert created.json()["columns"] == ["email", "org"]
+ assert Cohort.objects.filter(pk=created.json()["cohort_id"], team_id=self.team.id).exists()
+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand([("person_viewer", "viewer", 403), ("person_editor", "editor", 201)])
+ def test_import_needs_person_edit_access(self, _name: str, person_access: str, expected_status: int) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ AccessControl.objects.create(team=self.team, resource="person", resource_id=None, access_level=person_access)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/workflow_people_imports/",
+ {"name": "List", "rows": [{"email": "[email protected]"}]},
+ format="json",
+ )
+
+ assert response.status_code == expected_status, response.json()
+
+ @parameterized.expand(
+ [("cohort_only", ["cohort:write"], 403), ("cohort_and_person", ["cohort:write", "person:write"], 201)]
+ )
+ def test_import_needs_person_write_scope(self, _name: str, scopes: list[str], expected_status: int) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="t", user=self.user, secure_value=hash_key_value(token), scopes=scopes)
+ self.client.logout()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/workflow_people_imports/",
+ {"name": "List", "rows": [{"email": "[email protected]"}]},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == expected_status, response.json()
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 2355dffca29d..945de2e215e9 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -2150,6 +2150,38 @@ export interface EmailDraftApi {
template_reason: EmailDraftFallbackReasonEnumApi | null
}
+export type PeopleImportCreateApiRowsItem = { [key: string]: string }
+
+export interface PeopleImportCreateApi {
+ /**
+ * Name of the static cohort that holds the imported people.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * One object per person. Each needs "email". An optional "distinct_id" picks the person to update or create, and an "id" column counts as the distinct_id when there is no "distinct_id" column. Without either, the row updates the person with that email, or creates one keyed by the email. Every other key is set as a person property.
+ * @maxItems 50000
+ */
+ rows: PeopleImportCreateApiRowsItem[]
+}
+
+export interface PeopleImportApi {
+ /** The static cohort that fills with the imported people. */
+ cohort_id: number
+ /** People created or updated. */
+ row_count: number
+ /** Rows that create a person who isn't in PostHog yet. */
+ new_people: number
+ /** Person properties the rows set. */
+ columns: string[]
+ /** Rows dropped for a missing or invalid email. */
+ dropped_invalid_email: number
+ /** Rows dropped because an earlier row had the email or distinct ID. */
+ dropped_duplicate_email: number
+ /** Rows dropped for holding more than 4KB of data. */
+ dropped_too_large: number
+}
+
export type HogFlowTemplatesListParams = {
/**
* Number of results to return per page.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 19c3cffee3a7..a22255d22b3e 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -62,6 +62,8 @@ import type {
PatchedHogFlowScheduleApi,
PatchedHogFlowTemplateApi,
PatchedHogFlowUpdateApi,
+ PeopleImportApi,
+ PeopleImportCreateApi,
TeamEmailReputationResponseApi,
WorkflowEmailPauseStatusApi,
WorkflowProposalApi,
@@ -1336,6 +1338,26 @@ export const workflowEmailDraftsCreate = async (
})
}
+export const getWorkflowPeopleImportsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workflow_people_imports/`
+}
+
+/**
+ * @summary Create or update people from rows and add them to a new static cohort
+ */
+export const workflowPeopleImportsCreate = async (
+ projectId: string,
+ peopleImportCreateApi: PeopleImportCreateApi,
+ options?: RequestInit
+): Promise<PeopleImportApi> => {
+ return apiMutator<PeopleImportApi>(getWorkflowPeopleImportsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(peopleImportCreateApi),
+ })
+}
+
export const getInternalHogFlowsAccountAudienceCreateUrl = (teamId: string) => {
return `/api/projects/${teamId}/internal/hog_flows/account_audience`
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index fdeeb347a024..ab3b71794773 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -3190,3 +3190,23 @@ export const WorkflowEmailDraftsCreateBody = /* @__PURE__ */ zod.object({
.max(workflowEmailDraftsCreateBodySourceIdMax)
.describe('ID of that entity: an issue, early access feature or survey UUID, or a feature flag or cohort ID.'),
})
+
+/**
+ * @summary Create or update people from rows and add them to a new static cohort
+ */
+export const workflowPeopleImportsCreateBodyNameMax = 400
+
+export const workflowPeopleImportsCreateBodyRowsMax = 50000
+
+export const WorkflowPeopleImportsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(workflowPeopleImportsCreateBodyNameMax)
+ .describe('Name of the static cohort that holds the imported people.'),
+ rows: zod
+ .array(zod.record(zod.string(), zod.string()))
+ .max(workflowPeopleImportsCreateBodyRowsMax)
+ .describe(
+ 'One object per person. Each needs \"email\". An optional \"distinct_id\" picks the person to update or create, and an \"id\" column counts as the distinct_id when there is no \"distinct_id\" column. Without either, the row updates the person with that email, or creates one keyed by the email. Every other key is set as a person property.'
+ ),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c243572725c3..f8ae65639503 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -86853,6 +86853,38 @@ export namespace Schemas {
timestamp: string;
}
+ export interface PeopleImport {
+ /** The static cohort that fills with the imported people. */
+ cohort_id: number;
+ /** People created or updated. */
+ row_count: number;
+ /** Rows that create a person who isn't in PostHog yet. */
+ new_people: number;
+ /** Person properties the rows set. */
+ columns: string[];
+ /** Rows dropped for a missing or invalid email. */
+ dropped_invalid_email: number;
+ /** Rows dropped because an earlier row had the email or distinct ID. */
+ dropped_duplicate_email: number;
+ /** Rows dropped for holding more than 4KB of data. */
+ dropped_too_large: number;
+ }
+
+ export type PeopleImportCreateRowsItem = {[key: string]: string};
+
+ export interface PeopleImportCreate {
+ /**
+ * Name of the static cohort that holds the imported people.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * One object per person. Each needs "email". An optional "distinct_id" picks the person to update or create, and an "id" column counts as the distinct_id when there is no "distinct_id" column. Without either, the row updates the person with that email, or creates one keyed by the email. Every other key is set as a person property.
+ * @maxItems 50000
+ */
+ rows: PeopleImportCreateRowsItem[];
+ }
+
export interface PersonBulkDeleteRequest {
/** A list of PostHog person UUIDs to delete (max 1000). */
ids?: string[];