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(groups): add workflow to backfill group type mapping created_at (#64266)

Paweł Ledwońc7afc1dea3b1
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 0a9825239ba6..8ded4a8fe200 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -379,7 +379,7 @@ jobs:
- name: Check for changes that affect general purpose temporal worker
id: check_changes_general_purpose_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/temporal/backfill_group_type_created_at|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.py
index acd146a49229..41d7fe8fe1c5 100644
--- a/posthog/management/commands/execute_temporal_workflow.py
+++ b/posthog/management/commands/execute_temporal_workflow.py
@@ -10,6 +10,7 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from posthog.temporal.ai import AI_WORKFLOWS
from posthog.temporal.ai_observability import WORKFLOWS as LLM_ANALYTICS_WORKFLOWS
+from posthog.temporal.backfill_group_type_created_at import WORKFLOWS as BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS
from posthog.temporal.common.client import connect
from posthog.temporal.data_imports.settings import WORKFLOWS as DATA_IMPORT_WORKFLOWS
from posthog.temporal.data_modeling import WORKFLOWS as DATA_MODELING_WORKFLOWS
@@ -157,6 +158,7 @@ class Command(BaseCommand):
+ SUMMARIZATION_SWEEP_WORKFLOWS
+ WA_DIGEST_WORKFLOWS
+ SURFACING_SCORING_SWEEP_WORKFLOWS
+ + BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS
)
try:
workflow = next(workflow for workflow in WORKFLOWS if workflow.is_named(workflow_name))
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 9b0b3f574861..7a45265b9d69 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -35,6 +35,10 @@ from posthog.temporal.alerts import (
ACTIVITIES as ALERT_ACTIVITIES,
WORKFLOWS as ALERT_WORKFLOWS,
)
+from posthog.temporal.backfill_group_type_created_at import (
+ ACTIVITIES as BACKFILL_GROUP_TYPE_CREATED_AT_ACTIVITIES,
+ WORKFLOWS as BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS,
+)
from posthog.temporal.cleanup_property_definitions import (
ACTIVITIES as CLEANUP_PROPDEFS_ACTIVITIES,
WORKFLOWS as CLEANUP_PROPDEFS_WORKFLOWS,
@@ -257,6 +261,7 @@ _task_queue_specs = [
+ EXPERIMENTS_WORKFLOWS
+ EXPERIMENTS_RECALCULATION_WORKFLOWS
+ CLEANUP_PROPDEFS_WORKFLOWS
+ + BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS
+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS
+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,
PROXY_SERVICE_ACTIVITIES
@@ -271,6 +276,7 @@ _task_queue_specs = [
+ EXPERIMENTS_ACTIVITIES
+ EXPERIMENTS_RECALCULATION_ACTIVITIES
+ CLEANUP_PROPDEFS_ACTIVITIES
+ + BACKFILL_GROUP_TYPE_CREATED_AT_ACTIVITIES
+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES
+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,
),
diff --git a/posthog/temporal/backfill_group_type_created_at/__init__.py b/posthog/temporal/backfill_group_type_created_at/__init__.py
new file mode 100644
index 000000000000..ee287aebdf0f
--- /dev/null
+++ b/posthog/temporal/backfill_group_type_created_at/__init__.py
@@ -0,0 +1,14 @@
+from posthog.temporal.backfill_group_type_created_at.activities import (
+ apply_group_type_created_at_backfill,
+ plan_group_type_created_at_backfill,
+)
+from posthog.temporal.backfill_group_type_created_at.workflows import BackfillGroupTypeCreatedAtWorkflow
+
+WORKFLOWS = [
+ BackfillGroupTypeCreatedAtWorkflow,
+]
+
+ACTIVITIES = [
+ plan_group_type_created_at_backfill,
+ apply_group_type_created_at_backfill,
+]
diff --git a/posthog/temporal/backfill_group_type_created_at/activities.py b/posthog/temporal/backfill_group_type_created_at/activities.py
new file mode 100644
index 000000000000..c63c7c782fbb
--- /dev/null
+++ b/posthog/temporal/backfill_group_type_created_at/activities.py
@@ -0,0 +1,205 @@
+from datetime import UTC, datetime
+from uuid import uuid4
+
+from structlog.contextvars import bind_contextvars
+from temporalio import activity
+
+from posthog.models import Team
+from posthog.models.group_type_mapping import GroupTypeMapping, invalidate_group_types_cache
+from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+from posthog.sync import database_sync_to_async
+from posthog.temporal.backfill_group_type_created_at.types import (
+ ApplyBackfillInput,
+ BackfillGroupTypeCreatedAtError,
+ GroupTypeUpdate,
+ PlanBackfillInput,
+)
+from posthog.temporal.common.clickhouse import get_client
+from posthog.temporal.common.logger import get_write_only_logger
+
+LOGGER = get_write_only_logger()
+
+# $group_0..$group_4 are the materialized group key columns on the events table.
+GROUP_TYPE_INDEXES = range(5)
+
+
[email protected](name="plan-group-type-created-at-backfill")
+async def plan_group_type_created_at_backfill(input: PlanBackfillInput) -> dict:
+ """Build the list of created_at corrections without writing anything.
+
+ Resolves the team's project (and its sibling environments), reads the group type
+ mappings from Postgres, finds the earliest event timestamp per group column in
+ ClickHouse, and proposes lowering created_at to that earliest timestamp wherever
+ the current value is masking real events.
+ """
+ bind_contextvars(team_id=input.team_id)
+ logger = LOGGER.bind()
+
+ @database_sync_to_async
+ def fetch_mappings() -> dict:
+ try:
+ team = Team.objects.get(id=input.team_id)
+ except Team.DoesNotExist:
+ # Fatal: a missing team won't appear on retry. The workflow marks this type
+ # non-retryable so Temporal fails fast instead of spinning.
+ raise BackfillGroupTypeCreatedAtError(f"Team {input.team_id} not found")
+
+ project_id = team.project_id
+ # Group types are project-scoped, but events carry team_id, so the earliest
+ # event must be found across every environment in the project.
+ team_ids = list(Team.objects.filter(project_id=project_id).values_list("id", flat=True))
+ mappings = list(
+ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm
+ .filter(project_id=project_id)
+ .values("group_type", "group_type_index", "created_at")
+ )
+ return {"project_id": project_id, "team_ids": team_ids, "mappings": mappings}
+
+ pg = await fetch_mappings()
+ project_id = pg["project_id"]
+ team_ids = pg["team_ids"]
+ mappings = pg["mappings"]
+
+ result: dict = {
+ "team_id": input.team_id,
+ "project_id": project_id,
+ "team_ids_in_project": team_ids,
+ "updates": [],
+ "skipped": [],
+ }
+
+ if not mappings:
+ logger.info("No group type mappings for project", project_id=project_id)
+ return result
+
+ earliest = await _fetch_earliest_group_timestamps(team_ids)
+ result["updates"], result["skipped"] = _build_backfill_plan(mappings, earliest)
+
+ logger.info(
+ "Planned group type created_at backfill",
+ project_id=project_id,
+ updates=len(result["updates"]),
+ skipped=len(result["skipped"]),
+ )
+ return result
+
+
+def _build_backfill_plan(
+ mappings: list[dict], earliest: dict[int, datetime]
+) -> tuple[list[GroupTypeUpdate], list[dict]]:
+ """Decide which mappings need a lower created_at, given the earliest event per group.
+
+ A mapping is updated only when it currently masks real events — i.e. it has a
+ created_at that is strictly later than the earliest event carrying that group.
+ """
+ updates: list[GroupTypeUpdate] = []
+ skipped: list[dict] = []
+
+ for mapping in mappings:
+ index = mapping["group_type_index"]
+ group_type = mapping["group_type"]
+ created_at = mapping["created_at"]
+ earliest_ts = earliest.get(index)
+
+ if created_at is None:
+ # No created_at means HogQL never masks this group — nothing to fix.
+ skipped.append({"group_type_index": index, "group_type": group_type, "reason": "created_at already null"})
+ continue
+ if earliest_ts is None:
+ skipped.append(
+ {"group_type_index": index, "group_type": group_type, "reason": "no events carry this group"}
+ )
+ continue
+ if earliest_ts >= created_at:
+ skipped.append(
+ {
+ "group_type_index": index,
+ "group_type": group_type,
+ "reason": "created_at already at or before earliest event",
+ }
+ )
+ continue
+
+ updates.append(
+ {
+ "group_type": group_type,
+ "group_type_index": index,
+ "current_created_at": created_at.isoformat(),
+ "new_created_at": earliest_ts.isoformat(),
+ }
+ )
+
+ return updates, skipped
+
+
+async def _fetch_earliest_group_timestamps(team_ids: list[int]) -> dict[int, datetime]:
+ """Earliest event timestamp per $group_N column across the given teams, in UTC.
+
+ Returns only indexes that actually have at least one event carrying the group;
+ timestamps are floored to the second, which can only widen visibility (never mask).
+ """
+ select_exprs = ", ".join(
+ f"toUnixTimestamp(minIf(timestamp, notEmpty(`$group_{i}`))) AS min_{i}, "
+ f"countIf(notEmpty(`$group_{i}`)) AS cnt_{i}"
+ for i in GROUP_TYPE_INDEXES
+ )
+ query = f"""
+ SELECT {select_exprs}
+ FROM events
+ WHERE team_id IN %(team_ids)s
+ FORMAT JSONEachRow
+ """
+
+ async with get_client() as client:
+ rows = await client.read_query_as_jsonl(
+ query,
+ query_parameters={"team_ids": tuple(team_ids)},
+ query_id=str(uuid4()),
+ )
+
+ result: dict[int, datetime] = {}
+ if not rows:
+ return result
+
+ row = rows[0]
+ for i in GROUP_TYPE_INDEXES:
+ if int(row[f"cnt_{i}"]) > 0:
+ result[i] = datetime.fromtimestamp(int(row[f"min_{i}"]), tz=UTC)
+ return result
+
+
[email protected](name="apply-group-type-created-at-backfill")
+async def apply_group_type_created_at_backfill(input: ApplyBackfillInput) -> dict:
+ """Write the planned created_at values to Postgres and invalidate the cache.
+
+ The group type mapping table is personhog-owned (managed=False) but its created_at
+ has no personhog RPC, so we write directly to the persons DB — mirroring the ORM
+ fallback used elsewhere in group_type_mapping.py — then bust the group-types cache
+ so HogQL reads the new value instead of the stale masked one.
+ """
+ bind_contextvars(project_id=input.project_id)
+ logger = LOGGER.bind()
+
+ @database_sync_to_async
+ def apply() -> int:
+ updated = 0
+ for update in input.updates:
+ new_created_at = datetime.fromisoformat(update["new_created_at"])
+ # created_at__gt enforces the "only lower" invariant at the DB level, so a
+ # re-run — or the ingestion fix landing between plan and apply — can never
+ # raise created_at back up.
+ updated += (
+ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm
+ .filter(
+ project_id=input.project_id,
+ group_type_index=update["group_type_index"],
+ created_at__gt=new_created_at,
+ )
+ .update(created_at=new_created_at)
+ )
+ invalidate_group_types_cache(input.project_id)
+ return updated
+
+ updated = await apply()
+ logger.info("Applied group type created_at backfill", project_id=input.project_id, updated=updated)
+ return {"updated": updated}
diff --git a/posthog/temporal/backfill_group_type_created_at/types.py b/posthog/temporal/backfill_group_type_created_at/types.py
new file mode 100644
index 000000000000..3e412b5da761
--- /dev/null
+++ b/posthog/temporal/backfill_group_type_created_at/types.py
@@ -0,0 +1,56 @@
+from dataclasses import dataclass
+from typing import TypedDict
+
+from pydantic import BaseModel
+
+
+class GroupTypeUpdate(TypedDict):
+ """A single created_at correction, produced by the plan activity and applied by the apply activity."""
+
+ group_type: str
+ group_type_index: int
+ current_created_at: str # ISO-8601
+ new_created_at: str # ISO-8601
+
+
+class BackfillGroupTypeCreatedAtInput(BaseModel):
+ """Input for the group type created_at backfill workflow.
+
+ Imports stamp posthog_grouptypemapping.created_at with wall-clock now, which
+ postdates the imported events. HogQL then masks $group_N for events older than
+ created_at, hiding historical group data. This workflow recomputes created_at
+ from the earliest event actually carrying each group, across every environment
+ (team) in the project.
+ """
+
+ team_id: int
+ dry_run: bool = False
+
+
+@dataclass
+class PlanBackfillInput:
+ """Input for planning the backfill — resolves the project and reads both stores."""
+
+ team_id: int
+
+
+@dataclass
+class ApplyBackfillInput:
+ """Input for applying the planned created_at updates to Postgres.
+
+ `updates` is the list produced by the planning activity, each item carrying
+ `group_type_index` and the `new_created_at` ISO string to write.
+ """
+
+ project_id: int
+ updates: list[GroupTypeUpdate]
+
+
+class BackfillGroupTypeCreatedAtError(Exception):
+ """Fatal error during the backfill.
+
+ Listed in the plan activity's RetryPolicy.non_retryable_error_types (by class name),
+ so Temporal fails fast instead of retrying an error that won't resolve on its own.
+ """
+
+ pass
diff --git a/posthog/temporal/backfill_group_type_created_at/workflows.py b/posthog/temporal/backfill_group_type_created_at/workflows.py
new file mode 100644
index 000000000000..eb7b5340f51a
--- /dev/null
+++ b/posthog/temporal/backfill_group_type_created_at/workflows.py
@@ -0,0 +1,80 @@
+import json
+from datetime import timedelta
+from typing import Any
+
+from temporalio import common, workflow
+
+from posthog.temporal.backfill_group_type_created_at.activities import (
+ apply_group_type_created_at_backfill,
+ plan_group_type_created_at_backfill,
+)
+from posthog.temporal.backfill_group_type_created_at.types import (
+ ApplyBackfillInput,
+ BackfillGroupTypeCreatedAtInput,
+ PlanBackfillInput,
+)
+from posthog.temporal.common.base import PostHogWorkflow
+
+
[email protected](name="backfill-group-type-created-at")
+class BackfillGroupTypeCreatedAtWorkflow(PostHogWorkflow):
+ """Recompute posthog_grouptypemapping.created_at from the earliest event per group.
+
+ Imported historical events get masked in HogQL because the group type mapping's
+ created_at postdates them. This workflow lowers created_at to the earliest event
+ actually carrying each group, unblocking insights and dashboards for one customer.
+ Supports dry_run to preview the planned changes without writing.
+ """
+
+ @staticmethod
+ def parse_inputs(input: list[str]) -> BackfillGroupTypeCreatedAtInput:
+ loaded = json.loads(input[0])
+ return BackfillGroupTypeCreatedAtInput(**loaded)
+
+ @workflow.run
+ async def run(self, input: BackfillGroupTypeCreatedAtInput) -> dict:
+ plan = await workflow.execute_activity(
+ plan_group_type_created_at_backfill,
+ PlanBackfillInput(team_id=input.team_id),
+ # The ClickHouse min() scans the project's events; give it room.
+ start_to_close_timeout=timedelta(minutes=30),
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=30),
+ # A missing team is fatal — don't retry it (matched by class name).
+ non_retryable_error_types=["BackfillGroupTypeCreatedAtError"],
+ ),
+ )
+
+ result: dict[str, Any] = {
+ "team_id": input.team_id,
+ "project_id": plan["project_id"],
+ "dry_run": input.dry_run,
+ "updates": plan["updates"],
+ "skipped": plan["skipped"],
+ "updated": 0,
+ }
+
+ if input.dry_run:
+ workflow.logger.info(
+ f"DRY RUN: would backfill created_at for {len(plan['updates'])} group type mappings "
+ f"in project {plan['project_id']}: {plan['updates']}"
+ )
+ return result
+
+ if not plan["updates"]:
+ workflow.logger.info(f"No group type mappings need created_at backfill in project {plan['project_id']}")
+ return result
+
+ apply_result = await workflow.execute_activity(
+ apply_group_type_created_at_backfill,
+ ApplyBackfillInput(project_id=plan["project_id"], updates=plan["updates"]),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=30)),
+ )
+ result["updated"] = apply_result["updated"]
+
+ workflow.logger.info(
+ f"Backfilled created_at for {apply_result['updated']} group type mappings in project {plan['project_id']}"
+ )
+ return result
diff --git a/posthog/temporal/tests/backfill_group_type_created_at/__init__.py b/posthog/temporal/tests/backfill_group_type_created_at/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py
new file mode 100644
index 000000000000..2a59279afe2c
--- /dev/null
+++ b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py
@@ -0,0 +1,356 @@
+from datetime import UTC, datetime
+
+import pytest
+from posthog.test.base import _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from asgiref.sync import sync_to_async
+
+from posthog.models import Team
+from posthog.models.group_type_mapping import GroupTypeMapping
+from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+from posthog.temporal.backfill_group_type_created_at.activities import (
+ _build_backfill_plan,
+ apply_group_type_created_at_backfill,
+ plan_group_type_created_at_backfill,
+)
+from posthog.temporal.backfill_group_type_created_at.types import (
+ ApplyBackfillInput,
+ BackfillGroupTypeCreatedAtError,
+ GroupTypeUpdate,
+ PlanBackfillInput,
+)
+from posthog.test.test_utils import create_group_type_mapping_without_created_at
+
+CREATED_AT = datetime(2026, 5, 31, 22, 33, tzinfo=UTC)
+EARLIER = datetime(2026, 5, 12, 0, 0, tzinfo=UTC)
+LATER = datetime(2026, 6, 6, 0, 0, tzinfo=UTC)
+
+
+def _mapping(index: int, created_at: datetime | None) -> dict:
+ return {"group_type": f"g{index}", "group_type_index": index, "created_at": created_at}
+
+
+def test_build_plan_lowers_created_at_to_earliest_event():
+ updates, skipped = _build_backfill_plan([_mapping(0, CREATED_AT)], {0: EARLIER})
+
+ assert skipped == []
+ assert updates == [
+ {
+ "group_type": "g0",
+ "group_type_index": 0,
+ "current_created_at": CREATED_AT.isoformat(),
+ "new_created_at": EARLIER.isoformat(),
+ }
+ ]
+
+
+ "created_at,earliest,expected_reason",
+ [
+ (None, {0: EARLIER}, "created_at already null"),
+ (CREATED_AT, {}, "no events carry this group"),
+ (CREATED_AT, {0: LATER}, "created_at already at or before earliest event"),
+ (CREATED_AT, {0: CREATED_AT}, "created_at already at or before earliest event"),
+ ],
+)
+def test_build_plan_skips_when_no_correction_needed(created_at, earliest, expected_reason):
+ updates, skipped = _build_backfill_plan([_mapping(0, created_at)], earliest)
+
+ assert updates == []
+ assert len(skipped) == 1
+ assert skipped[0]["reason"] == expected_reason
+
+
+def test_build_plan_handles_mixed_mappings():
+ mappings = [_mapping(0, CREATED_AT), _mapping(1, None), _mapping(2, CREATED_AT)]
+ earliest = {0: EARLIER, 2: LATER}
+
+ updates, skipped = _build_backfill_plan(mappings, earliest)
+
+ assert [u["group_type_index"] for u in updates] == [0]
+ assert {s["group_type_index"] for s in skipped} == {1, 2}
+
+
+# Integration tests below exercise the real activities against Postgres + ClickHouse.
+
+MAPPING_CREATED_AT = datetime(2026, 5, 31, 22, 33, tzinfo=UTC)
+
+
+def _seed_mapping(team: Team, index: int, group_type: str, created_at: datetime | None) -> None:
+ if created_at is None:
+ create_group_type_mapping_without_created_at(
+ team=team, project_id=team.project_id, group_type=group_type, group_type_index=index
+ )
+ else:
+ GroupTypeMapping.objects.create(
+ team=team,
+ project_id=team.project_id,
+ group_type=group_type,
+ group_type_index=index,
+ created_at=created_at,
+ )
+
+
+def _seed_event(team: Team, distinct_id: str, group_index: int, group_key: str, timestamp: str) -> None:
+ # Setting properties[$group_N] populates the materialized $group_N column on the events table.
+ _create_event(
+ team=team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties={f"$group_{group_index}": group_key},
+ )
+
+
+def _read_created_at(project_id: int, index: int) -> datetime | None:
+ return (
+ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm
+ .get(project_id=project_id, group_type_index=index)
+ .created_at
+ )
+
+
[email protected]_db(transaction=True, databases=["default", "persons_db_writer", "persons_db_reader"])
+class TestPlanGroupTypeCreatedAtBackfillIntegration:
+ @pytest.fixture(autouse=True)
+ def setup(self, team, activity_environment):
+ self.team = team
+ self.activity_environment = activity_environment
+ yield
+ GroupTypeMapping.objects.filter(project_id=self.team.project_id).delete()
+
+ @pytest.mark.asyncio
+ async def test_lowers_created_at_to_earliest_event(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+ _seed_event(self.team, "u1", 0, "acme", "2023-03-01T00:00:00Z")
+ _seed_event(self.team, "u2", 0, "acme", "2023-01-15T10:00:00Z")
+ flush_persons_and_events()
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert result["project_id"] == self.team.project_id
+ assert result["skipped"] == []
+ assert len(result["updates"]) == 1
+ update = result["updates"][0]
+ assert update["group_type_index"] == 0
+ assert update["group_type"] == "organization"
+ assert datetime.fromisoformat(update["new_created_at"]) == datetime(2023, 1, 15, 10, 0, 0, tzinfo=UTC)
+ assert datetime.fromisoformat(update["current_created_at"]) == MAPPING_CREATED_AT
+
+ @pytest.mark.asyncio
+ async def test_skips_mapping_with_null_created_at(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", None)
+ _seed_event(self.team, "u1", 0, "acme", "2023-01-15T10:00:00Z")
+ flush_persons_and_events()
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert result["updates"] == []
+ assert any(s["reason"] == "created_at already null" for s in result["skipped"])
+
+ @pytest.mark.asyncio
+ async def test_skips_when_no_events_carry_the_group(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+ # Event carries a different group index, so $group_0 stays empty.
+ _seed_event(self.team, "u1", 1, "acme", "2023-01-15T10:00:00Z")
+ flush_persons_and_events()
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert result["updates"] == []
+ assert any(s["reason"] == "no events carry this group" for s in result["skipped"])
+
+ @pytest.mark.asyncio
+ async def test_skips_when_created_at_already_early(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", datetime(2020, 1, 1, tzinfo=UTC))
+ _seed_event(self.team, "u1", 0, "acme", "2023-01-15T10:00:00Z")
+ flush_persons_and_events()
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert result["updates"] == []
+ assert any(s["reason"] == "created_at already at or before earliest event" for s in result["skipped"])
+
+ @pytest.mark.asyncio
+ async def test_raises_for_invalid_team(self):
+ with pytest.raises(BackfillGroupTypeCreatedAtError, match="Team 99999999 not found"):
+ await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=99999999)
+ )
+
+ @pytest.mark.asyncio
+ async def test_considers_events_across_all_environments_in_project(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+ env_b = Team.objects.create(organization=self.team.organization, project=self.team.project, name="env-b")
+ # The earliest event lives in a sibling environment of the same project.
+ _seed_event(self.team, "u1", 0, "acme", "2023-03-01T00:00:00Z")
+ _seed_event(env_b, "u2", 0, "acme", "2023-01-01T00:00:00Z")
+ flush_persons_and_events()
+ return env_b.id
+
+ env_b_id = await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert env_b_id in result["team_ids_in_project"]
+ assert len(result["updates"]) == 1
+ assert datetime.fromisoformat(result["updates"][0]["new_created_at"]) == datetime(2023, 1, 1, tzinfo=UTC)
+
+ @pytest.mark.asyncio
+ async def test_ignores_events_from_other_projects(self, organization):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+ other_project_team = Team.objects.create(organization=organization, name="other-project")
+ # A much earlier event exists, but under a team in a DIFFERENT project.
+ _seed_event(self.team, "u1", 0, "acme", "2023-03-01T00:00:00Z")
+ _seed_event(other_project_team, "u2", 0, "acme", "2020-01-01T00:00:00Z")
+ flush_persons_and_events()
+ return other_project_team.id
+
+ other_team_id = await seed()
+
+ result = await self.activity_environment.run(
+ plan_group_type_created_at_backfill, PlanBackfillInput(team_id=self.team.id)
+ )
+
+ assert other_team_id not in result["team_ids_in_project"]
+ assert len(result["updates"]) == 1
+ # The other project's 2020 event must not pull this project's created_at back.
+ assert datetime.fromisoformat(result["updates"][0]["new_created_at"]) == datetime(2023, 3, 1, tzinfo=UTC)
+
+
[email protected]_db(transaction=True, databases=["default", "persons_db_writer", "persons_db_reader"])
+class TestApplyGroupTypeCreatedAtBackfillIntegration:
+ @pytest.fixture(autouse=True)
+ def setup(self, team, activity_environment):
+ self.team = team
+ self.activity_environment = activity_environment
+ yield
+ GroupTypeMapping.objects.filter(project_id=self.team.project_id).delete()
+
+ def _update(self, index: int, new_created_at: datetime) -> GroupTypeUpdate:
+ return {
+ "group_type": "organization",
+ "group_type_index": index,
+ "current_created_at": MAPPING_CREATED_AT.isoformat(),
+ "new_created_at": new_created_at.isoformat(),
+ }
+
+ @pytest.mark.asyncio
+ async def test_lowers_created_at(self):
+ target = datetime(2023, 1, 15, 10, 0, 0, tzinfo=UTC)
+
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ apply_group_type_created_at_backfill,
+ ApplyBackfillInput(project_id=self.team.project_id, updates=[self._update(0, target)]),
+ )
+
+ assert result["updated"] == 1
+ assert await sync_to_async(_read_created_at)(self.team.project_id, 0) == target
+
+ @pytest.mark.asyncio
+ async def test_does_not_raise_created_at(self):
+ # The created_at__gt guard must make this a no-op: the stored value is already earlier.
+ already_early = datetime(2020, 1, 1, tzinfo=UTC)
+
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", already_early)
+
+ await seed()
+
+ result = await self.activity_environment.run(
+ apply_group_type_created_at_backfill,
+ ApplyBackfillInput(
+ project_id=self.team.project_id, updates=[self._update(0, datetime(2023, 1, 1, tzinfo=UTC))]
+ ),
+ )
+
+ assert result["updated"] == 0
+ assert await sync_to_async(_read_created_at)(self.team.project_id, 0) == already_early
+
+ @pytest.mark.asyncio
+ async def test_only_updates_target_project(self, organization):
+ target = datetime(2023, 1, 1, tzinfo=UTC)
+
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+ other_team = Team.objects.create(organization=organization, name="other-project")
+ GroupTypeMapping.objects.create(
+ team=other_team,
+ project_id=other_team.project_id,
+ group_type="organization",
+ group_type_index=0,
+ created_at=MAPPING_CREATED_AT,
+ )
+ return other_team.project_id
+
+ other_project_id = await seed()
+
+ await self.activity_environment.run(
+ apply_group_type_created_at_backfill,
+ ApplyBackfillInput(project_id=self.team.project_id, updates=[self._update(0, target)]),
+ )
+
+ assert await sync_to_async(_read_created_at)(self.team.project_id, 0) == target
+ # The other project's mapping must be untouched.
+ assert await sync_to_async(_read_created_at)(other_project_id, 0) == MAPPING_CREATED_AT
+
+ await sync_to_async(GroupTypeMapping.objects.filter(project_id=other_project_id).delete)()
+
+ @pytest.mark.asyncio
+ async def test_invalidates_group_types_cache(self):
+ @sync_to_async
+ def seed():
+ _seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)
+
+ await seed()
+
+ with patch(
+ "posthog.temporal.backfill_group_type_created_at.activities.invalidate_group_types_cache"
+ ) as mock_invalidate:
+ await self.activity_environment.run(
+ apply_group_type_created_at_backfill,
+ ApplyBackfillInput(
+ project_id=self.team.project_id, updates=[self._update(0, datetime(2023, 1, 1, tzinfo=UTC))]
+ ),
+ )
+
+ mock_invalidate.assert_called_once_with(self.team.project_id)
diff --git a/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py b/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py
new file mode 100644
index 000000000000..dfc7f3677dd8
--- /dev/null
+++ b/posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py
@@ -0,0 +1,156 @@
+import uuid
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from posthog.temporal.backfill_group_type_created_at.types import (
+ ApplyBackfillInput,
+ BackfillGroupTypeCreatedAtInput,
+ PlanBackfillInput,
+)
+from posthog.temporal.backfill_group_type_created_at.workflows import BackfillGroupTypeCreatedAtWorkflow
+
+TEST_TEAM_ID = 12345
+TEST_PROJECT_ID = 12345
+SAMPLE_UPDATES = [
+ {
+ "group_type": "customer",
+ "group_type_index": 0,
+ "current_created_at": "2026-05-31T22:33:00+00:00",
+ "new_created_at": "2026-05-12T00:00:00+00:00",
+ }
+]
+
+
+async def test_workflow_applies_planned_updates():
+ applied_updates = None
+
+ @activity.defn(name="plan-group-type-created-at-backfill")
+ async def plan_mocked(input: PlanBackfillInput) -> dict:
+ assert input.team_id == TEST_TEAM_ID
+ return {
+ "team_id": TEST_TEAM_ID,
+ "project_id": TEST_PROJECT_ID,
+ "team_ids_in_project": [TEST_TEAM_ID],
+ "updates": SAMPLE_UPDATES,
+ "skipped": [],
+ }
+
+ @activity.defn(name="apply-group-type-created-at-backfill")
+ async def apply_mocked(input: ApplyBackfillInput) -> dict:
+ nonlocal applied_updates
+ assert input.project_id == TEST_PROJECT_ID
+ applied_updates = input.updates
+ return {"updated": len(input.updates)}
+
+ task_queue_name = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue_name,
+ workflows=[BackfillGroupTypeCreatedAtWorkflow],
+ activities=[plan_mocked, apply_mocked],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ BackfillGroupTypeCreatedAtWorkflow.run,
+ BackfillGroupTypeCreatedAtInput(team_id=TEST_TEAM_ID, dry_run=False),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue_name,
+ )
+
+ assert result["team_id"] == TEST_TEAM_ID
+ assert result["project_id"] == TEST_PROJECT_ID
+ assert result["dry_run"] is False
+ assert result["updated"] == 1
+ assert result["updates"] == SAMPLE_UPDATES
+ assert applied_updates == SAMPLE_UPDATES
+
+
+async def test_workflow_dry_run_does_not_apply():
+ @activity.defn(name="plan-group-type-created-at-backfill")
+ async def plan_mocked(input: PlanBackfillInput) -> dict:
+ return {
+ "team_id": TEST_TEAM_ID,
+ "project_id": TEST_PROJECT_ID,
+ "team_ids_in_project": [TEST_TEAM_ID],
+ "updates": SAMPLE_UPDATES,
+ "skipped": [],
+ }
+
+ @activity.defn(name="apply-group-type-created-at-backfill")
+ async def apply_mocked(input: ApplyBackfillInput) -> dict:
+ raise AssertionError("Should not be called in dry run mode")
+
+ task_queue_name = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue_name,
+ workflows=[BackfillGroupTypeCreatedAtWorkflow],
+ activities=[plan_mocked, apply_mocked],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ BackfillGroupTypeCreatedAtWorkflow.run,
+ BackfillGroupTypeCreatedAtInput(team_id=TEST_TEAM_ID, dry_run=True),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue_name,
+ )
+
+ assert result["dry_run"] is True
+ assert result["updated"] == 0
+ assert result["updates"] == SAMPLE_UPDATES
+
+
+async def test_workflow_skips_apply_when_nothing_to_update():
+ @activity.defn(name="plan-group-type-created-at-backfill")
+ async def plan_mocked(input: PlanBackfillInput) -> dict:
+ return {
+ "team_id": TEST_TEAM_ID,
+ "project_id": TEST_PROJECT_ID,
+ "team_ids_in_project": [TEST_TEAM_ID],
+ "updates": [],
+ "skipped": [{"group_type_index": 0, "group_type": "customer", "reason": "created_at already null"}],
+ }
+
+ @activity.defn(name="apply-group-type-created-at-backfill")
+ async def apply_mocked(input: ApplyBackfillInput) -> dict:
+ raise AssertionError("Should not be called when there are no updates")
+
+ task_queue_name = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue_name,
+ workflows=[BackfillGroupTypeCreatedAtWorkflow],
+ activities=[plan_mocked, apply_mocked],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ BackfillGroupTypeCreatedAtWorkflow.run,
+ BackfillGroupTypeCreatedAtInput(team_id=TEST_TEAM_ID, dry_run=False),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue_name,
+ )
+
+ assert result["updated"] == 0
+ assert result["updates"] == []
+ assert len(result["skipped"]) == 1
+
+
+def test_workflow_parse_inputs():
+ result = BackfillGroupTypeCreatedAtWorkflow.parse_inputs(['{"team_id": 12345, "dry_run": true}'])
+ assert result.team_id == 12345
+ assert result.dry_run is True
+
+ result = BackfillGroupTypeCreatedAtWorkflow.parse_inputs(['{"team_id": 99999}'])
+ assert result.team_id == 99999
+ assert result.dry_run is False