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.

fix(data-warehouse): gate duckgres sink by team membership (#69854)

Eric Duong618c9f99e376
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
index 0b5c268b8bae..b5c3202c7da3 100644
--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
@@ -51,7 +51,7 @@ from posthog.temporal.ducklake.metrics import (
)
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
-from products.warehouse_sources.backend.facade.pipelines import DUCKGRES_BATCH_SINK_FLAG
+from products.warehouse_sources.backend.facade.pipelines import DUCKGRES_BATCH_SINK_FLAG, is_duckgres_sink_team_member
LOGGER = get_logger(__name__)
DATA_IMPORTS_DUCKLAKE_WORKFLOW_PREFIX = "data_imports"
@@ -208,8 +208,10 @@ async def prepare_data_imports_ducklake_metadata_activity(
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.
+ # registered team's v3 sources (it mirrors them live + backfills history), so
+ # drop those here; non-v3 sources stay on the copy workflow because the sink never
+ # touches them. A flagged team without a DuckgresServerTeam membership remains
+ # on this copy path until it completes the enable flow.
# 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
@@ -218,17 +220,18 @@ async def prepare_data_imports_ducklake_metadata_activity(
is_pipeline_v3_enabled,
)
- sink_enabled = False
+ sink_enabled = is_dev_mode()
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,
- )
+ if not sink_enabled and await database_sync_to_async(is_duckgres_sink_team_member)(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))
+ await logger.awarning("Failed to resolve duckgres batch sink ownership; copying all schemas", error=str(error))
capture_exception(error)
sink_owns_source_type: dict[str, bool] = {}
diff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
index 7decd8336ff2..068ffb6f028b 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
@@ -10,6 +10,7 @@ import temporalio.converter
from temporalio import activity as temporal_activity
from temporalio.testing import WorkflowEnvironment
+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam
from posthog.ducklake.storage import compute_staging_uri
from posthog.ducklake.verification import DuckLakeCopyVerificationParameter, DuckLakeCopyVerificationQuery
from posthog.sync import database_sync_to_async
@@ -121,6 +122,10 @@ async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):
# 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(ducklake_module, "is_dev_mode", lambda: False)
+ # get_duckgres_server_by_team_org resolves the staging URI via its own module-level
+ # is_dev_mode, so it needs the same override or it short-circuits to None in tests.
+ monkeypatch.setattr("posthog.ducklake.common.is_dev_mode", lambda: False)
monkeypatch.setattr(
"posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.feature_enabled_or_false",
lambda *args, **kwargs: True, # duckgres-batch-sink on
@@ -131,6 +136,15 @@ async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):
create_job_model, "is_pipeline_v3_enabled", lambda team_id, source_type: source_type == "Postgres"
)
+ server = await database_sync_to_async(DuckgresServer.objects.create)(
+ organization_id=ateam.organization_id,
+ host="h",
+ username="root",
+ password="x",
+ bucket="bucket",
+ )
+ membership = await database_sync_to_async(DuckgresServerTeam.objects.create)(server=server, team=ateam)
+
credential = await database_sync_to_async(DataWarehouseCredential.objects.create)(
team=ateam, access_key="k", access_secret="s"
)
@@ -166,6 +180,11 @@ async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):
# 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)]
+ await database_sync_to_async(membership.delete)()
+ result_without_membership = await prepare_data_imports_ducklake_metadata_activity(inputs)
+
+ assert {m.source_schema_id for m in result_without_membership} == {str(v3_schema.id), str(non_v3_schema.id)}
+
@pytest.mark.asyncio
@pytest.mark.django_db
diff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.py
index 1ec2dd550384..a34b283e1183 100644
--- a/products/warehouse_sources/backend/facade/pipelines.py
+++ b/products/warehouse_sources/backend/facade/pipelines.py
@@ -22,6 +22,7 @@ _LAZY = {
"is_pipeline_v3_enabled": "workflow_activities.create_job_model",
"SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",
"DUCKGRES_BATCH_SINK_FLAG": "pipelines.pipeline_v3.duckgres.enablement",
+ "is_duckgres_sink_team_member": "pipelines.pipeline_v3.duckgres.enablement",
"HealthState": "pipelines.pipeline_v3.load.health",
"start_health_server": "pipelines.pipeline_v3.load.health",
"ensure_bucket": "pipelines.pipeline_v3.s3.common",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
index 7139adc85d40..a24ed02c40ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py
@@ -1,9 +1,10 @@
"""Which teams the Duckgres batch sink is enabled for.
-The sink must only claim batches for teams that (a) belong to an org with a
-provisioned DuckgresServer and (b) have the rollout feature flag on. Claiming
-anything else burns retries, fails sink runs, and floods Sentry for orgs that
-have no Duckgres to write to.
+The sink must only claim batches for teams that (a) have a DuckgresServerTeam
+membership and (b) have the rollout feature flag on. The membership is created
+when the team completes the managed-warehouse enable flow. Claiming anything
+else can switch an unregistered team from its legacy team-id schema to a newly
+chosen suffix after the sink has already primed it.
The flag also provides mutual exclusion with the legacy
DuckLakeCopyDataImportsWorkflow (full-table copy after each import job): that
@@ -15,6 +16,8 @@ from __future__ import annotations
from dataclasses import dataclass
+from django.db.models import F
+
import structlog
import posthoganalytics
@@ -26,6 +29,20 @@ logger = structlog.get_logger(__name__)
DUCKGRES_BATCH_SINK_FLAG = "duckgres-batch-sink"
+def is_duckgres_sink_team_member(team_id: int) -> bool:
+ """Whether a team has registered its membership in its org's Duckgres server.
+
+ ``table_suffix`` is intentionally not part of this check. Legacy memberships
+ with a NULL/empty suffix use the stable team-id schema naming fallback.
+ """
+ from posthog.ducklake.models import DuckgresServerTeam
+
+ return DuckgresServerTeam.objects.filter(
+ team_id=team_id,
+ server__organization_id=F("team__organization_id"),
+ ).exists()
+
+
@dataclass(frozen=True)
class SinkEnablement:
"""The sink's per-refresh view of who it serves and how hard it may push.
@@ -56,22 +73,14 @@ def duckgres_sink_enablement() -> SinkEnablement | None:
if is_dev_mode():
return None
- from posthog.ducklake.models import DuckgresServer
- from posthog.models import Team
-
- org_budgets = dict(
- DuckgresServer.objects.filter(organization_id__isnull=False).values_list(
- "organization_id", "sink_max_concurrency"
- )
- )
- if not org_budgets:
- return SinkEnablement(team_ids=[], team_org_budgets=[])
+ from posthog.ducklake.models import DuckgresServerTeam
enabled: list[int] = []
team_org_budgets: list[tuple[int, str, int]] = []
- for team_id, team_uuid, org_id in Team.objects.filter(organization_id__in=org_budgets.keys()).values_list(
- "id", "uuid", "organization_id"
- ):
+ memberships = DuckgresServerTeam.objects.filter(server__organization_id=F("team__organization_id")).values_list(
+ "team_id", "team__uuid", "team__organization_id", "server__sink_max_concurrency"
+ )
+ for team_id, team_uuid, org_id, sink_max_concurrency in memberships:
try:
if posthoganalytics.feature_enabled(
DUCKGRES_BATCH_SINK_FLAG,
@@ -85,7 +94,7 @@ def duckgres_sink_enablement() -> SinkEnablement | None:
send_feature_flag_events=False,
):
enabled.append(team_id)
- team_org_budgets.append((team_id, str(org_id), org_budgets[org_id]))
+ team_org_budgets.append((team_id, str(org_id), sink_max_concurrency))
except Exception as e:
# Flag evaluation failing for one team must not blind the whole sink;
# treat as disabled (safe direction: we skip, never wrongly claim).
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
index bc10ac6414a0..41183f208df3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py
@@ -1,7 +1,7 @@
import pytest
from unittest.mock import MagicMock, patch
-from posthog.ducklake.models import DuckgresServer
+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam
from posthog.models import Organization, Team
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import enablement
@@ -20,7 +20,8 @@ def test_duckgres_sink_flag_evaluated_locally_with_group_properties(
org+project group properties supplied inline and only-local evaluation."""
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")
+ server = DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")
+ DuckgresServerTeam.objects.create(server=server, team=team)
mock_feature_enabled.return_value = True
assert duckgres_sink_team_ids() == [team.id]
@@ -47,8 +48,9 @@ def test_duckgres_sink_skips_team_when_flag_unresolved_locally(
"""only_evaluate_locally returns None when the flag can't be resolved; that
falsy value must skip the team, never claim it."""
org = Organization.objects.create(name="Org")
- Team.objects.create(organization=org)
- DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")
+ DuckgresServerTeam.objects.create(server=server, team=team)
mock_feature_enabled.return_value = None
assert duckgres_sink_team_ids() == []
@@ -57,15 +59,22 @@ def test_duckgres_sink_skips_team_when_flag_unresolved_locally(
@pytest.mark.django_db
@patch.object(enablement, "is_dev_mode", return_value=False)
@patch.object(enablement.posthoganalytics, "feature_enabled")
-def test_duckgres_sink_enablement_carries_org_budgets(mock_feature_enabled: MagicMock, _mock_dev: MagicMock) -> None:
+def test_duckgres_sink_enablement_uses_memberships_and_carries_org_budgets(
+ mock_feature_enabled: MagicMock, _mock_dev: MagicMock
+) -> None:
"""The per-org sink_max_concurrency must ride along with each enabled team,
or the claim query silently applies no cap (empty mapping = uncapped)."""
org_a = Organization.objects.create(name="A")
org_b = Organization.objects.create(name="B")
team_a = Team.objects.create(organization=org_a)
team_b = Team.objects.create(organization=org_b)
- DuckgresServer.objects.create(organization=org_a, host="h", username="root", password="x")
- DuckgresServer.objects.create(organization=org_b, host="h", username="root", password="x", sink_max_concurrency=7)
+ Team.objects.create(organization=org_a)
+ server_a = DuckgresServer.objects.create(organization=org_a, host="h", username="root", password="x")
+ server_b = DuckgresServer.objects.create(
+ organization=org_b, host="h", username="root", password="x", sink_max_concurrency=7
+ )
+ DuckgresServerTeam.objects.create(server=server_a, team=team_a)
+ DuckgresServerTeam.objects.create(server=server_b, team=team_b, backfill_enabled=False)
mock_feature_enabled.return_value = True
result = enablement.duckgres_sink_enablement()
@@ -76,3 +85,6 @@ def test_duckgres_sink_enablement_carries_org_budgets(mock_feature_enabled: Magi
(team_a.id, str(org_a.id), 4), # model default
(team_b.id, str(org_b.id), 7),
}
+ # NULL suffix and disabled events backfill do not revoke sink membership;
+ # the unregistered third team is never evaluated even though its org is provisioned.
+ assert mock_feature_enabled.call_count == 2