: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse): simplify groups snapshot exports (#118278)
Eric Duongf3070b7906a1
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex 5dc81c23aa79..8ced539d465b 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -50,7 +50,9 @@ Rerun a team partition manually to refresh its groups; there is no daily groupsEach 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.+The export reads ClickHouse groups with `FINAL` and replaces the team's DuckLake snapshot in a transaction.+Deduplication follows the table engine: the highest `_timestamp` wins, with equal timestamps resolved by insertion order.+The export does not apply an explicit sort.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.@@ -58,6 +60,11 @@ Output metadata reports `superseded: true` when a newer snapshot or table resetThe job shares the events/persons backfill concurrency limit and supports `dry_run` and `skip_ducklake_registration`.Groups snapshots require `cleanup_existing_partition_data: true`.+Groups exports default to a 100 GiB query memory limit, matching full persons exports.+Override it with `clickhouse_settings.max_memory_usage` when launching a run.+For a memory failure, lower `max_s3_file_fanout` and rerun the same team partition with `delete_tables: false`.+A failed export does not replace the previous snapshot; only a successful export proceeds to registration.+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.diff --git a/products/managed_warehouse/backend/tests/test_groups_backfill.py b/products/managed_warehouse/backend/tests/test_groups_backfill.pyindex c98c6794ea12..aeda864aa4fc 100644--- a/products/managed_warehouse/backend/tests/test_groups_backfill.py+++ b/products/managed_warehouse/backend/tests/test_groups_backfill.py@@ -5,10 +5,11 @@ from contextlib import contextmanagerfrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import cast+from uuid import uuid4import pytestimport time_machine-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.conf import settings@@ -32,6 +33,7 @@ from products.managed_warehouse.dags.groups_backfill import (duckling_groups_backfill,duckling_groups_full_backfill_sensor,ensure_groups_table,+ export_groups_to_duckling_s3,groups_snapshot_select_sql,replace_groups_snapshot,reserve_groups_snapshot,@@ -40,35 +42,70 @@ from products.managed_warehouse.dags.groups_backfill import (def test_groups_snapshot_deduplicates_keys_within_each_team_and_group_type(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(settings, "CLICKHOUSE_USE_HTTP", False)+ table_name = f"test_groups_snapshot_{uuid4().hex}"with get_client_from_pool() as client:- client.execute("""- CREATE TEMPORARY TABLE groups (+ client.execute(f"""+ CREATE TABLE {table_name} (team_id Int64, group_type_index UInt8, group_key String, group_properties String,- created_at DateTime64(6), _timestamp DateTime64(6), _offset UInt64- ) ENGINE = Memory+ created_at DateTime64(3), _timestamp DateTime, _offset UInt64+ ) ENGINE = ReplacingMergeTree(_timestamp)+ ORDER BY (team_id, group_type_index, group_key)""")try:+ client.execute(f"SYSTEM STOP MERGES {table_name}")created = datetime(2025, 1, 1)latest = datetime(2025, 1, 2)client.execute(- "INSERT INTO groups VALUES",+ f"INSERT INTO {table_name} 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, 0, "tied", '{"name":"first insert"}', created, latest, 99),(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))+ client.execute(+ f"INSERT INTO {table_name} VALUES",+ [+ (7, 0, "company", '{"name":"old"}', created, created, 1),+ (7, 0, "tied", '{"name":"last insert"}', created, latest, 1),+ ],+ )+ query = groups_snapshot_select_sql(7).replace("FROM groups FINAL", f"FROM {table_name} FINAL")+ rows = client.execute(query)finally:- client.execute("DROP TEMPORARY TABLE groups")- assert [row[:6] for row in rows] == [+ client.execute(f"DROP TABLE {table_name}")+ assert sorted(row[:6] for row in rows) == [(7, 0, "company", '{"name":"latest"}', created, latest),+ (7, 0, "tied", '{"name":"last insert"}', created, latest),(7, 1, "company", '{"name":"another type"}', created, latest),][email protected]("memory_override", [None, 20 * 1024**3])+def test_groups_export_memory_default_and_operator_override(memory_override: int | None) -> None:+ client = MagicMock()+ client.execute.return_value = [(100,)]+ context = MagicMock()+ context.run.run_id = "synthetic-run"+ target = DucklingTarget(team_id=7, organization_id="org", bucket="unused", bucket_region="us-east-1")+ config = DucklingBackfillConfig(+ clickhouse_settings={"max_memory_usage": memory_override} if memory_override is not None else None+ )++ with patch(+ "products.managed_warehouse.dags.groups_backfill.get_s3_url_for_clickhouse", return_value="https://example.com"+ ):+ result = export_groups_to_duckling_s3(context, client, config, target)++ export_query = client.execute.call_args.args[0]+ export_settings = client.execute.call_args.kwargs["settings"]+ assert result == "s3://unused/backfill/groups/7/synthetic-run/*.parquet"+ assert "FROM groups FINAL" in export_query+ assert "ORDER BY" not in export_query+ assert export_settings["max_memory_usage"] == (memory_override if memory_override is not None else 100 * 1024**3)++class _LakeConnection:def __init__(self, connection: duckdb.DuckDBPyConnection) -> None:self.connection = connectiondiff --git a/products/managed_warehouse/dags/groups_backfill.py b/products/managed_warehouse/dags/groups_backfill.pyindex d79d34718235..60ddf6a22044 100644--- a/products/managed_warehouse/dags/groups_backfill.py+++ b/products/managed_warehouse/dags/groups_backfill.py@@ -81,21 +81,13 @@ GROUPS_COLUMN_TYPES = {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,+ group_properties, created_at,+ toDateTime64(_timestamp, 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+ FROM groups FINAL+ WHERE team_id = {int(team_id)}"""@@ -114,10 +106,10 @@ def export_groups_to_duckling_s3(settings = {**DEFAULT_CLICKHOUSE_SETTINGS,+ "max_memory_usage": 100 * 1024**3,**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