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(warehouse): add groups dagster backfills (#116508)

Eric Duongf2b2a0eb9e0d
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index e61d6d8b9769..4a17a44e35cf 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -158,7 +158,7 @@ Trino table rendering stays in Trino-specific modules. Neither the built-in numb
After deployment, Django shell can call the same compilation API. Construct the context with the intended team, user, effective modifiers, and `Database.create_for(...)`, then supply explicit Trino locators. No new HTTP endpoint or scheduled job is required.
-For managed DuckLake data, call `compile_hogql_to_trino_sql(...)` through the managed-warehouse client facade. This explicit entry point reads the organization's ready Trino catalog from the control plane and combines it with the project's authoritative team row. Pure manifest-backed compilation is the default. It maps `events` and `persons` to the project's provisioned tables in the `posthog` schema, and accepts additional allowlisted warehouse relations through `catalog_manifest`.
+For managed DuckLake data, call `compile_hogql_to_trino_sql(...)` through the managed-warehouse client facade. This explicit entry point reads the organization's ready Trino catalog from the control plane and combines it with the project's authoritative team row. Pure manifest-backed compilation is the default. It maps `events`, `persons`, and `groups` to the project's provisioned tables in the `posthog` schema, and accepts additional allowlisted warehouse relations through `catalog_manifest`.
Batch and session callers should use `prepare_hogql_to_trino_compiler(...)` through the same facade. Preparation resolves and validates the ready catalog and project mapping once, then builds the pure manifest catalog. The returned compiler is bound to that organization, project, and catalog and accepts only a `HogQLQuery` per compilation. Additional manifest relations keep their explicitly allowlisted physical locators; Trino authorizes catalog access when the query executes.
@@ -176,7 +176,7 @@ Previously stored diagnostic translations are not rewritten automatically; rerun
Pass `expansion_mode=TrinoExpansionMode.DJANGO` when a query requires actions, cohorts, saved queries, filters, variables, access-controlled warehouse discovery, or other Django-backed semantic expansion. This compatibility mode builds the full database and maps:
-- `events` and `persons` to the project's provisioned tables in the `posthog` schema;
+- `events`, `persons`, and `groups` to the project's provisioned tables in the `posthog` schema;
- materialized saved queries to their `posthog_data_modeling_team_<team_id>` DuckLake copies;
- copied warehouse sources to their provisioned data-import schema and table names.
@@ -194,6 +194,30 @@ Source metadata describes what HogQL means. Target mappings describe where the c
`test_trino_semantics.py` exercises action expansion, cohort expansion, V2 person attribution, and unsupported-mode rejection through the compilation API without using the execution adapter. A batch export script is a separate operational tool, not part of this release.
+## Managed warehouse groups
+
+`duckling_groups_backfill_job` exports a full ClickHouse groups snapshot for each enabled team to Parquet and registers the files in DuckLake.
+The full-backfill sensor rotates through at most 25 teams per tick, schedules at most three runs, and retries failures with exponential backoff from 10 to 320 minutes.
+The partition key is the team ID; rerun that partition in Dagster to refresh the snapshot.
+There is no daily groups top-up sensor.
+The sensor defaults to stopped for controlled rollout. Validate a manual team snapshot before starting automatic discovery; see the [groups rollout steps](../../posthog/dags/README_DUCKLINGS.md#groups-backfill).
+Starting the sensor discovers all eligible teams, including existing memberships. A stored running sensor state must be stopped explicitly in Dagster.
+
+The table name is `posthog.groups_<schema_name>`, derived from the control-plane team membership, including teams with grandfathered events or persons table names.
+Legacy teams without a membership use `posthog.groups` for manual runs.
+The export keeps the latest row per `(team_id, group_type_index, group_key)` using `_timestamp` and `_offset`.
+The export sorts rows by group type and key for Parquet encoding and pruning.
+A successful registration replaces the team's snapshot in one transaction, including clearing old rows when the source is empty.
+A generation reserved before export is committed with the rows in the table's `posthog_groups_backfill:` comment. Older exports are rejected after a newer snapshot commits, and a new epoch fences exports from before a table reset.
+The legacy shared `groups` table cannot be dropped with `delete_tables`.
+Failed exports leave the previous snapshot in place.
+Dry runs and S3-only exports are tagged as previews and do not mark the warehouse groups snapshot complete or hide prior snapshot history. Active runs are checked separately.
+Backfill lifecycle and metrics are recorded with dataset `groups`; the warehouse status UI continues to report events, persons, and sources.
+
+Both Django and pure Trino compilation map `groups` and `raw_groups` to the provisioned groups table.
+The physical columns preserve the ClickHouse groups schema, so HogQL `index`, `key`, `properties`, and `updated_at` resolve to `group_type_index`, `group_key`, `group_properties`, and `_timestamp`.
+Groups queries require the groups backfill to have created the table.
+
## Managed warehouse bulk translation
`managed-warehouse.translate-views` is the tracked bulk consumer of the managed-warehouse compiler facade. It calls `compile_hogql_to_trino_sql(...)` with `expansion_mode=TrinoExpansionMode.DJANGO` and `include_hogql=True`, because views reference saved queries and warehouse relations that pure manifest-backed compilation rejects. A `ManagedWarehouseViewTranslationJob` identifies the organization, trigger, Temporal run, aggregate counts, and terminal status. Its team-scoped `ManagedWarehouseViewTranslationResult` rows identify the saved-query snapshot and store either compiled SQL or an error.
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.md
index 51eb801ffe4b..5dc81c23aa79 100644
--- a/posthog/dags/README_DUCKLINGS.md
+++ b/posthog/dags/README_DUCKLINGS.md
@@ -8,7 +8,7 @@ This document describes the Dagster jobs and sensors for backfilling ClickHouse
DuckgresServer (Django model) + control-plane team rows
│ DuckgresServer stores the org connection; control-plane rows gate each team's enablement
▼
-ClickHouse (events/person tables)
+ClickHouse (events/person/groups tables)
│ export via s3() - bucket policy allows ClickHouse EC2 role
▼
Duckling S3 Bucket (parquet files)
@@ -42,6 +42,33 @@ Duckling RDS Catalog (PostgreSQL)
| `duckling_persons_daily_backfill_sensor` | Hourly sensor for yesterday's data (top-up) |
| `duckling_persons_full_backfill_sensor` | Sensor for historical backfill (full export) |
+### Groups backfill
+
+`duckling_groups_backfill_job` runs a full snapshot per team using the team ID as its partition key.
+`duckling_groups_full_backfill_sensor` discovers teams with backfills enabled in a ready warehouse and retries failed runs.
+Rerun a team partition manually to refresh its groups; there is no daily groups top-up sensor.
+Each sensor tick checks at most 25 teams, schedules at most three runs, and advances a cursor so repeated failures cannot block discovery.
+Failed snapshots retry with exponential backoff from 10 minutes to a maximum of 320 minutes.
+The sensor checks active runs separately from real snapshot history; previews do not hide a successful or active snapshot.
+The export uses the latest group properties from ClickHouse, sorts by group type and key, and replaces the team's DuckLake snapshot in a transaction.
+Before exporting, the job reserves a generation in the table comment. Registration commits that generation with the rows, so an older export cannot overwrite a newer snapshot, including an empty one.
+A table reset starts a new generation epoch. The `posthog_groups_backfill:` table comment is reserved for snapshot state; do not edit it manually.
+Output metadata reports `superseded: true` when a newer snapshot or table reset prevents registration.
+`delete_tables` is refused for the legacy shared `groups` table.
+The job shares the events/persons backfill concurrency limit and supports `dry_run` and `skip_ducklake_registration`.
+Groups snapshots require `cleanup_existing_partition_data: true`.
+
+The groups sensor defaults to stopped. Use a manual snapshot to validate rollout before enabling automatic discovery:
+
+1. Deploy the job and confirm `duckling_groups_full_backfill_sensor` is stopped in Dagster. The default does not override a previously stored running state.
+2. Add the selected team's ID to the `duckling_groups_backfill` dynamic partition set.
+3. Launch `duckling_groups_backfill_job` for that partition with `dry_run: false`, `skip_ducklake_registration: false`, and `delete_tables: false`.
+4. Verify the latest groups per type/key against ClickHouse and run a managed warehouse HogQL groups query. Use Dagster run status and output metadata to inspect registration.
+5. Start `duckling_groups_full_backfill_sensor` to discover all teams with `backfill_enabled: true` in ready warehouses. The successful manual snapshot is skipped.
+
+Stop the sensor to pause new discovery. Stop queued or active runs separately if they must not finish.
+Groups query mapping is available before the first snapshot completes; queries can fail before table creation or read an empty table during the initial export.
+
## Partition Strategy
Partitions use a composite key format: `{team_id}_{YYYY-MM-DD}`
diff --git a/posthog/dags/locations/data_stack.py b/posthog/dags/locations/data_stack.py
index c0cb670b57d1..f035cbb8c195 100644
--- a/posthog/dags/locations/data_stack.py
+++ b/posthog/dags/locations/data_stack.py
@@ -3,20 +3,24 @@ import dagster
from posthog.dags import events_backfill_to_duckling
from products.data_warehouse.backend.facade.dags import managed_viewset_sync
+from products.managed_warehouse.backend.facade.dags import groups_backfill
from . import loggers, resources
defs = dagster.Definitions(
assets=[
+ groups_backfill.duckling_groups_backfill,
events_backfill_to_duckling.duckling_events_backfill,
events_backfill_to_duckling.duckling_persons_backfill,
],
jobs=[
+ groups_backfill.duckling_groups_backfill_job,
managed_viewset_sync.sync_managed_viewsets_job,
events_backfill_to_duckling.duckling_events_backfill_job,
events_backfill_to_duckling.duckling_persons_backfill_job,
],
sensors=[
+ groups_backfill.duckling_groups_full_backfill_sensor,
events_backfill_to_duckling.duckling_events_daily_backfill_sensor,
events_backfill_to_duckling.duckling_events_full_backfill_sensor,
events_backfill_to_duckling.duckling_persons_daily_backfill_sensor,
diff --git a/posthog/hogql/transforms/trino/manifest.py b/posthog/hogql/transforms/trino/manifest.py
index 514b5a75c840..b7575bb0d150 100644
--- a/posthog/hogql/transforms/trino/manifest.py
+++ b/posthog/hogql/transforms/trino/manifest.py
@@ -115,7 +115,7 @@ class PreparedTrinoCatalog:
)
-_CORE_TABLES = frozenset({"events", "persons"})
+_CORE_TABLES = frozenset({"events", "persons", "groups", "raw_groups"})
_SUPPORTED_PURE_MODIFIERS = frozenset({"personsOnEventsMode", "convertToProjectTimezone"})
_FIELD_TYPES: dict[DatabaseSerializedFieldType, type[DatabaseField]] = {
DatabaseSerializedFieldType.INTEGER: IntegerDatabaseField,
diff --git a/products/data_warehouse/backend/migrations/0059_alter_managedwarehousebackfillpartition_dataset.py b/products/data_warehouse/backend/migrations/0059_alter_managedwarehousebackfillpartition_dataset.py
new file mode 100644
index 000000000000..650570fb1d0d
--- /dev/null
+++ b/products/data_warehouse/backend/migrations/0059_alter_managedwarehousebackfillpartition_dataset.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("data_warehouse", "0058_alter_managedwarehousebackfillpartition_team")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="managedwarehousebackfillpartition",
+ name="dataset",
+ field=models.CharField(
+ choices=[("events", "Events"), ("persons", "Persons"), ("groups", "Groups")], max_length=16
+ ),
+ ),
+ ]
diff --git a/products/data_warehouse/backend/migrations/max_migration.txt b/products/data_warehouse/backend/migrations/max_migration.txt
index 23ed9168b498..ab4220e7e294 100644
--- a/products/data_warehouse/backend/migrations/max_migration.txt
+++ b/products/data_warehouse/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0058_alter_managedwarehousebackfillpartition_team
+0059_alter_managedwarehousebackfillpartition_dataset
diff --git a/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py b/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py
index c80462f71e8b..ade4c01f7c07 100644
--- a/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py
+++ b/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py
@@ -8,6 +8,7 @@ class ManagedWarehouseBackfillPartition(TeamScopedRootMixin, UUIDModel):
class Dataset(models.TextChoices):
EVENTS = "events", "Events"
PERSONS = "persons", "Persons"
+ GROUPS = "groups", "Groups"
class Granularity(models.TextChoices):
DAY = "day", "Day"
diff --git a/products/managed_warehouse/backend/cp_teams.py b/products/managed_warehouse/backend/cp_teams.py
index 590126b690fc..56c73158d628 100644
--- a/products/managed_warehouse/backend/cp_teams.py
+++ b/products/managed_warehouse/backend/cp_teams.py
@@ -31,7 +31,6 @@ import time
import logging
import threading
from collections.abc import Callable
-from dataclasses import dataclass
from datetime import date
from functools import partial
@@ -39,8 +38,13 @@ from django.conf import settings
import requests as http_requests
+from posthog.dataclasses import frozen
from posthog.security.outbound_proxy import internal_requests
+from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehouseTableNames,
+ ManagedWarehouseTeamMembership,
+)
from products.managed_warehouse.backend.presentation import hogtower
logger = logging.getLogger(__name__)
@@ -50,7 +54,7 @@ logger = logging.getLogger(__name__)
CACHE_TTL_SECONDS: float = 60.0
-@dataclass
+@frozen
class CPTeam:
"""One duckgres control-plane org-team row."""
@@ -75,11 +79,31 @@ class CPTeam:
"""Persons table name: the grandfathered pin, else the transitional derivation."""
return self.persons_table_name or f"persons_{self.schema_name}"
+ @property
+ def resolved_groups_table(self) -> str:
+ return f"groups_{self.schema_name}"
+
@property
def resolved_data_imports_schema(self) -> str:
"""Data-imports schema: the grandfathered pin, else the transitional derivation."""
return self.schema_data_imports_name or f"posthog_data_imports_{self.schema_name}"
+ def to_membership(self) -> ManagedWarehouseTeamMembership:
+ return ManagedWarehouseTeamMembership(
+ team_id=self.team_id,
+ organization_id=self.organization_id,
+ schema_name=self.schema_name,
+ enabled=self.enabled,
+ backfill_enabled=self.backfill_enabled,
+ table_names=ManagedWarehouseTableNames(
+ events_table=self.resolved_events_table,
+ persons_table=self.resolved_persons_table,
+ groups_table=self.resolved_groups_table,
+ data_imports_schema=self.resolved_data_imports_schema,
+ ),
+ earliest_event_date=self.earliest_event_date,
+ )
+
def _parse_earliest_event_date(raw: object) -> date | None:
if not raw:
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index a1004a175606..77487ce81d55 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -217,6 +217,7 @@ class ManagedWarehouseTableNames:
events_table: str
persons_table: str
data_imports_schema: str
+ groups_table: str | None = None
@dataclass(frozen=True, kw_only=True)
diff --git a/products/managed_warehouse/backend/facade/cp_teams.py b/products/managed_warehouse/backend/facade/cp_teams.py
index bd514c159bd9..75c6e0d7a157 100644
--- a/products/managed_warehouse/backend/facade/cp_teams.py
+++ b/products/managed_warehouse/backend/facade/cp_teams.py
@@ -2,32 +2,7 @@
from __future__ import annotations
-from datetime import date
-from typing import Protocol
-
-from products.managed_warehouse.backend.facade.contracts import (
- ManagedWarehouseTableNames,
- ManagedWarehouseTeamMembership,
-)
-
-
-class _ControlPlaneTeam(Protocol):
- team_id: int
- organization_id: str
- schema_name: str
- enabled: bool
- backfill_enabled: bool
- earliest_event_date: date | None
-
- @property
- def resolved_events_table(self) -> str: ...
-
- @property
- def resolved_persons_table(self) -> str: ...
-
- @property
- def resolved_data_imports_schema(self) -> str: ...
-
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTeamMembership
__all__ = [
"clear_team_membership_cache",
@@ -39,22 +14,6 @@ __all__ = [
]
-def _to_membership(row: _ControlPlaneTeam) -> ManagedWarehouseTeamMembership:
- return ManagedWarehouseTeamMembership(
- team_id=row.team_id,
- organization_id=row.organization_id,
- schema_name=row.schema_name,
- enabled=row.enabled,
- backfill_enabled=row.backfill_enabled,
- table_names=ManagedWarehouseTableNames(
- events_table=row.resolved_events_table,
- persons_table=row.resolved_persons_table,
- data_imports_schema=row.resolved_data_imports_schema,
- ),
- earliest_event_date=row.earliest_event_date,
- )
-
-
def clear_team_membership_cache() -> None:
from products.managed_warehouse.backend import cp_teams
@@ -75,25 +34,25 @@ def list_org_team_memberships(
from products.managed_warehouse.backend import cp_teams
rows = cp_teams.list_org_teams(organization_id, use_cache=use_cache)
- return [_to_membership(row) for row in rows] if rows is not None else None
+ return [row.to_membership() for row in rows] if rows is not None else None
def get_org_team_membership(organization_id: str, team_id: int) -> ManagedWarehouseTeamMembership | None:
from products.managed_warehouse.backend import cp_teams
row = cp_teams.get_team(organization_id, team_id)
- return _to_membership(row) if row is not None else None
+ return row.to_membership() if row is not None else None
def list_team_memberships(*, use_cache: bool = True) -> list[ManagedWarehouseTeamMembership] | None:
from products.managed_warehouse.backend import cp_teams
rows = cp_teams.list_member_teams(use_cache=use_cache)
- return [_to_membership(row) for row in rows] if rows is not None else None
+ return [row.to_membership() for row in rows] if rows is not None else None
def list_enabled_backfill_team_memberships() -> list[ManagedWarehouseTeamMembership] | None:
from products.managed_warehouse.backend import cp_teams
rows = cp_teams.list_enabled_backfills()
- return [_to_membership(row) for row in rows] if rows is not None else None
+ return [row.to_membership() for row in rows] if rows is not None else None
diff --git a/products/managed_warehouse/backend/facade/dags.py b/products/managed_warehouse/backend/facade/dags.py
new file mode 100644
index 000000000000..b1d762b4a15a
--- /dev/null
+++ b/products/managed_warehouse/backend/facade/dags.py
@@ -0,0 +1,3 @@
+from products.managed_warehouse.dags import groups_backfill
+
+__all__ = ["groups_backfill"]
diff --git a/products/managed_warehouse/backend/facade/team_state.py b/products/managed_warehouse/backend/facade/team_state.py
index de6fade03997..69b99b924dc0 100644
--- a/products/managed_warehouse/backend/facade/team_state.py
+++ b/products/managed_warehouse/backend/facade/team_state.py
@@ -14,6 +14,7 @@ __all__ = [
"data_imports_table_naming_version",
"list_enabled_backfill_team_memberships",
"resolve_events_persons_tables",
+ "resolve_groups_table",
"team_backfill_membership",
"team_backfill_state",
]
@@ -25,6 +26,12 @@ def resolve_events_persons_tables(team_id: int) -> DucklingTables:
return team_state.resolve_events_persons_tables(team_id)
+def resolve_groups_table(team_id: int) -> str:
+ from products.managed_warehouse.backend import team_state
+
+ return team_state.resolve_groups_table(team_id)
+
+
def data_imports_schema(team_id: int) -> str:
from products.managed_warehouse.backend import team_state
diff --git a/products/managed_warehouse/backend/table_binding.py b/products/managed_warehouse/backend/table_binding.py
index 7e3b7442f362..f2ab9b205d45 100644
--- a/products/managed_warehouse/backend/table_binding.py
+++ b/products/managed_warehouse/backend/table_binding.py
@@ -73,6 +73,10 @@ def build_trino_table_locators(
"persons": (catalog_name, "posthog", table_names.persons_table),
}
+ if table_names.groups_table is not None:
+ for logical_name in ("groups", "raw_groups"):
+ locators[logical_name] = (catalog_name, "posthog", table_names.groups_table)
+
model_schema = ducklake_data_modeling_schema(team_id)
materialized_models = list(
DataWarehouseSavedQuery.objects.filter(team_id=team_id, is_materialized=True, table__isnull=False).exclude(
diff --git a/products/managed_warehouse/backend/team_state.py b/products/managed_warehouse/backend/team_state.py
index a8ec8524e397..04049d65ea4f 100644
--- a/products/managed_warehouse/backend/team_state.py
+++ b/products/managed_warehouse/backend/team_state.py
@@ -20,7 +20,6 @@ from products.managed_warehouse.backend.facade.contracts import (
CPUnavailableError,
DucklingTables,
ManagedWarehouseBackfillState,
- ManagedWarehouseTableNames,
ManagedWarehouseTeamMembership,
)
@@ -40,22 +39,6 @@ def _get_cp_row(team_id: int) -> cp_teams.CPTeam | None:
return next((team for team in teams if team.team_id == team_id), None)
-def _to_membership(row: cp_teams.CPTeam) -> ManagedWarehouseTeamMembership:
- return ManagedWarehouseTeamMembership(
- team_id=row.team_id,
- organization_id=row.organization_id,
- schema_name=row.schema_name,
- enabled=row.enabled,
- backfill_enabled=row.backfill_enabled,
- table_names=ManagedWarehouseTableNames(
- events_table=row.resolved_events_table,
- persons_table=row.resolved_persons_table,
- data_imports_schema=row.resolved_data_imports_schema,
- ),
- earliest_event_date=row.earliest_event_date,
- )
-
-
# --- events/persons table names (Dagster duckling backfill) -----------------------
@@ -76,6 +59,13 @@ def resolve_events_persons_tables(team_id: int) -> DucklingTables:
return DucklingTables(events_table=events_table, persons_table=persons_table)
+def resolve_groups_table(team_id: int) -> str:
+ row = _get_cp_row(team_id)
+ table = row.resolved_groups_table if row is not None else "groups"
+ validate_duckgres_identifier(table)
+ return table
+
+
# --- data-imports schema (v3 sink hot path) ---------------------------------------
@@ -117,7 +107,7 @@ def team_backfill_row(team_id: int) -> ManagedWarehouseTeamMembership | None:
except CPUnavailableError:
logger.warning("duckgres_team_state_cp_unavailable", call_site="team_backfill_row", team_id=team_id)
return None
- return _to_membership(row) if row is not None else None
+ return row.to_membership() if row is not None else None
def team_backfill_state(team_id: int) -> ManagedWarehouseBackfillState:
@@ -168,4 +158,4 @@ def list_enabled_backfill_rows(call_site: str) -> list[ManagedWarehouseTeamMembe
if cp_rows is None:
logger.warning("duckgres_team_state_cp_unavailable", call_site=call_site)
return []
- return [_to_membership(row) for row in sorted(cp_rows, key=lambda row: row.team_id)]
+ return [row.to_membership() for row in sorted(cp_rows, key=lambda row: row.team_id)]
diff --git a/products/managed_warehouse/backend/tests/test_groups_backfill.py b/products/managed_warehouse/backend/tests/test_groups_backfill.py
new file mode 100644
index 000000000000..c98c6794ea12
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_groups_backfill.py
@@ -0,0 +1,368 @@
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import cast
+
+import pytest
+import time_machine
+from unittest.mock import patch
+
+from django.conf import settings
+
+import duckdb
+import psycopg
+from dagster import DagsterInstance, DagsterRun, DagsterRunStatus, SensorResult, build_sensor_context, materialize
+from psycopg import sql
+
+from posthog.clickhouse.client.connection import get_client_from_pool
+from posthog.dags.events_backfill_to_duckling import DUCKLAKE_ALIAS, DucklingBackfillConfig, DucklingTarget
+
+from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehouseTableNames,
+ ManagedWarehouseTeamMembership,
+)
+from products.managed_warehouse.dags.groups_backfill import (
+ GROUPS_JOB_NAME,
+ GROUPS_SNAPSHOT_TAG,
+ MAX_TEAMS_PER_TICK,
+ RETRY_BASE_SECONDS,
+ duckling_groups_backfill,
+ duckling_groups_full_backfill_sensor,
+ ensure_groups_table,
+ groups_snapshot_select_sql,
+ replace_groups_snapshot,
+ reserve_groups_snapshot,
+)
+
+
+def test_groups_snapshot_deduplicates_keys_within_each_team_and_group_type(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "CLICKHOUSE_USE_HTTP", False)
+ with get_client_from_pool() as client:
+ client.execute("""
+ CREATE TEMPORARY TABLE groups (
+ team_id Int64, group_type_index UInt8, group_key String, group_properties String,
+ created_at DateTime64(6), _timestamp DateTime64(6), _offset UInt64
+ ) ENGINE = Memory
+ """)
+ try:
+ created = datetime(2025, 1, 1)
+ latest = datetime(2025, 1, 2)
+ client.execute(
+ "INSERT INTO groups VALUES",
+ [
+ (7, 0, "company", '{"name":"old"}', created, created, 1),
+ (7, 0, "company", '{"name":"latest"}', created, latest, 2),
+ (7, 0, "company", '{"name":"latest"}', created, latest, 2),
+ (7, 1, "company", '{"name":"another type"}', created, latest, 2),
+ (8, 0, "company", '{"name":"another team"}', created, latest, 2),
+ ],
+ )
+ rows = client.execute(groups_snapshot_select_sql(7))
+ finally:
+ client.execute("DROP TEMPORARY TABLE groups")
+ assert [row[:6] for row in rows] == [
+ (7, 0, "company", '{"name":"latest"}', created, latest),
+ (7, 1, "company", '{"name":"another type"}', created, latest),
+ ]
+
+
+class _LakeConnection:
+ def __init__(self, connection: duckdb.DuckDBPyConnection) -> None:
+ self.connection = connection
+
+ def execute(self, query: str | sql.Composable, params: tuple[object, ...] | None = None) -> _LakeConnection:
+ statement = query.as_string() if isinstance(query, sql.Composable) else query
+ self.connection.execute(statement.replace("%s", "?"), params)
+ return self
+
+ def fetchall(self) -> list[tuple[object, ...]]:
+ return self.connection.fetchall()
+
+ def cursor(self) -> _LakeConnection:
+ return self
+
+ def __enter__(self) -> _LakeConnection:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ pass
+
+ @contextmanager
+ def transaction(self) -> Iterator[None]:
+ self.connection.execute("BEGIN")
+ try:
+ yield
+ except BaseException:
+ self.connection.execute("ROLLBACK")
+ raise
+ else:
+ self.connection.execute("COMMIT")
+
+
+def lake(tmp_path: Path) -> Iterator[psycopg.Connection[tuple[object, ...]]]:
+ connection = duckdb.connect()
+ connection.execute("INSTALL ducklake")
+ connection.execute("LOAD ducklake")
+ connection.execute(
+ f"ATTACH 'ducklake:{tmp_path / 'catalog.ducklake'}' AS {DUCKLAKE_ALIAS} (DATA_PATH '{tmp_path / 'data'}')"
+ )
+ adapter = cast(psycopg.Connection[tuple[object, ...]], _LakeConnection(connection))
+ ensure_groups_table(adapter, "groups_production", DucklingBackfillConfig())
+ yield adapter
+ connection.close()
+
+
[email protected]("invalid_file", [False, True])
+def test_groups_snapshot_replacement_is_replayable_and_rolls_back_failed_registration(
+ lake: psycopg.Connection[tuple[object, ...]], tmp_path: Path, invalid_file: bool
+) -> None:
+ table = f"{DUCKLAKE_ALIAS}.posthog.groups_production"
+ target = DucklingTarget(team_id=7, organization_id="org", bucket="unused", bucket_region="us-east-1")
+ lake.execute(f"INSERT INTO {table} (team_id, group_type_index, group_key) VALUES (7, 0, 'old'), (8, 0, 'other')")
+ lake.execute(
+ f"COPY (SELECT * REPLACE ('new' AS group_key) FROM {table} WHERE team_id = 7) TO %s (FORMAT PARQUET)",
+ (str(tmp_path / "a.parquet"),),
+ )
+ ticket = reserve_groups_snapshot(lake, "groups_production")
+ if invalid_file:
+ (tmp_path / "b.parquet").write_bytes(b"invalid parquet")
+ with pytest.raises(duckdb.Error):
+ replace_groups_snapshot(lake, target, "groups_production", str(tmp_path / "*.parquet"), ticket)
+ assert lake.execute(f"SELECT team_id, group_key FROM {table} ORDER BY team_id").fetchall() == [
+ (7, "old"),
+ (8, "other"),
+ ]
+ else:
+ for _ in range(2):
+ assert (
+ replace_groups_snapshot(
+ lake, target, "groups_production", str(tmp_path / "*.parquet"), ticket
+ ).files_registered
+ == 1
+ )
+ assert lake.execute(f"SELECT team_id, group_key FROM {table} ORDER BY team_id").fetchall() == [
+ (7, "new"),
+ (8, "other"),
+ ]
+ empty_ticket = reserve_groups_snapshot(lake, "groups_production")
+ assert (
+ replace_groups_snapshot(
+ lake, target, "groups_production", str(tmp_path / "empty-*.parquet"), empty_ticket
+ ).files_registered
+ == 0
+ )
+ assert replace_groups_snapshot(
+ lake, target, "groups_production", str(tmp_path / "*.parquet"), ticket
+ ).superseded
+ assert lake.execute(f"SELECT team_id, group_key FROM {table}").fetchall() == [(8, "other")]
+
+
+_NOW = datetime(2026, 1, 1, tzinfo=UTC)
+
+
+def _membership(team_id: int) -> ManagedWarehouseTeamMembership:
+ return ManagedWarehouseTeamMembership(
+ team_id=team_id,
+ organization_id="org",
+ schema_name=f"team_{team_id}",
+ enabled=True,
+ backfill_enabled=True,
+ table_names=ManagedWarehouseTableNames(
+ events_table="events",
+ persons_table="persons",
+ groups_table=f"groups_{team_id}",
+ data_imports_schema="imports",
+ ),
+ earliest_event_date=None,
+ )
+
+
+def _add_run(
+ instance: DagsterInstance,
+ team_id: int,
+ run_id: str,
+ status: DagsterRunStatus,
+ *,
+ snapshot: bool = True,
+ age_seconds: int = RETRY_BASE_SECONDS + 1,
+) -> None:
+ instance.add_run(
+ DagsterRun(
+ job_name=GROUPS_JOB_NAME,
+ run_id=run_id,
+ status=status,
+ tags={"dagster/partition": str(team_id), GROUPS_SNAPSHOT_TAG: "true" if snapshot else "false"},
+ )
+ )
+ if status in (DagsterRunStatus.FAILURE, DagsterRunStatus.CANCELED):
+ run = instance.get_run_by_id(run_id)
+ assert run is not None
+ with time_machine.travel(_NOW - timedelta(seconds=age_seconds), tick=False):
+ instance.report_run_failed(run)
+
+
+ "status,preview,should_schedule",
+ [
+ (None, False, True),
+ (DagsterRunStatus.FAILURE, False, True),
+ (DagsterRunStatus.CANCELED, False, True),
+ (DagsterRunStatus.STARTING, False, False),
+ (DagsterRunStatus.SUCCESS, False, False),
+ (DagsterRunStatus.SUCCESS, True, True),
+ ],
+)
+@time_machine.travel(_NOW, tick=False)
+def test_groups_discovery_retries_only_when_no_snapshot_succeeded_or_is_running(
+ status: DagsterRunStatus | None, preview: bool, should_schedule: bool
+) -> None:
+ with DagsterInstance.ephemeral() as instance:
+ if status is not None:
+ instance.add_dynamic_partitions("duckling_groups_backfill", ["7"])
+ _add_run(instance, 7, "prior", status, snapshot=not preview)
+ with (
+ patch(
+ "products.managed_warehouse.dags.groups_backfill.list_enabled_backfill_team_memberships",
+ return_value=[_membership(7)],
+ ),
+ patch("products.managed_warehouse.dags.groups_backfill._repair_stale_running_statuses"),
+ ):
+ result = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance))
+ assert isinstance(result, SensorResult)
+ assert [r.partition_key for r in result.run_requests or []] == (["7"] if should_schedule else [])
+
+
[email protected]("prior_status", [DagsterRunStatus.SUCCESS, DagsterRunStatus.STARTED])
+@time_machine.travel(_NOW, tick=False)
+def test_preview_after_snapshot_or_during_active_snapshot_does_not_schedule_another_run(
+ prior_status: DagsterRunStatus,
+) -> None:
+ with DagsterInstance.ephemeral() as instance:
+ _add_run(instance, 7, "snapshot", prior_status)
+ _add_run(instance, 7, "preview", DagsterRunStatus.SUCCESS, snapshot=False)
+ with (
+ patch(
+ "products.managed_warehouse.dags.groups_backfill.list_enabled_backfill_team_memberships",
+ return_value=[_membership(7)],
+ ),
+ patch("products.managed_warehouse.dags.groups_backfill._repair_stale_running_statuses"),
+ ):
+ result = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance))
+ assert isinstance(result, SensorResult)
+ assert not result.run_requests
+
+
+@time_machine.travel(_NOW, tick=False)
+def test_failed_teams_do_not_starve_discovery_and_storage_reads_are_bounded() -> None:
+ memberships = [_membership(i) for i in range(1, MAX_TEAMS_PER_TICK + 10)]
+ with DagsterInstance.ephemeral() as instance:
+ for team_id in range(1, 4):
+ _add_run(instance, team_id, f"failure-{team_id}", DagsterRunStatus.FAILURE)
+ with (
+ patch(
+ "products.managed_warehouse.dags.groups_backfill.list_enabled_backfill_team_memberships",
+ return_value=memberships,
+ ),
+ patch("products.managed_warehouse.dags.groups_backfill._repair_stale_running_statuses"),
+ ):
+ first = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance))
+ assert isinstance(first, SensorResult)
+ second = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance, cursor=first.cursor))
+ assert isinstance(second, SensorResult)
+ assert [r.partition_key for r in second.run_requests or []] == ["4", "5", "6"]
+ for row in memberships:
+ _add_run(instance, row.team_id, f"success-{row.team_id}", DagsterRunStatus.SUCCESS)
+ with patch.object(instance, "get_run_records", wraps=instance.get_run_records) as reads:
+ scanned = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance))
+ assert isinstance(scanned, SensorResult)
+ assert scanned.cursor == str(MAX_TEAMS_PER_TICK)
+ assert reads.call_count <= MAX_TEAMS_PER_TICK
+ wrapped = duckling_groups_full_backfill_sensor(
+ build_sensor_context(instance=instance, cursor=str(memberships[-1].team_id))
+ )
+ assert isinstance(wrapped, SensorResult)
+ assert wrapped.cursor == str(MAX_TEAMS_PER_TICK)
+
+
[email protected]("age_seconds,expected", [(0, False), (RETRY_BASE_SECONDS + 1, True)])
+@time_machine.travel(_NOW, tick=False)
+def test_failed_snapshot_observes_retry_backoff(age_seconds: int, expected: bool) -> None:
+ with DagsterInstance.ephemeral() as instance:
+ _add_run(instance, 7, "failed", DagsterRunStatus.FAILURE, age_seconds=age_seconds)
+ with (
+ patch(
+ "products.managed_warehouse.dags.groups_backfill.list_enabled_backfill_team_memberships",
+ return_value=[_membership(7)],
+ ),
+ patch("products.managed_warehouse.dags.groups_backfill._repair_stale_running_statuses"),
+ ):
+ result = duckling_groups_full_backfill_sensor(build_sensor_context(instance=instance))
+ assert isinstance(result, SensorResult)
+ assert bool(result.run_requests) == expected
+
+
[email protected]("config", [{"dry_run": True}, {"skip_ducklake_registration": True}])
+def test_preview_clears_inherited_snapshot_tag(config: dict[str, bool]) -> None:
+ with DagsterInstance.ephemeral() as instance:
+ instance.add_dynamic_partitions("duckling_groups_backfill", ["7"])
+ with patch("products.managed_warehouse.dags.groups_backfill.run_groups_backfill"):
+ result = materialize(
+ [duckling_groups_backfill],
+ instance=instance,
+ partition_key="7",
+ tags={GROUPS_SNAPSHOT_TAG: "true"},
+ run_config={"ops": {"duckling_groups_backfill": {"config": config}}},
+ )
+ assert result.success
+ run = instance.get_run_by_id(result.run_id)
+ assert run is not None
+ assert run.tags[GROUPS_SNAPSHOT_TAG] == "false"
+
+
+def test_older_snapshot_cannot_overwrite_a_newer_snapshot(
+ lake: psycopg.Connection[tuple[object, ...]], tmp_path: Path
+) -> None:
+ table = f"{DUCKLAKE_ALIAS}.posthog.groups_production"
+ target = DucklingTarget(team_id=7, organization_id="org", bucket="unused", bucket_region="us-east-1")
+ lake.execute(f"INSERT INTO {table} (team_id, group_type_index, group_key) VALUES (7, 0, 'initial')")
+ lake.execute(
+ f"COPY (SELECT * REPLACE ('old' AS group_key) FROM {table}) TO %s (FORMAT PARQUET)",
+ (str(tmp_path / "old.parquet"),),
+ )
+ lake.execute(
+ f"COPY (SELECT * REPLACE ('new' AS group_key) FROM {table}) TO %s (FORMAT PARQUET)",
+ (str(tmp_path / "new.parquet"),),
+ )
+ old = reserve_groups_snapshot(lake, "groups_production")
+ new = reserve_groups_snapshot(lake, "groups_production")
+ adapter = cast(_LakeConnection, cast(object, lake))
+ competing = cast(psycopg.Connection[tuple[object, ...]], _LakeConnection(adapter.connection.cursor()))
+ execute = adapter.execute
+ interleaved = False
+
+ def commit_newer_before_older_marker(
+ query: str | sql.Composable, params: tuple[object, ...] | None = None
+ ) -> _LakeConnection:
+ nonlocal interleaved
+ if isinstance(query, sql.Composable) and query.as_string().startswith("COMMENT ON TABLE") and not interleaved:
+ interleaved = True
+ replace_groups_snapshot(competing, target, "groups_production", str(tmp_path / "new.parquet"), new)
+ return execute(query, params)
+
+ with patch.object(adapter, "execute", side_effect=commit_newer_before_older_marker):
+ assert replace_groups_snapshot(lake, target, "groups_production", str(tmp_path / "old.parquet"), old).superseded
+ assert interleaved
+ assert lake.execute(f"SELECT group_key FROM {table}").fetchall() == [("new",)]
+ ensure_groups_table(lake, "groups_production", DucklingBackfillConfig(delete_tables=True))
+ reset = reserve_groups_snapshot(lake, "groups_production")
+ assert reset.epoch != old.epoch
+ assert replace_groups_snapshot(lake, target, "groups_production", str(tmp_path / "old.parquet"), old).superseded
+
+
+def test_delete_tables_refuses_legacy_shared_table(lake: psycopg.Connection[tuple[object, ...]]) -> None:
+ with pytest.raises(ValueError, match="shared groups table"):
+ ensure_groups_table(lake, "groups", DucklingBackfillConfig(delete_tables=True))
diff --git a/products/managed_warehouse/backend/tests/test_team_state.py b/products/managed_warehouse/backend/tests/test_team_state.py
index b06e62180910..3fc892d401e7 100644
--- a/products/managed_warehouse/backend/tests/test_team_state.py
+++ b/products/managed_warehouse/backend/tests/test_team_state.py
@@ -109,10 +109,12 @@ class TestEventsPersonsTables:
org, team = _team()
with _patch_org_rows([_cp_row(team, "cp_schema", **overrides)]):
assert team_state.resolve_events_persons_tables(team.id) == expected
+ assert team_state.resolve_groups_table(team.id) == "groups_cp_schema"
def test_without_cp_row_falls_back_to_shared_tables(self) -> None:
org, team = _team()
with _patch_org_rows([]):
+ assert team_state.resolve_groups_table(team.id) == "groups"
assert team_state.resolve_events_persons_tables(team.id) == team_state.DucklingTables(
events_table="events", persons_table="persons"
)
@@ -122,6 +124,8 @@ class TestEventsPersonsTables:
with _patch_org_rows(None):
with pytest.raises(team_state.CPUnavailableError):
team_state.resolve_events_persons_tables(team.id)
+ with pytest.raises(team_state.CPUnavailableError):
+ team_state.resolve_groups_table(team.id)
def test_rejects_an_unsafe_resolved_name(self) -> None:
# Fail-closed SQL-safety: a CP row carrying a hostile identifier must never reach DDL.
@@ -210,6 +214,7 @@ class TestListEnabledBackfillRows:
events_table="events_cp_schema",
persons_table="persons_cp_schema",
data_imports_schema="posthog_data_imports_cp_schema",
+ groups_table="groups_cp_schema",
),
earliest_event_date=date(2020, 6, 15),
)
diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.py
index 48222336e4a6..8405d22cc3e6 100644
--- a/products/managed_warehouse/backend/tests/test_trino_compiler.py
+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py
@@ -49,6 +49,7 @@ def _membership(*, team_id: int, organization_id: str) -> ManagedWarehouseTeamMe
table_names=ManagedWarehouseTableNames(
events_table="events_production",
persons_table="persons_production",
+ groups_table="groups_production",
data_imports_schema="posthog_data_imports_production",
),
earliest_event_date=None,
@@ -425,6 +426,8 @@ class TestPreparedTrinoCompiler:
compiler = prepare_hogql_to_trino_compiler(team.pk, team=team)
first = compiler.compile(HogQLQuery(query="SELECT {value}", values={"value": "first"}))
second = compiler.compile(HogQLQuery(query="SELECT {value}", values={"value": "second"}))
+ groups = compiler.compile(HogQLQuery(query="SELECT index, key, properties.name FROM groups"))
+ raw_groups = compiler.compile(HogQLQuery(query="SELECT key, updated_at FROM raw_groups"))
get_catalog.assert_called_once_with(str(team.organization_id))
get_membership.assert_called_once_with(str(team.organization_id), team.pk)
@@ -434,6 +437,11 @@ class TestPreparedTrinoCompiler:
assert compiler.catalog_name == "org_catalog"
assert first.values == {"hogql_val_0": "first"}
assert second.values == {"hogql_val_0": "second"}
+ for result in (groups, raw_groups):
+ assert '"org_catalog"."posthog"."groups_production"' in result.sql
+ assert "group_key" in result.sql
+ assert "group_properties" in groups.sql
+ assert "_timestamp" in raw_groups.sql
def test_rejects_a_team_object_for_another_project(self) -> None:
team = _team()
@@ -545,6 +553,7 @@ def test_build_trino_table_locators_uses_provisioned_names_and_canonical_source_
table_names = ManagedWarehouseTableNames(
events_table="events_production",
persons_table="persons_production",
+ groups_table="groups_production",
data_imports_schema="imports_production",
)
database = mock.Mock()
@@ -564,6 +573,8 @@ def test_build_trino_table_locators_uses_provisioned_names_and_canonical_source_
assert locators == {
"events": ("org_catalog", "posthog", "events_production"),
"persons": ("org_catalog", "posthog", "persons_production"),
+ "groups": ("org_catalog", "posthog", "groups_production"),
+ "raw_groups": ("org_catalog", "posthog", "groups_production"),
"orders_model": (
"org_catalog",
f"posthog_data_modeling_team_{team.pk}",
diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.py
index 204a031975c3..6b555d1a0930 100644
--- a/products/managed_warehouse/backend/trino_compiler.py
+++ b/products/managed_warehouse/backend/trino_compiler.py
@@ -174,15 +174,26 @@ def prepare_hogql_to_trino_compiler(
raise TrinoTargetUnavailable("The physical table mapping does not match the requested project")
additional_tables = catalog_manifest.tables if catalog_manifest is not None else ()
- if any(table.logical_name in {"events", "persons"} for table in additional_tables):
+ if any(table.logical_name in {"events", "persons", "groups", "raw_groups"} for table in additional_tables):
_reject_pure_compilation(
TrinoLoweringError(
"TRINO_PURE_CORE_TABLE_OVERRIDE",
"core table manifest",
- detail="Managed warehouse compilation owns the events and persons physical mappings.",
+ detail="Managed warehouse compilation owns the core table physical mappings.",
),
feature_code="TRINO_PURE_CORE_TABLE_OVERRIDE",
)
+ groups_tables = (
+ tuple(
+ TrinoManifestTable(
+ logical_name=logical_name,
+ locator=(catalog_name, "posthog", membership.table_names.groups_table),
+ )
+ for logical_name in ("groups", "raw_groups")
+ )
+ if membership.table_names.groups_table is not None
+ else ()
+ )
pure_manifest = TrinoCatalogManifest(
tables=(
TrinoManifestTable(
@@ -193,6 +204,7 @@ def prepare_hogql_to_trino_compiler(
logical_name="persons",
locator=(catalog_name, "posthog", membership.table_names.persons_table),
),
+ *groups_tables,
*additional_tables,
),
timezone=team.timezone,
diff --git a/products/managed_warehouse/dags/groups_backfill.py b/products/managed_warehouse/dags/groups_backfill.py
new file mode 100644
index 000000000000..d79d34718235
--- /dev/null
+++ b/products/managed_warehouse/dags/groups_backfill.py
@@ -0,0 +1,409 @@
+import json
+from dataclasses import replace
+from typing import TYPE_CHECKING
+from uuid import uuid4
+
+from django.utils import timezone
+
+import psycopg
+from dagster import (
+ AssetExecutionContext,
+ DagsterRunStatus,
+ DefaultSensorStatus,
+ DynamicPartitionsDefinition,
+ RunRequest,
+ RunsFilter,
+ SensorEvaluationContext,
+ SensorResult,
+ asset,
+ define_asset_job,
+ sensor,
+)
+from psycopg import sql
+from tenacity import retry, retry_if_exception, stop_after_attempt, wait_random_exponential
+
+from posthog.hogql.escape_sql import escape_clickhouse_string
+
+from posthog.clickhouse.cluster import NodeRole, Workload
+from posthog.clickhouse.query_tagging import tags_context
+from posthog.cloud_utils import is_cloud
+from posthog.dags.common import JobOwners
+from posthog.dags.common.common import ACTIVE_RUN_STATUSES, dagster_tags, settings_with_log_comment
+from posthog.dags.events_backfill_to_duckling import (
+ DEFAULT_CLICKHOUSE_SETTINGS,
+ DUCKLAKE_ALIAS,
+ DUCKLING_BACKFILL_CONCURRENCY_TAG,
+ PARQUET_WRITER_SETTINGS,
+ DucklingBackfillConfig,
+ DucklingTarget,
+ _compute_fanout,
+ _DuckgresSession,
+ _get_cluster,
+ _glob_run_files,
+ _repair_stale_running_statuses,
+ _resolve_duckling_target,
+ get_s3_url_for_clickhouse,
+)
+from posthog.dataclasses import frozen
+
+from products.data_warehouse.backend.facade.backfill_status import record_backfill_finished, record_backfill_started
+from products.data_warehouse.backend.facade.models import ManagedWarehouseBackfillPartition
+from products.managed_warehouse.backend.facade.metrics import record_duckling_backfill_workload, track_duckling_backfill
+from products.managed_warehouse.backend.facade.team_state import (
+ list_enabled_backfill_team_memberships,
+ resolve_groups_table,
+)
+
+if TYPE_CHECKING:
+ from clickhouse_driver import Client
+
+GROUPS_DATASET = ManagedWarehouseBackfillPartition.Dataset.GROUPS
+GROUPS_JOB_NAME = "duckling_groups_backfill_job"
+GROUPS_SNAPSHOT_TAG = "groups_backfill/snapshot"
+MAX_TEAMS_PER_TICK = 25
+MAX_RUN_REQUESTS_PER_TICK = 3
+RETRY_HISTORY_LIMIT = 6
+RETRY_BASE_SECONDS = 600
+STATE_COMMENT_PREFIX = "posthog_groups_backfill:"
+GROUPS_TAGS = {"owner": JobOwners.TEAM_MANAGED_WAREHOUSE.value, **DUCKLING_BACKFILL_CONCURRENCY_TAG}
+duckling_groups_partitions_def = DynamicPartitionsDefinition(name="duckling_groups_backfill")
+GROUPS_COLUMN_TYPES = {
+ "team_id": "BIGINT",
+ "group_type_index": "UTINYINT",
+ "group_key": "VARCHAR",
+ "group_properties": "VARCHAR",
+ "created_at": "TIMESTAMP WITH TIME ZONE",
+ "_timestamp": "TIMESTAMP WITH TIME ZONE",
+ "_inserted_at": "TIMESTAMP WITH TIME ZONE",
+}
+
+
+def groups_snapshot_select_sql(team_id: int) -> str:
+ if team_id <= 0:
+ raise ValueError("Groups backfill requires a positive team ID")
+ # Unmerged updates can leave multiple versions of the same group in ClickHouse.
+ return f"""
+ SELECT team_id, group_type_index, group_key,
+ tupleElement(latest, 1) AS group_properties,
+ tupleElement(latest, 2) AS created_at,
+ toDateTime64(tupleElement(latest, 3), 6) AS _timestamp,
+ now64(6) AS _inserted_at
+ FROM (
+ SELECT team_id, group_type_index, group_key,
+ argMax(tuple(group_properties, created_at, _timestamp), tuple(_timestamp, _offset)) AS latest
+ FROM groups
+ WHERE team_id = {int(team_id)}
+ GROUP BY team_id, group_type_index, group_key
+ )
+ ORDER BY group_type_index, group_key
+ """
+
+
+def export_groups_to_duckling_s3(
+ context: AssetExecutionContext,
+ client: "Client",
+ config: DucklingBackfillConfig,
+ target: DucklingTarget,
+) -> str | None:
+ path = f"backfill/groups/{target.team_id}/{context.run.run_id}/{{_partition_id}}.parquet"
+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, path)
+ s3_glob = f"s3://{target.bucket}/{path.replace('{_partition_id}', '*')}"
+ if config.dry_run:
+ context.log.info(f"[DRY RUN] Would export the groups snapshot to {s3_glob}")
+ return None
+
+ settings = {
+ **DEFAULT_CLICKHOUSE_SETTINGS,
+ **settings_with_log_comment(context),
+ **(config.clickhouse_settings or {}),
+ }
+ settings.setdefault("max_bytes_before_external_group_by", 10 * 1024**3)
+ settings.update(PARQUET_WRITER_SETTINGS)
+ row_count = client.execute(
+ "SELECT count() FROM groups WHERE team_id = %(team_id)s", {"team_id": target.team_id}, settings=settings
+ )[0][0]
+ fanout = _compute_fanout(int(row_count), config.target_rows_per_file, config.max_s3_file_fanout)
+ export_sql = f"""
+ INSERT INTO FUNCTION s3({escape_clickhouse_string(s3_url)}, 'Parquet')
+ PARTITION BY toString(cityHash64(group_type_index, group_key) % {fanout})
+ {groups_snapshot_select_sql(target.team_id)}
+ SETTINGS s3_truncate_on_insert=1, use_hive_partitioning=0
+ """
+ # A failed export can leave partial S3 objects; only register files after the whole query succeeds.
+ client.execute(export_sql, settings=settings)
+ return s3_glob
+
+
+def ensure_groups_table(
+ conn: psycopg.Connection[tuple[object, ...]], table_name: str, config: DucklingBackfillConfig
+) -> None:
+ table = sql.Identifier(DUCKLAKE_ALIAS, "posthog", table_name)
+ if config.delete_tables:
+ if table_name == "groups":
+ raise ValueError("Cannot drop the shared groups table; use a team snapshot replacement")
+ conn.execute(sql.SQL("DROP TABLE IF EXISTS {}").format(table))
+ if config.create_tables_if_missing:
+ conn.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(DUCKLAKE_ALIAS, "posthog")))
+ columns = sql.SQL(", ").join(
+ sql.SQL("{} {}").format(sql.Identifier(name), sql.SQL(column_type))
+ for name, column_type in GROUPS_COLUMN_TYPES.items()
+ )
+ conn.execute(sql.SQL("CREATE TABLE IF NOT EXISTS {} ({})").format(table, columns))
+ if not config.skip_schema_validation:
+ rows = conn.execute(sql.SQL("DESCRIBE {}").format(table)).fetchall()
+ actual = {str(row[0]): str(row[1]) for row in rows}
+ if actual != GROUPS_COLUMN_TYPES:
+ raise ValueError(f"Groups table schema mismatch: expected {GROUPS_COLUMN_TYPES}, got {actual}")
+
+
+@frozen
+class GroupsSnapshotTicket:
+ epoch: str
+ generation: int
+
+
+@frozen
+class GroupsSnapshotRegistration:
+ files_registered: int
+ superseded: bool = False
+
+
+@frozen
+class _GroupsSnapshotState:
+ epoch: str
+ issued: int
+ applied: dict[str, int]
+
+
+def _read_snapshot_state(conn: psycopg.Connection[tuple[object, ...]], table_name: str) -> _GroupsSnapshotState:
+ rows = conn.execute(
+ "SELECT comment FROM duckdb_tables() WHERE database_name = %s AND schema_name = 'posthog' AND table_name = %s",
+ (DUCKLAKE_ALIAS, table_name),
+ ).fetchall()
+ if len(rows) != 1:
+ raise ValueError("Groups table is missing from the catalog")
+ comment = rows[0][0]
+ if comment is None:
+ return _GroupsSnapshotState(epoch=uuid4().hex, issued=0, applied={})
+ if not isinstance(comment, str) or not comment.startswith(STATE_COMMENT_PREFIX):
+ raise ValueError("Groups table has unexpected snapshot metadata")
+ payload = json.loads(comment[len(STATE_COMMENT_PREFIX) :])
+ if not isinstance(payload, dict):
+ raise ValueError("Invalid groups snapshot metadata")
+ epoch, issued, applied = payload.get("epoch"), payload.get("issued"), payload.get("applied")
+ if not isinstance(epoch, str) or type(issued) is not int or issued < 0 or not isinstance(applied, dict):
+ raise ValueError("Invalid groups snapshot metadata")
+ if any(not isinstance(k, str) or type(v) is not int or not 0 <= v <= issued for k, v in applied.items()):
+ raise ValueError("Invalid groups snapshot generations")
+ return _GroupsSnapshotState(epoch=epoch, issued=issued, applied=applied)
+
+
+def _write_snapshot_state(
+ conn: psycopg.Connection[tuple[object, ...]], table_name: str, state: _GroupsSnapshotState
+) -> None:
+ comment = STATE_COMMENT_PREFIX + json.dumps(
+ {"epoch": state.epoch, "issued": state.issued, "applied": state.applied}
+ )
+ conn.execute(
+ sql.SQL("COMMENT ON TABLE {} IS {}").format(
+ sql.Identifier(DUCKLAKE_ALIAS, "posthog", table_name), sql.Literal(comment)
+ )
+ )
+
+
+def _transaction_conflict(error: BaseException) -> bool:
+ return "transaction conflict" in str(error).lower()
+
+
+@retry(
+ retry=retry_if_exception(_transaction_conflict),
+ stop=stop_after_attempt(4),
+ wait=wait_random_exponential(multiplier=0.1, max=1),
+ reraise=True,
+)
+def reserve_groups_snapshot(conn: psycopg.Connection[tuple[object, ...]], table_name: str) -> GroupsSnapshotTicket:
+ with conn.transaction():
+ state = _read_snapshot_state(conn, table_name)
+ state = replace(state, issued=state.issued + 1)
+ _write_snapshot_state(conn, table_name, state)
+ return GroupsSnapshotTicket(epoch=state.epoch, generation=state.issued)
+
+
+@retry(
+ retry=retry_if_exception(_transaction_conflict),
+ stop=stop_after_attempt(4),
+ wait=wait_random_exponential(multiplier=0.1, max=1),
+ reraise=True,
+)
+def replace_groups_snapshot(
+ conn: psycopg.Connection[tuple[object, ...]],
+ target: DucklingTarget,
+ table_name: str,
+ s3_glob: str,
+ ticket: GroupsSnapshotTicket,
+) -> GroupsSnapshotRegistration:
+ files = _glob_run_files(conn, s3_glob)
+ # The generation marker commits with the data, so disconnects and empty snapshots preserve ordering.
+ with conn.transaction():
+ state = _read_snapshot_state(conn, table_name)
+ applied = state.applied.get(str(target.team_id), 0)
+ if ticket.epoch != state.epoch or ticket.generation < applied:
+ return GroupsSnapshotRegistration(files_registered=0, superseded=True)
+ if ticket.generation == applied:
+ return GroupsSnapshotRegistration(files_registered=len(files))
+ if ticket.generation > state.issued:
+ raise ValueError("Groups snapshot generation was not reserved")
+ conn.execute(
+ sql.SQL("DELETE FROM {} WHERE team_id = %s").format(sql.Identifier(DUCKLAKE_ALIAS, "posthog", table_name)),
+ (target.team_id,),
+ )
+ for path in files:
+ conn.execute(
+ "CALL ducklake_add_data_files(%s, %s, %s, schema => 'posthog', allow_missing => true)",
+ (DUCKLAKE_ALIAS, table_name, path),
+ )
+ _write_snapshot_state(
+ conn, table_name, replace(state, applied={**state.applied, str(target.team_id): ticket.generation})
+ )
+ return GroupsSnapshotRegistration(files_registered=len(files))
+
+
+def run_groups_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
+ team_id = int(context.partition_key)
+ groups_snapshot_select_sql(team_id)
+ if not config.cleanup_existing_partition_data:
+ raise ValueError("Groups snapshots require cleanup_existing_partition_data=True")
+ target = _resolve_duckling_target(team_id)
+ table_name = resolve_groups_table(team_id)
+ tags = dagster_tags(context)
+ session = None
+ registration = GroupsSnapshotRegistration(files_registered=0)
+ try:
+ ticket = None
+ if not (config.dry_run or config.skip_ducklake_registration):
+ session = _DuckgresSession(context, target)
+ session.run("ensure groups table", lambda conn: ensure_groups_table(conn, table_name, config))
+ ticket = session.run("reserve groups snapshot", lambda conn: reserve_groups_snapshot(conn, table_name))
+
+ def export(client: "Client") -> str | None:
+ with tags_context(kind="dagster", dagster=tags):
+ return export_groups_to_duckling_s3(context, client, config, target)
+
+ s3_glob = (
+ _get_cluster()
+ .any_host_by_role(
+ fn=export, workload=Workload.OFFLINE if is_cloud() else Workload.DEFAULT, node_role=NodeRole.DATA
+ )
+ .result()
+ )
+ if s3_glob is not None and session is not None and ticket is not None:
+ registration = session.run(
+ "replace groups snapshot",
+ lambda conn: replace_groups_snapshot(conn, target, table_name, s3_glob, ticket),
+ )
+ finally:
+ if session is not None:
+ session.close()
+ context.add_output_metadata(
+ {
+ "team_id": team_id,
+ "groups_table": table_name,
+ "files_registered": registration.files_registered,
+ "superseded": registration.superseded,
+ }
+ )
+ if not config.dry_run and not config.skip_ducklake_registration and not registration.superseded:
+ record_duckling_backfill_workload(
+ team_id=team_id,
+ dataset=GROUPS_DATASET,
+ mode="full",
+ files_registered=registration.files_registered,
+ partitions_exported=1,
+ )
+
+
+@asset(partitions_def=duckling_groups_partitions_def, tags=GROUPS_TAGS)
+def duckling_groups_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
+ if config.dry_run or config.skip_ducklake_registration:
+ context.instance.add_run_tags(context.run.run_id, {GROUPS_SNAPSHOT_TAG: "false"})
+ run_groups_backfill(context, config)
+ return
+ team_id = int(context.partition_key)
+ run_id = context.run.run_id
+ context.instance.add_run_tags(run_id, {GROUPS_SNAPSHOT_TAG: "true"})
+ record_backfill_started(team_id=team_id, dataset=GROUPS_DATASET, partition_key=context.partition_key, run_id=run_id)
+ with track_duckling_backfill(team_id=team_id, dataset=GROUPS_DATASET, mode="full"):
+ try:
+ run_groups_backfill(context, config)
+ except Exception as error:
+ record_backfill_finished(
+ team_id=team_id, dataset=GROUPS_DATASET, partition_key=context.partition_key, run_id=run_id, error=error
+ )
+ raise
+ record_backfill_finished(
+ team_id=team_id, dataset=GROUPS_DATASET, partition_key=context.partition_key, run_id=run_id
+ )
+
+
+duckling_groups_backfill_job = define_asset_job(
+ name=GROUPS_JOB_NAME, selection=["duckling_groups_backfill"], tags=GROUPS_TAGS
+)
+
+
+@sensor(job=duckling_groups_backfill_job, minimum_interval_seconds=600, default_status=DefaultSensorStatus.STOPPED)
+def duckling_groups_full_backfill_sensor(context: SensorEvaluationContext) -> SensorResult:
+ backfills = sorted(
+ list_enabled_backfill_team_memberships("groups_full_backfill_sensor"), key=lambda row: row.team_id
+ )
+ if not backfills:
+ return SensorResult(run_requests=[])
+ _repair_stale_running_statuses(context, GROUPS_DATASET)
+ after_team = int(context.cursor or "0")
+ candidates = [row for row in backfills if row.team_id > after_team] or backfills
+ existing = set(context.instance.get_dynamic_partitions("duckling_groups_backfill"))
+ new_partitions: list[str] = []
+ requests: list[RunRequest] = []
+ for membership in candidates[:MAX_TEAMS_PER_TICK]:
+ after_team = membership.team_id
+ key = str(membership.team_id)
+ active = context.instance.get_runs(
+ filters=RunsFilter(job_name=GROUPS_JOB_NAME, tags={"dagster/partition": key}, statuses=ACTIVE_RUN_STATUSES),
+ limit=1,
+ )
+ if active:
+ continue
+ history = context.instance.get_run_records(
+ filters=RunsFilter(job_name=GROUPS_JOB_NAME, tags={"dagster/partition": key, GROUPS_SNAPSHOT_TAG: "true"}),
+ limit=RETRY_HISTORY_LIMIT,
+ )
+ latest = history[0] if history else None
+ if latest is not None and latest.dagster_run.is_success:
+ continue
+ if latest is not None:
+ failures = 0
+ for record in history:
+ if record.dagster_run.status not in (DagsterRunStatus.FAILURE, DagsterRunStatus.CANCELED):
+ break
+ failures += 1
+ retry_after = RETRY_BASE_SECONDS * 2 ** max(failures - 1, 0)
+ ended_at = latest.end_time or latest.update_timestamp.timestamp()
+ if timezone.now().timestamp() < ended_at + retry_after:
+ continue
+ if key not in existing:
+ new_partitions.append(key)
+ requests.append(
+ RunRequest(
+ partition_key=key,
+ run_key=f"{key}_groups_{latest.dagster_run.run_id if latest else 'new'}",
+ tags={GROUPS_SNAPSHOT_TAG: "true"},
+ )
+ )
+ if len(requests) >= MAX_RUN_REQUESTS_PER_TICK:
+ break
+ return SensorResult(
+ run_requests=requests,
+ cursor=str(after_team),
+ dynamic_partitions_requests=[duckling_groups_partitions_def.build_add_request(new_partitions)]
+ if new_partitions
+ else [],
+ )