: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
feat(data-warehouse): scope duckgres sink coverage per-source (backfill + copy exclusion) (#66870)
Eric Duong1bebb50bf3f2
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.pyindex 851fcb66df5d..57a00069df4f 100644--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py@@ -148,7 +148,13 @@ class DuckLakeCopyDataImportsVerificationResult:@activity.defnasync def ducklake_copy_data_imports_gate_activity(inputs: DuckLakeCopyWorkflowGateInputs) -> bool:- """Evaluate whether the DuckLake data imports copy workflow should run for a team."""+ """Evaluate whether the DuckLake data imports copy workflow should run for a team.++ The mutual exclusion with the Duckgres v3 batch sink is per-source and lives in+ prepare_data_imports_ducklake_metadata_activity (v3 sources the sink owns are+ dropped there), not here: the sink only follows a team's v3 sources, so a+ sink-enabled team can still have non-v3 sources that this workflow must copy.+ """bind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()@@ -158,28 +164,6 @@ async def ducklake_copy_data_imports_gate_activity(inputs: DuckLakeCopyWorkflowGawait logger.aerror("Team does not exist when evaluating DuckLake data imports gate")return False- # Mutual exclusion with the Duckgres v3 batch sink: both writers target the- # same posthog_data_imports_team_{id} tables with zero coordination, so a- # team must never have both enabled. The sink wins.- try:- if feature_enabled_or_false(- DUCKGRES_BATCH_SINK_FLAG,- str(team.uuid),- groups={- "organization": str(team.organization_id),- "project": str(team.id),- },- send_feature_flag_events=False,- ):- await logger.ainfo("DuckLake copy workflow skipped: duckgres batch sink owns this team's tables")- return False- except Exception as error:- await logger.awarning(- "Failed to evaluate duckgres batch sink flag; continuing with copy-workflow gate",- error=str(error),- )- capture_exception(error)-try:return feature_enabled_or_false("ducklake-data-imports-copy-workflow",@@ -225,6 +209,31 @@ async def prepare_data_imports_ducklake_metadata_activity(# batch belong to one team, so this is loop-invariant — resolve it once.ducklake_schema_name = await database_sync_to_async(duckgres_data_imports_schema)(inputs.team_id)+ # Per-source mutual exclusion with the Duckgres v3 batch sink. The sink owns a+ # team's v3 sources (it mirrors them live + backfills history), so drop those+ # here; non-v3 sources stay on the copy workflow — the sink never touches them.+ # is_pipeline_v3_enabled is the same gate the v3 router uses, so "copy" and+ # "sink" never disagree on who owns a source (and both fail to "copy owns it").+ # Lazy import: create_job_model pulls in temporalio.activity + the data_warehouse+ # facade, which we don't want on this module's import path.+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import ( # noqa: PLC0415 — keeps the heavy temporal/facade deps off the import path+ is_pipeline_v3_enabled,+ )++ sink_enabled = False+ try:+ gate_team = await database_sync_to_async(Team.objects.only("uuid", "organization_id").get)(id=inputs.team_id)+ sink_enabled = feature_enabled_or_false(+ DUCKGRES_BATCH_SINK_FLAG,+ str(gate_team.uuid),+ groups={"organization": str(gate_team.organization_id), "project": str(gate_team.id)},+ send_feature_flag_events=False,+ )+ except Exception as error:+ await logger.awarning("Failed to evaluate duckgres batch sink flag; copying all schemas", error=str(error))+ capture_exception(error)+ sink_owns_source_type: dict[str, bool] = {}+model_list: list[DuckLakeCopyDataImportsMetadata] = []for schema_id in inputs.schema_ids:@@ -234,6 +243,19 @@ async def prepare_data_imports_ducklake_metadata_activity(normalized_name = schema.normalized_namesource_type = schema.source.source_type++ if sink_enabled:+ if source_type not in sink_owns_source_type:+ sink_owns_source_type[source_type] = await database_sync_to_async(is_pipeline_v3_enabled)(+ inputs.team_id, source_type+ )+ if sink_owns_source_type[source_type]:+ await logger.ainfo(+ "Skipping schema owned by the duckgres batch sink (v3 source)",+ schema_id=str(schema.id),+ source_type=source_type,+ )+ continuesource_table_uri = f"{settings.BUCKET_URL}/{schema.folder_path()}/{normalized_name}"staging_uri = await database_sync_to_async(_resolve_data_imports_staging_uri)(source_table_uri, team_id=inputs.team_iddiff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.pyindex 1347e50c5d8d..7decd8336ff2 100644--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py@@ -91,9 +91,6 @@ async def test_ducklake_copy_data_imports_gate_respects_feature_flag(monkeypatchonly_evaluate_locally=False,send_feature_flag_events=True,):- if key == "duckgres-batch-sink":- # The sink-exclusion check runs first; this team is not sink-enabled.- return Falsecaptured["key"] = keycaptured["distinct_id"] = distinct_idcaptured["groups"] = groups@@ -119,21 +116,55 @@ async def test_ducklake_copy_data_imports_gate_respects_feature_flag(monkeypatch@pytest.mark.asyncio@pytest.mark.django_db-async def test_ducklake_copy_data_imports_gate_skips_duckgres_sink_teams(monkeypatch, ateam):- """A team on the duckgres batch sink must never also run the copy workflow."""-- def fake_feature_enabled(key, distinct_id, **kwargs):- # Both flags enabled: the sink exclusion must win.- return True-+async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):+ # On a sink-enabled team the duckgres sink owns v3 sources, so the copy workflow+ # must drop those — but keep copying non-v3 sources the sink never follows. The+ # exclusion is per-source, not the old wholesale team-level skip.+ monkeypatch.setattr(ducklake_module, "_fetch_delta_partition_columns", lambda table_uri, *, team_id: ["created_at"])monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.feature_enabled_or_false",- fake_feature_enabled,+ lambda *args, **kwargs: True, # duckgres-batch-sink on)+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import create_job_model- result = await ducklake_copy_data_imports_gate_activity(DuckLakeCopyWorkflowGateInputs(team_id=ateam.id))+ monkeypatch.setattr(+ create_job_model, "is_pipeline_v3_enabled", lambda team_id, source_type: source_type == "Postgres"+ )++ credential = await database_sync_to_async(DataWarehouseCredential.objects.create)(+ team=ateam, access_key="k", access_secret="s"+ )+ v3_source = await database_sync_to_async(ExternalDataSource.objects.create)(+ team=ateam, source_id="v3", connection_id="c1", source_type="Postgres", status="Running"+ )+ v3_schema = await database_sync_to_async(ExternalDataSchema.objects.create)(team=ateam, name="pg", source=v3_source)+ non_v3_source = await database_sync_to_async(ExternalDataSource.objects.create)(+ team=ateam, source_id="nv3", connection_id="c2", source_type="Stripe", status="Running"+ )+ non_v3_table = await database_sync_to_async(DataWarehouseTable.objects.create)(+ team=ateam,+ name="charges",+ format="Delta",+ url_pattern="s3://bucket/path",+ credential=credential,+ external_data_source=non_v3_source,+ columns={"id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"}},+ )+ non_v3_schema = await database_sync_to_async(ExternalDataSchema.objects.create)(+ team=ateam,+ name="charges",+ source=non_v3_source,+ table=non_v3_table,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "created_at", "incremental_field_type": "DateTime"},+ )++ inputs = DataImportsDuckLakeCopyInputs(team_id=ateam.id, job_id="job", schema_ids=[v3_schema.id, non_v3_schema.id])++ result = await prepare_data_imports_ducklake_metadata_activity(inputs)- assert result is False+ # v3 source dropped (sink owns it); non-v3 source still copied.+ assert [m.source_schema_id for m in result] == [str(non_v3_schema.id)]@pytest.mark.asynciodiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.pyindex f329475ef2d4..45c1e5ae58b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py@@ -195,20 +195,44 @@ def replan_backfill(schema_id: str) -> None:def _bootstrap_state_rows(team_ids: list[int] | None) -> None:"""Create state rows for enabled teams' schemas that have none.+ Only schemas whose source is on warehouse-pipelines-v3 get a row: the sink+ follows v3 sources only, so priming a non-v3 source would create state the+ consumer never advances (and never primes).+Straight to PRIMED when no priming is needed:- full_refresh: every run's batch 0 replaces the table completely.- no Delta table yet: the first sync creates everything.- cdc: the sink rejects CDC batches outright; do not block the queue on it."""- schemas = ExternalDataSchema.objects.exclude(deleted=True).select_related("team")+ # Lazy import: create_job_model pulls in temporalio.activity + the data_warehouse+ # facade, which we don't want on the planner module's import path.+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import ( # noqa: PLC0415 — keeps the heavy temporal/facade deps off the import path+ is_pipeline_v3_enabled,+ )++ schemas = ExternalDataSchema.objects.exclude(deleted=True).select_related("team", "source")if team_ids is not None:schemas = schemas.filter(team_id__in=team_ids)existing = {str(s) for s in DuckgresSinkSchemaState.objects.all().values_list("schema_id", flat=True)}+ # The sink only follows v3 sources (warehouse-pipelines-v3 is evaluated per+ # team+source_type), so only prime schemas the consumer will actually mirror.+ # Memoized per (team_id, source_type) — the flag does a network eval, and a+ # team has only a handful of source types, so this stays cheap even with many schemas.+ v3_enabled: dict[tuple[int, str], bool] = {}++ def _source_is_v3(team_id: int, source_type: str) -> bool:+ key = (team_id, source_type)+ if key not in v3_enabled:+ v3_enabled[key] = is_pipeline_v3_enabled(team_id, source_type)+ return v3_enabled[key]+to_create: list[DuckgresSinkSchemaState] = []for schema in schemas:if str(schema.id) in existing:continue+ if not _source_is_v3(schema.team_id, schema.source.source_type):+ continueneeds_backfill = schema.sync_type not in ("full_refresh", "cdc", None) and schema.table_id is not Noneto_create.append(DuckgresSinkSchemaState(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.pyindex 2c73e5b85d86..26fa11b4db9b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_committed_batch_keys,_group_files_into_chunks,)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import create_job_model_State = DuckgresSinkSchemaState.State@@ -141,3 +142,33 @@ class TestPlanPendingConcurrencyCaps:candidate.refresh_from_db()assert candidate.state == _State.BACKFILLINGassert planned == [candidate.id]+++class TestBootstrapV3SourceGate:+ # warehouse-pipelines-v3 (is_pipeline_v3_enabled) is the network-flag boundary;+ # stub it so the assertion is on which schemas get a state row.+ def test_only_v3_sources_are_primed(self, monkeypatch):+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource++ monkeypatch.setattr(+ create_job_model,+ "is_pipeline_v3_enabled",+ lambda team_id, source_type: source_type == "Postgres",+ )++ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")+ v3_source = ExternalDataSource.objects.create(+ team=team, source_id="s1", connection_id="c1", source_type="Postgres", status="Running"+ )+ non_v3_source = ExternalDataSource.objects.create(+ team=team, source_id="s2", connection_id="c2", source_type="Stripe", status="Running"+ )+ v3_schema = ExternalDataSchema.objects.create(team=team, name="pg", source=v3_source)+ non_v3_schema = ExternalDataSchema.objects.create(team=team, name="stripe", source=non_v3_source)++ backfill_module._bootstrap_state_rows([team.id])++ primed = set(DuckgresSinkSchemaState.objects.filter(team=team).values_list("schema_id", flat=True))+ assert v3_schema.id in primed+ assert non_v3_schema.id not in primed