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): track account property sync lifecycle (#119578)

Arthur Moreira de Deus50cfba9e80ac
diff --git a/products/customer_analytics/backend/facade/temporal_contracts.py b/products/customer_analytics/backend/facade/temporal_contracts.py
index 0cf71caaedca..dc36a9f2afcc 100644
--- a/products/customer_analytics/backend/facade/temporal_contracts.py
+++ b/products/customer_analytics/backend/facade/temporal_contracts.py
@@ -1,3 +1,5 @@
+from typing import Literal
+
from posthog.dataclasses import frozen
@@ -33,3 +35,17 @@ class AccountPropertySyncInput:
saved_query_id: str
job_id: str
segment: str
+
+
+@frozen
+class AccountPropertySegmentTelemetryInput:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+ segment: str
+ path: Literal["legacy", "fanout"]
+ status: Literal["completed", "failed", "cancelled"]
+ duration_seconds: float
+ source_count: int | None = None
+ counts: dict[str, int] | None = None
+ error_type: str | None = None
diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.py
index f7df3d0cbe23..2008ab9c4ef5 100644
--- a/products/customer_analytics/backend/logic/account_property_sync.py
+++ b/products/customer_analytics/backend/logic/account_property_sync.py
@@ -64,7 +64,9 @@ class AccountPropertySyncPhase(StrEnum):
class AccountPropertySourceValueError(Exception):
- pass
+ def __init__(self, message: str, *, counts: dict[str, int]) -> None:
+ super().__init__(message)
+ self.counts = counts.copy()
@frozen
@@ -384,7 +386,7 @@ async def run_account_property_segment_sync(
job_id=job_id,
segment=segment.value,
)
- counts = {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0}
+ counts = {"rows_read": 0, "changed": 0, "matched": 0, "written": 0, "source_errors": 0, "source_count": 0}
states: list[SourceSyncState] = []
run_context = AccountPropertySyncRunContext(
@@ -395,12 +397,13 @@ async def run_account_property_segment_sync(
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}
+ return counts
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
]
+ counts["source_count"] = len(states)
phase_started_at = asyncio.get_running_loop().time()
for state in states:
state.prior_hashes.update(await _read_snapshot_hashes(team_id, binding, str(state.source.id), segment))
@@ -569,7 +572,8 @@ async def run_account_property_segment_sync(
if counts["source_errors"]:
raise AccountPropertySourceValueError(
- f"{counts['source_errors']} account-property source(s) contained invalid values"
+ f"{counts['source_errors']} account-property source(s) contained invalid values",
+ counts=counts,
)
await _mark_completed_and_maybe_cleanup(team_id, binding, job_id, segment)
diff --git a/products/customer_analytics/backend/logic/account_property_sync_monitoring.py b/products/customer_analytics/backend/logic/account_property_sync_monitoring.py
new file mode 100644
index 000000000000..df6becf130d2
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_sync_monitoring.py
@@ -0,0 +1,237 @@
+"""Best-effort lifecycle telemetry for warehouse account-property syncs.
+
+Every call emits one `warehouse_account_property_sync` product event and mirrors a few
+low-cardinality SDK metrics. Telemetry never raises into the sync and never blocks it:
+events go through `ph_background_capture()` because `ph_scoped_capture()` flushes
+synchronously on every call, which stalls a long-lived Temporal worker. Metrics use the
+SDK path because `OtelInstrumentFactory` binds a no-op meter on the worker deployments.
+
+Call this from activities, not from workflow code. A call inside a workflow is dropped,
+because a workflow replay would otherwise send the same event again.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+import math
+from collections.abc import Mapping
+from typing import Final, Literal, get_args
+
+import structlog
+import posthoganalytics
+
+from posthog.ph_client import ph_background_capture
+from posthog.utils import get_instance_region
+
+from products.customer_analytics.backend.models.custom_property_sync_run import SyncSegment
+
+logger = structlog.get_logger(__name__)
+
+ACCOUNT_PROPERTY_SYNC_EVENT: Final = "warehouse_account_property_sync"
+
+AccountPropertySyncPath = Literal["legacy", "fanout"]
+AccountPropertySyncScope = Literal["attempt", "segment"]
+AccountPropertySyncStatus = Literal["started", "completed", "failed", "cancelled"]
+
+ATTEMPTS_METRIC: Final = "customer_analytics.account_property_sync.attempts"
+SEGMENTS_METRIC: Final = "customer_analytics.account_property_sync.segments"
+ATTEMPT_DURATION_METRIC: Final = "customer_analytics.account_property_sync.attempt.duration"
+SEGMENT_DURATION_METRIC: Final = "customer_analytics.account_property_sync.segment.duration"
+SEGMENT_SOURCES_METRIC: Final = "customer_analytics.account_property_sync.segment.sources"
+ROWS_METRIC: Final = "customer_analytics.account_property_sync.rows"
+SOURCE_ERRORS_METRIC: Final = "customer_analytics.account_property_sync.source_errors"
+
+_PATHS: Final = frozenset(get_args(AccountPropertySyncPath))
+_SCOPES: Final = frozenset(get_args(AccountPropertySyncScope))
+_STATUSES: Final = frozenset(get_args(AccountPropertySyncStatus))
+_TERMINAL_STATUSES: Final = frozenset({"completed", "failed", "cancelled"})
+_SEGMENTS: Final = frozenset(SyncSegment.values)
+_UNKNOWN_SEGMENT: Final = "unknown"
+
+# Maps the counter keys that the sync returns to (event property, metric `kind` attribute).
+# Any other key is dropped, so a future counter can't leak an unreviewed value into telemetry.
+_ROW_COUNTERS: Final[Mapping[str, tuple[str, str]]] = {
+ "rows_read": ("rows_read", "read"),
+ "changed": ("rows_changed", "changed"),
+ "matched": ("rows_matched", "matched"),
+ "written": ("rows_written", "written"),
+}
+_SOURCE_ERRORS_COUNTER: Final = "source_errors"
+
+# An exception class name, optionally module-qualified. Anything else (for example
+# `str(error)`) can carry customer values, so it is replaced instead of sent.
+_ERROR_TYPE_PATTERN: Final = re.compile(r"[A-Za-z_][A-Za-z0-9_.]{0,127}")
+_INVALID_ERROR_TYPE: Final = "invalid"
+
+
+def capture_account_property_sync_event(
+ *,
+ team_id: int,
+ saved_query_id: str,
+ job_id: str,
+ segment: str,
+ path: AccountPropertySyncPath,
+ scope: AccountPropertySyncScope,
+ status: AccountPropertySyncStatus,
+ source_id: str | None = None,
+ duration_seconds: float | None = None,
+ attempt: int | None = None,
+ source_count: int | None = None,
+ counts: Mapping[str, int] | None = None,
+ error_type: str | None = None,
+ workflow_id: str | None = None,
+ workflow_run_id: str | None = None,
+) -> None:
+ if path not in _PATHS or scope not in _SCOPES or status not in _STATUSES:
+ # Log the field names only. The rejected values come from callers and stay out of logs.
+ logger.warning(
+ "account_property_sync_event_rejected",
+ path_valid=path in _PATHS,
+ scope_valid=scope in _SCOPES,
+ status_valid=status in _STATUSES,
+ )
+ return
+ try:
+ if _in_workflow():
+ return
+ normalized_segment = str(segment) if str(segment) in _SEGMENTS else _UNKNOWN_SEGMENT
+ valid_duration = _non_negative_float(duration_seconds)
+ valid_attempt = _non_negative_int(attempt) or None
+ valid_source_count = _non_negative_int(source_count)
+ valid_counts = _valid_counts(counts)
+ except Exception as error:
+ logger.warning("account_property_sync_event_rejected", error_type=type(error).__name__)
+ return
+
+ try:
+ properties: dict[str, object] = {
+ "$process_person_profile": False,
+ "team_id": int(team_id),
+ "region": get_instance_region() or "unknown",
+ "saved_query_id": str(saved_query_id),
+ "job_id": str(job_id),
+ "segment": normalized_segment,
+ "path": path,
+ "scope": scope,
+ "status": status,
+ }
+ optional_properties: dict[str, object | None] = {
+ "source_id": None if source_id is None else str(source_id),
+ "attempt": valid_attempt,
+ "is_retry": None if valid_attempt is None else valid_attempt > 1,
+ "source_count": valid_source_count,
+ "duration_seconds": valid_duration,
+ "error_type": _safe_error_type(error_type),
+ "workflow_id": None if workflow_id is None else str(workflow_id),
+ "workflow_run_id": None if workflow_run_id is None else str(workflow_run_id),
+ }
+ properties.update({key: value for key, value in optional_properties.items() if value is not None})
+ for counter, (event_property, _kind) in _ROW_COUNTERS.items():
+ if counter in valid_counts:
+ properties[event_property] = valid_counts[counter]
+ if _SOURCE_ERRORS_COUNTER in valid_counts:
+ properties["source_errors"] = valid_counts[_SOURCE_ERRORS_COUNTER]
+
+ ph_background_capture()(
+ distinct_id=f"warehouse_account_property_sync_team_{int(team_id)}",
+ event=ACCOUNT_PROPERTY_SYNC_EVENT,
+ properties=properties,
+ )
+ except Exception as error:
+ # No exc_info: a traceback can render locals, and those include the caller's IDs and counts.
+ logger.warning("account_property_sync_event_capture_failed", error_type=type(error).__name__)
+
+ try:
+ _record_metrics(
+ attributes={"path": path, "segment": normalized_segment, "status": status},
+ scope=scope,
+ attempt=valid_attempt,
+ duration_seconds=valid_duration,
+ source_count=valid_source_count,
+ counts=valid_counts,
+ )
+ except Exception as error:
+ logger.warning("account_property_sync_metrics_failed", error_type=type(error).__name__)
+
+
+def _record_metrics(
+ *,
+ attributes: dict[str, str],
+ scope: AccountPropertySyncScope,
+ attempt: int | None,
+ duration_seconds: float | None,
+ source_count: int | None,
+ counts: Mapping[str, int],
+) -> None:
+ client = posthoganalytics.default_client
+ metrics = getattr(client, "metrics", None) if client is not None else None
+ if metrics is None:
+ return
+ terminal = attributes["status"] in _TERMINAL_STATUSES
+
+ if scope == "segment":
+ metrics.count(SEGMENTS_METRIC, 1, unit="{segment}", attributes=dict(attributes))
+ if terminal and duration_seconds is not None:
+ metrics.histogram(SEGMENT_DURATION_METRIC, duration_seconds, unit="s", attributes=dict(attributes))
+ if terminal and source_count is not None:
+ metrics.histogram(SEGMENT_SOURCES_METRIC, source_count, unit="{source}", attributes=dict(attributes))
+ return
+
+ is_retry = "unknown" if attempt is None else str(attempt > 1).lower()
+ metrics.count(ATTEMPTS_METRIC, 1, unit="{attempt}", attributes={**attributes, "is_retry": is_retry})
+ if not terminal:
+ return
+ if duration_seconds is not None:
+ metrics.histogram(ATTEMPT_DURATION_METRIC, duration_seconds, unit="s", attributes=dict(attributes))
+ # Row counters come from attempts only. Segment events may carry the summed counts of
+ # the same attempts, so counting both scopes would double the totals.
+ for counter, (_event_property, kind) in _ROW_COUNTERS.items():
+ if counter in counts:
+ metrics.count(ROWS_METRIC, counts[counter], unit="{row}", attributes={**attributes, "kind": kind})
+ if _SOURCE_ERRORS_COUNTER in counts:
+ metrics.count(
+ SOURCE_ERRORS_METRIC, counts[_SOURCE_ERRORS_COUNTER], unit="{source}", attributes=dict(attributes)
+ )
+
+
+def _in_workflow() -> bool:
+ # Being in a workflow implies temporalio is already imported, so this check keeps the
+ # Temporal SDK off the import path of web and Celery callers.
+ if "temporalio" not in sys.modules:
+ return False
+
+ from temporalio import workflow # noqa: PLC0415 to keep the Temporal SDK off non-worker import paths
+
+ return workflow.in_workflow()
+
+
+def _non_negative_int(value: object) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int):
+ return None
+ return value if value >= 0 else None
+
+
+def _non_negative_float(value: object) -> float | None:
+ if not isinstance(value, int | float) or isinstance(value, bool):
+ return None
+ number = float(value)
+ return number if math.isfinite(number) and number >= 0 else None
+
+
+def _valid_counts(counts: Mapping[str, int] | None) -> dict[str, int]:
+ if not counts:
+ return {}
+ allowed = (*_ROW_COUNTERS, _SOURCE_ERRORS_COUNTER)
+ valid: dict[str, int] = {}
+ for key in allowed:
+ value = _non_negative_int(counts.get(key))
+ if value is not None:
+ valid[key] = value
+ return valid
+
+
+def _safe_error_type(error_type: str | None) -> str | None:
+ if error_type is None:
+ return None
+ return error_type if _ERROR_TYPE_PATTERN.fullmatch(error_type) else _INVALID_ERROR_TYPE
diff --git a/products/customer_analytics/backend/logic/account_property_sync_monitoring_test.py b/products/customer_analytics/backend/logic/account_property_sync_monitoring_test.py
new file mode 100644
index 000000000000..96dc7ecfa477
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_property_sync_monitoring_test.py
@@ -0,0 +1,336 @@
+import json
+from collections.abc import Iterator
+from dataclasses import asdict
+from typing import Any, Literal
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.dataclasses import frozen
+from posthog.ph_client import ScopedCapture
+
+from products.customer_analytics.backend.logic.account_property_sync_monitoring import (
+ capture_account_property_sync_event,
+)
+
+MODULE = "products.customer_analytics.backend.logic.account_property_sync_monitoring"
+
+REQUIRED: dict[str, Any] = {
+ "team_id": 42,
+ "saved_query_id": "view-0001",
+ "job_id": "job-0001",
+ "segment": "tracked",
+}
+ALLOWED_METRIC_ATTRIBUTES = {
+ "path": {"legacy", "fanout"},
+ "segment": {"tracked", "ignored", "unknown"},
+ "status": {"started", "completed", "failed", "cancelled"},
+ "is_retry": {"true", "false", "unknown"},
+ "kind": {"read", "changed", "matched", "written"},
+}
+
+
+@frozen
+class _MetricCall:
+ instrument: Literal["count", "histogram"]
+ name: str
+ value: float
+ unit: str | None
+ attributes: dict[str, str]
+
+
+class TestCaptureAccountPropertySyncEvent:
+ @pytest.fixture(autouse=True)
+ def sinks(self) -> Iterator[None]:
+ self.capture = MagicMock()
+ self.client = MagicMock()
+ with (
+ patch(f"{MODULE}.ph_background_capture", return_value=self.capture) as background,
+ patch(f"{MODULE}.posthoganalytics.default_client", self.client),
+ ):
+ self.background = background
+ yield
+
+ def _metric_calls(self) -> list[_MetricCall]:
+ instruments: tuple[tuple[Literal["count", "histogram"], MagicMock], ...] = (
+ ("count", self.client.metrics.count),
+ ("histogram", self.client.metrics.histogram),
+ )
+ return [
+ _MetricCall(
+ instrument=instrument,
+ name=c.args[0],
+ value=c.args[1],
+ unit=c.kwargs["unit"],
+ attributes=c.kwargs["attributes"],
+ )
+ for instrument, mock in instruments
+ for c in mock.call_args_list
+ ]
+
+ @parameterized.expand(
+ [
+ (
+ "fanout_attempt_with_every_optional_field",
+ {
+ "path": "fanout",
+ "scope": "attempt",
+ "status": "failed",
+ "source_id": "source-0001",
+ "duration_seconds": 12.5,
+ "attempt": 2,
+ "source_count": 3,
+ "counts": {"rows_read": 10, "changed": 4, "matched": 3, "written": 2, "source_errors": 1},
+ "error_type": "ApplicationError",
+ "workflow_id": "wf-0001",
+ "workflow_run_id": "run-0001",
+ },
+ {
+ "path": "fanout",
+ "scope": "attempt",
+ "status": "failed",
+ "source_id": "source-0001",
+ "duration_seconds": 12.5,
+ "attempt": 2,
+ "is_retry": True,
+ "source_count": 3,
+ "rows_read": 10,
+ "rows_changed": 4,
+ "rows_matched": 3,
+ "rows_written": 2,
+ "source_errors": 1,
+ "error_type": "ApplicationError",
+ "workflow_id": "wf-0001",
+ "workflow_run_id": "run-0001",
+ },
+ "US",
+ ),
+ (
+ "legacy_segment_without_optional_fields",
+ {"path": "legacy", "scope": "segment", "status": "started"},
+ {"path": "legacy", "scope": "segment", "status": "started"},
+ "EU",
+ ),
+ ]
+ )
+ def test_emits_personless_event_with_only_provided_fields(
+ self, _name: str, kwargs: dict[str, Any], expected_properties: dict[str, Any], region: str
+ ) -> None:
+ with override_settings(CLOUD_DEPLOYMENT=region):
+ capture_account_property_sync_event(**REQUIRED, **kwargs)
+
+ self.capture.assert_called_once_with(
+ distinct_id="warehouse_account_property_sync_team_42",
+ event="warehouse_account_property_sync",
+ properties={
+ "$process_person_profile": False,
+ "team_id": 42,
+ "region": region,
+ "saved_query_id": "view-0001",
+ "job_id": "job-0001",
+ "segment": "tracked",
+ **expected_properties,
+ },
+ )
+
+ def test_drops_untrusted_values_before_they_reach_any_sink(self) -> None:
+ capture_account_property_sync_event(
+ team_id=42,
+ saved_query_id="view-0001",
+ job_id="job-0001",
+ segment="acme-secret-segment",
+ path="fanout",
+ scope="attempt",
+ status="failed",
+ duration_seconds=float("nan"),
+ attempt=0,
+ source_count=-1,
+ counts={"rows_read": -5, "changed": True, "matched": 3, "customer_value": 99, "[email protected]": 1},
+ error_type="ValueError: invalid value '[email protected]' for property plan",
+ )
+
+ properties = self.capture.call_args.kwargs["properties"]
+ assert properties["segment"] == "unknown"
+ assert properties["error_type"] == "invalid"
+ assert properties["rows_matched"] == 3
+ for absent in ("duration_seconds", "attempt", "is_retry", "source_count", "rows_read", "rows_changed"):
+ assert absent not in properties
+ emitted = json.dumps([properties, [asdict(c) for c in self._metric_calls()]]).lower()
+ for leaked in ("acme", "customer_value", "invalid value", "nan", "99"):
+ assert leaked not in emitted
+
+ @parameterized.expand(
+ [
+ ("path", {"path": "shadow", "scope": "attempt", "status": "completed"}),
+ ("scope", {"path": "legacy", "scope": "source", "status": "completed"}),
+ ("status", {"path": "legacy", "scope": "attempt", "status": "succeeded"}),
+ ]
+ )
+ def test_rejects_values_outside_the_enums(self, _name: str, kwargs: dict[str, Any]) -> None:
+ capture_account_property_sync_event(**REQUIRED, **kwargs)
+
+ self.background.assert_not_called()
+ assert self._metric_calls() == []
+
+ @parameterized.expand(
+ [
+ ("background_client_unavailable", "background", "event"),
+ ("event_enqueue_fails", "capture", "event"),
+ ("metric_record_fails", "metrics", "metrics"),
+ ]
+ )
+ def test_sink_failures_never_raise_and_spare_the_other_sink(
+ self, _name: str, failing: str, failed_sink: str
+ ) -> None:
+ error = RuntimeError("token phx_fake_secret leaked")
+ {
+ "background": self.background,
+ "capture": self.capture,
+ "metrics": self.client.metrics.count,
+ }[failing].side_effect = error
+
+ with patch(f"{MODULE}.logger") as logger:
+ capture_account_property_sync_event(**REQUIRED, path="legacy", scope="attempt", status="completed")
+
+ assert (self.capture.called if failed_sink == "metrics" else self.client.metrics.count.called) is True
+ logger.warning.assert_called_once()
+ assert "phx_fake_secret" not in str(logger.warning.call_args)
+
+ @parameterized.expand(
+ [
+ (
+ "terminal_attempt",
+ {
+ "path": "fanout",
+ "scope": "attempt",
+ "status": "completed",
+ "attempt": 1,
+ "duration_seconds": 3.5,
+ "source_count": 3,
+ "counts": {"rows_read": 10, "changed": 4, "matched": 3, "written": 2, "source_errors": 1},
+ },
+ [
+ _MetricCall(
+ instrument="count",
+ name="customer_analytics.account_property_sync.attempts",
+ value=1,
+ unit="{attempt}",
+ attributes={"path": "fanout", "segment": "tracked", "status": "completed", "is_retry": "false"},
+ ),
+ *[
+ _MetricCall(
+ instrument="count",
+ name="customer_analytics.account_property_sync.rows",
+ value=value,
+ unit="{row}",
+ attributes={"path": "fanout", "segment": "tracked", "status": "completed", "kind": kind},
+ )
+ for kind, value in (("read", 10), ("changed", 4), ("matched", 3), ("written", 2))
+ ],
+ _MetricCall(
+ instrument="count",
+ name="customer_analytics.account_property_sync.source_errors",
+ value=1,
+ unit="{source}",
+ attributes={"path": "fanout", "segment": "tracked", "status": "completed"},
+ ),
+ _MetricCall(
+ instrument="histogram",
+ name="customer_analytics.account_property_sync.attempt.duration",
+ value=3.5,
+ unit="s",
+ attributes={"path": "fanout", "segment": "tracked", "status": "completed"},
+ ),
+ ],
+ ),
+ (
+ "started_attempt_records_no_terminal_measures",
+ {
+ "path": "legacy",
+ "scope": "attempt",
+ "status": "started",
+ "duration_seconds": 3.5,
+ "counts": {"rows_read": 10},
+ },
+ [
+ _MetricCall(
+ instrument="count",
+ name="customer_analytics.account_property_sync.attempts",
+ value=1,
+ unit="{attempt}",
+ attributes={"path": "legacy", "segment": "tracked", "status": "started", "is_retry": "unknown"},
+ ),
+ ],
+ ),
+ (
+ "terminal_segment_skips_row_counters",
+ {
+ "path": "legacy",
+ "scope": "segment",
+ "status": "cancelled",
+ "attempt": 3,
+ "duration_seconds": 61.0,
+ "source_count": 2,
+ "counts": {"rows_read": 10, "source_errors": 1},
+ },
+ [
+ _MetricCall(
+ instrument="count",
+ name="customer_analytics.account_property_sync.segments",
+ value=1,
+ unit="{segment}",
+ attributes={"path": "legacy", "segment": "tracked", "status": "cancelled"},
+ ),
+ _MetricCall(
+ instrument="histogram",
+ name="customer_analytics.account_property_sync.segment.duration",
+ value=61.0,
+ unit="s",
+ attributes={"path": "legacy", "segment": "tracked", "status": "cancelled"},
+ ),
+ _MetricCall(
+ instrument="histogram",
+ name="customer_analytics.account_property_sync.segment.sources",
+ value=2,
+ unit="{source}",
+ attributes={"path": "legacy", "segment": "tracked", "status": "cancelled"},
+ ),
+ ],
+ ),
+ ]
+ )
+ def test_records_low_cardinality_sdk_metrics(
+ self, _name: str, kwargs: dict[str, Any], expected: list[_MetricCall]
+ ) -> None:
+ capture_account_property_sync_event(
+ **REQUIRED, source_id="source-0001", workflow_id="wf-0001", workflow_run_id="run-0001", **kwargs
+ )
+
+ recorded = self._metric_calls()
+ assert recorded == expected
+ for call in recorded:
+ for key, value in call.attributes.items():
+ assert value in ALLOWED_METRIC_ATTRIBUTES[key]
+
+ def test_skips_both_sinks_inside_workflow_code(self) -> None:
+ with patch("temporalio.workflow.in_workflow", return_value=True):
+ capture_account_property_sync_event(**REQUIRED, path="fanout", scope="segment", status="completed")
+
+ self.background.assert_not_called()
+ assert self._metric_calls() == []
+
+ def test_disabled_sinks_send_nothing(self) -> None:
+ client = MagicMock()
+ self.background.return_value = ScopedCapture(client)
+
+ with (
+ patch("posthog.ph_client.is_cloud", return_value=False),
+ patch(f"{MODULE}.posthoganalytics.default_client", None),
+ ):
+ capture_account_property_sync_event(**REQUIRED, path="legacy", scope="attempt", status="completed")
+
+ assert client.mock_calls == []
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 c0e31fda93fb..1fe4071452e6 100644
--- a/products/customer_analytics/backend/logic/account_property_sync_test.py
+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py
@@ -20,6 +20,7 @@ from products.customer_analytics.backend.logic.account_property_runs import (
start_account_property_sync_runs,
)
from products.customer_analytics.backend.logic.account_property_sync import (
+ AccountPropertySourceValueError,
AccountPropertySyncPhase,
AccountPropertySyncSegment,
AppliedSourceValues,
@@ -297,14 +298,15 @@ def test_source_values_preserve_explicit_nulls_but_skip_missing_columns(rows, ex
@pytest.mark.asyncio
-async def test_each_staged_batch_is_shared_across_sources() -> None:
[email protected]("source_columns", [("value_0", "value_1"), ("value_0", None), ()])
+async def test_each_staged_batch_is_shared_across_sources(source_columns: tuple[str | None, ...]) -> None:
binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
sources = []
- for index in range(2):
+ for index, source_column in enumerate(source_columns):
source = MagicMock()
source.id = f"source-{index}"
source.key_column = "organization_id"
- source.source_column = f"value_{index}"
+ source.source_column = source_column
sources.append(source)
batch_calls = 0
@@ -324,7 +326,7 @@ async def test_each_staged_batch_is_shared_across_sources() -> None:
patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
):
- await run_account_property_segment_sync(
+ counts = await run_account_property_segment_sync(
team_id=7,
binding=binding,
job_id="job-1",
@@ -332,10 +334,12 @@ async def test_each_staged_batch_is_shared_across_sources() -> None:
)
assert batch_calls == 1
+ assert counts["source_count"] == sum(column is not None for column in source_columns)
@pytest.mark.asyncio
-async def test_sync_records_each_phase_duration() -> None:
[email protected]("invalid_source_values", [False, True])
+async def test_sync_records_each_phase_duration(invalid_source_values: bool) -> None:
binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
source = MagicMock()
source.id = "source-1"
@@ -344,17 +348,21 @@ async def test_sync_records_each_phase_duration() -> None:
phase_duration_recorder = MagicMock()
async def batches(*args):
- yield [{"organization_id": "org-1", "value": 1}]
+ yield [{"organization_id": "org-1", "value": 1}, {"organization_id": "org-2", "value": "invalid"}]
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={"org-1": MagicMock()}),
+ patch(f"{_MODULE}._matching_account_ids", return_value={"org-1": MagicMock(), "org-2": MagicMock()}),
patch(
f"{_MODULE}._apply_source_values",
- return_value=AppliedSourceValues(written=1, hashes={"org-1": "hash"}, failed=False),
+ return_value=AppliedSourceValues(
+ written=1 if invalid_source_values else 2,
+ hashes={"org-1": "hash"} if invalid_source_values else {"org-1": "hash", "org-2": "hash-2"},
+ failed=invalid_source_values,
+ ),
),
patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
@@ -362,13 +370,31 @@ async def test_sync_records_each_phase_duration() -> None:
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(
- team_id=7,
- binding=binding,
- job_id="job-1",
- segment=AccountPropertySyncSegment.TRACKED,
- )
+ if invalid_source_values:
+ with pytest.raises(AccountPropertySourceValueError) as raised:
+ await run_account_property_segment_sync(
+ team_id=7,
+ binding=binding,
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ )
+ counts = raised.value.counts
+ else:
+ counts = await run_account_property_segment_sync(
+ team_id=7,
+ binding=binding,
+ job_id="job-1",
+ segment=AccountPropertySyncSegment.TRACKED,
+ )
+ assert counts == {
+ "rows_read": 2,
+ "changed": 2,
+ "matched": 2,
+ "written": 1 if invalid_source_values else 2,
+ "source_errors": int(invalid_source_values),
+ "source_count": 1,
+ }
assert [call.kwargs["phase"] for call in phase_duration_recorder.call_args_list] == [
phase.value for phase in AccountPropertySyncPhase
]
diff --git a/products/customer_analytics/backend/temporal/account_property_sync.py b/products/customer_analytics/backend/temporal/account_property_sync.py
index 651c4a95a5f4..9e3b666d3eb0 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync.py
@@ -2,16 +2,20 @@ from __future__ import annotations
import json
import time
+import asyncio
+from typing import Literal
from temporalio import activity, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
-from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
+from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlreadyStartedError, is_cancelled_exception
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from products.customer_analytics.backend.facade.temporal_contracts import (
+ AccountPropertySegmentTelemetryInput,
AccountPropertySyncInput,
DispatchAccountPropertySyncInput,
FinalizeAccountPropertySyncRunsInput,
@@ -40,6 +44,9 @@ with workflow.unsafe.imports_passed_through():
AccountPropertySyncSegment,
run_account_property_segment_sync,
)
+ from products.customer_analytics.backend.logic.account_property_sync_monitoring import (
+ capture_account_property_sync_event,
+ )
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
@@ -49,6 +56,7 @@ 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_SEGMENT_TELEMETRY_PATCH = "account-property-segment-telemetry-2026-10"
ACCOUNT_PROPERTY_ACTIVITY_MAX_ATTEMPTS = 5
_STAGING_FAILED_ERROR = (
@@ -71,6 +79,110 @@ ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS = Histogram(
buckets=(0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),
)
+_SyncPath = Literal["legacy", "fanout"]
+_TerminalStatus = Literal["completed", "failed", "cancelled"]
+
+
+def _failure_type(error: BaseException) -> str:
+ cause = error.cause if isinstance(error, ActivityError) and error.cause is not None else error
+ if isinstance(cause, ApplicationError) and cause.type:
+ return cause.type
+ return type(cause).__name__
+
+
+def _failure_counts(error: BaseException) -> dict[str, int] | None:
+ cause = error.cause if isinstance(error, ActivityError) and error.cause is not None else error
+ if not isinstance(cause, ApplicationError) or cause.type != "AccountPropertySourceValueError":
+ return None
+ if not cause.details or not isinstance(cause.details[0], dict):
+ return None
+ return {
+ key: value
+ for key, value in cause.details[0].items()
+ if isinstance(key, str) and isinstance(value, int) and not isinstance(value, bool)
+ }
+
+
+@frozen
+class _AttemptTelemetry:
+ team_id: int
+ saved_query_id: str
+ job_id: str
+ segment: str
+ path: _SyncPath
+ source_id: str | None
+ attempt: int
+ workflow_id: str | None
+ workflow_run_id: str | None
+ started_at: float
+
+ @classmethod
+ def start(
+ cls,
+ *,
+ team_id: int,
+ saved_query_id: str,
+ job_id: str,
+ segment: str,
+ path: _SyncPath,
+ source_id: str | None = None,
+ ) -> _AttemptTelemetry:
+ info = activity.info()
+ telemetry = cls(
+ team_id=team_id,
+ saved_query_id=saved_query_id,
+ job_id=job_id,
+ segment=segment,
+ path=path,
+ source_id=source_id,
+ attempt=info.attempt,
+ workflow_id=info.workflow_id,
+ workflow_run_id=info.workflow_run_id,
+ started_at=time.monotonic(),
+ )
+ telemetry._capture("started")
+ return telemetry
+
+ def finish(
+ self,
+ status: _TerminalStatus,
+ *,
+ counts: dict[str, int] | None = None,
+ error: BaseException | None = None,
+ ) -> None:
+ self._capture(
+ status,
+ duration_seconds=time.monotonic() - self.started_at,
+ counts=counts,
+ error_type=None if error is None else type(error).__name__,
+ )
+
+ def _capture(
+ self,
+ status: Literal["started", "completed", "failed", "cancelled"],
+ *,
+ duration_seconds: float | None = None,
+ counts: dict[str, int] | None = None,
+ error_type: str | None = None,
+ ) -> None:
+ capture_account_property_sync_event(
+ team_id=self.team_id,
+ saved_query_id=self.saved_query_id,
+ job_id=self.job_id,
+ segment=self.segment,
+ path=self.path,
+ scope="attempt",
+ status=status,
+ source_id=self.source_id,
+ duration_seconds=duration_seconds,
+ attempt=self.attempt,
+ source_count=None if counts is None else counts.get("source_count"),
+ counts=counts,
+ error_type=error_type,
+ workflow_id=self.workflow_id,
+ workflow_run_id=self.workflow_run_id,
+ )
+
@activity.defn(name="start-warehouse-account-property-runs")
async def start_warehouse_account_property_runs_activity(input: DispatchAccountPropertySyncInput) -> None:
@@ -178,6 +290,17 @@ async def dispatch_warehouse_account_property_sync_activity(input: DispatchAccou
job_id=input.job_id,
segment=segment,
)
+ continue
+ capture_account_property_sync_event(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=segment,
+ path="legacy",
+ scope="segment",
+ status="started",
+ workflow_id=workflow_id,
+ )
@activity.defn
@@ -202,6 +325,13 @@ async def sync_warehouse_account_properties_activity(input: AccountPropertySyncI
job_id=input.job_id,
segment=segment.value,
)
+ telemetry = _AttemptTelemetry.start(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=segment.value,
+ path="legacy",
+ )
started = time.monotonic()
try:
async with Heartbeater():
@@ -214,20 +344,86 @@ async def sync_warehouse_account_properties_activity(input: AccountPropertySyncI
)
except AccountPropertySourceValueError as error:
ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="failed").inc()
+ telemetry.finish("failed", counts=error.counts, error=error)
log.warning("Account-property segment sync rejected invalid source values", error=str(error))
- raise ApplicationError(str(error), non_retryable=True) from error
+ raise ApplicationError(str(error), error.counts, type=type(error).__name__, non_retryable=True) from error
+ except asyncio.CancelledError:
+ telemetry.finish("cancelled")
+ raise
except Exception as error:
ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="failed").inc()
+ telemetry.finish("failed", error=error)
log.exception("Account-property segment sync failed")
capture_exception(error)
raise
ACCOUNT_PROPERTY_SYNC_TOTAL.labels(team_id=str(input.team_id), segment=segment.value, outcome="completed").inc()
ACCOUNT_PROPERTY_SYNC_DURATION_SECONDS.labels(segment=segment.value).observe(time.monotonic() - started)
+ telemetry.finish("completed", counts=result)
log.info("Account-property segment sync completed", **result)
return result
[email protected](name="emit-warehouse-account-property-segment-telemetry")
+async def emit_warehouse_account_property_segment_telemetry_activity(
+ input: AccountPropertySegmentTelemetryInput,
+) -> None:
+ activity_info = activity.info()
+ capture_account_property_sync_event(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=input.segment,
+ path=input.path,
+ scope="segment",
+ status=input.status,
+ duration_seconds=input.duration_seconds,
+ source_count=input.source_count,
+ counts=input.counts,
+ error_type=input.error_type,
+ workflow_id=activity_info.workflow_id,
+ workflow_run_id=activity_info.workflow_run_id,
+ )
+
+
+async def _emit_segment_telemetry(
+ input: AccountPropertySyncInput,
+ *,
+ path: _SyncPath,
+ status: _TerminalStatus,
+ started_at: float,
+ source_count: int | None = None,
+ counts: dict[str, int] | None = None,
+ error: BaseException | None = None,
+) -> None:
+ # Workflow code runs again on replay, so it sends the event through an activity, and it measures
+ # the duration with the deterministic workflow clock.
+ try:
+ await workflow.execute_activity(
+ emit_warehouse_account_property_segment_telemetry_activity,
+ AccountPropertySegmentTelemetryInput(
+ team_id=input.team_id,
+ saved_query_id=input.saved_query_id,
+ job_id=input.job_id,
+ segment=input.segment,
+ path=path,
+ status=status,
+ duration_seconds=max(workflow.time() - started_at, 0.0),
+ source_count=source_count,
+ counts=counts,
+ error_type=None if error is None else _failure_type(error),
+ ),
+ start_to_close_timeout=timedelta(minutes=1),
+ schedule_to_close_timeout=timedelta(minutes=3),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except ActivityError:
+ workflow.logger.warning(
+ "Account-property segment telemetry failed",
+ extra={"job_id": input.job_id, "segment": input.segment, "path": path},
+ )
+
+
@workflow.defn(name=ACCOUNT_PROPERTY_STAGING_WORKFLOW_NAME)
class StageWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
@staticmethod
@@ -327,16 +523,42 @@ class SyncWarehouseAccountPropertiesWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: AccountPropertySyncInput) -> None:
- await workflow.execute_activity(
- sync_warehouse_account_properties_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),
- ),
- )
+ # Histories recorded before the patch have no telemetry activity, so replay must skip it.
+ telemetry_enabled = workflow.patched(ACCOUNT_PROPERTY_SEGMENT_TELEMETRY_PATCH)
+ started_at = workflow.time()
+ try:
+ counts = await workflow.execute_activity(
+ sync_warehouse_account_properties_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 (asyncio.CancelledError, Exception) as error:
+ if telemetry_enabled:
+ failure_counts = _failure_counts(error)
+ await _emit_segment_telemetry(
+ input,
+ path="legacy",
+ status="cancelled" if is_cancelled_exception(error) else "failed",
+ started_at=started_at,
+ source_count=None if failure_counts is None else failure_counts.get("source_count"),
+ counts=failure_counts,
+ error=error,
+ )
+ raise
+ if telemetry_enabled:
+ await _emit_segment_telemetry(
+ input,
+ path="legacy",
+ status="completed",
+ started_at=started_at,
+ source_count=counts.get("source_count"),
+ counts=counts,
+ )
ACCOUNT_PROPERTY_SYNC_WORKFLOWS = [
@@ -349,4 +571,5 @@ ACCOUNT_PROPERTY_SYNC_ACTIVITIES = [
stage_warehouse_account_property_files_activity,
dispatch_warehouse_account_property_sync_activity,
sync_warehouse_account_properties_activity,
+ emit_warehouse_account_property_segment_telemetry_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 e0fcb0617d5b..295b0447a268 100644
--- a/products/customer_analytics/backend/temporal/account_property_sync_test.py
+++ b/products/customer_analytics/backend/temporal/account_property_sync_test.py
@@ -1,25 +1,39 @@
import uuid
+import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
+from datetime import timedelta
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from temporalio import activity, workflow
-from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.client import WorkflowFailureError
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import (
+ ActivityError,
+ ApplicationError,
+ TimeoutError,
+ TimeoutType,
+ WorkflowAlreadyStartedError,
+)
from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
from products.customer_analytics.backend.facade.temporal_contracts import (
+ AccountPropertySegmentTelemetryInput,
DispatchAccountPropertySyncInput,
FinalizeAccountPropertySyncRunsInput,
StageAccountPropertySyncInput,
)
+from products.customer_analytics.backend.logic.account_property_sync import AccountPropertySourceValueError
from products.customer_analytics.backend.temporal.account_property_sync import (
+ ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME,
AccountPropertySyncInput,
StageWarehouseAccountPropertiesWorkflow,
SyncWarehouseAccountPropertiesWorkflow,
dispatch_warehouse_account_property_sync_activity,
+ emit_warehouse_account_property_segment_telemetry_activity,
finalize_warehouse_account_property_runs_activity,
stage_warehouse_account_property_files_activity,
start_warehouse_account_property_runs_activity,
@@ -28,6 +42,24 @@ from products.customer_analytics.backend.temporal.account_property_sync import (
pytestmark = pytest.mark.asyncio
+_MODULE = "products.customer_analytics.backend.temporal.account_property_sync"
+_SOURCE_COUNTS = {"rows_read": 10, "changed": 4, "matched": 3, "written": 2, "source_errors": 0, "source_count": 2}
+_FAILED_COUNTS = {**_SOURCE_COUNTS, "written": 1, "source_errors": 1}
+
+
+def _create_activity_error(cause: Exception) -> ActivityError:
+ error = ActivityError(
+ "Activity failed",
+ scheduled_event_id=1,
+ started_event_id=2,
+ identity="worker",
+ activity_type="sync_warehouse_account_properties_activity",
+ activity_id="1",
+ retry_state=None,
+ )
+ error.__cause__ = cause
+ return error
+
def _staging_input() -> StageAccountPropertySyncInput:
return StageAccountPropertySyncInput(
@@ -39,6 +71,15 @@ def _staging_input() -> StageAccountPropertySyncInput:
)
+def _segment_input() -> AccountPropertySyncInput:
+ return AccountPropertySyncInput(
+ team_id=7,
+ saved_query_id="019f0000-0000-7000-8000-000000000001",
+ job_id="job-1",
+ segment="tracked",
+ )
+
+
@asynccontextmanager
async def _no_heartbeat() -> AsyncIterator[None]:
yield
@@ -195,28 +236,236 @@ async def test_dispatch_starts_missing_segment_when_its_sibling_already_runs() -
patch(
"products.customer_analytics.backend.temporal.account_property_sync.update_account_property_sync_runs_phase"
),
+ patch(
+ "products.customer_analytics.backend.logic.account_property_sync_monitoring.ph_background_capture"
+ ) as capture_factory,
):
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
- assert [call.args[1].segment for call in client.start_workflow.await_args_list] == ["tracked", "ignored"]
+ calls = client.start_workflow.await_args_list
+ assert [call.args[0] for call in calls] == [
+ ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME,
+ ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME,
+ ]
+ assert [call.args[1].segment for call in calls] == ["tracked", "ignored"]
+ assert [call.kwargs["id"] for call in calls] == [
+ "sync-warehouse-account-properties-job-1-tracked",
+ "sync-warehouse-account-properties-job-1-ignored",
+ ]
+ capture = capture_factory.return_value
+ capture.assert_called_once()
+ properties = capture.call_args.kwargs["properties"]
+ assert {key: properties[key] for key in ("scope", "status", "path", "segment", "workflow_id")} == {
+ "scope": "segment",
+ "status": "started",
+ "path": "legacy",
+ "segment": "ignored",
+ "workflow_id": "sync-warehouse-account-properties-job-1-ignored",
+ }
-async def test_workflow_executes_one_retryable_segment_activity() -> None:
- execute_activity = AsyncMock()
- input = AccountPropertySyncInput(
- team_id=7,
- saved_query_id="019f0000-0000-7000-8000-000000000001",
- job_id="job-1",
- segment="tracked",
+ "telemetry_enabled,sync_result,expected_status,expected_counts",
+ [
+ (False, dict(_SOURCE_COUNTS), None, None),
+ (True, dict(_SOURCE_COUNTS), "completed", _SOURCE_COUNTS),
+ (True, {"rows_read": 0}, "completed", {"rows_read": 0}),
+ (True, RuntimeError("sync failed"), "failed", None),
+ (
+ True,
+ _create_activity_error(
+ ApplicationError("Invalid values", _FAILED_COUNTS, type="AccountPropertySourceValueError")
+ ),
+ "failed",
+ _FAILED_COUNTS,
+ ),
+ ],
+)
+async def test_legacy_workflow_reports_segment_outcome_only_after_the_patch(
+ telemetry_enabled: bool,
+ sync_result: object,
+ expected_status: str | None,
+ expected_counts: dict[str, int] | None,
+) -> None:
+ execute_activity = AsyncMock(side_effect=[sync_result, None])
+ input = _segment_input()
+
+ with (
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=telemetry_enabled),
+ patch.object(workflow, "time", side_effect=[100.0, 160.0]),
+ ):
+ if isinstance(sync_result, Exception):
+ with pytest.raises(type(sync_result)) as raised:
+ await SyncWarehouseAccountPropertiesWorkflow().run(input)
+ assert raised.value is sync_result
+ else:
+ await SyncWarehouseAccountPropertiesWorkflow().run(input)
+
+ first_call = execute_activity.await_args_list[0]
+ assert first_call.args == (sync_warehouse_account_properties_activity, input)
+ assert first_call.kwargs["retry_policy"].maximum_attempts == 5
+ if expected_status is None:
+ assert execute_activity.await_count == 1
+ return
+ assert execute_activity.await_args_list[1].args[0] == emit_warehouse_account_property_segment_telemetry_activity
+ telemetry = execute_activity.await_args_list[1].args[1]
+ assert isinstance(telemetry, AccountPropertySegmentTelemetryInput)
+ assert (telemetry.path, telemetry.status, telemetry.duration_seconds) == ("legacy", expected_status, 60.0)
+ assert telemetry.counts == expected_counts
+ assert telemetry.source_count == (None if expected_counts is None else expected_counts.get("source_count"))
+ assert execute_activity.await_args_list[1].kwargs["schedule_to_close_timeout"] == timedelta(minutes=3)
+
+
[email protected]("sync_failed", [False, True])
+async def test_legacy_workflow_preserves_sync_outcome_when_telemetry_times_out(sync_failed: bool) -> None:
+ sync_result = RuntimeError("Sync failed") if sync_failed else dict(_SOURCE_COUNTS)
+ telemetry_error = _create_activity_error(
+ TimeoutError("Telemetry timed out", type=TimeoutType.SCHEDULE_TO_CLOSE, last_heartbeat_details=[])
)
+ execute_activity = AsyncMock(side_effect=[sync_result, telemetry_error])
+
+ with (
+ patch.object(workflow, "execute_activity", new=execute_activity),
+ patch.object(workflow, "patched", return_value=True),
+ patch.object(workflow, "time", side_effect=[100.0, 160.0]),
+ patch.object(workflow, "logger"),
+ ):
+ if sync_failed:
+ with pytest.raises(RuntimeError, match="Sync failed"):
+ await SyncWarehouseAccountPropertiesWorkflow().run(_segment_input())
+ else:
+ await SyncWarehouseAccountPropertiesWorkflow().run(_segment_input())
+
+
[email protected](name=ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME)
+class _PreTelemetrySyncWorkflow:
+ @workflow.run
+ async def run(self, input: AccountPropertySyncInput) -> None:
+ await workflow.execute_activity(
+ "sync_warehouse_account_properties_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)),
+ )
+
+
[email protected]("invalid_source_values", [False, True])
+async def test_legacy_workflow_replays_histories_from_before_and_after_the_telemetry_patch(
+ invalid_source_values: bool,
+) -> None:
+ telemetry_inputs: list[AccountPropertySegmentTelemetryInput] = []
+
+ @activity.defn(name="sync_warehouse_account_properties_activity")
+ async def sync_segment(_input: AccountPropertySyncInput) -> dict[str, int]:
+ if invalid_source_values:
+ raise ApplicationError(
+ "Invalid values", _FAILED_COUNTS, type="AccountPropertySourceValueError", non_retryable=True
+ )
+ return dict(_SOURCE_COUNTS)
- with patch.object(workflow, "execute_activity", new=execute_activity):
- await SyncWarehouseAccountPropertiesWorkflow().run(input)
+ @activity.defn(name="emit-warehouse-account-property-segment-telemetry")
+ async def emit_telemetry(input: AccountPropertySegmentTelemetryInput) -> None:
+ telemetry_inputs.append(input)
- execute_activity.assert_awaited_once()
- assert execute_activity.await_args is not None
- assert execute_activity.await_args.args == (sync_warehouse_account_properties_activity, input)
- assert execute_activity.await_args.kwargs["retry_policy"].maximum_attempts == 5
+ scheduled_by_recorder: dict[str, list[str]] = {}
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ for recorder in (_PreTelemetrySyncWorkflow, SyncWarehouseAccountPropertiesWorkflow):
+ task_queue = str(uuid.uuid4())
+ async with Worker(
+ environment.client,
+ task_queue=task_queue,
+ workflows=[recorder],
+ activities=[sync_segment, emit_telemetry],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await environment.client.start_workflow(
+ ACCOUNT_PROPERTY_SYNC_WORKFLOW_NAME,
+ _segment_input(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ execution_timeout=timedelta(minutes=10),
+ )
+ if invalid_source_values:
+ with pytest.raises(WorkflowFailureError):
+ await handle.result()
+ else:
+ await handle.result()
+ history = await handle.fetch_history()
+ await Replayer(
+ workflows=[SyncWarehouseAccountPropertiesWorkflow], workflow_runner=UnsandboxedWorkflowRunner()
+ ).replay_workflow(history)
+ scheduled_by_recorder[recorder.__name__] = [
+ event.activity_task_scheduled_event_attributes.activity_type.name
+ for event in history.events
+ if event.HasField("activity_task_scheduled_event_attributes")
+ ]
+
+ assert len(telemetry_inputs) == 1
+ assert telemetry_inputs[0].status == ("failed" if invalid_source_values else "completed")
+ assert telemetry_inputs[0].counts == (_FAILED_COUNTS if invalid_source_values else _SOURCE_COUNTS)
+ assert telemetry_inputs[0].source_count == 2
+ assert scheduled_by_recorder == {
+ "_PreTelemetrySyncWorkflow": ["sync_warehouse_account_properties_activity"],
+ "SyncWarehouseAccountPropertiesWorkflow": [
+ "sync_warehouse_account_properties_activity",
+ "emit-warehouse-account-property-segment-telemetry",
+ ],
+ }
+
+
+ "runtime_result,expected_status,expected_error_type",
+ [
+ (dict(_SOURCE_COUNTS), "completed", None),
+ (RuntimeError("warehouse unavailable"), "failed", "RuntimeError"),
+ (
+ AccountPropertySourceValueError("bad value", counts=_FAILED_COUNTS),
+ "failed",
+ "AccountPropertySourceValueError",
+ ),
+ (asyncio.CancelledError(), "cancelled", None),
+ ],
+)
+async def test_sync_activity_reports_attempt_lifecycle(
+ runtime_result: object, expected_status: str, expected_error_type: str | None
+) -> None:
+ runtime = AsyncMock(side_effect=[runtime_result])
+
+ with (
+ patch(f"{_MODULE}.run_account_property_segment_sync", new=runtime),
+ patch(f"{_MODULE}.capture_account_property_sync_event") as capture_event,
+ patch(f"{_MODULE}.capture_exception"),
+ patch(f"{_MODULE}.saved_query_binding"),
+ patch(f"{_MODULE}.update_account_property_sync_runs_phase"),
+ patch(f"{_MODULE}.Heartbeater", side_effect=lambda: _no_heartbeat()),
+ patch(f"{_MODULE}.activity.info") as activity_info,
+ ):
+ activity_info.return_value.attempt = 2
+ activity_info.return_value.workflow_id = "segment-workflow"
+ activity_info.return_value.workflow_run_id = "segment-run"
+ if isinstance(runtime_result, BaseException):
+ with pytest.raises(BaseException) as raised:
+ await sync_warehouse_account_properties_activity(_segment_input())
+ if isinstance(runtime_result, AccountPropertySourceValueError):
+ assert isinstance(raised.value, ApplicationError) and raised.value.non_retryable
+ assert raised.value.type == "AccountPropertySourceValueError"
+ assert raised.value.details == (_FAILED_COUNTS,)
+ else:
+ assert await sync_warehouse_account_properties_activity(_segment_input()) == runtime_result
+
+ events = [call.kwargs for call in capture_event.call_args_list]
+ assert [event["status"] for event in events] == ["started", expected_status]
+ assert {(event["path"], event["scope"], event["source_id"], event["attempt"]) for event in events} == {
+ ("legacy", "attempt", None, 2)
+ }
+ assert events[1]["error_type"] == expected_error_type
+ assert events[1]["duration_seconds"] is not None
+ expected_counts = runtime_result if isinstance(runtime_result, dict) else None
+ if isinstance(runtime_result, AccountPropertySourceValueError):
+ expected_counts = _FAILED_COUNTS
+ assert events[1]["counts"] == expected_counts
+ assert events[1]["source_count"] == (None if expected_counts is None else expected_counts["source_count"])