: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(warehouse-sources): show how far an interrupted person property run got (#122264)
Jovan Sakovicc166a7017033
diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.pyindex 573d00af97b7..ad167700cf6f 100644--- a/products/customer_analytics/backend/apps.py+++ b/products/customer_analytics/backend/apps.py@@ -68,9 +68,11 @@ class CustomerAnalyticsConfig(AppConfig):"""from products.warehouse_sources.backend.facade.hooks import (PersonPropertySourceProjection,+ PersonPropertySyncProgress,PersonPropertySyncRunRecord,PersonPropertySyncSource,register_person_property_projection,+ register_person_property_sync_progress_recorder,register_person_property_sync_recorder,register_person_property_sync_sources,register_saved_query_property_sources,@@ -102,7 +104,15 @@ class CustomerAnalyticsConfig(AppConfig):return saved_queries_with_property_sources(team_id, saved_query_ids)+ def _progress_recorder(progress: PersonPropertySyncProgress) -> None:+ from products.customer_analytics.backend.logic.person_property_runs import ( # noqa: PLC0415+ record_sync_progress,+ )++ record_sync_progress(progress)+register_person_property_projection(_projection_resolver)register_person_property_sync_sources(_sync_sources_resolver)register_person_property_sync_recorder(_run_recorder)register_saved_query_property_sources(_saved_query_sources_resolver)+ register_person_property_sync_progress_recorder(_progress_recorder)diff --git a/products/customer_analytics/backend/logic/person_property_runs.py b/products/customer_analytics/backend/logic/person_property_runs.pyindex 6f3735d760db..b40a13b4d404 100644--- a/products/customer_analytics/backend/logic/person_property_runs.py+++ b/products/customer_analytics/backend/logic/person_property_runs.py@@ -9,6 +9,8 @@ account-path ``sourceSyncStatus`` UI helper works for person sources too.from datetime import datetimefrom django.db import transaction+from django.db.models import F+from django.db.models.functions import Greatestimport structlog@@ -24,7 +26,11 @@ from products.customer_analytics.backend.models import (SyncStatus,SyncTrigger,)-from products.warehouse_sources.backend.facade.hooks import BINDING_KIND_SAVED_QUERY, PersonPropertySyncRunRecord+from products.warehouse_sources.backend.facade.hooks import (+ BINDING_KIND_SAVED_QUERY,+ PersonPropertySyncProgress,+ PersonPropertySyncRunRecord,+)logger = structlog.get_logger(__name__)@@ -38,8 +44,13 @@ _SYNC_TRIGGERS = frozenset({SyncTrigger.SCHEDULED.value, SyncTrigger.SYNC.value}# row created by "Sync now" keeps its own trigger when the terminal record lands on it._USER_TRIGGERS = frozenset({SyncTrigger.SYNC.value, SyncTrigger.MANUAL.value})+_PROGRESS_COUNTS = ("existing", "produced")+# A retry diffs again everything not yet delivered, so the first attempt's totals are the run's totals.+# Missing persons are never delivered, so each attempt skips them again.+_ATTEMPT_TOTALS = ("rows_read", "changed", "skipped_missing_person")+-def _binding_fields(record: PersonPropertySyncRunRecord) -> dict[str, str | None]:+def _binding_fields(record: PersonPropertySyncRunRecord | PersonPropertySyncProgress) -> dict[str, str | None]:"""The run row's binding columns. Both are kept nullable and only one is ever set, so a run staysreadable after the schema or view it read is deleted."""if record.binding_kind == BINDING_KIND_SAVED_QUERY:@@ -57,7 +68,7 @@ def _parse_iso(value: str | None) -> datetime | None:def _find_reconcilable_run(- team_id: int, source: CustomPropertySource, record: PersonPropertySyncRunRecord+ team_id: int, source: CustomPropertySource, job_id: str | None, trigger: str) -> CustomPropertySyncRun | None:"""The existing row this record belongs to, or None to insert a new one.@@ -67,12 +78,16 @@ def _find_reconcilable_run(pipeline — either a placeholder the UI created on "Sync now"/"Backfill" (progress + double-submitguard) or the row the activity opened when it started."""runs = CustomPropertySyncRun.objects.for_team(team_id).select_for_update().filter(source=source)- if record.job_id:- run = runs.filter(job_id=record.job_id).order_by("-created_at").first()+ if job_id:+ run = runs.filter(job_id=job_id).order_by("-created_at").first()if run is not None:return run- triggers = _BACKFILL_TRIGGERS if record.trigger in _BACKFILL_TRIGGERS else _SYNC_TRIGGERS- return runs.filter(status=SyncStatus.RUNNING.value, trigger__in=triggers).order_by("-created_at").first()+ triggers = _BACKFILL_TRIGGERS if trigger in _BACKFILL_TRIGGERS else _SYNC_TRIGGERS+ in_progress = runs.filter(status=SyncStatus.RUNNING.value, trigger__in=triggers)+ if job_id:+ # Only a row nobody has claimed yet: another job's running row keeps its own counts.+ in_progress = in_progress.filter(job_id__isnull=True)+ return in_progress.order_by("-created_at").first()def record_sync_run(record: PersonPropertySyncRunRecord) -> None:@@ -98,7 +113,7 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:finished_at = _parse_iso(record.finished_at)succeeded = record.status == SyncStatus.COMPLETED.value- run = _find_reconcilable_run(record.team_id, source, record)+ run = _find_reconcilable_run(record.team_id, source, record.job_id, record.trigger)already_failed = run is not None and run.status == SyncStatus.FAILED.valuefields: dict = {@@ -118,6 +133,14 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:if run is not None:if run.trigger in _USER_TRIGGERS:fields.pop("trigger")+ # Chunk progress has already added up what every attempt delivered, and the first+ # attempt saw the most rows. This record holds only the last attempt's counts, so it+ # can raise these but never lower them.+ for count in (*_PROGRESS_COUNTS, *_ATTEMPT_TOTALS):+ fields[count] = Greatest(F(count), fields[count])+ # A backfill retry re-reads the table, so it can find rows the first attempt never saw.+ # Deliveries already counted must not outgrow the changed total.+ fields["changed"] = Greatest(F("changed"), record.changed, F("existing"), record.existing)for attr, value in fields.items():setattr(run, attr, value)run.save()@@ -161,3 +184,46 @@ def record_sync_run(record: PersonPropertySyncRunRecord) -> None:except Exception as error:log.exception("person-property run recorder failed")capture_exception(error)+++def record_sync_progress(progress: PersonPropertySyncProgress) -> None:+ """Add one produced chunk's counts to the run row the terminal record will reconcile to."""+ log = logger.bind(+ team_id=progress.team_id,+ source_id=progress.source_id,+ binding_kind=progress.binding_kind,+ binding_id=progress.binding_id,+ trigger=progress.trigger,+ )+ try:+ with transaction.atomic():+ source = CustomPropertySource.objects.for_team(progress.team_id).filter(id=progress.source_id).first()+ if source is None:+ log.info("person-property progress recorder: source no longer exists, skipping")+ return+ run = _find_reconcilable_run(progress.team_id, source, progress.job_id, progress.trigger)+ if run is None:+ CustomPropertySyncRun.objects.for_team(progress.team_id).create(+ team_id=progress.team_id,+ source=source,+ **_binding_fields(progress),+ job_id=progress.job_id,+ trigger=progress.trigger,+ status=SyncStatus.RUNNING.value,+ rows_read=progress.rows_read,+ changed=progress.changed,+ existing=progress.existing,+ produced=progress.produced,+ skipped_missing_person=progress.skipped_missing_person,+ )+ return+ CustomPropertySyncRun.objects.for_team(progress.team_id).filter(id=run.id).update(+ rows_read=Greatest(F("rows_read"), progress.rows_read),+ changed=Greatest(F("changed"), progress.changed, F("existing") + progress.existing),+ existing=F("existing") + progress.existing,+ produced=F("produced") + progress.produced,+ skipped_missing_person=Greatest(F("skipped_missing_person"), progress.skipped_missing_person),+ )+ except Exception as error:+ log.exception("person-property progress recorder failed")+ capture_exception(error)diff --git a/products/customer_analytics/backend/logic/person_property_runs_test.py b/products/customer_analytics/backend/logic/person_property_runs_test.pyindex 04da8d173697..9e0739583448 100644--- a/products/customer_analytics/backend/logic/person_property_runs_test.py+++ b/products/customer_analytics/backend/logic/person_property_runs_test.py@@ -7,11 +7,11 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom products.customer_analytics.backend.logic.custom_property_source_health import MAX_CONSECUTIVE_SYNC_FAILURES-from products.customer_analytics.backend.logic.person_property_runs import record_sync_run+from products.customer_analytics.backend.logic.person_property_runs import record_sync_progress, record_sync_runfrom products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun, TargetTypefrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixinfrom products.customer_analytics.backend.test.factories import create_custom_property_definition-from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncRunRecord+from products.warehouse_sources.backend.facade.hooks import PersonPropertySyncProgress, PersonPropertySyncRunRecordfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -181,6 +181,90 @@ class TestRecordSyncRun(TeamScopedTestMixin, APIBaseTest):self.source.refresh_from_db()assert self.source.consecutive_failures == 1+ def _progress(self, **overrides) -> PersonPropertySyncProgress:+ kwargs: dict = {+ "team_id": self.team.id,+ "binding_kind": "schema",+ "binding_id": self.schema_id,+ "source_id": str(self.source.id),+ "job_id": "job-1",+ "trigger": "scheduled",+ "rows_read": 10,+ "changed": 8,+ "existing": 0,+ "produced": 0,+ "skipped_missing_person": 0,+ }+ kwargs.update(overrides)+ return PersonPropertySyncProgress(**kwargs)++ @parameterized.expand([("job_id", "job-1", "scheduled"), ("no_job_id", None, "backfill")])+ def test_chunk_progress_accumulates_across_attempts_and_survives_terminal_records(self, _name, job_id, trigger):+ # A killed attempt records zero counts, and a retry only sees the rows still left to send. The+ # row must still show everything delivered across the whole run.+ zeros = {"rows_read": 0, "changed": 0, "existing": 0, "produced": 0, "skipped_missing_person": 0}+ record_sync_run(self._record(job_id=job_id, trigger=trigger, status="running", finished_at="", **zeros))+ # skipped_missing_person is the attempt's running total: a missing person is never snapshotted, so+ # every retry skips it again and adding the reports up would count it once per attempt.+ record_sync_progress(+ self._progress(job_id=job_id, trigger=trigger, existing=2, produced=2, skipped_missing_person=1)+ )+ record_sync_progress(+ self._progress(job_id=job_id, trigger=trigger, existing=2, produced=2, skipped_missing_person=2)+ )+ if job_id is not None:+ record_sync_run(self._record(job_id=job_id, trigger=trigger, status="failed", error="killed", **zeros))+ failed = CustomPropertySyncRun.objects.unscoped().get(source=self.source)+ # The killed run still shows how far it got: 4 of the 8 changed rows.+ assert (+ failed.status,+ failed.produced,+ failed.existing,+ failed.skipped_missing_person,+ failed.rows_read,+ failed.changed,+ ) == ("failed", 4, 4, 2, 10, 8)+ record_sync_run(self._record(job_id=job_id, trigger=trigger, status="running", finished_at="", **zeros))+ # The retry diffs against the snapshot, so it sees only the 4 rows still left.+ record_sync_progress(+ self._progress(job_id=job_id, trigger=trigger, changed=4, existing=3, produced=3, skipped_missing_person=3)+ )+ record_sync_run(self._record(job_id=job_id, trigger=trigger, status="completed"))++ run = CustomPropertySyncRun.objects.unscoped().get(source=self.source)+ assert run.status == "completed"+ assert (run.rows_read, run.changed) == (10, 8)+ assert (run.existing, run.produced, run.skipped_missing_person) == (7, 7, 3)++ def test_overlapping_jobs_keep_their_progress_in_separate_rows(self):+ opener = {"status": "running", "finished_at": "", "rows_read": 0, "changed": 0, "existing": 0, "produced": 0}+ record_sync_run(self._record(job_id="job-a", **opener))+ record_sync_progress(self._progress(job_id="job-a", changed=4, existing=4, produced=4))+ record_sync_run(self._record(job_id="job-b", **opener))+ record_sync_progress(self._progress(job_id="job-b", changed=6, existing=6, produced=6))++ runs = CustomPropertySyncRun.objects.unscoped().filter(source=self.source)+ assert {(run.job_id, run.changed, run.existing, run.produced) for run in runs} == {+ ("job-a", 4, 4, 4),+ ("job-b", 6, 6, 6),+ }++ def test_changed_never_reads_lower_than_what_was_delivered(self):+ # A backfill retry re-reads the table and can find rows the interrupted attempt never saw, so its+ # own changed count can undercount the deliveries added across attempts.+ opener = {"status": "running", "finished_at": "", "rows_read": 0, "changed": 0, "existing": 0, "produced": 0}+ record_sync_run(self._record(job_id=None, trigger="backfill", **opener))+ record_sync_progress(self._progress(job_id=None, trigger="backfill", changed=2, existing=1, produced=1))+ record_sync_progress(self._progress(job_id=None, trigger="backfill", changed=2, existing=2, produced=2))+ run = CustomPropertySyncRun.objects.unscoped().get(source=self.source)+ assert (run.changed, run.existing) == (3, 3)++ record_sync_run(+ self._record(job_id=None, trigger="backfill", status="completed", changed=2, existing=2, produced=2)+ )+ run.refresh_from_db()+ assert (run.changed, run.existing) == (3, 3)+def test_scheduled_retry_that_finally_succeeds_clears_the_failure(self):# A transient failure followed by a successful retry (same job_id) must resolve the row to# completed and reset the source's failure streak / last-synced time.diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsxindex 8ed14876b494..0ed8336fde6b 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx@@ -189,7 +189,9 @@ export function CustomPropertySyncRuns({},{title: 'Updated',- tooltip: `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed.`,+ tooltip: accountRuns+ ? `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed.`+ : `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed. A run that stopped part way shows how far it got.`,align: 'right',render: (_, run) => {const share = updatedShare(run.existing, run.changed)diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex 1c3501aaa573..208626074d85 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -110,6 +110,23 @@ class RevenueViewSyncInput:schema_name: str+@dataclass(frozen=True)+class PersonPropertySyncProgress:+ """One produced chunk's counts for one person-property source."""++ team_id: int+ binding_kind: str+ binding_id: str+ source_id: str+ job_id: str | None+ trigger: str+ rows_read: int+ changed: int+ existing: int+ produced: int+ skipped_missing_person: int++@dataclass(frozen=True)class RevenueSourceTable:id: UUIDdiff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.pyindex 500a1c184f41..26c31743f69f 100644--- a/products/warehouse_sources/backend/facade/hooks.py+++ b/products/warehouse_sources/backend/facade/hooks.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hregister_emit_signals_gate,register_engineering_analytics_view_sync,register_person_property_projection,+ register_person_property_sync_progress_recorder,register_person_property_sync_recorder,register_person_property_sync_sources,register_revenue_view_sync,@@ -35,7 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hschema_binding,)-from .contracts import RevenueViewSyncInput+from .contracts import PersonPropertySyncProgress, RevenueViewSyncInput__all__ = ["BINDING_KIND_SAVED_QUERY",@@ -45,6 +46,7 @@ __all__ = ["EmitSignalsActivityInputs","PersonPropertySourceProjection","PersonPropertySyncActivityInputs",+ "PersonPropertySyncProgress","PersonPropertySyncRunRecord","PersonPropertySyncSource","RevenueViewSyncInput",@@ -56,6 +58,7 @@ __all__ = ["register_emit_signals_gate","register_engineering_analytics_view_sync","register_person_property_projection",+ "register_person_property_sync_progress_recorder","register_person_property_sync_recorder","register_person_property_sync_sources","register_revenue_view_sync",diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.pyindex cec1015cb93d..50a75c8fb94c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py@@ -14,7 +14,7 @@ import dataclassesfrom collections.abc import Callable, Collectionfrom typing import TYPE_CHECKING, Any, Optional-from products.warehouse_sources.backend.facade.contracts import RevenueViewSyncInput+from products.warehouse_sources.backend.facade.contracts import PersonPropertySyncProgress, RevenueViewSyncInputif TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -449,3 +449,18 @@ def record_person_property_sync_run(record: PersonPropertySyncRunRecord) -> Noneif _person_property_sync_recorder is None:return_person_property_sync_recorder(record)+++PersonPropertySyncProgressRecorder = Callable[[PersonPropertySyncProgress], None]+_person_property_sync_progress_recorder: Optional[PersonPropertySyncProgressRecorder] = None+++def register_person_property_sync_progress_recorder(fn: PersonPropertySyncProgressRecorder) -> None:+ global _person_property_sync_progress_recorder+ _person_property_sync_progress_recorder = fn+++def record_person_property_sync_progress(progress: PersonPropertySyncProgress) -> None:+ if _person_property_sync_progress_recorder is None:+ return+ _person_property_sync_progress_recorder(progress)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.pyindex 92f82e730142..141b9297054f 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@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync import (failed_run_error,is_worker_interruption,+ progress_recorder,record_completed_runs,record_failed_runs,record_started_runs,@@ -87,7 +88,14 @@ async def backfill_warehouse_person_properties_activity(inputs: PersonPropertyBa)try:async with Heartbeater():- result = await run_person_property_backfill(team_id=inputs.team_id, binding=binding, trigger=inputs.trigger)+ result = await run_person_property_backfill(+ team_id=inputs.team_id,+ binding=binding,+ trigger=inputs.trigger,+ on_progress=progress_recorder(+ team_id=inputs.team_id, binding=binding, job_id=None, trigger=inputs.trigger+ ),+ )except Exception as e:log.exception("Person-property backfill failed")capture_exception(e)diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.pyindex 8bd7158a9047..f212e4c52d88 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job.py@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync import (failed_run_error,is_worker_interruption,+ progress_recorder,record_completed_runs,record_failed_runs,record_started_runs,@@ -78,7 +79,8 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAclog = logger.bind(**inputs.properties_to_log)log.info(f"Starting person-property sync for {inputs.source_type}/{inputs.schema_name}")start = time.monotonic()- started_at = datetime.now(UTC).isoformat()+ # A retry keeps the time the run was first scheduled, so the run row shows its whole duration.+ started_at = activity.info().scheduled_time.isoformat()binding = inputs.bindingawait record_started_runs(team_id=inputs.team_id,@@ -89,7 +91,14 @@ async def sync_warehouse_person_properties_activity(inputs: PersonPropertySyncAc)try:async with Heartbeater():- result = await run_person_property_sync(team_id=inputs.team_id, binding=binding, job_id=inputs.job_id)+ result = await run_person_property_sync(+ team_id=inputs.team_id,+ binding=binding,+ job_id=inputs.job_id,+ on_progress=progress_recorder(+ team_id=inputs.team_id, binding=binding, job_id=inputs.job_id, trigger="scheduled"+ ),+ )except Exception as e:# Re-raised so Temporal retries; captured so a terminal failure is visible in error# tracking rather than dying silently in an abandoned child workflow. The failed outcome isdiff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job_test.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job_test.pyindex f89d74052779..c571e711c360 100644--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_sync_job_test.py@@ -1,6 +1,6 @@import uuidimport dataclasses-from datetime import timedelta+from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.person_property_sySyncWarehousePersonPropertiesWorkflow,sync_warehouse_person_properties_activity,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_sync import SyncResultMODULE = "products.warehouse_sources.backend.temporal.data_imports.person_property_sync_job"@@ -346,3 +347,40 @@ async def test_sync_activity_deadline_leaves_time_to_record_the_failure_before_t# The recorder needs up to 3 attempts of 5 minutes after the sync activity gives up.deadline = scheduled[0].schedule_to_close_timeout.ToTimedelta()assert timedelta(0) < deadline <= timedelta(hours=6) - timedelta(minutes=15)+++@patch(f"{MODULE}.record_completed_runs", new_callable=AsyncMock)+@patch(f"{MODULE}.record_started_runs", new_callable=AsyncMock)+@patch(f"{MODULE}.run_person_property_sync", new_callable=AsyncMock)+@patch(f"{MODULE}.Heartbeater")+async def test_a_retried_run_keeps_the_time_it_was_first_scheduled(+ mock_heartbeater_cls: MagicMock,+ mock_run_sync: AsyncMock,+ mock_record_started: AsyncMock,+ mock_record_completed: AsyncMock,+) -> None:+ mock_heartbeater_cls.return_value.__aenter__ = AsyncMock(return_value=None)+ mock_heartbeater_cls.return_value.__aexit__ = AsyncMock(return_value=None)+ mock_run_sync.return_value = SyncResult()+ first_scheduled = datetime(2026, 1, 1, 10, 0, tzinfo=UTC)+ environment = ActivityEnvironment()+ environment.info = dataclasses.replace(+ environment.info,+ attempt=2,+ scheduled_time=first_scheduled,+ current_attempt_scheduled_time=first_scheduled + timedelta(minutes=40),+ )+ inputs = PersonPropertySyncActivityInputs(+ team_id=1,+ schema_id=uuid.uuid4(),+ source_id=uuid.uuid4(),+ job_id="job-retried",+ source_type="Stripe",+ schema_name="public.charges",+ last_synced_at=None,+ )++ await environment.run(sync_warehouse_person_properties_activity, inputs)++ assert mock_record_started.await_args_list[0].kwargs["started_at"] == first_scheduled.isoformat()+ assert mock_record_completed.await_args_list[0].kwargs["started_at"] == first_scheduled.isoformat()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.pyindex a35fff71044e..b4e75a7345de 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@@ -28,6 +28,7 @@ import uuidimport asyncioimport hashlibimport dataclasses+from collections.abc import Awaitable, Callablefrom datetime import date, datetime, timefrom decimal import Decimalfrom typing import TYPE_CHECKING, Any@@ -54,10 +55,12 @@ from products.data_warehouse.backend.facade.api import aget_s3_client, get_s3_clfrom products.warehouse_sources.backend.facade.person_property_provenance import stamp_person_property_provenancefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ PersonPropertySyncProgress,PersonPropertySyncRunRecord,PersonPropertySyncSource,WarehouseBinding,person_property_sync_sources_for,+ record_person_property_sync_progress,record_person_property_sync_run,)from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention@@ -127,6 +130,19 @@ class PerSourceResult:error: str | None = None+@frozen+class PerSourceProgress:+ source_id: str+ produced_increment: int+ rows_read_total: int+ changed_total: int+ # Missing people have no snapshot, so retries need a total to avoid counting them twice.+ skipped_missing_person_total: int+++ProgressCallback = Callable[[PerSourceProgress], Awaitable[None]]++class PropertyUpdatesNotDeliveredError(Exception):"""Kafka did not confirm some property-update intents. Raised so the run fails and Temporal retriesit. The snapshot holds only confirmed intents, so the retry sends only the undelivered ones."""@@ -577,6 +593,7 @@ async def _process_source_bundles(bundles: list[tuple[str, dict]],rows_read: int,run_token: str,+ on_progress: ProgressCallback | None = None,) -> PerSourceResult:"""Diff one source's bundles against its snapshot, drop entities that don't exist, produce updateintents (person `$set` or group `$groupidentify`), stamp provenance, and advance the snapshot. Works@@ -626,20 +643,20 @@ async def _process_source_bundles(team_id, source, [key for key, _ in chunk])to_send = [(key, bundle) for key, bundle in chunk if key in existing]- ps.existing += len(to_send)+ existing_count = len(to_send)+ delivered: set[str] = set()+ if to_send:+ delivered = await asyncio.to_thread(+ _produce_intents,+ team_id,+ team_api_token,+ source,+ to_send,+ team_uuid=team_uuid,+ group_type_name=group_type_name,+ )+ ps.existing += existing_countps.skipped_missing_person += len(chunk) - len(to_send)- if not to_send:- continue-- delivered = await asyncio.to_thread(- _produce_intents,- team_id,- team_api_token,- source,- to_send,- team_uuid=team_uuid,- group_type_name=group_type_name,- )ps.produced += len(delivered)ps.undelivered += len(to_send) - len(delivered)@@ -654,6 +671,18 @@ async def _process_source_bundles(confirmed_hashes.update(delivered_hashes)chunks_written += 1+ if on_progress is not None:+ # Snapshot first so a retry cannot report these deliveries twice.+ await on_progress(+ PerSourceProgress(+ source_id=ps.source_id,+ produced_increment=len(delivered),+ rows_read_total=ps.rows_read,+ changed_total=ps.changed,+ skipped_missing_person_total=ps.skipped_missing_person,+ )+ )+if chunks_written:# Fold this run's chunk files, and any left by an earlier run that was stopped part way, into# one ``{run_token}.parquet`` so the folder stays at about one file per source.@@ -693,6 +722,7 @@ async def _process_accumulated_source(bundles_by_source: dict[str, dict[str, dict]],rows_read: int,run_token: str,+ on_progress: ProgressCallback | None = None,) -> PerSourceResult:bundles = list(bundles_by_source.pop(str(source.source_id)).items())return await _process_source_bundles(@@ -705,6 +735,7 @@ async def _process_accumulated_source(bundles=bundles,rows_read=rows_read,run_token=run_token,+ on_progress=on_progress,)@@ -725,7 +756,9 @@ def _raise_if_undelivered(result: SyncResult) -> None:)-async def run_person_property_sync(*, team_id: int, binding: WarehouseBinding, job_id: str) -> SyncResult:+async def run_person_property_sync(+ *, team_id: int, binding: WarehouseBinding, job_id: str, on_progress: ProgressCallback | None = None+) -> SyncResult:result = SyncResult()sources = await database_sync_to_async(person_property_sync_sources_for, thread_sensitive=False)(team_id, binding)if not sources:@@ -762,6 +795,7 @@ async def run_person_property_sync(*, team_id: int, binding: WarehouseBinding, jbundles_by_source=read.bundles_by_source,rows_read=read.rows_read,run_token=job_id,+ on_progress=on_progress,)_accumulate(result, ps)@@ -858,7 +892,9 @@ def _delta_uri_for_binding(team_id: int, binding: WarehouseBinding) -> str | Nonreturn _schema_delta_uri(team_id, binding.id)-async def run_person_property_backfill(*, team_id: int, binding: WarehouseBinding, trigger: str) -> SyncResult:+async def run_person_property_backfill(+ *, team_id: int, binding: WarehouseBinding, trigger: str, on_progress: ProgressCallback | None = None+) -> SyncResult:"""Populate person properties from a warehouse table's full Delta data (rather than theincrementally staged rows) — for a new/changed mapping that never saw historical rows. Reads thetable once and upserts every enabled person source on the binding; the snapshot diff still skips@@ -925,6 +961,7 @@ async def run_person_property_backfill(*, team_id: int, binding: WarehouseBindinbundles_by_source=read.bundles_by_source,rows_read=read.rows_read,run_token=BACKFILL_RUN_TOKEN,+ on_progress=on_progress,)_accumulate(result, ps)@@ -970,6 +1007,41 @@ def _record()+def progress_recorder(*, team_id: int, binding: WarehouseBinding, job_id: str | None, trigger: str) -> ProgressCallback:+ """A callback that adds each chunk's counts to the run row, so a run that stops part way, and a+ run retried over several attempts, shows everything it delivered. Never raises, because+ bookkeeping must not fail the sync it describes."""++ async def _record_progress(increment: PerSourceProgress) -> None:+ try:+ await database_sync_to_async(record_person_property_sync_progress, thread_sensitive=False)(+ PersonPropertySyncProgress(+ team_id=team_id,+ binding_kind=binding.kind,+ binding_id=binding.id,+ source_id=increment.source_id,+ job_id=job_id,+ trigger=trigger,+ rows_read=increment.rows_read_total,+ changed=increment.changed_total,+ existing=increment.produced_increment,+ produced=increment.produced_increment,+ skipped_missing_person=increment.skipped_missing_person_total,+ )+ )+ except Exception as e:+ logger.exception(+ "person-property run: failed to record progress",+ team_id=team_id,+ **_log_fields(binding),+ job_id=job_id,+ trigger=trigger,+ )+ capture_exception(e, {"team_id": team_id, **_log_fields(binding), "trigger": trigger})++ return _record_progress++async def record_started_runs(*, team_id: int, binding: WarehouseBinding, job_id: str | None, trigger: str, started_at: str) -> None: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.pyindex 18e3271c3e82..bea18a872bce 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@@ -210,36 +210,78 @@ class TestRunOrchestration:clear.assert_awaited_once()assert order == ["reconcile", "produce", "snapshot", "compact"]+ @parameterized.expand([("unconfirmed_delivery", False), ("snapshot_write_failure", True)])@pytest.mark.asyncio- async def test_undelivered_intents_stay_out_of_the_snapshot_and_fail_the_run(self):+ async def test_undelivered_intents_stay_out_of_the_snapshot_and_fail_the_run(self, _name, snapshot_write_fails):team = MagicMock(api_token="tok", project_id=7)fake = _FakeS3()_stage(fake, "chunk_1_000000", [{"distinct_id": "a", "plan": "pro"}, {"distinct_id": "b", "plan": "free"}])+ progress: list[pps.PerSourceProgress] = []++ async def _on_progress(increment: pps.PerSourceProgress) -> None:+ progress.append(increment)+with (_fake_s3_patch(fake),patch(f"{_MODULE}.person_property_sync_sources_for", return_value=[self._source()]),patch(f"{_MODULE}.Team") as team_cls,patch(f"{_MODULE}._filter_existing_ids", return_value={"a", "b"}),- patch(f"{_MODULE}._produce_intents", return_value={"a"}),+ patch(+ f"{_MODULE}._produce_intents",+ side_effect=({"a", "b"}, {"a", "b"}) if snapshot_write_fails else ({"a"}, {"b"}),+ ),patch(f"{_MODULE}._reconcile_property_definitions"),patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,):team_cls.objects.get.return_value = team- with pytest.raises(pps.PropertyUpdatesNotDeliveredError, match="1 of 2"):- await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")+ if snapshot_write_fails:+ with (+ patch.object(fake, "_pipe_file", side_effect=RuntimeError("snapshot write failed")),+ pytest.raises(RuntimeError, match="snapshot write failed"),+ ):+ await pps.run_person_property_sync(+ team_id=1, binding=_SCHEMA, job_id="job-1", on_progress=_on_progress+ )+ assert progress == []+ else:+ with pytest.raises(pps.PropertyUpdatesNotDeliveredError, match="1 of 2"):+ await pps.run_person_property_sync(+ team_id=1, binding=_SCHEMA, job_id="job-1", on_progress=_on_progress+ )+ result = await pps.run_person_property_sync(+ team_id=1, binding=_SCHEMA, job_id="job-1", on_progress=_on_progress+ )hashes = await pps._read_snapshot_hashes(1, _SCHEMA, "source-1")- assert set(hashes) == {"a"}- clear.assert_not_awaited()+ assert set(hashes) == {"a", "b"}+ assert sum(increment.produced_increment for increment in progress) == 2+ assert result.produced == (2 if snapshot_write_fails else 1)+ clear.assert_awaited_once()@pytest.mark.asyncioasync def test_a_killed_run_keeps_confirmed_chunks_but_a_later_job_cannot_resume_undelivered_rows(self):team = MagicMock(api_token="tok", project_id=7)fake = _FakeS3()_stage(fake, "chunk_1_000000", [{"distinct_id": f"p{n}", "plan": "pro"} for n in range(6)], job_id="job-1")- _stage(fake, "chunk_1_000000", [{"distinct_id": "p6", "plan": "pro"}], job_id="job-2")+ _stage(+ fake,+ "chunk_1_000000",+ [+ {"distinct_id": "p6", "plan": "pro"},+ {"distinct_id": "ghost-1", "plan": "pro"},+ {"distinct_id": "ghost-2", "plan": "pro"},+ ],+ job_id="job-2",+ )sent_per_run: dict[str, list[str]] = {"job-1": [], "job-2": []}+ progress_per_run: dict[str, list[pps.PerSourceProgress]] = {"job-1": [], "job-2": []}current_job = "job-1"++ async def _on_progress(increment: pps.PerSourceProgress) -> None:+ hashes = await pps._read_snapshot_hashes(1, _SCHEMA, increment.source_id)+ assert set(sent_per_run[current_job]) <= set(hashes)+ progress_per_run[current_job].append(increment)+kill_after = 2def _produce(_team_id, _token, _source, items, **_kwargs):@@ -255,16 +297,21 @@ class TestRunOrchestration:patch(f"{_MODULE}._PRODUCE_CHUNK_SIZE", 2),patch(f"{_MODULE}.person_property_sync_sources_for", return_value=[self._source()]),patch(f"{_MODULE}.Team") as team_cls,- patch(f"{_MODULE}._filter_existing_ids", side_effect=lambda _team_id, _source, ids: set(ids)),+ patch(+ f"{_MODULE}._filter_existing_ids",+ side_effect=lambda _team_id, _source, ids: {key for key in ids if not key.startswith("ghost-")},+ ),patch(f"{_MODULE}._produce_intents", side_effect=_produce),patch(f"{_MODULE}._reconcile_property_definitions"),):team_cls.objects.get.return_value = teamwith pytest.raises(RuntimeError, match="worker stopped"):- await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")+ await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1", on_progress=_on_progress)current_job = "job-2"- result = await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-2")+ result = await pps.run_person_property_sync(+ team_id=1, binding=_SCHEMA, job_id="job-2", on_progress=_on_progress+ )prefix = pps._snapshot_prefix(1, _SCHEMA, "source-1")snapshot_files = await pps._list_snapshot_files(fake, prefix)@@ -273,6 +320,27 @@ class TestRunOrchestration:assert sent_per_run["job-1"] == ["p0", "p1"]assert sent_per_run["job-2"] == ["p6"]assert result.produced == 1+ # The killed run reports what it delivered before it died, so its run row is not left at zero.+ assert progress_per_run["job-1"] == [+ pps.PerSourceProgress(+ source_id="source-1",+ produced_increment=2,+ rows_read_total=6,+ changed_total=6,+ skipped_missing_person_total=0,+ )+ ]+ assert sum(p.produced_increment for p in progress_per_run["job-2"]) == result.produced+ assert progress_per_run["job-2"] == [+ pps.PerSourceProgress(+ source_id="source-1",+ produced_increment=produced,+ rows_read_total=3,+ changed_total=3,+ skipped_missing_person_total=skipped,+ )+ for produced, skipped in [(1, 1), (0, 2)]+ ]# The completed run folds the killed run's leftover file and its own chunk files into one.assert [pps._s3_key(key) for key in snapshot_files] == [f"{prefix}/job-2.parquet"]assert set(hashes) == {"p0", "p1", "p6"}@@ -697,29 +765,6 @@ class TestSnapshotCompaction:assert merge.hashes == {}assert not merge.complete- @pytest.mark.asyncio- async def test_read_relists_after_concurrent_compaction_instead_of_resending_everything(self):- fake = _FakeS3()- prefix = pps._snapshot_prefix(1, _SCHEMA, "src")- with _fake_s3_patch(fake):- await pps._write_snapshot_chunk(1, _SCHEMA, "src", "job-1", {"a": "h1"})- await pps._write_snapshot_chunk(1, _SCHEMA, "src", "job-2", {"b": "h2"})- original_cat_file = fake._cat_file- compacted = False-- async def _cat_with_one_concurrent_compaction(path):- nonlocal compacted- if not compacted:- compacted = True- await pps._put_snapshot_file(fake, f"{prefix}/concurrent.parquet", {"a": "h1", "b": "h2"})- await fake._rm([f"{prefix}/job-1.parquet", f"{prefix}/job-2.parquet"])- return await original_cat_file(path)-- with patch.object(fake, "_cat_file", _cat_with_one_concurrent_compaction):- hashes = await pps._read_snapshot_hashes(1, _SCHEMA, "src")-- assert hashes == {"a": "h1", "b": "h2"}-@pytest.mark.asyncioasync def test_current_deliveries_win_when_snapshot_timestamps_tie(self):fake = _FakeS3()@@ -759,6 +804,29 @@ class TestSnapshotCompaction:assert hashes == {"a": "new"}assert list(fake.store) == [f"{prefix}/concurrent.parquet"]+ @pytest.mark.asyncio+ async def test_read_relists_after_concurrent_compaction_instead_of_resending_everything(self):+ fake = _FakeS3()+ prefix = pps._snapshot_prefix(1, _SCHEMA, "src")+ with _fake_s3_patch(fake):+ await pps._write_snapshot_chunk(1, _SCHEMA, "src", "job-1", {"a": "h1"})+ await pps._write_snapshot_chunk(1, _SCHEMA, "src", "job-2", {"b": "h2"})+ original_cat_file = fake._cat_file+ compacted = False++ async def _cat_with_one_concurrent_compaction(path):+ nonlocal compacted+ if not compacted:+ compacted = True+ await pps._put_snapshot_file(fake, f"{prefix}/concurrent.parquet", {"a": "h1", "b": "h2"})+ await fake._rm([f"{prefix}/job-1.parquet", f"{prefix}/job-2.parquet"])+ return await original_cat_file(path)++ with patch.object(fake, "_cat_file", _cat_with_one_concurrent_compaction):+ hashes = await pps._read_snapshot_hashes(1, _SCHEMA, "src")++ assert hashes == {"a": "h1", "b": "h2"}+class TestGroupTarget:"""The group branch: a group source produces a $groupidentify-shaped intent and checks group