: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): gate duckgres sink claim on the v3 pipeline flag (#67223)
Eric Duong26d929d843c6
diff --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 46f50159d67b..f1358f78803d 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@@ -105,6 +105,7 @@ __all__ = ["mark_primed","replan_backfill","run_backfill_planner",+ "sink_eligible_schema_ids",]@@ -148,6 +149,53 @@ def blocked_schema_ids(team_ids: list[int] | None) -> list[str]:return [str(sid) for sid in schemas.values_list("id", flat=True) if str(sid) not in primed_ids]+def sink_eligible_schema_ids(team_ids: list[int]) -> list[str]:+ """Schema ids whose (team, source_type) is on warehouse-pipelines-v3.++ The sink claims batches ONLY for these schemas, keeping consumption in+ lockstep with the v3 routing flag — the same gate that decides which source+ types the v3 pipeline produces for and which schemas get primed here. The+ shared queue can hold batches for non-v3 source types (a source_type that+ was v3 during an earlier flag window, or the flag-independent CDC writer);+ without this gate the team-scoped claim applies them anyway, and replace-head+ batches (full_refresh / first-ever incremental) even bypass the unprimed+ block. Enabling a source_type later lets its schemas bootstrap, prime, and+ begin live application through the normal path.++ Evaluated per (team_id, source_type) with a local cache — the same gate+ ``_bootstrap_state_rows`` uses to decide priming, so consumption and priming+ never disagree. Raises on app-DB errors so the caller keeps its previous+ cached set; a transient blip must not silently empty the allow-list.++ Prod only: the consumer calls this with a concrete team list. Dev mode+ (no team filter) is left ungated by the caller.+ """+ close_old_connections()+ if not team_ids:+ return []++ # Lazy import: create_job_model pulls in temporalio.activity + the data+ # warehouse facade, kept off 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)+ .filter(team_id__in=team_ids)+ .values("id", "team_id", "source__source_type")+ )+ v3_enabled: dict[tuple[int, str], bool] = {}+ eligible: list[str] = []+ for schema in schemas.iterator(chunk_size=BOOTSTRAP_BATCH_SIZE):+ key = (schema["team_id"], schema["source__source_type"])+ if key not in v3_enabled:+ v3_enabled[key] = is_pipeline_v3_enabled(schema["team_id"], schema["source__source_type"])+ if v3_enabled[key]:+ eligible.append(str(schema["id"]))+ return eligible++def mark_primed(schema_id: str, *, chunks_applied: int | None = None) -> None:"""Fast path called by the processor right after the swap commits.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex e0474c8b6e08..6c8381a8cf56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (blocked_schema_ids as compute_blocked_schema_ids,run_backfill_planner,+ sink_eligible_schema_ids as compute_eligible_schema_ids,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (duckgres_sink_team_ids,@@ -92,6 +93,10 @@ class DuckgresBatchConsumerAdapter:# None = not yet computed; the fetch claims nothing until the first# successful planner pass so unprimed schemas can't sneak live batches in.self._blocked_schema_ids: list[str] | None = None+ # Allow-list of v3-enabled schema ids (prod only). None = not yet computed+ # (fetch claims nothing) in prod; stays None in dev where team_ids is None+ # and the sink is intentionally ungated.+ self._eligible_schema_ids: list[str] | None = Noneasync def _enabled_team_ids(self) -> list[int] | None:"""Cached duckgres-enabled team set; keeps the previous set on app-DB errors."""@@ -133,7 +138,10 @@ class DuckgresBatchConsumerAdapter:logger.info("duckgres_superseded_obsolete_batches", count=superseded)backlog, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(- conn, team_ids=team_ids, blocked_schema_ids=self._blocked_schema_ids+ conn,+ team_ids=team_ids,+ blocked_schema_ids=self._blocked_schema_ids,+ eligible_schema_ids=self._eligible_schema_ids,)SINK_ELIGIBLE_BACKLOG.set(backlog)SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)@@ -146,6 +154,13 @@ class DuckgresBatchConsumerAdapter:# refresh the live-batch block list it derives from.await sync_to_async(run_backfill_planner, thread_sensitive=False)(team_ids)self._blocked_schema_ids = await sync_to_async(compute_blocked_schema_ids, thread_sensitive=False)(team_ids)+ # v3 allow-list: prod only. In dev (team_ids None) the sink stays+ # ungated, matching the team filter. Kept in the planner try so a+ # transient app-DB/flag blip leaves the previous allow-list intact.+ if team_ids is not None:+ self._eligible_schema_ids = await sync_to_async(compute_eligible_schema_ids, thread_sensitive=False)(+ team_ids+ )if block_list_was_unset:# First successful planner pass: the sink can now claim live# batches (fetch returns [] until this happens).@@ -167,6 +182,7 @@ class DuckgresBatchConsumerAdapter:eligible_backlog=backlog,blocked_backlog=blocked,blocked_schema_count=None if self._blocked_schema_ids is None else len(self._blocked_schema_ids),+ eligible_schema_count=None if self._eligible_schema_ids is None else len(self._eligible_schema_ids),)async def fetch_and_lock(@@ -192,12 +208,19 @@ class DuckgresBatchConsumerAdapter:# write partial history for unprimed schemas. Wait for it.return []+ if team_ids is not None and self._eligible_schema_ids is None:+ # Prod: the v3 allow-list has not been computed yet. Claim nothing+ # rather than risk applying batches for non-v3 source types. (Dev,+ # team_ids None, is intentionally ungated.)+ return []+return await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn,limit=limit,retry_backoff_base_seconds=retry_backoff_base_seconds,team_ids=team_ids,blocked_schema_ids=self._blocked_schema_ids,+ eligible_schema_ids=self._eligible_schema_ids,)async def unlock(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pyindex 4a6bcf8df2f0..140f3ec14fef 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -152,6 +152,7 @@ class DuckgresBatchQueue:retry_backoff_base_seconds: int = 0,team_ids: list[int] | None = None,blocked_schema_ids: list[str] | None = None,+ eligible_schema_ids: list[str] | None = None,) -> list[PendingBatch]:"""Fetch Duckgres-eligible batches whose Delta load has succeeded.@@ -169,6 +170,14 @@ class DuckgresBatchQueue:not yet primed into duckgres (backfill pending/in-flight) — the schema'sown backfill-run batches (metadata.duckgres_backfill) pass through.+ ``eligible_schema_ids`` restricts the claim to schemas whose source is on+ warehouse-pipelines-v3 (None = no filter, for tests/dev). This keeps the+ sink in lockstep with the v3 routing flag: the shared queue can hold+ batches for non-v3 source types (an earlier flag window, or the+ flag-independent CDC writer), and without this gate the team-scoped claim+ would apply them — including replace-head batches that bypass the unprimed+ block. Computed by ``sink_eligible_schema_ids``.+Cross-run head-of-line: a batch is ineligible while an older run (by runstart time) of the same (team_id, schema_id) still has unapplied,non-failed data batches. Without this, a newer run's batch-0@@ -191,6 +200,7 @@ class DuckgresBatchQueue:WHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))AND NOT {BLOCKED_LIVE_BATCH_CONDITION}AND ds.job_state = 'succeeded'AND (@@ -279,6 +289,7 @@ class DuckgresBatchQueue:"backoff": retry_backoff_base_seconds,"team_ids": team_ids,"blocked_schema_ids": blocked_schema_ids,+ "eligible_schema_ids": eligible_schema_ids,},)rows = await cur.fetchall()@@ -369,6 +380,7 @@ class DuckgresBatchQueue:*,team_ids: list[int] | None = None,blocked_schema_ids: list[str] | None = None,+ eligible_schema_ids: list[str] | None = None,) -> tuple[int, float | None, int, float | None]:"""(eligible_count, eligible_oldest_age, blocked_count, blocked_oldest_age).@@ -395,6 +407,7 @@ class DuckgresBatchQueue:AND a.batch_index = b.batch_indexWHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))AND ds.job_state = 'succeeded'AND b.is_final_batch = falseAND a.id IS NULL@@ -407,7 +420,11 @@ class DuckgresBatchQueue:EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE is_blocked))FROM backlog""",- {"team_ids": team_ids, "blocked_schema_ids": blocked_schema_ids},+ {+ "team_ids": team_ids,+ "blocked_schema_ids": blocked_schema_ids,+ "eligible_schema_ids": eligible_schema_ids,+ },)row = await cur.fetchone()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.pyindex d3436578169f..3d3caddbea6e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py@@ -223,6 +223,10 @@ class TestDuckgresEnablementGating:"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",return_value=["blocked-schema"],),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",+ return_value=["eligible-schema"],+ ),):await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=30, owner_token="test-owner", lease_ttl_seconds=300@@ -231,6 +235,7 @@ class TestDuckgresEnablementGating:assert mock_fetch.call_args[1]["team_ids"] == [1, 2]assert mock_fetch.call_args[1]["retry_backoff_base_seconds"] == 30assert mock_fetch.call_args[1]["blocked_schema_ids"] == ["blocked-schema"]+ assert mock_fetch.call_args[1]["eligible_schema_ids"] == ["eligible-schema"]mock_supersede.assert_called_once()mock_backlog.assert_called_once()mock_planner.assert_called_once_with([1, 2])@@ -269,6 +274,49 @@ class TestDuckgresEnablementGating:assert batches == []mock_fetch.assert_not_called()+ @pytest.mark.asyncio+ async def test_fetch_claims_nothing_until_eligible_list_ready(self):+ # Prod fail-closed: even with the block list computed, an uncomputed v3+ # allow-list must halt claiming so non-v3 source types can't be applied.+ adapter = DuckgresBatchConsumerAdapter()+ adapter._team_ids = [1]+ adapter._team_ids_fetched_at = time.monotonic()+ conn = _make_healthy_conn()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",+ new_callable=AsyncMock,+ ) as mock_fetch,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",+ new_callable=AsyncMock,+ return_value=0,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",+ new_callable=AsyncMock,+ return_value=(0, None, 0, None),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",+ return_value=["blocked-schema"],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",+ side_effect=RuntimeError("flag eval down"),+ ),+ ):+ batches = await adapter.fetch_and_lock(+ conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300+ )++ assert batches == []+ mock_fetch.assert_not_called()+class TestStuckBatchWatchdog:@pytest.mark.asynciodiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.pyindex 4c6cd94f44c8..abdfe441d9f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py@@ -381,6 +381,13 @@ class TestDuckgresTeamFilterAndBacklog:assert (count, blocked) == (0, 1)assert oldest_age is None and blocked_age is not None+ # The v3 allow-list scopes the gauges too: a non-eligible schema drops+ # out of both the eligible and blocked counts.+ count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ conn, eligible_schema_ids=["other-schema"]+ )+ assert (count, blocked) == (0, 0)+await _mark_applied_raw(conn, batch_id=batch_id, run_uuid="run-1", batch_index=0)count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(conn)assert (count, blocked) == (0, 0)@@ -546,3 +553,37 @@ class TestBackfillQueueContracts:batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])assert [str(b.id) for b in batches] == [head]++ @pytest.mark.asyncio+ async def test_eligible_schema_ids_restricts_claim_to_v3_schemas(self, conn):+ # The v3 allow-list must exclude a claimable (delta-succeeded, unblocked)+ # batch when its schema is not v3-enabled — the default batch is+ # full_refresh, which otherwise bypasses the unprimed block. Guards the+ # leak where non-v3 (e.g. Postgres) batches were applied via the+ # team-scoped claim. None = no filter (dev/tests); [] = nothing eligible.+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ async def claim(eligible: list[str] | None) -> list[Any]:+ return await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, eligible_schema_ids=eligible)++ assert len(await claim(None)) == 1+ assert len(await claim(["schema-1"])) == 1+ assert await claim(["other-schema"]) == []+ assert await claim([]) == []++ @pytest.mark.asyncio+ async def test_eligible_gate_excludes_replace_head_that_bypasses_block(self, conn):+ # A full_refresh replace-head bypasses the unprimed block, but the v3+ # allow-list must still exclude it when the schema is not v3-enabled — the+ # eligibility gate overrides the replace-head carve-out.+ head = await _insert_batch(conn, run_uuid="run-refresh", sync_type="full_refresh", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=head, job_state="succeeded", attempt=1)++ bypasses = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ assert [str(b.id) for b in bypasses] == [head]++ gated = await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn, blocked_schema_ids=["schema-1"], eligible_schema_ids=["other-schema"]+ )+ assert gated == []