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(customer-analytics): show account property sync history (#88871)

Arthur Moreira de Deusdb8e199bff0d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c2c6a610bc05..6e6fa680f49f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2052,6 +2052,14 @@ snapshots:
hash: v1.k794b7964.536f41c62e83935877a0b961d6b2a1aa0e4199dfab49f84587178447e844a8ba.tpDdDBmJuJBZKOX_RFz8CcNUGsUdse6LfVJWG1XNDeQ
components-verticalnesteddnd--base--light:
hash: v1.k794b7964.d5489b1b81f5796e1828217bfd382f980062e90cae10ebe23fb4e8aa5aea07e6.12qSy0lIe-5pOxJ9lBpDJoSa1oh-a24bC0-yeEIbfrg
+ customer-analytics-custom-property-sync-runs--account-lifecycle--dark:
+ hash: v1.k794b7964.4c68902b4f73221926fdd50c1aec035ad5342b685c967b040bf217264747ea5a.NpTBSnGrlQly4iiuvI6iXwVcpKA3PLSxc9pbDo4Vrqs
+ customer-analytics-custom-property-sync-runs--account-lifecycle--light:
+ hash: v1.k794b7964.e6afccf6ad88bdac711a3a0365b99d9950bda78530069a29bb07611a8c24dac8.JMizxMj_SjD6uMxlC-wOEoUmiDcrTTtIKqXE8HbLYic
+ customer-analytics-custom-property-sync-runs--loading--dark:
+ hash: v1.k794b7964.a1866d682eb35809e8a9bea08ec0c7af8cb77581e4667745851bd9db5f49918d.mhIpdnK7yIoTFvovSR-wJrEHGV_7_T3eTvSNRv0UbtY
+ customer-analytics-custom-property-sync-runs--loading--light:
+ hash: v1.k794b7964.b376cab90219eb5e85b659c1399b40c0d60caf7a91b006c0d168375ed365d2af.61Y57PmrNuzzIfBps59FSyMmFnBf3yzKDcPD6vs5VHI
data-warehouse-query-history-modal--empty--dark:
hash: v1.k794b7964.4c38283dea0ebc9b3e3e0aa03a05f6e4153bfe3550336ead008a187a43ddab4c.4ArpfVpkJGTdOVoU2PbGNjGH1Kzbq84osask8eFk-BA
data-warehouse-query-history-modal--empty--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a849336d494c..dc0924c984f3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -527,6 +527,7 @@ export const FEATURE_FLAGS = {
UX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveys
VISION_ENTRYPOINT_EXPERIMENTS: 'vision-entrypoint-experiments', // owner: #team-replay, cross-sell entry points from experiments
VISUAL_REVIEW: 'visual-review', // owner: #team-devex
+ WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC: 'warehouse-account-properties-s3-sync', // owner: @arthurdedeus #team-customer-analytics, gates staged account-property sync and its run history
WAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)
WEB_ANALYTICS_ACHIEVEMENTS: 'web-analytics-achievements', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_BACK_NAVIGATION_RESET: 'web-analytics-back-navigation-reset', // owner: @jordanm-posthog #team-web-analytics
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index e5ee5df53928..5e23803353c4 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -1,6 +1,7 @@
import asyncio
import contextlib
from collections.abc import AsyncIterator, Collection, Iterable
+from dataclasses import replace
from io import BytesIO
from typing import Any, cast
from uuid import uuid4
@@ -1876,6 +1877,7 @@ class TestMaterializeViewStagesAccountPropertyRows:
Prefix=prefix.removeprefix(f"{bucket_name}/"),
)
assert result.delta_version is not None
+ activity_environment.info = replace(activity_environment.info, workflow_run_id=str(uuid4()))
staged = await activity_environment.run(
stage_warehouse_account_property_files_activity,
StageAccountPropertySyncInput(
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.md
index c6217bebf3dc..cbc62fba46a4 100644
--- a/products/customer_analytics/backend/COMPROMISES.md
+++ b/products/customer_analytics/backend/COMPROMISES.md
@@ -12,15 +12,13 @@ Shortcuts taken to ship the first version. Revisit when they bite.
## Custom property view sync
-- **Two bulk paths during rollout.** The legacy Celery task still re-queries the live view, records
- source status, and has no retry. A flagged successful materialization starts an isolated Temporal
- workflow that reads its committed Delta snapshot and writes job-scoped Parquet. Staging failures
- remain visible in Temporal and logs without failing the materialized view. Keep the legacy recorder
- until the staged path can aggregate both segment outcomes without double-counting failures. Source
- create and re-enable still use Celery until the staged path gains manual recovery.
-- **Staged runs have no run-level UI yet.** Temporal shows the staging workflow and both segment
- workflows, while logs carry the job and view identifiers. The job-scoped Parquet stays until both
- segments succeed. A bounded sweep removes abandoned staging prefixes.
+- **Two bulk paths during rollout.** The legacy Celery task still re-queries the live view and has no
+ retry. A flagged successful materialization starts an isolated Temporal workflow that reads its
+ committed Delta snapshot and writes job-scoped Parquet. Staging failures remain visible without
+ failing the materialized view. Source create and re-enable still use Celery until the staged path
+ gains manual recovery.
+- **Run history is per source and segment.** Each source gets tracked and ignored records before
+ staging starts. After both segments finish, their combined outcome updates the source status once.
- **Tracked and ignored segments are independent.** They use separate snapshots, retries, and
completion markers. Churned accounts are excluded from both. Only staged-file cleanup waits for
both markers.
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index d87b0626eefd..d588136a642e 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -53,7 +53,7 @@ from django.db.models import (
Value,
)
from django.db.models.fields.json import KeyTextTransform
-from django.db.models.functions import Coalesce
+from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
import structlog
@@ -1407,9 +1407,28 @@ class CustomPropertySourceValidationError(Exception):
already source-backed (→ 400)."""
-def _to_sync_run_view(run: "CustomPropertySyncRun") -> contracts.CustomPropertySyncRunView:
+def _temporal_run_url(run: "CustomPropertySyncRun") -> str | None:
+ if not run.workflow_id or not run.workflow_run_id:
+ return None
+ base = settings.TEMPORAL_UI_HOST
+ namespace = settings.TEMPORAL_NAMESPACE
+ if not base or not namespace:
+ return None
+ return f"{base.rstrip('/')}/namespaces/{namespace}/workflows/{run.workflow_id}/{run.workflow_run_id}"
+
+
+def _to_sync_run_view(
+ run: "CustomPropertySyncRun", *, include_temporal_url: bool = False
+) -> contracts.CustomPropertySyncRunView:
return contracts.CustomPropertySyncRunView(
id=run.id,
+ job_id=run.job_id,
+ account_segment=run.segment,
+ sync_phase=run.phase,
+ attempt=run.attempt,
+ workflow_id=run.workflow_id if include_temporal_url else None,
+ workflow_run_id=run.workflow_run_id if include_temporal_url else None,
+ temporal_url=_temporal_run_url(run) if include_temporal_url else None,
trigger=run.trigger,
status=run.status,
started_at=run.started_at,
@@ -1778,22 +1797,26 @@ _WAREHOUSE_PROFILE_TARGETS = (TargetType.PERSON.value, TargetType.GROUP.value)
_ONE_PROFILE_BINDING_ERROR = "A person/group property source needs exactly one of external_data_schema and saved_query."
-# A run row only reaches a terminal state when its activity records one, so a sync that died before
-# getting there — an import that failed ahead of the person-property step, a killed worker — would sit
-# "running" forever, misreporting the source and keeping its sync/backfill buttons disabled. Six hours
-# matches the sync activity's start_to_close timeout, so nothing live is behind an older row.
+# A run row only reaches a terminal state when its activity records one. Account segment workflows can
+# retry for a full day, while profile sync activities time out after six hours.
STALE_RUNNING_RUN_AFTER = timedelta(hours=6)
-STALE_RUNNING_RUN_ERROR = "This run never reported a result. The sync may have failed before it ran."
+STALE_ACCOUNT_RUNNING_RUN_AFTER = timedelta(hours=25)
+STALE_RUNNING_RUN_ERROR = (
+ "This run stopped reporting progress. Run the warehouse source again. If it keeps failing, contact support."
+)
def _expire_stale_running_runs(team_id: int, runs: "Iterable[CustomPropertySyncRun | None]") -> None:
"""Fail abandoned 'running' rows, both in the database and in the passed-in objects so the caller
serializes what it just wrote. Runs on the read paths the UI polls, so a stuck row self-heals."""
- cutoff = timezone.now() - STALE_RUNNING_RUN_AFTER
+ now = timezone.now()
stale = [
run
for run in runs
- if run is not None and run.status == SyncStatus.RUNNING.value and (run.started_at or run.created_at) < cutoff
+ if run is not None
+ and run.status == SyncStatus.RUNNING.value
+ and (run.started_at or run.created_at)
+ < now - (STALE_ACCOUNT_RUNNING_RUN_AFTER if run.segment is not None else STALE_RUNNING_RUN_AFTER)
]
if not stale:
return
@@ -2226,20 +2249,42 @@ def delete_custom_property_source(
def list_custom_property_sync_runs(
- team_id: int, source_id: str, offset: int, limit: int, user_access_control: "UserAccessControl | None" = None
+ team_id: int,
+ source_id: str,
+ offset: int,
+ limit: int,
+ user_access_control: "UserAccessControl | None" = None,
+ include_temporal_urls: bool = False,
+ search: str | None = None,
) -> tuple[list[contracts.CustomPropertySyncRunView], int]:
- """Person-property sync/backfill runs for a source, newest first. Returns ``(page, total_count)``.
- Scoped by team and source, so a run of another team's/source's is never returned. The runs expose
- the warehouse object's row counts and raw sync errors, so reading them requires the caller's viewer
- access on it (→ 403 via ``ResourceForbiddenError``)."""
+ """Warehouse-backed custom property sync runs for a source, newest first. Returns ``(page, total_count)``.
+ Scoped by team and source, so another team's or source's runs are never returned. Profile-source
+ histories require viewer access to their warehouse object; account-source histories are visible to
+ the same callers who can view the source."""
source = CustomPropertySource.objects.for_team(team_id).select_related("definition").filter(id=source_id).first()
if source is not None:
_assert_warehouse_viewer(team_id, _profile_binding(source), user_access_control)
- queryset = CustomPropertySyncRun.objects.for_team(team_id).filter(source_id=source_id).order_by("-created_at")
+ queryset: QuerySet[CustomPropertySyncRun] = CustomPropertySyncRun.objects.for_team(team_id).filter(
+ source_id=source_id
+ )
+ if search:
+ queryset = cast(
+ "QuerySet[CustomPropertySyncRun]",
+ queryset.annotate(workflow_run_id_text=Cast("workflow_run_id", output_field=CharField())).filter(
+ Q(job_id__icontains=search)
+ | Q(workflow_id__icontains=search)
+ | Q(workflow_run_id_text__icontains=search)
+ | Q(status__icontains=search)
+ | Q(segment__icontains=search)
+ | Q(trigger__icontains=search)
+ | Q(error__icontains=search)
+ ),
+ )
+ queryset = queryset.order_by("-created_at")
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
_expire_stale_running_runs(team_id, page)
- return [_to_sync_run_view(run) for run in page], total_count
+ return [_to_sync_run_view(run, include_temporal_url=include_temporal_urls) for run in page], total_count
FeatureRequestValidationError = _feature_requests_logic.FeatureRequestValidationError
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 4b3da6398ff7..93bc0cc02cf0 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -939,11 +939,16 @@ class CustomPropertySourceView:
@stdlib_dataclass(frozen=True)
class CustomPropertySyncRunView:
- """One person-property sync/backfill run, as returned by the source ``runs`` endpoint and nested
- on a source as ``latest_run``. The counts are the sync funnel (read -> changed -> existing (=
- persons affected) -> produced; skipped_missing_person is changed rows with no matching person)."""
+ """One warehouse-backed custom property sync run."""
id: UUID | None = None
+ job_id: str | None = None
+ account_segment: str | None = None
+ sync_phase: str | None = None
+ attempt: int | None = None
+ workflow_id: str | None = None
+ workflow_run_id: UUID | None = None
+ temporal_url: str | None = None
trigger: str = ""
status: str = ""
started_at: datetime | None = None
diff --git a/products/customer_analytics/backend/facade/temporal_contracts.py b/products/customer_analytics/backend/facade/temporal_contracts.py
index a8f28bae17cf..0cf71caaedca 100644
--- a/products/customer_analytics/backend/facade/temporal_contracts.py
+++ b/products/customer_analytics/backend/facade/temporal_contracts.py
@@ -17,6 +17,16 @@ class DispatchAccountPropertySyncInput:
job_id: str
+@frozen
+class FinalizeAccountPropertySyncRunsInput:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+ status: str
+ phase: str
+ error: str | None = None
+
+
@frozen
class AccountPropertySyncInput:
team_id: int
diff --git a/products/customer_analytics/backend/logic/account_property_runs.py b/products/customer_analytics/backend/logic/account_property_runs.py
new file mode 100644
index 000000000000..ba52bc57a521
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_runs.py
@@ -0,0 +1,283 @@
+from datetime import datetime
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+
+from products.customer_analytics.backend.models import CustomPropertySource, TargetType
+from products.customer_analytics.backend.models.custom_property_sync_run import (
+ CustomPropertySyncRun,
+ SyncPhase,
+ SyncSegment,
+ SyncStatus,
+ SyncTrigger,
+)
+
+
+@frozen
+class AccountPropertySyncRunContext:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+
+
+@frozen
+class AccountPropertySyncRunOutcome:
+ source_id: UUID
+ rows_read: int
+ changed: int
+ matched: int
+ written: int
+ error: str | None = None
+
+
+_ACCOUNT_SEGMENTS = {segment.value for segment in SyncSegment}
+_MAX_CONSECUTIVE_SYNC_FAILURES = 5
+
+
+def start_account_property_sync_runs(
+ context: AccountPropertySyncRunContext,
+ *,
+ workflow_id: str | None,
+ workflow_run_id: str | None,
+) -> None:
+ source_ids = list(
+ CustomPropertySource.objects.for_team(context.team_id)
+ .filter(
+ saved_query_id=context.saved_query_id,
+ is_enabled=True,
+ definition__target_type=TargetType.ACCOUNT.value,
+ source_column__isnull=False,
+ )
+ .values_list("id", flat=True)
+ )
+ if not source_ids:
+ return
+
+ with transaction.atomic():
+ existing_runs = {
+ (run.source_id, run.segment): run
+ for run in CustomPropertySyncRun.objects.for_team(context.team_id)
+ .select_for_update()
+ .filter(source_id__in=source_ids, job_id=context.job_id)
+ .order_by("created_at")
+ }
+ started_at = timezone.now()
+ for source_id in source_ids:
+ for segment in SyncSegment:
+ run = existing_runs.get((source_id, segment.value))
+ if run is None:
+ CustomPropertySyncRun.objects.for_team(context.team_id).create(
+ team_id=context.team_id,
+ source_id=source_id,
+ saved_query_id=context.saved_query_id,
+ job_id=context.job_id,
+ segment=segment.value,
+ phase=SyncPhase.STAGING.value,
+ attempt=0,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ trigger=SyncTrigger.SCHEDULED.value,
+ status=SyncStatus.RUNNING.value,
+ started_at=started_at,
+ )
+ continue
+ if run.status == SyncStatus.COMPLETED.value:
+ continue
+ run.status = SyncStatus.RUNNING.value
+ run.phase = SyncPhase.STAGING.value
+ run.attempt = 0
+ run.workflow_id = workflow_id
+ run.workflow_run_id = workflow_run_id
+ run.finished_at = None
+ run.rows_read = 0
+ run.changed = 0
+ run.existing = 0
+ run.produced = 0
+ run.skipped_missing_person = 0
+ run.error = None
+ run.save(
+ update_fields=[
+ "status",
+ "phase",
+ "attempt",
+ "workflow_id",
+ "workflow_run_id",
+ "finished_at",
+ "rows_read",
+ "changed",
+ "existing",
+ "produced",
+ "skipped_missing_person",
+ "error",
+ ]
+ )
+
+
+def update_account_property_sync_runs_phase(
+ context: AccountPropertySyncRunContext,
+ *,
+ phase: SyncPhase,
+ workflow_id: str | None,
+ workflow_run_id: str | None,
+ attempt: int,
+ segment: SyncSegment | None = None,
+) -> None:
+ runs = CustomPropertySyncRun.objects.for_team(context.team_id).filter(
+ job_id=context.job_id,
+ saved_query_id=context.saved_query_id,
+ status=SyncStatus.RUNNING.value,
+ )
+ if segment is not None:
+ runs = runs.filter(segment=segment.value)
+ if phase == SyncPhase.DISPATCHING:
+ runs = runs.filter(phase__in=[SyncPhase.STAGING.value, SyncPhase.DISPATCHING.value])
+ runs.update(
+ phase=phase.value,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ attempt=attempt,
+ )
+
+
+def _update_source_status_for_terminal_runs(
+ team_id: int,
+ job_id: str,
+ transitioned_source_ids: set[UUID],
+) -> None:
+ if not transitioned_source_ids:
+ return
+
+ runs_by_source_id: dict[UUID, list[CustomPropertySyncRun]] = {}
+ for run in (
+ CustomPropertySyncRun.objects.for_team(team_id)
+ .select_for_update()
+ .filter(source_id__in=transitioned_source_ids, job_id=job_id)
+ ):
+ runs_by_source_id.setdefault(run.source_id, []).append(run)
+
+ sources_by_id = {
+ source.id: source
+ for source in CustomPropertySource.objects.for_team(team_id)
+ .select_for_update()
+ .filter(id__in=transitioned_source_ids)
+ }
+ for source_id, runs in runs_by_source_id.items():
+ if {run.segment for run in runs} != _ACCOUNT_SEGMENTS or any(
+ run.status == SyncStatus.RUNNING.value for run in runs
+ ):
+ continue
+
+ source = sources_by_id.get(source_id)
+ if source is None:
+ continue
+
+ failed_runs = [run for run in runs if run.status == SyncStatus.FAILED.value]
+ if failed_runs:
+ source.consecutive_failures = (source.consecutive_failures or 0) + 1
+ source.last_sync_error = next((run.error for run in failed_runs if run.error), None)
+ if source.consecutive_failures >= _MAX_CONSECUTIVE_SYNC_FAILURES:
+ source.is_enabled = False
+ source.save(
+ update_fields=[
+ "consecutive_failures",
+ "last_sync_error",
+ "is_enabled",
+ "updated_at",
+ ]
+ )
+ continue
+
+ finished_at = max((run.finished_at for run in runs if run.finished_at is not None), default=None)
+ if finished_at is None:
+ continue
+ source.last_synced_at = finished_at
+ source.last_sync_error = None
+ source.consecutive_failures = 0
+ source.save(update_fields=["last_synced_at", "last_sync_error", "consecutive_failures", "updated_at"])
+
+
+def finalize_account_property_sync_runs(
+ context: AccountPropertySyncRunContext,
+ *,
+ status: SyncStatus,
+ phase: SyncPhase,
+ error: str | None = None,
+ segment: SyncSegment | None = None,
+) -> None:
+ with transaction.atomic():
+ runs = (
+ CustomPropertySyncRun.objects.for_team(context.team_id)
+ .select_for_update()
+ .filter(
+ job_id=context.job_id,
+ saved_query_id=context.saved_query_id,
+ status=SyncStatus.RUNNING.value,
+ )
+ )
+ if segment is not None:
+ runs = runs.filter(segment=segment.value)
+ transitioned_source_ids = set(runs.values_list("source_id", flat=True))
+ runs.update(
+ status=status.value,
+ phase=phase.value,
+ finished_at=timezone.now(),
+ error=error,
+ )
+ _update_source_status_for_terminal_runs(context.team_id, context.job_id, transitioned_source_ids)
+
+
+def finish_account_property_sync_runs(
+ context: AccountPropertySyncRunContext,
+ segment: SyncSegment,
+ outcomes: list[AccountPropertySyncRunOutcome],
+ *,
+ finished_at: datetime | None = None,
+) -> None:
+ if not outcomes:
+ return
+
+ outcomes_by_source_id = {outcome.source_id: outcome for outcome in outcomes}
+ with transaction.atomic():
+ runs = list(
+ CustomPropertySyncRun.objects.for_team(context.team_id)
+ .select_for_update()
+ .filter(
+ source_id__in=outcomes_by_source_id,
+ job_id=context.job_id,
+ segment=segment.value,
+ )
+ )
+ completed_at = finished_at or timezone.now()
+ transitioned_source_ids: set[UUID] = set()
+ for run in runs:
+ if run.status in {SyncStatus.COMPLETED.value, SyncStatus.FAILED.value}:
+ continue
+ outcome = outcomes_by_source_id[run.source_id]
+ failed = outcome.error is not None
+ run.status = SyncStatus.FAILED.value if failed else SyncStatus.COMPLETED.value
+ run.phase = SyncPhase.SYNCING.value if failed else SyncPhase.COMPLETED.value
+ run.finished_at = completed_at
+ run.rows_read = outcome.rows_read
+ run.changed = outcome.changed
+ run.existing = outcome.matched
+ run.produced = outcome.written
+ run.skipped_missing_person = max(outcome.changed - outcome.matched, 0)
+ run.error = outcome.error
+ transitioned_source_ids.add(run.source_id)
+ run.save(
+ update_fields=[
+ "status",
+ "phase",
+ "finished_at",
+ "rows_read",
+ "changed",
+ "existing",
+ "produced",
+ "skipped_missing_person",
+ "error",
+ ]
+ )
+ _update_source_status_for_terminal_runs(context.team_id, context.job_id, transitioned_source_ids)
diff --git a/products/customer_analytics/backend/logic/account_property_runs_test.py b/products/customer_analytics/backend/logic/account_property_runs_test.py
new file mode 100644
index 000000000000..9aee609128a5
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_runs_test.py
@@ -0,0 +1,251 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.apps import apps
+from django.utils import timezone
+
+from products.customer_analytics.backend.facade import api
+from products.customer_analytics.backend.logic.account_property_runs import (
+ AccountPropertySyncRunContext,
+ AccountPropertySyncRunOutcome,
+ finalize_account_property_sync_runs,
+ finish_account_property_sync_runs,
+ start_account_property_sync_runs,
+ update_account_property_sync_runs_phase,
+)
+from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun
+from products.customer_analytics.backend.models.custom_property_sync_run import SyncPhase, SyncSegment, SyncStatus
+from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
+from products.customer_analytics.backend.test.factories import create_custom_property_definition
+
+DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
+
+
+class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="accounts",
+ columns={"external_id": {}, "plan": {}},
+ )
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self.source = CustomPropertySource.objects.create(
+ team=self.team,
+ definition=definition,
+ saved_query=self.saved_query,
+ key_column="external_id",
+ source_column="plan",
+ )
+ self.context = AccountPropertySyncRunContext(
+ team_id=self.team.id,
+ saved_query_id=str(self.saved_query.id),
+ job_id="job-1",
+ )
+
+ def _create_outcome(
+ self,
+ *,
+ rows_read: int = 10,
+ changed: int = 4,
+ matched: int = 3,
+ written: int = 2,
+ error: str | None = None,
+ ) -> AccountPropertySyncRunOutcome:
+ return AccountPropertySyncRunOutcome(
+ source_id=self.source.id,
+ rows_read=rows_read,
+ changed=changed,
+ matched=matched,
+ written=written,
+ error=error,
+ )
+
+ def _start_runs(
+ self,
+ workflow_id: str = "stage-workflow-job-1",
+ workflow_run_id: str = "00000000-0000-4000-8000-000000000001",
+ ) -> None:
+ start_account_property_sync_runs(
+ self.context,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ )
+
+ def test_start_opens_both_segments_before_staging_and_exposes_them_through_the_api(self) -> None:
+ self._start_runs()
+
+ runs = CustomPropertySyncRun.objects.for_team(self.team.id).filter(source=self.source)
+ assert runs.count() == 2
+ assert {run.segment for run in runs} == {"tracked", "ignored"}
+ assert {run.phase for run in runs} == {"staging"}
+ assert {run.workflow_id for run in runs} == {"stage-workflow-job-1"}
+ assert {str(run.workflow_run_id) for run in runs} == {"00000000-0000-4000-8000-000000000001"}
+ assert {run.attempt for run in runs} == {0}
+
+ views, total_count = api.list_custom_property_sync_runs(
+ self.team.id,
+ str(self.source.id),
+ offset=0,
+ limit=10,
+ )
+ assert total_count == 2
+ assert {view.account_segment for view in views} == {"tracked", "ignored"}
+ assert {view.sync_phase for view in views} == {"staging"}
+ assert {view.job_id for view in views} == {"job-1"}
+ assert {view.workflow_id for view in views} == {None}
+ assert {view.workflow_run_id for view in views} == {None}
+ assert {view.temporal_url for view in views} == {None}
+
+ staff_views, _ = api.list_custom_property_sync_runs(
+ self.team.id,
+ str(self.source.id),
+ offset=0,
+ limit=10,
+ include_temporal_urls=True,
+ )
+ assert {view.workflow_id for view in staff_views} == {"stage-workflow-job-1"}
+ assert {str(view.workflow_run_id) for view in staff_views} == {"00000000-0000-4000-8000-000000000001"}
+ assert all(view.temporal_url is not None for view in staff_views)
+
+ search_views, search_count = api.list_custom_property_sync_runs(
+ self.team.id,
+ str(self.source.id),
+ offset=0,
+ limit=20,
+ search="ignored",
+ )
+ assert search_count == 1
+ assert [view.account_segment for view in search_views] == ["ignored"]
+
+ def test_phase_updates_record_retries_without_regressing_the_sibling(self) -> None:
+ self._start_runs()
+ update_account_property_sync_runs_phase(
+ self.context,
+ phase=SyncPhase.DISPATCHING,
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ attempt=2,
+ )
+ update_account_property_sync_runs_phase(
+ self.context,
+ phase=SyncPhase.SYNCING,
+ workflow_id="sync-workflow-job-1-tracked",
+ workflow_run_id="00000000-0000-4000-8000-000000000002",
+ attempt=3,
+ segment=SyncSegment.TRACKED,
+ )
+ update_account_property_sync_runs_phase(
+ self.context,
+ phase=SyncPhase.DISPATCHING,
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ attempt=4,
+ )
+
+ tracked = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=self.source, segment="tracked")
+ ignored = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=self.source, segment="ignored")
+ assert (tracked.phase, tracked.attempt, tracked.workflow_id, str(tracked.workflow_run_id)) == (
+ "syncing",
+ 3,
+ "sync-workflow-job-1-tracked",
+ "00000000-0000-4000-8000-000000000002",
+ )
+ assert (ignored.phase, ignored.attempt, ignored.workflow_id, str(ignored.workflow_run_id)) == (
+ "dispatching",
+ 4,
+ "stage-workflow-job-1",
+ "00000000-0000-4000-8000-000000000001",
+ )
+
+ def test_account_runs_remain_active_during_their_workflow_timeout(self) -> None:
+ self._start_runs()
+ CustomPropertySyncRun.objects.for_team(self.team.id).filter(source=self.source).update(
+ started_at=timezone.now() - timedelta(hours=7)
+ )
+
+ views, _ = api.list_custom_property_sync_runs(
+ self.team.id,
+ str(self.source.id),
+ offset=0,
+ limit=10,
+ )
+
+ assert {view.status for view in views} == {"running"}
+
+ def test_staging_failure_finishes_both_segments_with_a_safe_error(self) -> None:
+ self._start_runs()
+
+ finalize_account_property_sync_runs(
+ self.context,
+ status=SyncStatus.FAILED,
+ phase=SyncPhase.STAGING,
+ error="Couldn't prepare warehouse rows.",
+ )
+
+ runs = CustomPropertySyncRun.objects.for_team(self.team.id).filter(source=self.source)
+ assert {run.status for run in runs} == {"failed"}
+ assert {run.phase for run in runs} == {"staging"}
+ assert {run.error for run in runs} == {"Couldn't prepare warehouse rows."}
+ assert all(run.finished_at is not None for run in runs)
+ self.source.refresh_from_db()
+ assert self.source.last_sync_error == "Couldn't prepare warehouse rows."
+ assert self.source.consecutive_failures == 1
+
+ finalize_account_property_sync_runs(
+ self.context,
+ status=SyncStatus.FAILED,
+ phase=SyncPhase.STAGING,
+ error="Couldn't prepare warehouse rows.",
+ )
+ self.source.refresh_from_db()
+ assert self.source.consecutive_failures == 1
+
+ def test_finishing_both_segments_updates_the_source_summary(self) -> None:
+ self.source.last_sync_error = "Previous failure"
+ self.source.consecutive_failures = 2
+ self.source.save(update_fields=["last_sync_error", "consecutive_failures"])
+ self._start_runs()
+ tracked_finished_at = timezone.now()
+ ignored_finished_at = tracked_finished_at + timedelta(seconds=2)
+
+ finish_account_property_sync_runs(
+ self.context,
+ SyncSegment.TRACKED,
+ [self._create_outcome(written=3)],
+ finished_at=tracked_finished_at,
+ )
+ source_after_tracked = CustomPropertySource.objects.for_team(self.team.id).get(id=self.source.id)
+ assert source_after_tracked.last_synced_at is None
+ assert source_after_tracked.last_sync_error == "Previous failure"
+ assert source_after_tracked.consecutive_failures == 2
+
+ finish_account_property_sync_runs(
+ self.context,
+ SyncSegment.IGNORED,
+ [self._create_outcome(written=0)],
+ finished_at=ignored_finished_at,
+ )
+ source_after_ignored = CustomPropertySource.objects.for_team(self.team.id).get(id=self.source.id)
+ assert source_after_ignored.last_synced_at == ignored_finished_at
+ assert source_after_ignored.last_sync_error is None
+ assert source_after_ignored.consecutive_failures == 0
+
+ def test_retry_reuses_rows_and_preserves_a_completed_segment(self) -> None:
+ self._start_runs()
+ finalize_account_property_sync_runs(
+ self.context,
+ status=SyncStatus.FAILED,
+ phase=SyncPhase.DISPATCHING,
+ error="Couldn't start account updates.",
+ )
+ self._start_runs("stage-workflow-job-1-retry")
+ finish_account_property_sync_runs(self.context, SyncSegment.TRACKED, [self._create_outcome(written=3)])
+ self._start_runs("stage-workflow-job-1-retry-2")
+
+ tracked = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=self.source, segment="tracked")
+ ignored = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=self.source, segment="ignored")
+ assert (tracked.status, tracked.phase, tracked.produced) == ("completed", "completed", 3)
+ assert (ignored.status, ignored.phase, ignored.error) == ("running", "staging", None)
+ assert CustomPropertySyncRun.objects.for_team(self.team.id).filter(source=self.source).count() == 2
diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.py
index ea713aa818e7..0c95024a01df 100644
--- a/products/customer_analytics/backend/logic/account_property_sync.py
+++ b/products/customer_analytics/backend/logic/account_property_sync.py
@@ -18,12 +18,23 @@ from structlog.typing import FilteringBoundLogger
from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async
+from products.customer_analytics.backend.logic.account_property_runs import (
+ AccountPropertySyncRunContext,
+ AccountPropertySyncRunOutcome,
+ finalize_account_property_sync_runs,
+ finish_account_property_sync_runs,
+)
from products.customer_analytics.backend.logic.custom_property_values import (
InvalidCustomPropertyValue,
set_synced_custom_property_value,
)
from products.customer_analytics.backend.metrics import record_account_property_sync_phase_duration
from products.customer_analytics.backend.models import Account, CustomPropertySource, TargetType
+from products.customer_analytics.backend.models.custom_property_sync_run import (
+ SyncPhase,
+ SyncSegment as AccountPropertySyncSegment,
+ SyncStatus,
+)
from products.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.facade.hooks import WarehouseBinding
from products.warehouse_sources.backend.facade.temporal import (
@@ -37,11 +48,10 @@ logger = structlog.get_logger(__name__)
_ACCOUNT_LOOKUP_CHUNK_SIZE = 1_000
_PARQUET_BATCH_SIZE = 50_000
_SEGMENTS_REQUIRED_FOR_CLEANUP = frozenset({"tracked", "ignored"})
-
-
-class AccountPropertySyncSegment(StrEnum):
- TRACKED = "tracked"
- IGNORED = "ignored"
+_RUN_FAILED_ERROR = "Couldn't update accounts. Run the source view again. If it keeps failing, contact support."
+_INVALID_VALUE_ERROR = (
+ "A warehouse value doesn't match this property's type. Update the source data, then run the view again."
+)
class AccountPropertySyncPhase(StrEnum):
@@ -69,7 +79,11 @@ class SourceSyncState:
source: CustomPropertySource
prior_hashes: dict[str, str]
applied_hashes: dict[str, str] = field(default_factory=dict)
- failed: bool = False
+ rows_read: int = 0
+ changed: int = 0
+ matched: int = 0
+ written: int = 0
+ error: str | None = None
def _record_phase_duration(
@@ -308,11 +322,13 @@ async def _mark_completed_and_maybe_cleanup(
async def run_account_property_segment_sync(
- *, team_id: int, binding: WarehouseBinding, job_id: str, segment: AccountPropertySyncSegment
+ *,
+ team_id: int,
+ binding: WarehouseBinding,
+ job_id: str,
+ segment: AccountPropertySyncSegment,
+ final_attempt: bool = False,
) -> dict[str, int]:
- if await _segment_already_completed(team_id, binding, job_id, segment):
- return {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
-
log = logger.bind(
team_id=team_id,
saved_query_id=binding.id,
@@ -321,132 +337,190 @@ async def run_account_property_segment_sync(
)
counts = {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
- phase_started_at = asyncio.get_running_loop().time()
- sources = await database_sync_to_async(_enabled_sources, thread_sensitive=False)(team_id, binding)
states: list[SourceSyncState] = []
- for source in sources:
- if source.source_column is None:
- continue
- states.append(
- SourceSyncState(
- source=source,
- prior_hashes=await _read_snapshot_hashes(team_id, binding, str(source.id), segment),
- )
- )
- _record_phase_duration(
- log,
- segment,
- AccountPropertySyncPhase.LOAD_STATE,
- phase_started_at,
- {"source_count": len(states)},
+ run_context = AccountPropertySyncRunContext(
+ team_id=team_id,
+ saved_query_id=binding.id,
+ job_id=job_id,
)
- batch_index = 0
- batches = aiter(_iter_parquet_row_batches(team_id, binding, job_id))
- while True:
+ try:
+ if await _segment_already_completed(team_id, binding, job_id, segment):
+ return {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
+
+ sources = await database_sync_to_async(_enabled_sources, thread_sensitive=False)(team_id, binding)
+ states = [
+ SourceSyncState(source=source, prior_hashes={}) for source in sources if source.source_column is not None
+ ]
phase_started_at = asyncio.get_running_loop().time()
- try:
- rows = await anext(batches)
- except StopAsyncIteration:
- break
+ for state in states:
+ state.prior_hashes.update(await _read_snapshot_hashes(team_id, binding, str(state.source.id), segment))
_record_phase_duration(
log,
segment,
- AccountPropertySyncPhase.READ_STAGED_ROWS,
+ AccountPropertySyncPhase.LOAD_STATE,
phase_started_at,
- {"batch_index": batch_index, "batch_rows": len(rows)},
+ {"source_count": len(states)},
)
- counts["rows_read"] += len(rows)
- for state in states:
- source = state.source
- source_column = source.source_column
- if source_column is None:
- continue
+ batch_index = 0
+ batches = aiter(_iter_parquet_row_batches(team_id, binding, job_id))
+ while True:
phase_started_at = asyncio.get_running_loop().time()
- values_by_external_id: dict[str, Any] = {}
- for row in rows:
- external_id = row.get(source.key_column)
- value = row.get(source_column)
- if external_id is not None and value is not None:
- values_by_external_id[str(external_id)] = _json_safe(value)
- changed = {
- external_id: value
- for external_id, value in values_by_external_id.items()
- if state.prior_hashes.get(external_id) != _value_hash(value)
- }
- counts["changed"] += len(changed)
- phase_details: dict[str, bool | float | int | str] = {
- "batch_index": batch_index,
- "source_id": str(source.id),
- "candidate_values": len(values_by_external_id),
- "changed_values": len(changed),
- }
+ try:
+ rows = await anext(batches)
+ except StopAsyncIteration:
+ break
_record_phase_duration(
log,
segment,
- AccountPropertySyncPhase.DIFF_VALUES,
+ AccountPropertySyncPhase.READ_STAGED_ROWS,
phase_started_at,
- phase_details,
+ {"batch_index": batch_index, "batch_rows": len(rows)},
)
- if not changed:
- continue
+ counts["rows_read"] += len(rows)
+ for state in states:
+ state.rows_read += len(rows)
+ source = state.source
+ source_column = source.source_column
+ if source_column is None:
+ continue
+
+ phase_started_at = asyncio.get_running_loop().time()
+ values_by_external_id: dict[str, Any] = {}
+ for row in rows:
+ external_id = row.get(source.key_column)
+ value = row.get(source_column)
+ if external_id is not None and value is not None:
+ values_by_external_id[str(external_id)] = _json_safe(value)
+ changed = {
+ external_id: value
+ for external_id, value in values_by_external_id.items()
+ if state.prior_hashes.get(external_id) != _value_hash(value)
+ }
+ state.changed += len(changed)
+ counts["changed"] += len(changed)
+ phase_details: dict[str, bool | float | int | str] = {
+ "batch_index": batch_index,
+ "source_id": str(source.id),
+ "candidate_values": len(values_by_external_id),
+ "changed_values": len(changed),
+ }
+ _record_phase_duration(
+ log,
+ segment,
+ AccountPropertySyncPhase.DIFF_VALUES,
+ phase_started_at,
+ phase_details,
+ )
+ if not changed:
+ continue
+
+ phase_started_at = asyncio.get_running_loop().time()
+ account_ids = await database_sync_to_async(_matching_account_ids, thread_sensitive=False)(
+ team_id, segment, list(changed)
+ )
+ state.matched += len(account_ids)
+ counts["matched"] += len(account_ids)
+ _record_phase_duration(
+ log,
+ segment,
+ AccountPropertySyncPhase.MATCH_ACCOUNTS,
+ phase_started_at,
+ {**phase_details, "matched_accounts": len(account_ids)},
+ )
+
+ phase_started_at = asyncio.get_running_loop().time()
+ applied = await database_sync_to_async(_apply_source_values, thread_sensitive=False)(
+ team_id, source, account_ids, changed, segment
+ )
+ state.written += applied.written
+ counts["written"] += applied.written
+ if applied.failed:
+ state.error = _INVALID_VALUE_ERROR
+ state.applied_hashes.update(applied.hashes)
+ state.prior_hashes.update(applied.hashes)
+ _record_phase_duration(
+ log,
+ segment,
+ AccountPropertySyncPhase.APPLY_VALUES,
+ phase_started_at,
+ {
+ **phase_details,
+ "matched_accounts": len(account_ids),
+ "written_values": applied.written,
+ "source_failed": applied.failed,
+ },
+ )
+ batch_index += 1
- phase_started_at = asyncio.get_running_loop().time()
- account_ids = await database_sync_to_async(_matching_account_ids, thread_sensitive=False)(
- team_id, segment, list(changed)
- )
- counts["matched"] += len(account_ids)
- _record_phase_duration(
- log,
- segment,
- AccountPropertySyncPhase.MATCH_ACCOUNTS,
- phase_started_at,
- {**phase_details, "matched_accounts": len(account_ids)},
- )
-
- phase_started_at = asyncio.get_running_loop().time()
- applied = await database_sync_to_async(_apply_source_values, thread_sensitive=False)(
- team_id, source, account_ids, changed, segment
- )
- counts["written"] += applied.written
- state.failed = state.failed or applied.failed
- state.applied_hashes.update(applied.hashes)
- state.prior_hashes.update(applied.hashes)
- _record_phase_duration(
- log,
+ phase_started_at = asyncio.get_running_loop().time()
+ persisted_hashes = 0
+ for state in states:
+ if state.error is not None:
+ counts["source_errors"] += 1
+ await _write_snapshot_hashes(
+ team_id,
+ binding,
+ str(state.source.id),
segment,
- AccountPropertySyncPhase.APPLY_VALUES,
- phase_started_at,
- {
- **phase_details,
- "matched_accounts": len(account_ids),
- "written_values": applied.written,
- "source_failed": applied.failed,
- },
+ job_id,
+ state.applied_hashes,
)
- batch_index += 1
-
- phase_started_at = asyncio.get_running_loop().time()
- persisted_hashes = 0
- for state in states:
- if state.failed:
- counts["source_errors"] += 1
- await _write_snapshot_hashes(
- team_id,
- binding,
- str(state.source.id),
+ persisted_hashes += len(state.applied_hashes)
+ _record_phase_duration(
+ log,
segment,
- job_id,
- state.applied_hashes,
+ AccountPropertySyncPhase.PERSIST_STATE,
+ phase_started_at,
+ {"source_count": len(states), "persisted_hashes": persisted_hashes},
)
- persisted_hashes += len(state.applied_hashes)
- _record_phase_duration(
- log,
+ except Exception:
+ if final_attempt:
+ await database_sync_to_async(finish_account_property_sync_runs)(
+ run_context,
+ segment,
+ [
+ AccountPropertySyncRunOutcome(
+ source_id=state.source.id,
+ rows_read=state.rows_read,
+ changed=state.changed,
+ matched=state.matched,
+ written=state.written,
+ error=_RUN_FAILED_ERROR,
+ )
+ for state in states
+ ],
+ )
+ await database_sync_to_async(finalize_account_property_sync_runs)(
+ run_context,
+ status=SyncStatus.FAILED,
+ phase=SyncPhase.SYNCING,
+ error=_RUN_FAILED_ERROR,
+ segment=segment,
+ )
+ raise
+
+ await database_sync_to_async(finish_account_property_sync_runs)(
+ run_context,
segment,
- AccountPropertySyncPhase.PERSIST_STATE,
- phase_started_at,
- {"source_count": len(states), "persisted_hashes": persisted_hashes},
+ [
+ AccountPropertySyncRunOutcome(
+ source_id=state.source.id,
+ rows_read=state.rows_read,
+ changed=state.changed,
+ matched=state.matched,
+ written=state.written,
+ error=state.error,
+ )
+ for state in states
+ ],
+ )
+ await database_sync_to_async(finalize_account_property_sync_runs)(
+ run_context,
+ status=SyncStatus.COMPLETED,
+ phase=SyncPhase.COMPLETED,
+ segment=segment,
)
if counts["source_errors"]:
diff --git a/products/customer_analytics/backend/logic/account_property_sync_test.py b/products/customer_analytics/backend/logic/account_property_sync_test.py
index 046ff2239ecd..7c51b26e1b07 100644
--- a/products/customer_analytics/backend/logic/account_property_sync_test.py
+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py
@@ -1,12 +1,20 @@
from datetime import UTC, datetime
+from uuid import uuid4
import pytest
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.apps import apps
+
import pyarrow as pa
import pyarrow.parquet as pq
+from asgiref.sync import async_to_sync
+from products.customer_analytics.backend.logic.account_property_runs import (
+ AccountPropertySyncRunContext,
+ start_account_property_sync_runs,
+)
from products.customer_analytics.backend.logic.account_property_sync import (
AccountPropertySyncPhase,
AccountPropertySyncSegment,
@@ -17,15 +25,32 @@ from products.customer_analytics.backend.logic.account_property_sync import (
_value_hash,
run_account_property_segment_sync,
)
+from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun
from products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin
-from products.customer_analytics.backend.test.factories import create_account
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
from products.warehouse_sources.backend.facade.hooks import saved_query_binding
from products.warehouse_sources.backend.facade.temporal import account_property_job_staged_prefix
_MODULE = "products.customer_analytics.backend.logic.account_property_sync"
+DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
class AccountPropertySegmentTest(TeamScopedTestMixin, BaseTest):
+ def _create_source(self) -> CustomPropertySource:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="accounts",
+ columns={"external_id": {}, "plan": {}},
+ )
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ return CustomPropertySource.objects.create(
+ team=self.team,
+ definition=definition,
+ saved_query=saved_query,
+ key_column="external_id",
+ source_column="plan",
+ )
+
def test_segments_tracked_and_ignored_accounts_and_excludes_churned_accounts(self) -> None:
tracked = create_account(team_id=self.team.id, external_id="tracked")
ignored = create_account(team_id=self.team.id, external_id="ignored", ignored_at=datetime.now(UTC))
@@ -48,6 +73,139 @@ class AccountPropertySegmentTest(TeamScopedTestMixin, BaseTest):
def test_value_hash_is_stable_for_equivalent_values(self) -> None:
assert _value_hash({"a": 1, "b": [2, 3]}) == _value_hash({"b": [2, 3], "a": 1})
+ def test_segment_sync_persists_source_run_counts(self) -> None:
+ source = self._create_source()
+ start_account_property_sync_runs(
+ AccountPropertySyncRunContext(
+ team_id=self.team.id,
+ saved_query_id=str(source.saved_query_id),
+ job_id="job-1",
+ ),
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ )
+
+ async def batches(*args):
+ yield [{"external_id": "acme", "plan": "enterprise"}]
+
+ with (
+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
+ patch(f"{_MODULE}._enabled_sources", return_value=[source]),
+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
+ patch(f"{_MODULE}._iter_parquet_row_batches", side_effect=batches),
+ patch(f"{_MODULE}._matching_account_ids", return_value={"acme": uuid4()}),
+ patch(
+ f"{_MODULE}._apply_source_values",
+ return_value=AppliedSourceValues(written=1, hashes={"acme": "hash"}, failed=False),
+ ),
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
+ patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
+ ):
+ async_to_sync(run_account_property_segment_sync)(
+ team_id=self.team.id,
+ binding=saved_query_binding(str(source.saved_query_id)),
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ )
+
+ run = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=source, segment="tracked")
+ assert (run.status, run.phase) == ("completed", "completed")
+ assert (run.rows_read, run.changed, run.existing, run.produced) == (1, 1, 1, 1)
+
+ def test_final_attempt_persists_a_failed_run(self) -> None:
+ source = self._create_source()
+ start_account_property_sync_runs(
+ AccountPropertySyncRunContext(
+ team_id=self.team.id,
+ saved_query_id=str(source.saved_query_id),
+ job_id="job-1",
+ ),
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ )
+
+ with (
+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
+ patch(f"{_MODULE}._enabled_sources", return_value=[source]),
+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(side_effect=OSError("S3 unavailable"))),
+ ):
+ with pytest.raises(OSError, match="S3 unavailable"):
+ async_to_sync(run_account_property_segment_sync)(
+ team_id=self.team.id,
+ binding=saved_query_binding(str(source.saved_query_id)),
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.IGNORED,
+ final_attempt=True,
+ )
+
+ run = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=source, segment="ignored")
+ assert run.status == "failed"
+ assert run.finished_at is not None
+
+ def test_final_attempt_finishes_runs_when_source_loading_fails(self) -> None:
+ source = self._create_source()
+ start_account_property_sync_runs(
+ AccountPropertySyncRunContext(
+ team_id=self.team.id,
+ saved_query_id=str(source.saved_query_id),
+ job_id="job-1",
+ ),
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ )
+
+ with (
+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
+ patch(f"{_MODULE}._enabled_sources", side_effect=OSError("database unavailable")),
+ pytest.raises(OSError, match="database unavailable"),
+ ):
+ async_to_sync(run_account_property_segment_sync)(
+ team_id=self.team.id,
+ binding=saved_query_binding(str(source.saved_query_id)),
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ final_attempt=True,
+ )
+
+ run = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=source, segment="tracked")
+ assert run.status == "failed"
+ assert run.finished_at is not None
+
+ def test_disabled_source_run_finishes_without_work(self) -> None:
+ source = self._create_source()
+ start_account_property_sync_runs(
+ AccountPropertySyncRunContext(
+ team_id=self.team.id,
+ saved_query_id=str(source.saved_query_id),
+ job_id="job-1",
+ ),
+ workflow_id="stage-workflow-job-1",
+ workflow_run_id="00000000-0000-4000-8000-000000000001",
+ )
+ source.is_enabled = False
+ source.save(update_fields=["is_enabled"])
+
+ async def no_batches(*args):
+ for _ in range(0):
+ yield []
+
+ with (
+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
+ patch(f"{_MODULE}._enabled_sources", return_value=[]),
+ patch(f"{_MODULE}._iter_parquet_row_batches", side_effect=no_batches),
+ patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
+ ):
+ async_to_sync(run_account_property_segment_sync)(
+ team_id=self.team.id,
+ binding=saved_query_binding(str(source.saved_query_id)),
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ )
+
+ run = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=source, segment="tracked")
+ assert run.status == "completed"
+ assert run.finished_at is not None
+
class _S3ClientContext:
def __init__(self, client: MagicMock) -> None:
@@ -81,6 +239,8 @@ async def test_each_staged_batch_is_shared_across_sources() -> None:
patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),
patch(f"{_MODULE}._enabled_sources", return_value=sources),
patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),
+ patch(f"{_MODULE}.finish_account_property_sync_runs"),
+ patch(f"{_MODULE}.finalize_account_property_sync_runs"),
patch(f"{_MODULE}._iter_parquet_row_batches", side_effect=batches),
patch(f"{_MODULE}._matching_account_ids", return_value={}),
patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
@@ -120,6 +280,8 @@ async def test_sync_records_each_phase_duration() -> None:
),
patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
+ patch(f"{_MODULE}.finish_account_property_sync_runs"),
+ patch(f"{_MODULE}.finalize_account_property_sync_runs"),
patch(f"{_MODULE}.record_account_property_sync_phase_duration", phase_duration_recorder),
):
await run_account_property_segment_sync(
diff --git a/products/customer_analytics/backend/migrations/0043_custom_property_sync_run_observability.py b/products/customer_analytics/backend/migrations/0043_custom_property_sync_run_observability.py
new file mode 100644
index 000000000000..53169293a380
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0043_custom_property_sync_run_observability.py
@@ -0,0 +1,45 @@
+# Generated by Django 5.2.17 on 2026-08-22 02:32
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("customer_analytics", "0042_backfill_account_track_rules_enabled_at")]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertysyncrun",
+ name="attempt",
+ field=models.PositiveSmallIntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="custompropertysyncrun",
+ name="phase",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("staging", "staging"),
+ ("dispatching", "dispatching"),
+ ("syncing", "syncing"),
+ ("completed", "completed"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="custompropertysyncrun",
+ name="segment",
+ field=models.CharField(
+ blank=True,
+ choices=[("tracked", "tracked"), ("ignored", "ignored")],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="custompropertysyncrun",
+ name="workflow_id",
+ field=models.CharField(blank=True, max_length=400, null=True),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0044_custom_property_sync_run_temporal_run_id.py b/products/customer_analytics/backend/migrations/0044_custom_property_sync_run_temporal_run_id.py
new file mode 100644
index 000000000000..9eb736040f55
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0044_custom_property_sync_run_temporal_run_id.py
@@ -0,0 +1,15 @@
+# Generated by Django 5.2.17 on 2026-08-25 20:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("customer_analytics", "0043_custom_property_sync_run_observability")]
+
+ operations = [
+ migrations.AddField(
+ model_name="custompropertysyncrun",
+ name="workflow_run_id",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 7ad4ea945ad3..fb38ebe404a2 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0042_backfill_account_track_rules_enabled_at
+0044_custom_property_sync_run_temporal_run_id
diff --git a/products/customer_analytics/backend/models/custom_property_sync_run.py b/products/customer_analytics/backend/models/custom_property_sync_run.py
index d3d33ec8a029..98d8ff236180 100644
--- a/products/customer_analytics/backend/models/custom_property_sync_run.py
+++ b/products/customer_analytics/backend/models/custom_property_sync_run.py
@@ -23,10 +23,20 @@ class SyncStatus(models.TextChoices):
FAILED = "failed", "failed"
+class SyncSegment(models.TextChoices):
+ TRACKED = "tracked", "tracked"
+ IGNORED = "ignored", "ignored"
+
+
+class SyncPhase(models.TextChoices):
+ STAGING = "staging", "staging"
+ DISPATCHING = "dispatching", "dispatching"
+ SYNCING = "syncing", "syncing"
+ COMPLETED = "completed", "completed"
+
+
class CustomPropertySyncRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
- """One person-property sync run for a single source. Persists the funnel counts the sync/backfill
- activities compute (which otherwise live only in Prometheus/logs) so the UI can show run history
- and how many person profiles were affected."""
+ """One warehouse sync run for a single custom property source."""
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
created_by = models.ForeignKey(
@@ -44,6 +54,11 @@ class CustomPropertySyncRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
# The warehouse job this run rode on: an import job, or a view materialization. Null for
# backfill/manual runs, which read the table directly instead of riding a job.
job_id = models.CharField(max_length=400, null=True, blank=True)
+ segment = models.CharField(max_length=20, choices=SyncSegment.choices, null=True, blank=True)
+ phase = models.CharField(max_length=20, choices=SyncPhase.choices, null=True, blank=True)
+ attempt = models.PositiveSmallIntegerField(null=True, blank=True)
+ workflow_id = models.CharField(max_length=400, null=True, blank=True)
+ workflow_run_id = models.UUIDField(null=True, blank=True)
trigger = models.CharField(max_length=20, choices=SyncTrigger.choices)
status = models.CharField(max_length=20, choices=SyncStatus.choices, default=SyncStatus.RUNNING)
@@ -51,9 +66,7 @@ class CustomPropertySyncRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
started_at = models.DateTimeField(null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
- # Funnel: read -> changed (survived the snapshot diff) -> existing (distinct_id resolved to a
- # person) -> produced (intent on Kafka); skipped_missing_person is the changed rows that dropped
- # because no person matched.
+ # The same funnel serves all targets. For accounts, existing means matched and produced means written.
rows_read = models.PositiveIntegerField(default=0)
changed = models.PositiveIntegerField(default=0)
existing = models.PositiveIntegerField(default=0)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 1fc2b13e9b8a..f6f85755ddb1 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1440,11 +1440,60 @@ class CustomPropertySyncTriggerResponseSerializer(serializers.Serializer):
)
+class CustomPropertySyncRunListQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Match run IDs, workflow IDs, job IDs, statuses, segments, triggers, or errors.",
+ )
+
+
class CustomPropertySyncRunSerializer(DataclassSerializer):
- """One person- or group-property sync or backfill run. Read-only: runs are created by the
- sync/backfill pipeline, never through the API."""
+ """One warehouse-backed custom property sync run."""
id = serializers.UUIDField(read_only=True)
+ job_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Warehouse import or materialization job associated with the run, if any.",
+ )
+ account_segment = serializers.ChoiceField(
+ choices=[("tracked", "tracked"), ("ignored", "ignored")],
+ read_only=True,
+ allow_null=True,
+ help_text="Account segment processed by this run. Person and group property runs return null.",
+ )
+ sync_phase = serializers.ChoiceField(
+ choices=[
+ ("staging", "staging"),
+ ("dispatching", "dispatching"),
+ ("syncing", "syncing"),
+ ("completed", "completed"),
+ ],
+ read_only=True,
+ allow_null=True,
+ help_text="Current account sync phase. Person and group property runs return null.",
+ )
+ attempt = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="Latest Temporal activity attempt for the current account sync phase.",
+ )
+ workflow_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Temporal workflow identifier associated with the current account sync phase.",
+ )
+ workflow_run_id = serializers.UUIDField(
+ read_only=True,
+ allow_null=True,
+ help_text="Temporal run identifier associated with the current account sync phase.",
+ )
+ temporal_url = serializers.URLField(
+ read_only=True,
+ allow_null=True,
+ help_text="Staff-only link to this run in Temporal. Null for non-staff users and runs without a Temporal ID.",
+ )
trigger = serializers.CharField(
read_only=True,
help_text=(
@@ -1462,14 +1511,14 @@ class CustomPropertySyncRunSerializer(DataclassSerializer):
changed = serializers.IntegerField(read_only=True, help_text="Rows whose mapped values changed since the last run.")
existing = serializers.IntegerField(
read_only=True,
- help_text="Person or group profiles updated (changed rows that matched an existing person/group).",
+ help_text="Changed rows that matched an existing account, person, or group.",
)
produced = serializers.IntegerField(
- read_only=True, help_text="Property-update intents produced to the ingestion pipeline."
+ read_only=True, help_text="Property updates written or produced to the ingestion pipeline."
)
skipped_missing_person = serializers.IntegerField(
read_only=True,
- help_text="Changed rows dropped because no existing person/group matched the key column value.",
+ help_text="Changed rows skipped because no existing account, person, or group matched the key column value.",
)
error = serializers.CharField(
read_only=True, allow_null=True, help_text="Error summary if the run failed, else null."
@@ -1481,6 +1530,13 @@ class CustomPropertySyncRunSerializer(DataclassSerializer):
ref_name = "CustomPropertySyncRun"
fields = [
"id",
+ "job_id",
+ "account_segment",
+ "sync_phase",
+ "attempt",
+ "workflow_id",
+ "workflow_run_id",
+ "temporal_url",
"trigger",
"status",
"started_at",
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index a01e2ae85eb0..cd5b5842efe3 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -79,6 +79,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
CustomPropertyDefinitionSerializer,
CustomPropertySourceSerializer,
CustomPropertySourceUpdateSerializer,
+ CustomPropertySyncRunListQuerySerializer,
CustomPropertySyncRunSerializer,
CustomPropertySyncTriggerResponseSerializer,
CustomPropertyValueSerializer,
@@ -1335,13 +1336,13 @@ class CustomPropertySourceViewSet(
@extend_schema(
operation_id="custom_property_sources_runs_list",
+ parameters=[CustomPropertySyncRunListQuerySerializer],
responses={200: CustomPropertySyncRunSerializer(many=True)},
)
@action(methods=["GET"], detail=True)
def runs(self, request: Request, *args, **kwargs) -> Response:
- """Person and group sources only: the source's sync/backfill run history, newest first. Gated
- on the caller's warehouse-source viewer access, since the runs expose its row counts and sync
- errors."""
+ """The source's sync history, newest first. Person and group runs require viewer access to
+ their warehouse source because the response includes row counts and sync errors."""
# Hide the run history of a group-target source from callers without group read authorization.
source = api.get_custom_property_source(self.team_id, self.kwargs["pk"])
if (
@@ -1350,6 +1351,11 @@ class CustomPropertySourceViewSet(
and not _has_group_scope(request, write=False)
):
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ if source is not None and self._definition_target_type(source.definition) == "account":
+ self._report_usage(request, "account property sync history viewed")
+ query = CustomPropertySyncRunListQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ search = query.validated_data.get("search", "").strip() or None
try:
return self._paginate_via_facade(
request,
@@ -1359,6 +1365,8 @@ class CustomPropertySourceViewSet(
offset=offset,
limit=limit,
user_access_control=_warehouse_scoped_uac(self),
+ include_temporal_urls=bool(request.user.is_staff or is_impersonated(request)),
+ search=search,
),
CustomPropertySyncRunSerializer,
)
diff --git a/products/customer_analytics/backend/temporal/account_property_sync.py b/products/customer_analytics/backend/temporal/account_property_sync.py
index 42f861c3becb..651c4a95a5f4 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync.py
@@ -14,6 +14,7 @@ from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from products.customer_analytics.backend.facade.temporal_contracts import (
AccountPropertySyncInput,
DispatchAccountPropertySyncInput,
+ FinalizeAccountPropertySyncRunsInput,
StageAccountPropertySyncInput,
)
@@ -25,13 +26,21 @@ with workflow.unsafe.imports_passed_through():
import structlog
from prometheus_client import Counter, Histogram
+ from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
+ from products.customer_analytics.backend.logic.account_property_runs import (
+ AccountPropertySyncRunContext,
+ finalize_account_property_sync_runs,
+ start_account_property_sync_runs,
+ update_account_property_sync_runs_phase,
+ )
from products.customer_analytics.backend.logic.account_property_sync import (
AccountPropertySourceValueError,
AccountPropertySyncSegment,
run_account_property_segment_sync,
)
+ from products.customer_analytics.backend.models.custom_property_sync_run import SyncPhase, SyncStatus
from products.warehouse_sources.backend.facade.hooks import saved_query_binding
from products.warehouse_sources.backend.facade.temporal import AccountPropertyRowSink
@@ -39,6 +48,15 @@ logger = structlog.get_logger(__name__)
ACCOUNT_PROPERTY_STAGING_WORKFLOW_NAME = "stage-warehouse-account-properties"
ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME = "sync-warehouse-account-properties"
+ACCOUNT_PROPERTY_RUN_HISTORY_PATCH = "account-property-run-history-2026-08"
+ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS = 5
+
+_STAGING_FAILED_ERROR = (
+ "Couldn't prepare warehouse rows. Run the source view again. If it keeps failing, contact support."
+)
+_DISPATCH_FAILED_ERROR = (
+ "Couldn't start account updates. Run the source view again. If it keeps failing, contact support."
+)
ACCOUNT_PROPERTY_SYNC_TOTAL = Counter(
"warehouse_account_property_sync_total",
@@ -54,8 +72,48 @@ ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS = Histogram(
)
[email protected](name="start-warehouse-account-property-runs")
+async def start_warehouse_account_property_runs_activity(input: DispatchAccountPropertySyncInput) -> None:
+ activity_info = activity.info()
+ await database_sync_to_async(start_account_property_sync_runs)(
+ AccountPropertySyncRunContext(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ workflow_id=activity_info.workflow_id,
+ workflow_run_id=activity_info.workflow_run_id,
+ )
+
+
[email protected](name="finalize-warehouse-account-property-runs")
+async def finalize_warehouse_account_property_runs_activity(input: FinalizeAccountPropertySyncRunsInput) -> None:
+ await database_sync_to_async(finalize_account_property_sync_runs)(
+ AccountPropertySyncRunContext(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ status=SyncStatus(input.status),
+ phase=SyncPhase(input.phase),
+ error=input.error,
+ )
+
+
@activity.defn(name="stage-warehouse-account-property-files")
async def stage_warehouse_account_property_files_activity(input: StageAccountPropertySyncInput) -> bool:
+ activity_info = activity.info()
+ await database_sync_to_async(update_account_property_sync_runs_phase)(
+ AccountPropertySyncRunContext(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ phase=SyncPhase.STAGING,
+ workflow_id=activity_info.workflow_id,
+ workflow_run_id=activity_info.workflow_run_id,
+ attempt=activity_info.attempt,
+ )
log = logger.bind(
team_id=input.team_id,
saved_query_id=input.saved_query_id,
@@ -84,6 +142,18 @@ async def stage_warehouse_account_property_files_activity(input: StageAccountPro
@activity.defn(name="dispatch-warehouse-account-property-sync")
async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccountPropertySyncInput) -> None:
+ activity_info = activity.info()
+ await database_sync_to_async(update_account_property_sync_runs_phase)(
+ AccountPropertySyncRunContext(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ phase=SyncPhase.DISPATCHING,
+ workflow_id=activity_info.workflow_id,
+ workflow_run_id=activity_info.workflow_run_id,
+ attempt=activity_info.attempt,
+ )
client = await async_connect()
for segment in ("tracked", "ignored"):
workflow_id = f"sync-warehouse-account-properties-{input.job_id}-{segment}"
@@ -113,6 +183,19 @@ async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccou
@activity.defn
async def sync_warehouse_account_properties_activity(input: AccountPropertySyncInput) -> dict[str, int]:
segment = AccountPropertySyncSegment(input.segment)
+ activity_info = activity.info()
+ await database_sync_to_async(update_account_property_sync_runs_phase)(
+ AccountPropertySyncRunContext(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ ),
+ phase=SyncPhase.SYNCING,
+ workflow_id=activity_info.workflow_id,
+ workflow_run_id=activity_info.workflow_run_id,
+ attempt=activity_info.attempt,
+ segment=segment,
+ )
log = logger.bind(
team_id=input.team_id,
saved_query_id=input.saved_query_id,
@@ -127,6 +210,7 @@ async def sync_warehouse_account_properties_activity(input: AccountPropertySyncI
binding=saved_query_binding(input.saved_query_id),
job_id=input.job_id,
segment=segment,
+ final_attempt=activity_info.attempt >= ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS,
)
except AccountPropertySourceValueError as error:
ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="failed").inc()
@@ -152,25 +236,87 @@ class StageWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: StageAccountPropertySyncInput) -> None:
- staged = await workflow.execute_activity(
- stage_warehouse_account_property_files_activity,
- input,
- start_to_close_timeout=timedelta(hours=6),
- heartbeat_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=30)),
+ run_history_enabled = workflow.patched(ACCOUNT_PROPERTY_RUN_HISTORY_PATCH)
+ lifecycle_input = DispatchAccountPropertySyncInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
)
+ if run_history_enabled:
+ await workflow.execute_activity(
+ start_warehouse_account_property_runs_activity,
+ lifecycle_input,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS),
+ )
+
+ try:
+ staged = await workflow.execute_activity(
+ stage_warehouse_account_property_files_activity,
+ input,
+ start_to_close_timeout=timedelta(hours=6),
+ heartbeat_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(
+ maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS,
+ initial_interval=timedelta(seconds=30),
+ ),
+ )
+ except Exception:
+ if run_history_enabled:
+ await workflow.execute_activity(
+ finalize_warehouse_account_property_runs_activity,
+ FinalizeAccountPropertySyncRunsInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ status=SyncStatus.FAILED.value,
+ phase=SyncPhase.STAGING.value,
+ error=_STAGING_FAILED_ERROR,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS),
+ )
+ raise
+
if not staged:
+ if run_history_enabled:
+ await workflow.execute_activity(
+ finalize_warehouse_account_property_runs_activity,
+ FinalizeAccountPropertySyncRunsInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ status=SyncStatus.COMPLETED.value,
+ phase=SyncPhase.COMPLETED.value,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS),
+ )
return
- await workflow.execute_activity(
- dispatch_warehouse_account_property_sync_activity,
- DispatchAccountPropertySyncInput(
- team_id=input.team_id,
- saved_query_id=input.saved_query_id,
- job_id=input.job_id,
- ),
- start_to_close_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=5),
- )
+
+ try:
+ await workflow.execute_activity(
+ dispatch_warehouse_account_property_sync_activity,
+ lifecycle_input,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS),
+ )
+ except Exception:
+ if run_history_enabled:
+ await workflow.execute_activity(
+ finalize_warehouse_account_property_runs_activity,
+ FinalizeAccountPropertySyncRunsInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ status=SyncStatus.FAILED.value,
+ phase=SyncPhase.DISPATCHING.value,
+ error=_DISPATCH_FAILED_ERROR,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS),
+ )
+ raise
@workflow.defn(name=ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME)
@@ -186,7 +332,10 @@ class SyncWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
input,
start_to_close_timeout=timedelta(hours=6),
heartbeat_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=30)),
+ retry_policy=RetryPolicy(
+ maximum_attempts=ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS,
+ initial_interval=timedelta(seconds=30),
+ ),
)
@@ -195,6 +344,8 @@ ACCOUNT_PROPERTY_SYNC_WORKFLOWS = [
SyncWarehouseAccountPropertiesWorkflow,
]
ACCOUNT_PROPERTY_SYNC_ACTIVITIES = [
+ start_warehouse_account_property_runs_activity,
+ finalize_warehouse_account_property_runs_activity,
stage_warehouse_account_property_files_activity,
dispatch_warehouse_account_property_sync_activity,
sync_warehouse_account_properties_activity,
diff --git a/products/customer_analytics/backend/temporal/account_property_sync_test.py b/products/customer_analytics/backend/temporal/account_property_sync_test.py
index d1d288958f78..e0fcb0617d5b 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync_test.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync_test.py
@@ -12,6 +12,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from products.customer_analytics.backend.facade.temporal_contracts import (
DispatchAccountPropertySyncInput,
+ FinalizeAccountPropertySyncRunsInput,
StageAccountPropertySyncInput,
)
from products.customer_analytics.backend.temporal.account_property_sync import (
@@ -19,7 +20,9 @@ from products.customer_analytics.backend.temporal.account_property_sync import (
StageWarehouseAccountPropertiesWorkflow,
SyncWarehouseAccountPropertiesWorkflow,
dispatch_warehouse_account_property_sync_activity,
+ finalize_warehouse_account_property_runs_activity,
stage_warehouse_account_property_files_activity,
+ start_warehouse_account_property_runs_activity,
sync_warehouse_account_properties_activity,
)
@@ -54,36 +57,95 @@ async def test_staging_activity_reads_the_committed_delta_version() -> None:
"products.customer_analytics.backend.temporal.account_property_sync.Heartbeater",
return_value=_no_heartbeat(),
),
+ patch("products.customer_analytics.backend.temporal.account_property_sync.activity.info") as activity_info,
+ patch(
+ "products.customer_analytics.backend.temporal.account_property_sync.update_account_property_sync_runs_phase"
+ ),
):
+ activity_info.return_value.attempt = 1
+ activity_info.return_value.workflow_id = "stage-workflow-job-1"
staged = await stage_warehouse_account_property_files_activity(_staging_input())
assert staged is True
sink.stage_delta_snapshot.assert_awaited_once_with("s3://data-warehouse/dlt/table", 5)
-async def test_staging_workflow_dispatches_segments_only_after_staging_succeeds() -> None:
+async def test_staging_workflow_opens_history_before_staging_and_dispatches_after_success() -> None:
+ execute_activity = AsyncMock(side_effect=[None, True, None])
+
+ with (
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=True),
+ ):
+ await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
+
+ assert [call.args[0] for call in execute_activity.await_args_list] == [
+ start_warehouse_account_property_runs_activity,
+ stage_warehouse_account_property_files_activity,
+ dispatch_warehouse_account_property_sync_activity,
+ ]
+
+
+async def test_staging_workflow_preserves_the_pre_history_command_sequence() -> None:
execute_activity = AsyncMock(side_effect=[True, None])
- with patch.object(workflow, "execute_activity", new=execute_activity):
+ with (
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=False),
+ ):
await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
- assert execute_activity.await_count == 2
- assert execute_activity.await_args_list[0].args[0] == stage_warehouse_account_property_files_activity
- assert execute_activity.await_args_list[1].args[0] == dispatch_warehouse_account_property_sync_activity
+ assert [call.args[0] for call in execute_activity.await_args_list] == [
+ stage_warehouse_account_property_files_activity,
+ dispatch_warehouse_account_property_sync_activity,
+ ]
-async def test_staging_workflow_stops_when_no_sources_remain() -> None:
- execute_activity = AsyncMock(return_value=False)
+async def test_staging_workflow_finishes_empty_history_when_no_sources_remain() -> None:
+ execute_activity = AsyncMock(side_effect=[None, False, None])
- with patch.object(workflow, "execute_activity", new=execute_activity):
+ with (
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=True),
+ ):
await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
- execute_activity.assert_awaited_once()
+ assert execute_activity.await_args_list[-1].args[0] == finalize_warehouse_account_property_runs_activity
+ finalization = execute_activity.await_args_list[-1].args[1]
+ assert isinstance(finalization, FinalizeAccountPropertySyncRunsInput)
+ assert (finalization.status, finalization.phase, finalization.error) == ("completed", "completed", None)
+
+
+ "activity_results,failed_phase",
+ [
+ ([None, RuntimeError("staging failed"), None], "staging"),
+ ([None, True, RuntimeError("dispatch failed"), None], "dispatching"),
+ ],
+)
+async def test_staging_workflow_finishes_failed_history(activity_results: list[object], failed_phase: str) -> None:
+ execute_activity = AsyncMock(side_effect=activity_results)
+
+ with (
+ pytest.raises(RuntimeError),
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=True),
+ ):
+ await StageWarehouseAccountPropertiesWorkflow().run(_staging_input())
+
+ finalization = execute_activity.await_args_list[-1].args[1]
+ assert isinstance(finalization, FinalizeAccountPropertySyncRunsInput)
+ assert (finalization.status, finalization.phase) == ("failed", failed_phase)
+ assert finalization.error is not None
async def test_staging_and_dispatch_recover_from_transient_activity_failures() -> None:
attempts: list[tuple[str, int]] = []
+ @activity.defn(name="start-warehouse-account-property-runs")
+ async def start_runs(_input: DispatchAccountPropertySyncInput) -> None:
+ return None
+
@activity.defn(name="stage-warehouse-account-property-files")
async def stage_files(_input: StageAccountPropertySyncInput) -> bool:
attempt = activity.info().attempt
@@ -105,7 +167,7 @@ async def test_staging_and_dispatch_recover_from_transient_activity_failures() -
environment.client,
task_queue=task_queue,
workflows=[StageWarehouseAccountPropertiesWorkflow],
- activities=[stage_files, dispatch],
+ activities=[start_runs, stage_files, dispatch],
workflow_runner=UnsandboxedWorkflowRunner(),
):
await environment.client.execute_workflow(
@@ -127,7 +189,15 @@ async def test_dispatch_starts_missing_segment_when_its_sibling_already_runs() -
job_id="job-1",
)
- with patch("products.customer_analytics.backend.temporal.account_property_sync.async_connect", return_value=client):
+ with (
+ patch("products.customer_analytics.backend.temporal.account_property_sync.async_connect", return_value=client),
+ patch("products.customer_analytics.backend.temporal.account_property_sync.activity.info") as activity_info,
+ patch(
+ "products.customer_analytics.backend.temporal.account_property_sync.update_account_property_sync_runs_phase"
+ ),
+ ):
+ activity_info.return_value.attempt = 1
+ activity_info.return_value.workflow_id = "stage-workflow-job-1"
await dispatch_warehouse_account_property_sync_activity(input)
assert client.start_workflow.await_count == 2
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 12816ed831a3..02a5df45cdd8 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1178,11 +1178,73 @@ export interface CustomPropertyOptionApi {
}
/**
- * One person- or group-property sync or backfill run. Read-only: runs are created by the
- * sync/backfill pipeline, never through the API.
+ * * `tracked` - tracked
+ * * `ignored` - ignored
+ */
+export type AccountSegmentEnumApi = (typeof AccountSegmentEnumApi)[keyof typeof AccountSegmentEnumApi]
+
+export const AccountSegmentEnumApi = {
+ Tracked: 'tracked',
+ Ignored: 'ignored',
+} as const
+
+/**
+ * * `staging` - staging
+ * * `dispatching` - dispatching
+ * * `syncing` - syncing
+ * * `completed` - completed
+ */
+export type SyncPhaseEnumApi = (typeof SyncPhaseEnumApi)[keyof typeof SyncPhaseEnumApi]
+
+export const SyncPhaseEnumApi = {
+ Staging: 'staging',
+ Dispatching: 'dispatching',
+ Syncing: 'syncing',
+ Completed: 'completed',
+} as const
+
+/**
+ * One warehouse-backed custom property sync run.
*/
export interface CustomPropertySyncRunApi {
readonly id: string
+ /**
+ * Warehouse import or materialization job associated with the run, if any.
+ * @nullable
+ */
+ readonly job_id: string | null
+ /** Account segment processed by this run. Person and group property runs return null.
+ *
+ * * `tracked` - tracked
+ * * `ignored` - ignored */
+ readonly account_segment: AccountSegmentEnumApi | null
+ /** Current account sync phase. Person and group property runs return null.
+ *
+ * * `staging` - staging
+ * * `dispatching` - dispatching
+ * * `syncing` - syncing
+ * * `completed` - completed */
+ readonly sync_phase: SyncPhaseEnumApi | null
+ /**
+ * Latest Temporal activity attempt for the current account sync phase.
+ * @nullable
+ */
+ readonly attempt: number | null
+ /**
+ * Temporal workflow identifier associated with the current account sync phase.
+ * @nullable
+ */
+ readonly workflow_id: string | null
+ /**
+ * Temporal run identifier associated with the current account sync phase.
+ * @nullable
+ */
+ readonly workflow_run_id: string | null
+ /**
+ * Staff-only link to this run in Temporal. Null for non-staff users and runs without a Temporal ID.
+ * @nullable
+ */
+ readonly temporal_url: string | null
/** What started the run: 'scheduled' (rode a warehouse sync), 'sync' (a warehouse sync started from the UI), 'manual' (a backfill started from the UI), or 'backfill' (the automatic backfill run when a mapping is created or re-enabled). */
readonly trigger: string
/** Run status: 'running', 'completed', or 'failed'. */
@@ -1201,11 +1263,11 @@ export interface CustomPropertySyncRunApi {
readonly rows_read: number
/** Rows whose mapped values changed since the last run. */
readonly changed: number
- /** Person or group profiles updated (changed rows that matched an existing person/group). */
+ /** Changed rows that matched an existing account, person, or group. */
readonly existing: number
- /** Property-update intents produced to the ingestion pipeline. */
+ /** Property updates written or produced to the ingestion pipeline. */
readonly produced: number
- /** Changed rows dropped because no existing person/group matched the key column value. */
+ /** Changed rows skipped because no existing account, person, or group matched the key column value. */
readonly skipped_missing_person: number
/**
* Error summary if the run failed, else null.
@@ -2685,6 +2747,10 @@ export type CustomPropertySourcesRunsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Match run IDs, workflow IDs, job IDs, statuses, segments, triggers, or errors.
+ */
+ search?: string
}
export type CustomerJourneysListParams = {
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 97346de3d152..8691cfebd4e6 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -1260,9 +1260,8 @@ export const getCustomPropertySourcesRunsListUrl = (
}
/**
- * Person and group sources only: the source's sync/backfill run history, newest first. Gated
- * on the caller's warehouse-source viewer access, since the runs expose its row counts and sync
- * errors.
+ * The source's sync history, newest first. Person and group runs require viewer access to
+ * their warehouse source because the response includes row counts and sync errors.
*/
export const customPropertySourcesRunsList = async (
projectId: string,
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
index 684401bb9ac3..d2be9e26b877 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
@@ -13,11 +13,12 @@ import {
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TZLabel } from 'lib/components/TZLabel'
-import { TeamMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
import { Link } from 'lib/lemon-ui/Link'
import { Popover } from 'lib/lemon-ui/Popover'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import type {
@@ -27,6 +28,7 @@ import type {
import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { CustomPropertyModal } from './CustomPropertyModal'
+import { CustomPropertySyncRuns } from './CustomPropertySyncRuns'
import { labelForDisplayType, type SourceSyncStatusLevel, sourceSyncStatus } from './customPropertyTypes'
const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
@@ -37,14 +39,33 @@ const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
}
export function CustomPropertiesConfig(): JSX.Element {
- const { filteredDefinitions, definitionsLoading, searchTerm, targetTypeFilter } =
- useValues(customPropertyDefinitionsLogic)
- const { openCreateModal, openEditModal, deleteDefinition, setSearchTerm, setTargetTypeFilter } =
- useActions(customPropertyDefinitionsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const {
+ filteredDefinitions,
+ definitionsLoading,
+ searchTerm,
+ targetTypeFilter,
+ runsBySourceId,
+ runsCountBySourceId,
+ runsOffsetBySourceId,
+ runsSearchBySourceId,
+ runsLoadingBySourceId,
+ runsLoadFailedBySourceId,
+ } = useValues(customPropertyDefinitionsLogic)
+ const {
+ openCreateModal,
+ openEditModal,
+ deleteDefinition,
+ setSearchTerm,
+ setTargetTypeFilter,
+ setRunsSearch,
+ loadRuns,
+ } = useActions(customPropertyDefinitionsLogic)
const restrictionReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
})
+ const accountSyncHistoryEnabled = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC]
const confirmDelete = (definition: CustomPropertyDefinitionApi): void => {
LemonDialog.open({
@@ -123,7 +144,16 @@ export function CustomPropertiesConfig(): JSX.Element {
),
},
{
- title: 'Sync',
+ title: accountSyncHistoryEnabled ? (
+ <span className="flex items-center gap-1">
+ Sync
+ <Tooltip title="Expand a warehouse-backed account property to see staging, retries, and account updates.">
+ <IconInfo className="text-secondary" />
+ </Tooltip>
+ </span>
+ ) : (
+ 'Sync'
+ ),
render: (_, definition) => {
if (definition.is_canonical) {
return <span className="text-secondary">Auto</span>
@@ -212,6 +242,59 @@ export function CustomPropertiesConfig(): JSX.Element {
loading={definitionsLoading}
rowKey="id"
pagination={{ pageSize: 20, hideOnSinglePage: true }}
+ expandable={{
+ rowExpandable: (definition) =>
+ accountSyncHistoryEnabled &&
+ definition.target_type === 'account' &&
+ !!definition.source?.saved_query,
+ onRowExpand: (definition) => definition.source && loadRuns({ sourceId: definition.source.id }),
+ noIndent: true,
+ expandedRowRender: (definition) =>
+ definition.source ? (
+ <CustomPropertySyncRuns
+ runs={runsBySourceId[definition.source.id] ?? []}
+ loading={runsLoadingBySourceId[definition.source.id] ?? false}
+ loadFailed={runsLoadFailedBySourceId[definition.source.id] ?? false}
+ targetType="account"
+ searchTerm={runsSearchBySourceId[definition.source.id] ?? ''}
+ entryCount={runsCountBySourceId[definition.source.id] ?? 0}
+ currentPage={Math.floor((runsOffsetBySourceId[definition.source.id] ?? 0) / 20) + 1}
+ onSearch={(searchTerm) => {
+ if (definition.source) {
+ setRunsSearch({ sourceId: definition.source.id, searchTerm })
+ }
+ }}
+ onForward={() => {
+ if (definition.source) {
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: (runsOffsetBySourceId[definition.source.id] ?? 0) + 20,
+ })
+ }
+ }}
+ onBackward={() => {
+ if (definition.source) {
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: Math.max((runsOffsetBySourceId[definition.source.id] ?? 0) - 20, 0),
+ })
+ }
+ }}
+ syncsUrl={
+ definition.source.saved_query
+ ? urls.sqlEditor({ view_id: definition.source.saved_query })
+ : null
+ }
+ onReload={() =>
+ definition.source &&
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: runsOffsetBySourceId[definition.source.id] ?? 0,
+ })
+ }
+ />
+ ) : null,
+ }}
emptyState={
searchTerm || targetTypeFilter !== 'all'
? 'No custom properties match your filters.'
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.stories.tsx
new file mode 100644
index 000000000000..0ce3b73ac3d3
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.stories.tsx
@@ -0,0 +1,85 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { CustomPropertySyncRunApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { CustomPropertySyncRuns } from './CustomPropertySyncRuns'
+
+const accountRuns: CustomPropertySyncRunApi[] = [
+ {
+ id: '01890000-0000-0000-0000-0000000000c1',
+ job_id: '019f0000-0000-7000-8000-000000000001',
+ account_segment: 'tracked',
+ sync_phase: 'completed',
+ attempt: 1,
+ workflow_id: 'sync-warehouse-account-properties-job-1-tracked',
+ workflow_run_id: '01890000-0000-4000-8000-0000000000d1',
+ temporal_url:
+ 'https://temporal.example.com/namespaces/default/workflows/sync-warehouse-account-properties-job-1-tracked/01890000-0000-4000-8000-0000000000d1',
+ trigger: 'scheduled',
+ status: 'completed',
+ started_at: '2026-08-21T14:29:00Z',
+ finished_at: '2026-08-21T14:30:00Z',
+ rows_read: 4210,
+ changed: 118,
+ existing: 112,
+ produced: 112,
+ skipped_missing_person: 6,
+ error: null,
+ created_at: '2026-08-21T14:29:00Z',
+ },
+ {
+ id: '01890000-0000-0000-0000-0000000000c2',
+ job_id: '019f0000-0000-7000-8000-000000000001',
+ account_segment: 'ignored',
+ sync_phase: 'staging',
+ attempt: 3,
+ workflow_id: 'stage-warehouse-account-properties-job-1',
+ workflow_run_id: '01890000-0000-4000-8000-0000000000d2',
+ temporal_url: null,
+ trigger: 'scheduled',
+ status: 'failed',
+ started_at: '2026-08-21T14:29:00Z',
+ finished_at: '2026-08-21T14:35:00Z',
+ rows_read: 0,
+ changed: 0,
+ existing: 0,
+ produced: 0,
+ skipped_missing_person: 0,
+ error: "Couldn't prepare warehouse rows. Run the source view again. If it keeps failing, contact support.",
+ created_at: '2026-08-21T14:29:00Z',
+ },
+]
+
+const meta: Meta<typeof CustomPropertySyncRuns> = {
+ title: 'Customer analytics/Custom property sync runs',
+ component: CustomPropertySyncRuns,
+ args: {
+ runs: accountRuns,
+ loading: false,
+ loadFailed: false,
+ targetType: 'account',
+ syncsUrl: null,
+ searchTerm: '',
+ entryCount: accountRuns.length,
+ currentPage: 1,
+ onSearch: () => undefined,
+ onForward: () => undefined,
+ onBackward: () => undefined,
+ onReload: () => undefined,
+ },
+ parameters: {
+ layout: 'padded',
+ mockDate: '2026-08-21T15:00:00Z',
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof CustomPropertySyncRuns>
+
+export const AccountLifecycle: Story = {}
+
+export const Loading: Story = {
+ args: { runs: [], loading: true },
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx
new file mode 100644
index 000000000000..8ed14876b494
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertySyncRuns.tsx
@@ -0,0 +1,318 @@
+import { IconExternal, IconRefresh } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonInput,
+ LemonTable,
+ LemonTableColumns,
+ Spinner,
+ Tooltip,
+} from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { Link } from 'lib/lemon-ui/Link'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+
+import type { CustomPropertySyncRunApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { runOutcomeNote } from './customPropertyTypes'
+
+const TAG_TYPE_BY_RUN_STATUS: Record<string, LemonTagType> = {
+ completed: 'success',
+ running: 'primary',
+ failed: 'danger',
+}
+
+const RUN_STATUS_LABELS: Record<string, string> = {
+ completed: 'Completed',
+ running: 'Running',
+ failed: 'Failed',
+}
+
+const RUN_TRIGGERS: Record<string, { label: string; type: LemonTagType }> = {
+ scheduled: { label: 'Scheduled', type: 'default' },
+ sync: { label: 'Sync now', type: 'option' },
+ manual: { label: 'Backfill', type: 'option' },
+ backfill: { label: 'Auto backfill', type: 'default' },
+}
+
+const ACCOUNT_SEGMENT_LABELS: Record<string, string> = {
+ tracked: 'Tracked',
+ ignored: 'Ignored',
+}
+
+type TargetType = 'account' | 'person' | 'group'
+
+type TargetLabels = {
+ entity: string
+ entityPlural: string
+}
+
+const TARGET_LABELS: Record<TargetType, TargetLabels> = {
+ account: { entity: 'account', entityPlural: 'accounts' },
+ person: { entity: 'person', entityPlural: 'people' },
+ group: { entity: 'group', entityPlural: 'groups' },
+}
+
+function RunCount({ value }: { value: number }): JSX.Element {
+ return <span className={value ? 'font-medium' : 'text-secondary'}>{humanFriendlyNumber(value)}</span>
+}
+
+function runDuration(run: CustomPropertySyncRunApi): string {
+ if (!run.started_at || !run.finished_at) {
+ return '-'
+ }
+ const seconds = Math.max((new Date(run.finished_at).getTime() - new Date(run.started_at).getTime()) / 1000, 0)
+ return humanFriendlyDuration(seconds, { maxUnits: 2 })
+}
+
+function updatedShare(existing: number, changed: number): string | null {
+ if (changed <= 0) {
+ return null
+ }
+ if (existing >= changed) {
+ return '100%'
+ }
+ const share = existing / changed
+ if (share < 0.01) {
+ return '<1%'
+ }
+ return percentage(Math.min(share, 0.99), 0)
+}
+
+export interface CustomPropertySyncRunsProps {
+ runs: CustomPropertySyncRunApi[]
+ loading: boolean
+ loadFailed: boolean
+ targetType: TargetType
+ syncsUrl?: string | null
+ searchTerm: string
+ entryCount: number
+ currentPage: number
+ onSearch: (searchTerm: string) => void
+ onForward: () => void
+ onBackward: () => void
+ onReload: () => void
+}
+
+export function CustomPropertySyncRuns({
+ runs,
+ loading,
+ loadFailed,
+ targetType,
+ syncsUrl,
+ searchTerm,
+ entryCount,
+ currentPage,
+ onSearch,
+ onForward,
+ onBackward,
+ onReload,
+}: CustomPropertySyncRunsProps): JSX.Element {
+ const labels = TARGET_LABELS[targetType]
+ const accountRuns = targetType === 'account'
+
+ if (loadFailed) {
+ return (
+ <div className="w-full p-4">
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: onReload }}>
+ Couldn't load run history.
+ </LemonBanner>
+ </div>
+ )
+ }
+
+ const columns: LemonTableColumns<CustomPropertySyncRunApi> = [
+ {
+ title: 'Status',
+ tooltip: accountRuns
+ ? 'Whether this account segment finished. A completed run can update zero accounts when no mapped values changed.'
+ : 'Whether the run finished. A completed run can update nobody when no mapped values changed.',
+ render: (_, run) => {
+ const note = runOutcomeNote(run, labels.entityPlural)
+ return (
+ <div className="flex items-center gap-2">
+ <Tooltip title={run.error ?? undefined}>
+ <LemonTag
+ type={TAG_TYPE_BY_RUN_STATUS[run.status] ?? 'default'}
+ icon={run.status === 'running' ? <Spinner /> : undefined}
+ >
+ {RUN_STATUS_LABELS[run.status] ?? run.status}
+ </LemonTag>
+ </Tooltip>
+ {note && (
+ <Tooltip title={note.tooltip}>
+ <span className="text-secondary text-xs whitespace-nowrap">{note.label}</span>
+ </Tooltip>
+ )}
+ </div>
+ )
+ },
+ },
+ ]
+
+ if (accountRuns) {
+ columns.push({
+ title: 'Segment',
+ tooltip:
+ 'Tracked and ignored accounts run separately. Ignored accounts stay in sync because a property change can make them tracked later.',
+ render: (_, run) =>
+ run.account_segment ? (
+ <LemonTag type="muted">
+ {ACCOUNT_SEGMENT_LABELS[run.account_segment] ?? run.account_segment}
+ </LemonTag>
+ ) : (
+ <span className="text-secondary">-</span>
+ ),
+ })
+ } else {
+ columns.push({
+ title: 'Trigger',
+ tooltip: 'What started the run: the table schedule, Sync now, or Backfill.',
+ render: (_, run) => {
+ const trigger = RUN_TRIGGERS[run.trigger]
+ return <LemonTag type={trigger?.type ?? 'default'}>{trigger?.label ?? run.trigger}</LemonTag>
+ },
+ })
+ }
+
+ columns.push(
+ {
+ title: 'Rows read',
+ tooltip: accountRuns
+ ? 'Rows read from the materialized view snapshot for this account segment.'
+ : 'Warehouse rows this sync staged.',
+ align: 'right',
+ render: (_, run) => <RunCount value={run.rows_read} />,
+ },
+ {
+ title: 'Updated',
+ tooltip: `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed.`,
+ align: 'right',
+ render: (_, run) => {
+ const share = updatedShare(run.existing, run.changed)
+ return (
+ <span className="whitespace-nowrap">
+ <RunCount value={run.existing} />
+ <span className="text-secondary">
+ {' '}
+ of {humanFriendlyNumber(run.changed)} changed{share ? ` (${share})` : ''}
+ </span>
+ </span>
+ )
+ },
+ }
+ )
+
+ if (accountRuns) {
+ columns.push({
+ title: 'Run',
+ tooltip: 'The materialization job for this update. Share this identifier when asking support for help.',
+ render: (_, run) => {
+ if (!run.workflow_run_id) {
+ return <span className="text-secondary">-</span>
+ }
+ const runId = <code>{run.workflow_run_id.slice(0, 8)}</code>
+ return (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-1">
+ <span>Temporal run: {run.workflow_run_id}</span>
+ {run.workflow_id && <span>Workflow: {run.workflow_id}</span>}
+ {run.job_id && <span>Job: {run.job_id}</span>}
+ {(run.attempt ?? 0) > 1 && <span>Attempt: {run.attempt}</span>}
+ </div>
+ }
+ >
+ {run.temporal_url ? (
+ <Link to={run.temporal_url} target="_blank">
+ {runId}
+ </Link>
+ ) : (
+ runId
+ )}
+ </Tooltip>
+ )
+ },
+ })
+ }
+
+ columns.push(
+ {
+ title: 'Duration',
+ render: (_, run) => runDuration(run),
+ },
+ {
+ title: 'Finished',
+ render: (_, run) =>
+ run.finished_at ? <TZLabel time={run.finished_at} /> : <span className="text-secondary">-</span>,
+ }
+ )
+
+ if (syncsUrl) {
+ columns.push({
+ title: '',
+ width: 0,
+ render: () => (
+ <LemonButton
+ size="small"
+ icon={<IconExternal />}
+ to={syncsUrl}
+ targetBlank
+ tooltip="Open the source's warehouse history"
+ />
+ ),
+ })
+ }
+
+ return (
+ <div className="flex w-full flex-col gap-2 p-4">
+ <div className="flex items-center gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Refresh runs"
+ onClick={onReload}
+ loading={loading}
+ // Pinned because autocapture dashboards and browser tests use this interaction name.
+ data-attr="custom-property-sync-runs-refresh"
+ />
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder="Search runs"
+ value={searchTerm}
+ onChange={onSearch}
+ className="w-full max-w-sm"
+ />
+ </div>
+ <LemonTable
+ columns={columns}
+ dataSource={runs}
+ loading={loading}
+ rowKey="id"
+ size="small"
+ nouns={['run', 'runs']}
+ pagination={{
+ controlled: true,
+ pageSize: 20,
+ currentPage,
+ entryCount,
+ onForward,
+ onBackward,
+ hideOnSinglePage: true,
+ }}
+ emptyState={
+ searchTerm
+ ? 'No runs match your search.'
+ : accountRuns
+ ? 'No runs yet. Run the source view to start a sync.'
+ : 'No runs yet. Sync or backfill the source to start a run.'
+ }
+ />
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
index be51f7f95aee..44155db2389a 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconExternal, IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
+import { IconPencil, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
@@ -8,18 +8,18 @@ import { TZLabel } from 'lib/components/TZLabel'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
-import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import type {
CustomPropertyDefinitionApi,
CustomPropertySourceApi,
- CustomPropertySyncRunApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { CustomPropertyTargetType, customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { CustomPropertyModal } from './CustomPropertyModal'
-import { type SourceSyncStatusLevel, runOutcomeNote, sourceSyncStatus } from './customPropertyTypes'
+import { CustomPropertySyncRuns } from './CustomPropertySyncRuns'
+import { type SourceSyncStatusLevel, sourceSyncStatus } from './customPropertyTypes'
const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
synced: 'success',
@@ -28,21 +28,6 @@ const TAG_TYPE_BY_SYNC_LEVEL: Record<SourceSyncStatusLevel, LemonTagType> = {
pending: 'default',
}
-const TAG_TYPE_BY_RUN_STATUS: Record<string, LemonTagType> = {
- completed: 'success',
- running: 'primary',
- failed: 'danger',
-}
-
-// The stored trigger values, as something a person reading their run history can act on. 'manual' is
-// the Backfill button; 'backfill' is the one the system runs itself when a mapping is set up.
-const RUN_TRIGGERS: Record<string, { label: string; type: LemonTagType }> = {
- scheduled: { label: 'Scheduled', type: 'default' },
- sync: { label: 'Sync now', type: 'option' },
- manual: { label: 'Backfill', type: 'option' },
- backfill: { label: 'Auto backfill', type: 'default' },
-}
-
// Labels that differ between the person- and group-target views of the same warehouse-sync machinery.
type ProfileLabels = { entity: string; entityPlural: string; keyColumn: string }
const LABELS_BY_TARGET: Record<'person' | 'group', ProfileLabels> = {
@@ -50,26 +35,6 @@ const LABELS_BY_TARGET: Record<'person' | 'group', ProfileLabels> = {
group: { entity: 'group', entityPlural: 'groups', keyColumn: 'Group key column' },
}
-function RunCount({ value }: { value: number }): JSX.Element {
- return <span className={value ? 'font-medium' : 'text-secondary'}>{humanFriendlyNumber(value)}</span>
-}
-
-// The updated share, as a whole percent. 100% has to mean every changed row landed, so a near-miss
-// stays at 99% instead of rounding up, and a tiny share reads as <1% instead of collapsing to 0%.
-function updatedShare(existing: number, changed: number): string | null {
- if (changed <= 0) {
- return null
- }
- if (existing >= changed) {
- return '100%'
- }
- const share = existing / changed
- if (share < 0.01) {
- return '<1%'
- }
- return percentage(Math.min(share, 0.99), 0)
-}
-
// Whether the source reads a materialized view rather than a synced table.
function bindsAView(source: CustomPropertySourceApi): boolean {
return !!source.saved_query && !source.external_data_schema
@@ -87,133 +52,22 @@ function sourceRunsUrl(source: CustomPropertySourceApi): string | null {
return urls.dataWarehouseSourceSchema(source.external_data_source, source.external_data_schema, 'syncs')
}
-// Run history for one source, loaded lazily when its row is expanded. `syncsUrl` points at the
-// warehouse table's own sync history, where a run that rode a failing import shows the real error.
-function ProfilePropertyRuns({
- sourceId,
- labels,
- syncsUrl,
-}: {
- sourceId: string
- labels: ProfileLabels
- syncsUrl: string | null
-}): JSX.Element {
- const { runsBySourceId, runsLoadingBySourceId } = useValues(customPropertyDefinitionsLogic)
- const runs = runsBySourceId[sourceId] ?? []
-
- const columns: LemonTableColumns<CustomPropertySyncRunApi> = [
- {
- title: 'Status',
- tooltip:
- 'Whether the run finished. A completed run that updated nobody is normal: a sync only looks at rows the warehouse import itself changed.',
- render: (_, run) => {
- const note = runOutcomeNote(run, labels.entityPlural)
- return (
- <div className="flex items-center gap-2">
- <Tooltip title={run.error ?? undefined}>
- <LemonTag
- type={TAG_TYPE_BY_RUN_STATUS[run.status] ?? 'default'}
- icon={run.status === 'running' ? <Spinner /> : undefined}
- >
- {run.status}
- </LemonTag>
- </Tooltip>
- {note && (
- <Tooltip title={note.tooltip}>
- <span className="text-secondary text-xs whitespace-nowrap">{note.label}</span>
- </Tooltip>
- )}
- </div>
- )
- },
- },
- {
- title: 'Trigger',
- tooltip: 'What started the run: the table\'s sync schedule, or a "Sync now" or "Backfill" you asked for.',
- render: (_, run) => {
- const trigger = RUN_TRIGGERS[run.trigger]
- return <LemonTag type={trigger?.type ?? 'default'}>{trigger?.label ?? run.trigger}</LemonTag>
- },
- },
- {
- title: 'Rows read',
- tooltip:
- 'Warehouse rows this sync staged. A sync only stages rows the import itself added or changed, so a quiet table reads zero.',
- align: 'right',
- render: (_, run) => <RunCount value={run.rows_read} />,
- },
- {
- title: 'Updated',
- tooltip: `How many ${labels.entityPlural} this run updated, out of the rows whose mapped values changed. Rows that already hold the values last sent are skipped, even on a full refresh.`,
- align: 'right',
- render: (_, run) => {
- const share = updatedShare(run.existing, run.changed)
- return (
- <span className="whitespace-nowrap">
- <RunCount value={run.existing} />
- <span className="text-secondary">
- {' '}
- of {humanFriendlyNumber(run.changed)} changed{share ? ` (${share})` : ''}
- </span>
- </span>
- )
- },
- },
- {
- title: `Skipped (no ${labels.entity})`,
- tooltip: `Changed rows dropped because their key column value matched no existing ${labels.entity}. The most common reason a property never shows up.`,
- align: 'right',
- render: (_, run) => (
- <span className="text-secondary">{humanFriendlyNumber(run.skipped_missing_person)}</span>
- ),
- },
- {
- title: 'Started',
- render: (_, run) =>
- run.started_at ? <TZLabel time={run.started_at} /> : <span className="text-secondary">—</span>,
- },
- {
- title: 'Finished',
- render: (_, run) =>
- run.finished_at ? <TZLabel time={run.finished_at} /> : <span className="text-secondary">—</span>,
- },
- ]
-
- if (syncsUrl) {
- columns.push({
- title: '',
- width: 0,
- render: () => (
- <LemonButton
- size="small"
- icon={<IconExternal />}
- to={syncsUrl}
- targetBlank
- tooltip="Open this table's sync history in the data warehouse to see import errors"
- />
- ),
- })
- }
-
- return (
- <LemonTable
- columns={columns}
- dataSource={runs}
- loading={runsLoadingBySourceId[sourceId] ?? false}
- rowKey="id"
- size="small"
- nouns={['run', 'runs']}
- emptyState="No runs yet."
- />
- )
-}
-
// First-class Customer analytics view of the warehouse → person/group property sources: manages the
// column mappings, shows the next scheduled sync, lets you trigger a sync or backfill, and expands to
// run history. Parametrized by target so the person and group settings entries share one implementation.
function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person' | 'group' }): JSX.Element {
- const { definitions, definitionsInitialLoading, triggeringSourceIds } = useValues(customPropertyDefinitionsLogic)
- const { openCreateModal, openEditModal, deleteDefinition, triggerSync, triggerBackfill, loadRuns } =
+ const {
+ definitions,
+ definitionsInitialLoading,
+ triggeringSourceIds,
+ runsBySourceId,
+ runsCountBySourceId,
+ runsOffsetBySourceId,
+ runsSearchBySourceId,
+ runsLoadingBySourceId,
+ runsLoadFailedBySourceId,
+ } = useValues(customPropertyDefinitionsLogic)
+ const { openCreateModal, openEditModal, deleteDefinition, triggerSync, triggerBackfill, setRunsSearch, loadRuns } =
useActions(customPropertyDefinitionsLogic)
const restrictionReason = useRestrictedArea({
scope: RestrictionScope.Project,
@@ -417,12 +271,46 @@ function WarehouseProfilePropertiesSetting({ targetType }: { targetType: 'person
expandable={{
rowExpandable: (definition) => !!definition.source,
onRowExpand: (definition) => definition.source && loadRuns({ sourceId: definition.source.id }),
+ noIndent: true,
expandedRowRender: (definition) =>
definition.source ? (
- <ProfilePropertyRuns
- sourceId={definition.source.id}
- labels={labels}
+ <CustomPropertySyncRuns
+ runs={runsBySourceId[definition.source.id] ?? []}
+ loading={runsLoadingBySourceId[definition.source.id] ?? false}
+ loadFailed={runsLoadFailedBySourceId[definition.source.id] ?? false}
+ targetType={targetType}
+ searchTerm={runsSearchBySourceId[definition.source.id] ?? ''}
+ entryCount={runsCountBySourceId[definition.source.id] ?? 0}
+ currentPage={Math.floor((runsOffsetBySourceId[definition.source.id] ?? 0) / 20) + 1}
+ onSearch={(searchTerm) => {
+ if (definition.source) {
+ setRunsSearch({ sourceId: definition.source.id, searchTerm })
+ }
+ }}
+ onForward={() => {
+ if (definition.source) {
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: (runsOffsetBySourceId[definition.source.id] ?? 0) + 20,
+ })
+ }
+ }}
+ onBackward={() => {
+ if (definition.source) {
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: Math.max((runsOffsetBySourceId[definition.source.id] ?? 0) - 20, 0),
+ })
+ }
+ }}
syncsUrl={sourceRunsUrl(definition.source)}
+ onReload={() =>
+ definition.source &&
+ loadRuns({
+ sourceId: definition.source.id,
+ offset: runsOffsetBySourceId[definition.source.id] ?? 0,
+ })
+ }
/>
) : null,
}}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 6331969f90fb..40928398c3fb 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -256,7 +256,11 @@ export interface customPropertyDefinitionsLogicValues {
personPropertyDefinitionsLoading: boolean
profileSourceBinding: ProfileSourceBinding | null
runsBySourceId: Record<string, CustomPropertySyncRunApi[]>
+ runsCountBySourceId: Record<string, number>
+ runsLoadFailedBySourceId: Record<string, boolean>
runsLoadingBySourceId: Record<string, boolean>
+ runsOffsetBySourceId: Record<string, number>
+ runsSearchBySourceId: Record<string, string>
savedQueries: DataWarehouseSavedQuery[]
savedQueriesLoading: boolean
searchTerm: string
@@ -348,7 +352,8 @@ export interface customPropertyDefinitionsLogicActions {
personPropertyDefinitions: PropertyDefinition[]
payload?: any
}
- loadRuns: ({ sourceId }: { sourceId: string }) => {
+ loadRuns: ({ sourceId, offset }: { offset?: number; sourceId: string }) => {
+ offset: number
sourceId: string
}
loadSavedQueries: () => any
@@ -433,7 +438,19 @@ export interface customPropertyDefinitionsLogicActions {
runsLoadFailed: ({ sourceId }: { sourceId: string }) => {
sourceId: string
}
- runsLoaded: ({ sourceId, runs }: { runs: CustomPropertySyncRunApi[]; sourceId: string }) => {
+ runsLoaded: ({
+ sourceId,
+ runs,
+ count,
+ offset,
+ }: {
+ count: number
+ offset: number
+ runs: CustomPropertySyncRunApi[]
+ sourceId: string
+ }) => {
+ count: number
+ offset: number
runs: CustomPropertySyncRunApi[]
sourceId: string
}
@@ -453,6 +470,10 @@ export interface customPropertyDefinitionsLogicActions {
setEditingDefinition: (definition: CustomPropertyDefinitionApi) => {
definition: CustomPropertyDefinitionApi
}
+ setRunsSearch: ({ sourceId, searchTerm }: { searchTerm: string; sourceId: string }) => {
+ searchTerm: string
+ sourceId: string
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -577,10 +598,24 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
removeTriggeringSource: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
// Run history per source (lazy on row-expand), driven by explicit actions so loading state is
// tracked per source rather than one shared loader boolean.
- loadRuns: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
- runsLoaded: ({ sourceId, runs }: { sourceId: string; runs: CustomPropertySyncRunApi[] }) => ({
+ loadRuns: ({ sourceId, offset }: { sourceId: string; offset?: number }) => ({
+ sourceId,
+ offset: offset ?? 0,
+ }),
+ runsLoaded: ({
sourceId,
runs,
+ count,
+ offset,
+ }: {
+ sourceId: string
+ runs: CustomPropertySyncRunApi[]
+ count: number
+ offset: number
+ }) => ({ sourceId, runs, count, offset }),
+ setRunsSearch: ({ sourceId, searchTerm }: { sourceId: string; searchTerm: string }) => ({
+ sourceId,
+ searchTerm,
}),
runsLoadFailed: ({ sourceId }: { sourceId: string }) => ({ sourceId }),
// Poll definitions/runs after a trigger until the source's run settles, so the buttons and
@@ -647,13 +682,39 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
removeTriggeringSource: (state, { sourceId }) => state.filter((id) => id !== sourceId),
},
],
- // Sync/backfill run history per person source, loaded lazily when a row is expanded.
+ // Sync run history per source, loaded lazily when a row is expanded.
runsBySourceId: [
{} as Record<string, CustomPropertySyncRunApi[]>,
{
runsLoaded: (state, { sourceId, runs }) => ({ ...state, [sourceId]: runs }),
},
],
+ runsCountBySourceId: [
+ {} as Record<string, number>,
+ {
+ runsLoaded: (state, { sourceId, count }) => ({ ...state, [sourceId]: count }),
+ },
+ ],
+ runsOffsetBySourceId: [
+ {} as Record<string, number>,
+ {
+ runsLoaded: (state, { sourceId, offset }) => ({ ...state, [sourceId]: offset }),
+ },
+ ],
+ runsSearchBySourceId: [
+ {} as Record<string, string>,
+ {
+ setRunsSearch: (state, { sourceId, searchTerm }) => ({ ...state, [sourceId]: searchTerm }),
+ },
+ ],
+ runsLoadFailedBySourceId: [
+ {} as Record<string, boolean>,
+ {
+ loadRuns: (state, { sourceId }) => ({ ...state, [sourceId]: false }),
+ runsLoaded: (state, { sourceId }) => ({ ...state, [sourceId]: false }),
+ runsLoadFailed: (state, { sourceId }) => ({ ...state, [sourceId]: true }),
+ },
+ ],
// Per-source loading flag so expanding one row's history doesn't spin every expanded row.
runsLoadingBySourceId: [
{} as Record<string, boolean>,
@@ -1132,6 +1193,10 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
],
}),
listeners(({ actions, values, cache }) => ({
+ setRunsSearch: async ({ sourceId }, breakpoint) => {
+ await breakpoint(300)
+ actions.loadRuns({ sourceId, offset: 0 })
+ },
mapAllColumns: () => {
if (!values.mappableColumns.length) {
return
@@ -1324,14 +1389,18 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
actions.removeTriggeringSource({ sourceId })
}
},
- loadRuns: async ({ sourceId }) => {
+ loadRuns: async ({ sourceId, offset }) => {
try {
- const response = await customPropertySourcesRunsList(String(values.currentProjectId), sourceId)
- actions.runsLoaded({ sourceId, runs: response.results })
+ const search = values.runsSearchBySourceId[sourceId]?.trim()
+ const response = await customPropertySourcesRunsList(String(values.currentProjectId), sourceId, {
+ limit: 20,
+ offset,
+ ...(search ? { search } : {}),
+ })
+ actions.runsLoaded({ sourceId, runs: response.results, count: response.count, offset })
} catch (error) {
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadRuns' })
actions.runsLoadFailed({ sourceId })
- lemonToast.error('Failed to load run history')
}
},
pollRunsStatus: ({ sourceId }) => {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
index 98f79e1dc3cf..4b616eb790d1 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes.ts
@@ -132,7 +132,7 @@ export function runOutcomeNote(run: CustomPropertySyncRunApi, entityPlural: stri
if (run.rows_read === 0) {
return {
label: 'no new rows',
- tooltip: `This sync imported no rows for the table, so there was nothing to map onto ${entityPlural}.`,
+ tooltip: `This run read no warehouse rows, so there was nothing to map onto ${entityPlural}.`,
}
}
if (run.changed === 0) {
diff --git a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
index f9f57a97485d..04fe083bee38 100644
--- a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
@@ -51,6 +51,13 @@ const definitions: CustomPropertyDefinitionApi[] = [
next_sync_at: '2023-02-16T14:30:00Z',
latest_run: {
id: '01890000-0000-0000-0000-0000000000b1',
+ job_id: null,
+ account_segment: null,
+ sync_phase: null,
+ attempt: null,
+ workflow_id: null,
+ workflow_run_id: null,
+ temporal_url: null,
trigger: 'scheduled',
status: 'completed',
started_at: '2023-02-15T14:29:00Z',
@@ -160,6 +167,13 @@ const definitions: CustomPropertyDefinitionApi[] = [
next_sync_at: '2023-02-15T13:00:00Z',
latest_run: {
id: '01890000-0000-0000-0000-0000000000b4',
+ job_id: null,
+ account_segment: null,
+ sync_phase: null,
+ attempt: null,
+ workflow_id: null,
+ workflow_run_id: null,
+ temporal_url: null,
trigger: 'scheduled',
status: 'completed',
started_at: '2023-02-15T11:59:00Z',
@@ -179,6 +193,13 @@ const definitions: CustomPropertyDefinitionApi[] = [
const runs: CustomPropertySyncRunApi[] = [
{
id: '01890000-0000-0000-0000-0000000000c1',
+ job_id: null,
+ account_segment: null,
+ sync_phase: null,
+ attempt: null,
+ workflow_id: null,
+ workflow_run_id: null,
+ temporal_url: null,
trigger: 'scheduled',
status: 'completed',
started_at: '2023-02-15T14:29:00Z',
@@ -193,6 +214,13 @@ const runs: CustomPropertySyncRunApi[] = [
},
{
id: '01890000-0000-0000-0000-0000000000c2',
+ job_id: null,
+ account_segment: null,
+ sync_phase: null,
+ attempt: null,
+ workflow_id: null,
+ workflow_run_id: null,
+ temporal_url: null,
trigger: 'manual',
status: 'failed',
started_at: '2023-02-14T09:00:00Z',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f6f1e7ea8a95..f1aa250a09b9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -630,6 +630,18 @@ export namespace Schemas {
user: number;
}
+ /**
+ * * `tracked` - tracked
+ * * `ignored` - ignored
+ */
+ export type AccountSegmentEnum = typeof AccountSegmentEnum[keyof typeof AccountSegmentEnum];
+
+
+ export const AccountSegmentEnum = {
+ Tracked: 'tracked',
+ Ignored: 'ignored',
+ } as const;
+
export interface AccountSupportTicketMessage {
/** UUID of the support ticket message. */
readonly id: string;
@@ -19858,11 +19870,63 @@ export namespace Schemas {
}
/**
- * One person- or group-property sync or backfill run. Read-only: runs are created by the
- * sync/backfill pipeline, never through the API.
+ * * `staging` - staging
+ * * `dispatching` - dispatching
+ * * `syncing` - syncing
+ * * `completed` - completed
+ */
+ export type SyncPhaseEnum = typeof SyncPhaseEnum[keyof typeof SyncPhaseEnum];
+
+
+ export const SyncPhaseEnum = {
+ Staging: 'staging',
+ Dispatching: 'dispatching',
+ Syncing: 'syncing',
+ Completed: 'completed',
+ } as const;
+
+ /**
+ * One warehouse-backed custom property sync run.
*/
export interface CustomPropertySyncRun {
readonly id: string;
+ /**
+ * Warehouse import or materialization job associated with the run, if any.
+ * @nullable
+ */
+ readonly job_id: string | null;
+ /** Account segment processed by this run. Person and group property runs return null.
+ *
+ * * `tracked` - tracked
+ * * `ignored` - ignored */
+ readonly account_segment: AccountSegmentEnum | null;
+ /** Current account sync phase. Person and group property runs return null.
+ *
+ * * `staging` - staging
+ * * `dispatching` - dispatching
+ * * `syncing` - syncing
+ * * `completed` - completed */
+ readonly sync_phase: SyncPhaseEnum | null;
+ /**
+ * Latest Temporal activity attempt for the current account sync phase.
+ * @nullable
+ */
+ readonly attempt: number | null;
+ /**
+ * Temporal workflow identifier associated with the current account sync phase.
+ * @nullable
+ */
+ readonly workflow_id: string | null;
+ /**
+ * Temporal run identifier associated with the current account sync phase.
+ * @nullable
+ */
+ readonly workflow_run_id: string | null;
+ /**
+ * Staff-only link to this run in Temporal. Null for non-staff users and runs without a Temporal ID.
+ * @nullable
+ */
+ readonly temporal_url: string | null;
/** What started the run: 'scheduled' (rode a warehouse sync), 'sync' (a warehouse sync started from the UI), 'manual' (a backfill started from the UI), or 'backfill' (the automatic backfill run when a mapping is created or re-enabled). */
readonly trigger: string;
/** Run status: 'running', 'completed', or 'failed'. */
@@ -19881,11 +19945,11 @@ export namespace Schemas {
readonly rows_read: number;
/** Rows whose mapped values changed since the last run. */
readonly changed: number;
- /** Person or group profiles updated (changed rows that matched an existing person/group). */
+ /** Changed rows that matched an existing account, person, or group. */
readonly existing: number;
- /** Property-update intents produced to the ingestion pipeline. */
+ /** Property updates written or produced to the ingestion pipeline. */
readonly produced: number;
- /** Changed rows dropped because no existing person/group matched the key column value. */
+ /** Changed rows skipped because no existing account, person, or group matched the key column value. */
readonly skipped_missing_person: number;
/**
* Error summary if the run failed, else null.
@@ -88888,6 +88952,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Match run IDs, workflow IDs, job IDs, statuses, segments, triggers, or errors.
+ */
+ search?: string;
};
export type CustomerJourneysListParams = {
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 30c6f18e328c..da4e3c411ec6 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -869,9 +869,8 @@ export const CustomPropertySourcesBackfillParams = /* @__PURE__ */ zod.object({
})
/**
- * Person and group sources only: the source's sync/backfill run history, newest first. Gated
- * on the caller's warehouse-source viewer access, since the runs expose its row counts and sync
- * errors.
+ * The source's sync history, newest first. Person and group runs require viewer access to
+ * their warehouse source because the response includes row counts and sync errors.
*/
export const CustomPropertySourcesRunsListParams = /* @__PURE__ */ zod.object({
id: zod.string(),
@@ -885,6 +884,10 @@ export const CustomPropertySourcesRunsListParams = /* @__PURE__ */ zod.object({
export const CustomPropertySourcesRunsListQueryParams = /* @__PURE__ */ zod.object({
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ search: zod
+ .string()
+ .optional()
+ .describe('Match run IDs, workflow IDs, job IDs, statuses, segments, triggers, or errors.'),
})
/**
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 1a3a0f0f0acf..f4a143ab4612 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -1022,6 +1022,7 @@ const customPropertySourcesRunsList = (): ToolBase<
query: {
limit: params.limit,
offset: params.offset,
+ search: params.search,
},
})
return await withPostHogUrl(context, result, '/customer_analytics')