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): bound duckgres bootstrap memory to stop OOM crashloop (#66901)

Eric Duongcdc220fa67c9
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.py
index 45c1e5ae58b9..46f50159d67b 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
@@ -192,6 +192,9 @@ def replan_backfill(schema_id: str) -> None:
# ---------------------------------------------------------------------------
+BOOTSTRAP_BATCH_SIZE = 1000
+
+
def _bootstrap_state_rows(team_ids: list[int] | None) -> None:
"""Create state rows for enabled teams' schemas that have none.
@@ -203,6 +206,11 @@ def _bootstrap_state_rows(team_ids: list[int] | None) -> None:
- 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.
+
+ Memory-bounded: a single team can own tens of thousands of schemas, so we
+ anti-join in Postgres to skip schemas that already have a state row, stream
+ the rest with a server-side cursor instead of materializing the whole set,
+ and flush in fixed batches so the in-flight list never grows unbounded.
"""
# 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.
@@ -210,10 +218,13 @@ def _bootstrap_state_rows(team_ids: list[int] | None) -> None:
is_pipeline_v3_enabled,
)
- schemas = ExternalDataSchema.objects.exclude(deleted=True).select_related("team", "source")
+ schemas = (
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .exclude(id__in=DuckgresSinkSchemaState.objects.values("schema_id"))
+ .values("id", "team_id", "sync_type", "table_id", "source__source_type")
+ )
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.
@@ -227,17 +238,16 @@ def _bootstrap_state_rows(team_ids: list[int] | None) -> None:
v3_enabled[key] = is_pipeline_v3_enabled(team_id, source_type)
return v3_enabled[key]
+ created = 0
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):
+ for schema in schemas.iterator(chunk_size=BOOTSTRAP_BATCH_SIZE):
+ if not _source_is_v3(schema["team_id"], schema["source__source_type"]):
continue
- needs_backfill = schema.sync_type not in ("full_refresh", "cdc", None) and schema.table_id is not None
+ needs_backfill = schema["sync_type"] not in ("full_refresh", "cdc", None) and schema["table_id"] is not None
to_create.append(
DuckgresSinkSchemaState(
- team_id=schema.team_id,
- schema_id=schema.id,
+ team_id=schema["team_id"],
+ schema_id=schema["id"],
state=(
DuckgresSinkSchemaState.State.PENDING_BACKFILL
if needs_backfill
@@ -245,9 +255,16 @@ def _bootstrap_state_rows(team_ids: list[int] | None) -> None:
),
)
)
+ if len(to_create) >= BOOTSTRAP_BATCH_SIZE:
+ DuckgresSinkSchemaState.objects.bulk_create(to_create, ignore_conflicts=True)
+ created += len(to_create)
+ to_create = []
+
if to_create:
DuckgresSinkSchemaState.objects.bulk_create(to_create, ignore_conflicts=True)
- logger.info("duckgres_backfill_bootstrapped", created=len(to_create))
+ created += len(to_create)
+ if created:
+ logger.info("duckgres_backfill_bootstrapped", created=created)
def _plan_pending(team_ids: list[int] | None) -> None:
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.py
index 077bb6ebd306..e0474c8b6e08 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
@@ -99,8 +99,18 @@ class DuckgresBatchConsumerAdapter:
if self._team_ids_fetched_at is not None and now - self._team_ids_fetched_at < ENABLEMENT_REFRESH_SECONDS:
return self._team_ids
try:
+ first_resolution = self._team_ids_fetched_at is None
+ previous = self._team_ids
self._team_ids = await sync_to_async(duckgres_sink_team_ids, thread_sensitive=False)()
self._team_ids_fetched_at = now
+ if first_resolution or self._team_ids != previous:
+ # Only on the first resolution or an actual change — the refresh
+ # itself runs every ~60s and would otherwise spam.
+ logger.info(
+ "duckgres_sink_enabled_teams_resolved",
+ first_resolution=first_resolution,
+ team_count=None if self._team_ids is None else len(self._team_ids),
+ )
except Exception as e:
logger.exception("duckgres_sink_enablement_refresh_failed")
capture_exception(e)
@@ -130,17 +140,35 @@ class DuckgresBatchConsumerAdapter:
SINK_BLOCKED_BACKLOG.set(blocked)
SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)
+ block_list_was_unset = self._blocked_schema_ids is None
try:
# Backfill planner: bootstrap/plan/reconcile schema priming, then
# 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)
+ if block_list_was_unset:
+ # First successful planner pass: the sink can now claim live
+ # batches (fetch returns [] until this happens).
+ logger.info(
+ "duckgres_backfill_block_list_ready",
+ blocked_schema_count=len(self._blocked_schema_ids),
+ )
except Exception as e:
# An app-DB blip must not crash the poll loop; keep the previous
# block list (or keep claiming nothing if we never had one).
logger.exception("duckgres_backfill_planner_failed")
capture_exception(e)
+ # Heartbeat: confirms the ~30s maintenance pass (enablement set, supersede
+ # sweep, planner) actually ran. Bounded to one line per maintenance tick.
+ logger.info(
+ "duckgres_maintenance_ran",
+ team_count=None if team_ids is None else len(team_ids),
+ eligible_backlog=backlog,
+ blocked_backlog=blocked,
+ blocked_schema_count=None if self._blocked_schema_ids is None else len(self._blocked_schema_ids),
+ )
+
async def fetch_and_lock(
self,
conn: psycopg.AsyncConnection[Any],
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.py
index 26fa11b4db9b..cd1369281371 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
@@ -4,10 +4,14 @@ import pytest
from posthog.models import DuckgresSinkSchemaState, Organization, Team
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (
backfill as backfill_module,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (
+ _bootstrap_state_rows,
_plan_pending,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (
@@ -71,6 +75,54 @@ def test_chunk_dataclass_shape():
assert (c.index, c.byte_size, c.row_count) == (0, 1, 2)
+def test_bootstrap_state_rows_streams_batches_and_skips_existing(monkeypatch):
+ # A single team can own far more schemas than fit in one bulk_create, so the
+ # bootstrap streams and flushes in batches. Force a tiny batch so the schemas
+ # below straddle a flush boundary — guards against the final partial batch
+ # being dropped and against the anti-join re-creating rows that already exist.
+ monkeypatch.setattr(backfill_module, "BOOTSTRAP_BATCH_SIZE", 2)
+ # The v3-source gate does a network flag eval; stub it on so this test stays
+ # about the streaming/batching path, not flag resolution.
+ monkeypatch.setattr(create_job_model, "is_pipeline_v3_enabled", lambda team_id, source_type: True)
+
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = ExternalDataSource.objects.create(
+ team_id=team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ table = DataWarehouseTable.objects.create(name="t", format="Parquet", team=team, url_pattern="https://b.s3/data/*")
+
+ def _schema(name, sync_type, *, with_table):
+ return ExternalDataSchema.objects.create(
+ team_id=team.pk, source=source, name=name, sync_type=sync_type, table=table if with_table else None
+ )
+
+ # Only incremental-with-a-table needs priming; the rest land straight in PRIMED.
+ needs_priming = _schema("incremental", ExternalDataSchema.SyncType.INCREMENTAL, with_table=True)
+ full_refresh = _schema("full_refresh", ExternalDataSchema.SyncType.FULL_REFRESH, with_table=True)
+ cdc = _schema("cdc", ExternalDataSchema.SyncType.CDC, with_table=True)
+ no_table = _schema("no_table", ExternalDataSchema.SyncType.INCREMENTAL, with_table=False)
+
+ _bootstrap_state_rows([team.pk])
+
+ states = {s.schema_id: s.state for s in DuckgresSinkSchemaState.objects.all()}
+ assert states == {
+ needs_priming.id: DuckgresSinkSchemaState.State.PENDING_BACKFILL,
+ full_refresh.id: DuckgresSinkSchemaState.State.PRIMED,
+ cdc.id: DuckgresSinkSchemaState.State.PRIMED,
+ no_table.id: DuckgresSinkSchemaState.State.PRIMED,
+ }
+
+ # Re-running must not duplicate or revert anything — the anti-join skips all four.
+ _bootstrap_state_rows([team.pk])
+ assert DuckgresSinkSchemaState.objects.count() == 4
+
+
def test_committed_batch_keys_filters_to_snapshot_version():
class FakeDeltaTable:
def history(self):