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(warehouse-sources): fail a person-property backfill whose key column is missing (#100879)

posthog[bot]8e2235e74f6f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py
index 163b04a7ab7d..468fafc475a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py
@@ -36,6 +36,7 @@ from django.db.models import Q
import structlog
import pyarrow.parquet as pq
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES
@@ -87,7 +88,7 @@ def _log_fields(binding: WarehouseBinding) -> dict[str, str]:
_EXISTENCE_LOOKUP_CHUNK_SIZE = 1_000
+@frozen(frozen=False)
class PerSourceResult:
"""One source's funnel counts within a run, so the recorder can persist a run row per source."""
@@ -97,6 +98,9 @@ class PerSourceResult:
existing: int = 0
produced: int = 0
skipped_missing_person: int = 0
+ # Set when the source can't write anything for a reason its counts alone don't explain, so the
+ # recorder persists a failed run instead of a clean one that produced nothing.
+ error: str | None = None
@dataclasses.dataclass
@@ -648,12 +652,21 @@ BACKFILL_BATCH_SIZE = 50_000
BACKFILL_RUN_TOKEN = "backfill"
+@frozen
+class DeltaBundleRead:
+ """What one full-table Delta read yielded for a backfill."""
+
+ bundles_by_source: dict[str, dict[str, dict]]
+ rows_read: int
+ sources_missing_key_column: frozenset[str]
+
+
def _read_delta_bundles(
uri: str, storage_options: dict[str, str], sources: list[PersonPropertySyncSource]
-) -> tuple[dict[str, dict[str, dict]], int]:
+) -> DeltaBundleRead:
"""Stream the table's Delta files from S3 and accumulate {source_id: {distinct_id: bundle}}
(last-write-wins per distinct_id). Streams batches — never materializes the whole table — so peak
- memory tracks distinct persons, not row count. Returns (accumulated, rows_read)."""
+ memory tracks distinct persons, not row count."""
import deltalake # noqa: PLC0415 — keeps the heavy delta-rs/pandas stack off the import path
accumulated: dict[str, dict[str, dict]] = {str(source.source_id): {} for source in sources}
@@ -662,7 +675,7 @@ def _read_delta_bundles(
# as an empty read rather than erroring, but log it since a persistent empty backfill is a
# likely "why didn't anything happen" answer.
logger.warning("person-property backfill: no Delta table at URI, reading 0 rows", uri=uri)
- return accumulated, 0
+ return DeltaBundleRead(bundles_by_source=accumulated, rows_read=0, sources_missing_key_column=frozenset())
dataset = deltalake.DeltaTable(uri, storage_options=storage_options).to_pyarrow_dataset()
available = set(dataset.schema.names)
@@ -673,10 +686,12 @@ def _read_delta_bundles(
project = sorted(wanted & available)
# A source whose key column itself is missing produces zero bundles for the whole table, which is
- # otherwise indistinguishable from a genuinely idle backfill. Log it so a misconfigured mapping
- # (table dropped/renamed the identifier column) is diagnosable rather than silent.
+ # otherwise indistinguishable from a genuinely idle backfill. Report it back so the caller can fail
+ # the run rather than complete a no-op, and log it for the same reason.
+ missing_key_column: set[str] = set()
for source in sources:
if source.key_column not in available:
+ missing_key_column.add(str(source.source_id))
logger.warning(
"person-property backfill: source key column missing from table, will produce nothing",
uri=uri,
@@ -692,7 +707,11 @@ def _read_delta_bundles(
bucket = accumulated[str(source.source_id)]
for distinct_id, bundle in build_bundles(rows, source.key_column, source.column_property_map or {}):
bucket[distinct_id] = bundle
- return accumulated, rows_read
+ return DeltaBundleRead(
+ bundles_by_source=accumulated,
+ rows_read=rows_read,
+ sources_missing_key_column=frozenset(missing_key_column),
+ )
def _schema_delta_uri(team_id: int, schema_id: str) -> str | None:
@@ -748,20 +767,37 @@ async def run_person_property_backfill(*, team_id: int, binding: WarehouseBindin
return result
team = await database_sync_to_async(Team.objects.get, thread_sensitive=False)(id=team_id)
- accumulated, rows_read = await asyncio.to_thread(_read_delta_bundles, uri, delta_storage_options(), sources)
+ read = await asyncio.to_thread(_read_delta_bundles, uri, delta_storage_options(), sources)
result.sources = len(sources)
- result.rows_read = rows_read
+ result.rows_read = read.rows_read
logger.info(
"person-property backfill: read full Delta table",
team_id=team_id,
**_log_fields(binding),
trigger=trigger,
sources=len(sources),
- rows_read=rows_read,
+ rows_read=read.rows_read,
)
for source in sources:
- bundles = list(accumulated[str(source.source_id)].items())
+ if str(source.source_id) in read.sources_missing_key_column:
+ # Nothing this source can match on, so every later stage is a no-op. Surfaced as a failed
+ # run because the mapping stays broken until someone changes it — a completed run would
+ # clear the source's last error and read as a healthy sync that happened to write nothing.
+ _accumulate(
+ result,
+ PerSourceResult(
+ source_id=str(source.source_id),
+ rows_read=read.rows_read,
+ error=(
+ f"Key column '{source.key_column}' is not a column of the synced table, so no rows "
+ "could be matched. It may have been renamed or dropped upstream, or it may be a "
+ "query-time SQL expression rather than a synced column."
+ ),
+ ),
+ )
+ continue
+ bundles = list(read.bundles_by_source[str(source.source_id)].items())
ps = await _process_source_bundles(
team_id=team_id,
project_id=team.project_id,
@@ -770,7 +806,7 @@ async def run_person_property_backfill(*, team_id: int, binding: WarehouseBindin
team_uuid=str(team.uuid),
source=source,
bundles=bundles,
- rows_read=rows_read,
+ rows_read=read.rows_read,
run_token=BACKFILL_RUN_TOKEN,
)
_accumulate(result, ps)
@@ -857,7 +893,8 @@ async def record_completed_runs(
finished_at: str,
result: SyncResult,
) -> None:
- """Persist one completed run row per source. Never raises — the recorder swallows its own errors,
+ """Persist one terminal run row per source: completed, or failed for a source that carried an
+ error the run's counts alone wouldn't explain. Never raises — the recorder swallows its own errors,
and we still guard here so run bookkeeping can't fail the sync/backfill that produced it (which
would otherwise trigger a wasteful Temporal retry of an already-successful, produced run)."""
try:
@@ -867,11 +904,11 @@ async def record_completed_runs(
binding=binding,
job_id=job_id,
trigger=trigger,
- status="completed",
+ status="failed" if ps.error else "completed",
started_at=started_at,
finished_at=finished_at,
ps=ps,
- error=None,
+ error=ps.error,
)
except Exception as e:
logger.exception(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py
index 87bca87a62a3..85bd9ed9f2de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py
@@ -238,18 +238,40 @@ class TestReadDeltaBundles:
with patch("deltalake.DeltaTable") as dt_cls:
dt_cls.is_deltatable.return_value = True
dt_cls.return_value = fake_dt
- accumulated, rows_read = pps._read_delta_bundles("s3://uri", {}, sources)
+ read = pps._read_delta_bundles("s3://uri", {}, sources)
- assert rows_read == 3
- assert accumulated["s1"] == {"a": {"plan_tier": "pro"}, "b": {"plan_tier": "team"}}
- assert accumulated["s2"] == {"a": {"tier": "pro"}, "b": {"tier": "team"}}
+ assert read.rows_read == 3 and read.sources_missing_key_column == frozenset()
+ assert read.bundles_by_source["s1"] == {"a": {"plan_tier": "pro"}, "b": {"plan_tier": "team"}}
+ assert read.bundles_by_source["s2"] == {"a": {"tier": "pro"}, "b": {"tier": "team"}}
+
+ def test_reports_a_source_whose_key_column_the_table_lacks(self):
+ # The key column is what every row is matched on, so its absence produces nothing at all —
+ # the reader has to say so, or the backfill can't tell this apart from an idle table.
+ sources = [
+ PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"}),
+ PersonPropertySyncSource("s2", "d2", "computed_key", {"plan": "tier"}),
+ ]
+ fake_dt = MagicMock()
+ fake_dt.to_pyarrow_dataset.return_value = self._dataset(
+ [{"distinct_id": "a", "plan": "free"}], ["distinct_id", "plan"]
+ )
+ with patch("deltalake.DeltaTable") as dt_cls:
+ dt_cls.is_deltatable.return_value = True
+ dt_cls.return_value = fake_dt
+ read = pps._read_delta_bundles("s3://uri", {}, sources)
+
+ assert read.sources_missing_key_column == frozenset({"s2"})
+ assert read.bundles_by_source["s1"] == {"a": {"plan_tier": "free"}}
+ assert read.bundles_by_source["s2"] == {}
+ assert read.rows_read == 1
def test_missing_table_returns_empty(self):
sources = [PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})]
with patch("deltalake.DeltaTable") as dt_cls:
dt_cls.is_deltatable.return_value = False
- accumulated, rows_read = pps._read_delta_bundles("s3://uri", {}, sources)
- assert accumulated == {"s1": {}} and rows_read == 0
+ read = pps._read_delta_bundles("s3://uri", {}, sources)
+ assert read.bundles_by_source == {"s1": {}} and read.rows_read == 0
+ assert read.sources_missing_key_column == frozenset()
class TestBackfillOrchestration:
@@ -273,7 +295,12 @@ class TestBackfillOrchestration:
patch(f"{_MODULE}._get_schema", return_value=schema),
patch(f"{_MODULE}.Team") as team_cls,
patch(f"{_MODULE}.delta_storage_options", return_value={}),
- patch(f"{_MODULE}._read_delta_bundles", return_value=(accumulated, 5)) as read_delta,
+ patch(
+ f"{_MODULE}._read_delta_bundles",
+ return_value=pps.DeltaBundleRead(
+ bundles_by_source=accumulated, rows_read=5, sources_missing_key_column=frozenset()
+ ),
+ ) as read_delta,
patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
patch(f"{_MODULE}._filter_existing_ids", return_value={"a"}),
patch(f"{_MODULE}._produce_intents", return_value=1) as produce,
@@ -294,6 +321,65 @@ class TestBackfillOrchestration:
assert all(call.args[3] == pps.BACKFILL_RUN_TOKEN for call in write_snapshot.await_args_list)
assert produce.call_count == 2
+ @pytest.mark.asyncio
+ async def test_source_without_its_key_column_fails_instead_of_producing_nothing(self):
+ # Previously this completed clean with produced=0, which cleared the source's last error and
+ # read as a healthy sync — the mapping stays broken until someone changes the key column.
+ team = MagicMock(api_token="tok", project_id=7)
+ schema = MagicMock()
+ schema.folder_path.return_value = "team_1_source_schema-1"
+ schema.resolved_s3_folder_name = "orders"
+ schema.name = "orders"
+ sources = [PersonPropertySyncSource("s1", "d1", "computed_key", {"plan": "plan_tier"})]
+ with (
+ patch(f"{_MODULE}.person_property_sync_sources_for", return_value=sources),
+ patch(f"{_MODULE}._get_schema", return_value=schema),
+ patch(f"{_MODULE}.Team") as team_cls,
+ patch(f"{_MODULE}.delta_storage_options", return_value={}),
+ patch(
+ f"{_MODULE}._read_delta_bundles",
+ return_value=pps.DeltaBundleRead(
+ bundles_by_source={"s1": {}}, rows_read=8, sources_missing_key_column=frozenset({"s1"})
+ ),
+ ),
+ patch(f"{_MODULE}._produce_intents") as produce,
+ patch(f"{_MODULE}._reconcile_property_definitions") as reconcile,
+ ):
+ team_cls.objects.get.return_value = team
+ result = await pps.run_person_property_backfill(team_id=1, binding=_SCHEMA, trigger="backfill")
+
+ (ps,) = result.per_source
+ assert ps.source_id == "s1"
+ assert ps.rows_read == 8 and ps.produced == 0
+ assert "computed_key" in (ps.error or "")
+ # The source is skipped outright rather than walked through stages that cannot match a row.
+ produce.assert_not_called()
+ reconcile.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_a_source_error_is_recorded_as_a_failed_run(self):
+ result = pps.SyncResult(
+ per_source=[
+ pps.PerSourceResult(source_id="s1", rows_read=8, error="Key column 'computed_key' is not a column"),
+ pps.PerSourceResult(source_id="s2", rows_read=8, produced=2),
+ ]
+ )
+ with patch(f"{_MODULE}.record_person_property_sync_run") as record:
+ await pps.record_completed_runs(
+ team_id=1,
+ binding=_SCHEMA,
+ job_id="job-1",
+ trigger="backfill",
+ started_at="2026-01-01T00:00:00+00:00",
+ finished_at="2026-01-01T00:00:01+00:00",
+ result=result,
+ )
+
+ recorded = {call.args[0].source_id: call.args[0] for call in record.call_args_list}
+ # Only the errored source fails, so one broken mapping can't mark a healthy sibling failed.
+ assert recorded["s1"].status == "failed" and "computed_key" in recorded["s1"].error
+ assert recorded["s2"].status == "completed" and recorded["s2"].error is None
+
@parameterized.expand([("schema", _SCHEMA), ("saved_query", _VIEW)])
@pytest.mark.asyncio
async def test_missing_warehouse_table_is_a_noop(self, _name, binding):
@@ -322,7 +408,12 @@ class TestBackfillOrchestration:
"products.data_modeling.backend.facade.api.get_materialized_table_uri",
return_value="s3://bucket/team_1_model_abc/modeling/enriched_users",
) as model_uri,
- patch(f"{_MODULE}._read_delta_bundles", return_value=({"s1": {}}, 0)) as read_delta,
+ patch(
+ f"{_MODULE}._read_delta_bundles",
+ return_value=pps.DeltaBundleRead(
+ bundles_by_source={"s1": {}}, rows_read=0, sources_missing_key_column=frozenset()
+ ),
+ ) as read_delta,
patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
patch(f"{_MODULE}._reconcile_property_definitions"),
):