: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(data-warehouse): stop deleted schemas and dead lock holders from wedging the duckgres planner (#69103)
Eric Duong162a11f12844
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 f1358f78803d..ccff7267ad30 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@@ -221,7 +221,17 @@ def replan_backfill(schema_id: str) -> None:"""state = DuckgresSinkSchemaState.objects.get(schema_id=schema_id)if state.backfill_run_uuid:- with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ with psycopg.connect(+ settings.WAREHOUSE_SOURCES_DATABASE_URL,+ autocommit=True,+ # These run inline in the consumer fetch path: a half-open connection+ # must fail in minutes, not the OS TCP timeout (hours).+ connect_timeout=30,+ keepalives=1,+ keepalives_idle=60,+ keepalives_interval=15,+ keepalives_count=4,+ ) as conn:retire_backfill_run(conn, run_uuid=state.backfill_run_uuid)DuckgresSinkSchemaState.objects.filter(id=state.id).update(state=DuckgresSinkSchemaState.State.PENDING_BACKFILL,@@ -406,9 +416,27 @@ def _plan_one(state: DuckgresSinkSchemaState) -> None:A crash after step 2 is healed by _reconcile_one (replay 3-4 from thestored plan); a crash before it is healed by the planning lease."""- schema = ExternalDataSchema.objects.select_related("source", "team").get(id=state.schema_id)+ schema = (+ ExternalDataSchema.objects.select_related("source", "team").filter(deleted=False, id=state.schema_id).first()+ )+ if schema is None:+ # Soft-deleted (or vanished) schema: its chunks would be unclaimable and+ # the row would pin a backfill slot forever. The purge sweep in+ # _reconcile retires the run and removes the state row.+ logger.warning("duckgres_backfill_plan_skipped_deleted_schema", schema_id=str(state.schema_id))+ return- with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ with psycopg.connect(+ settings.WAREHOUSE_SOURCES_DATABASE_URL,+ autocommit=True,+ # These run inline in the consumer fetch path: a half-open connection+ # must fail in minutes, not the OS TCP timeout (hours).+ connect_timeout=30,+ keepalives=1,+ keepalives_idle=60,+ keepalives_interval=15,+ keepalives_count=4,+ ) as conn:plan = resolve_snapshot_plan(schema)snapshot_version = plan.snapshot_versionchunks = plan.chunks@@ -465,6 +493,37 @@ def _plan_one(state: DuckgresSinkSchemaState) -> None:# ---------------------------------------------------------------------------+def _purge_deleted_schema_states(conn: psycopg.Connection[Any], team_ids: list[int] | None) -> None:+ """Drop sink state for soft-deleted schemas and retire their runs.++ Schema deletion has no signal into this state machine: a deleted schema's+ chunks become unclaimable (the eligibility gate excludes deleted schemas),+ so a BACKFILLING row would sit forever — invisible on the failing gauges+ (zero failures) while permanently consuming one of the global backfill+ slots, and its chunks would be re-enqueued after every queue prune. Five+ routine source deletions would halt all backfill planning fleet-wide.+ Deleting the row is safe: bootstrap re-creates PENDING_BACKFILL if the+ schema ever comes back.+ """+ states = DuckgresSinkSchemaState.objects.all()+ if team_ids is not None:+ if not team_ids:+ return+ states = states.filter(team_id__in=team_ids)+ run_by_schema = dict(states.values_list("schema_id", "backfill_run_uuid"))+ if not run_by_schema:+ return+ deleted_ids = list(+ ExternalDataSchema.objects.filter(id__in=run_by_schema.keys(), deleted=True).values_list("id", flat=True)+ )+ for schema_id in deleted_ids:+ run_uuid = run_by_schema[schema_id]+ if run_uuid:+ retire_backfill_run(conn, run_uuid=run_uuid)+ DuckgresSinkSchemaState.objects.filter(schema_id=schema_id).delete()+ logger.warning("duckgres_backfill_state_purged_for_deleted_schema", schema_id=str(schema_id))++def _reconcile(team_ids: list[int] | None) -> None:"""Heal and progress every non-terminal state. Authoritative for PRIMED."""# Half-claimed rows (crash between the lease CAS and the plan CAS) carry@@ -488,10 +547,25 @@ def _reconcile(team_ids: list[int] | None) -> None:needs_resync = needs_resync.filter(team_id__in=team_ids)rows = [s for s in backfilling if s.backfill_run_uuid]resync_rows = list(needs_resync)- if not rows and not resync_rows:- return- with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ with psycopg.connect(+ settings.WAREHOUSE_SOURCES_DATABASE_URL,+ autocommit=True,+ # These run inline in the consumer fetch path: a half-open connection+ # must fail in minutes, not the OS TCP timeout (hours).+ connect_timeout=30,+ keepalives=1,+ keepalives_idle=60,+ keepalives_interval=15,+ keepalives_count=4,+ ) as conn:+ try:+ _purge_deleted_schema_states(conn, team_ids)+ except Exception as e:+ logger.exception("duckgres_backfill_deleted_schema_purge_failed")+ capture_exception(e)+ if not rows and not resync_rows:+ returnfor state in rows:try:_reconcile_one(conn, state)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.pyindex 89a5d67ab9aa..9dd0a94a3535 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py@@ -11,6 +11,7 @@ import uuidfrom typing import Anyimport psycopg+import structlogfrom products.warehouse_sources.backend.models import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (@@ -26,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSTATUS_TABLE as DELTA_STATUS_TABLE,)+logger = structlog.get_logger(__name__)+BACKFILL_JOB_ID = "duckgres-backfill"# Session advisory-lock namespace that serializes enqueue_chunks per run_uuid.@@ -147,10 +150,22 @@ def enqueue_chunks(the later pod reads a complete ``existing`` set and inserts nothing."""inserted = 0- conn.execute(- "SELECT pg_advisory_lock(%s, hashtext(%s))",- [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],- )+ # The advisory lock is session-scoped and previously unbounded: a pod dying+ # without FIN leaves the server session (and the lock) alive for hours, and+ # every other pod's reconciler replay then blocks here — inline in the+ # consumer's fetch path — halting all duckgres claiming fleet-wide. Bound+ # the wait; a timeout skips the replay for this tick and the next tick+ # retries after the dead session is reaped.+ conn.execute("SET lock_timeout = '10s'")+ try:+ conn.execute(+ "SELECT pg_advisory_lock(%s, hashtext(%s))",+ [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],+ )+ except psycopg.errors.LockNotAvailable:+ conn.execute("RESET lock_timeout")+ logger.warning("duckgres_backfill_enqueue_lock_timeout", run_uuid=run_uuid)+ return 0try:existing = {row[0]@@ -205,6 +220,7 @@ def enqueue_chunks("SELECT pg_advisory_unlock(%s, hashtext(%s))",[BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],)+ conn.execute("RESET lock_timeout")return inserteddiff --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 cd1369281371..29f61d2cc2c2 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@@ -1,6 +1,9 @@import uuidimport pytest+from unittest.mock import MagicMock, patch++import psycopgfrom posthog.models import DuckgresSinkSchemaState, Organization, Team@@ -224,3 +227,85 @@ class TestBootstrapV3SourceGate:primed = set(DuckgresSinkSchemaState.objects.filter(team=team).values_list("schema_id", flat=True))assert v3_schema.id in primedassert non_v3_schema.id not in primed+++class TestDeletedSchemaPurge:+ def _fixture(self, deleted: bool, run_uuid: str | None = "run-1"):+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")+ source = ExternalDataSource.objects.create(+ team=team, source_id="s", connection_id="c", source_type="Stripe", status="Running"+ )+ schema = ExternalDataSchema.objects.create(team=team, source=source, name="customers", deleted=deleted)+ state = DuckgresSinkSchemaState.objects.create(+ team=team,+ schema_id=schema.id,+ state=DuckgresSinkSchemaState.State.BACKFILLING,+ backfill_run_uuid=run_uuid,+ )+ return schema, state++ def test_purge_retires_run_and_drops_state_for_deleted_schema(self):+ # A deleted schema's chunks are unclaimable, so its BACKFILLING row would+ # otherwise pin one of the global backfill slots forever with zero+ # failures on any gauge.+ _, state = self._fixture(deleted=True)+ conn = MagicMock()++ with patch.object(backfill_module, "retire_backfill_run") as retire:+ backfill_module._purge_deleted_schema_states(conn, None)++ retire.assert_called_once_with(conn, run_uuid="run-1")+ assert not DuckgresSinkSchemaState.objects.filter(id=state.id).exists()++ def test_purge_leaves_live_schemas_untouched(self):+ _, state = self._fixture(deleted=False)+ conn = MagicMock()++ with patch.object(backfill_module, "retire_backfill_run") as retire:+ backfill_module._purge_deleted_schema_states(conn, None)++ retire.assert_not_called()+ assert DuckgresSinkSchemaState.objects.filter(id=state.id).exists()++ def test_plan_one_skips_deleted_schema(self):+ # The default manager includes soft-deleted rows, so without the guard a+ # deleted schema would be planned and its unclaimable chunks enqueued+ # (and re-enqueued after every queue prune).+ schema, state = self._fixture(deleted=True, run_uuid=None)++ with (+ patch.object(backfill_module, "resolve_snapshot_plan") as resolve,+ patch.object(backfill_module.psycopg, "connect") as connect,+ ):+ backfill_module._plan_one(state)++ resolve.assert_not_called()+ connect.assert_not_called()+++class TestEnqueueLockTimeout:+ def test_lock_timeout_skips_replay_and_resets(self):+ # A dead lock-holder session previously blocked every pod's reconciler+ # replay indefinitely, inline in the consumer fetch path.+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (+ backfill_queue,+ )++ conn = MagicMock()++ def execute(query, *args, **kwargs):+ if "pg_advisory_lock" in str(query):+ raise psycopg.errors.LockNotAvailable()+ return MagicMock()++ conn.execute.side_effect = execute+ schema = MagicMock()++ inserted = backfill_queue.enqueue_chunks(conn, schema, "run-x", [])++ assert inserted == 0+ executed = [str(c.args[0]) for c in conn.execute.call_args_list]+ assert any("SET lock_timeout" in q for q in executed)+ assert any("RESET lock_timeout" in q for q in executed)+ assert not any("INSERT INTO" in q for q in executed)