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.

feat(data-warehouse): close metric gaps in warehouse person-property sync (#84502)

Tom Owers65f51d3db927
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py
index b149c952e3c6..dc2fbbe58a08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job.py
@@ -51,6 +51,14 @@ PERSON_PROPERTY_BACKFILL_DURATION_SECONDS = Histogram(
buckets=(0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),
)
+# Same funnel stages as the scheduled sync (warehouse_person_property_sync_rows_total), kept as a
+# separate metric so a large one-off backfill can't distort the steady-state sync funnel.
+PERSON_PROPERTY_BACKFILL_ROWS_TOTAL = Counter(
+ "warehouse_person_property_backfill_rows_total",
+ "Rows flowing through each stage of the person-property backfill funnel",
+ labelnames=["team_id", "stage"],
+)
+
@activity.defn
async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBackfillActivityInputs) -> dict[str, Any]:
@@ -89,6 +97,15 @@ async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBa
)
PERSON_PROPERTY_BACKFILL_TOTAL.labels(team_id=str(inputs.team_id), outcome="completed").inc()
PERSON_PROPERTY_BACKFILL_DURATION_SECONDS.observe(time.monotonic() - start)
+ for stage, count in (
+ ("read", result.rows_read),
+ ("changed", result.changed),
+ ("existing", result.existing),
+ ("produced", result.produced),
+ ("skipped_missing_person", result.skipped_missing_person),
+ ):
+ if count:
+ PERSON_PROPERTY_BACKFILL_ROWS_TOTAL.labels(team_id=str(inputs.team_id), stage=stage).inc(count)
log.info(
"Person-property backfill finished",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job_test.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job_test.py
new file mode 100644
index 000000000000..066f09b64f77
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_backfill_job_test.py
@@ -0,0 +1,80 @@
+import uuid
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from temporalio.testing import ActivityEnvironment
+
+from products.warehouse_sources.backend.temporal.data_imports import person_property_backfill_job as bj
+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (
+ PersonPropertyBackfillActivityInputs,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync import SyncResult
+
+
+def _inputs(team_id: int) -> PersonPropertyBackfillActivityInputs:
+ return PersonPropertyBackfillActivityInputs(
+ team_id=team_id,
+ schema_id=uuid.uuid4(),
+ source_type="Stripe",
+ schema_name="charges",
+ trigger="manual",
+ )
+
+
[email protected]_db(transaction=True)
+class TestBackfillWarehousePersonPropertiesActivity:
+ async def test_records_one_stage_per_nonzero_funnel_count(self) -> None:
+ # A distinct team_id per test keeps the module-level Counter's label values from a previous
+ # test run bleeding into this one's assertions.
+ team_id = 900001
+ result = SyncResult(sources=1, rows_read=5, changed=3, existing=0, produced=3, skipped_missing_person=1)
+ with (
+ patch.object(bj, "run_person_property_backfill", AsyncMock(return_value=result)),
+ patch.object(bj, "record_completed_runs", AsyncMock()) as mock_record,
+ ):
+ returned = await ActivityEnvironment().run(
+ bj.backfill_warehouse_person_properties_activity, _inputs(team_id)
+ )
+
+ assert returned == {
+ "sources": 1,
+ "rows_read": 5,
+ "changed": 3,
+ "existing": 0,
+ "produced": 3,
+ "skipped_missing_person": 1,
+ "per_source": [],
+ }
+ mock_record.assert_awaited_once()
+
+ def stage_value(stage: str) -> float:
+ return bj.PERSON_PROPERTY_BACKFILL_ROWS_TOTAL.labels(team_id=str(team_id), stage=stage)._value.get()
+
+ # Every nonzero stage got its count.
+ assert stage_value("read") == 5
+ assert stage_value("changed") == 3
+ assert stage_value("produced") == 3
+ assert stage_value("skipped_missing_person") == 1
+ # A zero-count stage is skipped rather than recorded as a no-op increment, so the label
+ # never appears on a backfill that didn't touch it.
+ assert stage_value("existing") == 0
+
+ async def test_read_rows_with_no_changes_still_recorded(self) -> None:
+ # Regression: a backfill that reads rows but changes/produces nothing (the "no metrics but
+ # logs" gap this metric exists to close) must still report the read count.
+ team_id = 900002
+ result = SyncResult(sources=1, rows_read=10, changed=0, existing=10, produced=0, skipped_missing_person=0)
+ with (
+ patch.object(bj, "run_person_property_backfill", AsyncMock(return_value=result)),
+ patch.object(bj, "record_completed_runs", AsyncMock()),
+ ):
+ await ActivityEnvironment().run(bj.backfill_warehouse_person_properties_activity, _inputs(team_id))
+
+ def stage_value(stage: str) -> float:
+ return bj.PERSON_PROPERTY_BACKFILL_ROWS_TOTAL.labels(team_id=str(team_id), stage=stage)._value.get()
+
+ assert stage_value("read") == 10
+ assert stage_value("existing") == 10
+ assert stage_value("changed") == 0
+ assert stage_value("produced") == 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
index c298b8aeba08..b8ff49dfb0fd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
@@ -50,8 +50,16 @@ _RATE_KEY = f"{_RATE_DOMAIN}:global"
# pods just run slower, never faster). Keep in sync with charts ``autoscaling.maxPods``.
_IN_MEMORY_DIVIDER = 6
-SENT_TOTAL = Counter("warehouse_person_property_sent_total", "person-property $set events sent to capture")
-DLQ_TOTAL = Counter("warehouse_person_property_dlq_total", "person-property update messages routed to DLQ")
+SENT_TOTAL = Counter(
+ "warehouse_person_property_sent_total",
+ "person-property update events sent to capture ($set for persons, $groupidentify for groups)",
+ labelnames=["kind"],
+)
+DLQ_TOTAL = Counter(
+ "warehouse_person_property_dlq_total",
+ "person-property update messages routed to DLQ",
+ labelnames=["reason"],
+)
DLQ_FAILED_TOTAL = Counter(
"warehouse_person_property_dlq_failed_total", "person-property DLQ writes that failed to deliver"
)
@@ -158,6 +166,12 @@ DLQ = "dlq"
RETRY = "retry"
+def _dlq_reason_label(reason: str) -> str:
+ """Collapse a DLQ reason to a bounded metric label: drop per-message detail after ':' (status
+ codes) and replace spaces so the validation sentences become stable slugs."""
+ return reason.split(":", 1)[0].replace(" ", "_")
+
+
def _is_permanent_client_error(status_code: object) -> bool:
"""True for a 4xx that can never succeed on retry (bad/stale token, validation) -> DLQ. The
retryable 4xx (408 timeout, 429 throttled) are excluded so a client hammering capture into
@@ -212,6 +226,7 @@ class PersonPropertyUpdateConsumer:
topic=KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ,
data={"raw": value.decode("utf-8", "replace"), "reason": reason},
)
+ reason_label = _dlq_reason_label(reason)
# Bound the flush: an unavailable DLQ broker must not block past the liveness timeout and get
# the pod killed mid-write. Heartbeat either side so a slow-but-progressing write stays live.
self._health_reporter()
@@ -223,7 +238,7 @@ class PersonPropertyUpdateConsumer:
DLQ_FAILED_TOTAL.inc()
logger.exception("person_property_update.dlq_delivery_failed", reason=reason)
return RETRY
- DLQ_TOTAL.inc()
+ DLQ_TOTAL.labels(reason=reason_label).inc()
return DLQ
def _acquire_slot(self) -> bool:
@@ -290,7 +305,7 @@ class PersonPropertyUpdateConsumer:
logger.exception("person_property_update.capture_error")
return RETRY
if result.succeeded():
- SENT_TOTAL.inc()
+ SENT_TOTAL.labels(kind="group" if kwargs["event_name"] == "$groupidentify" else "person").inc()
return SENT
# A drop is terminal: capture rejected the event permanently (e.g. invalid/stale token,
# validation failure), so it's poison. DLQ it rather than redelivering forever.