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): time account property sync phases (#88821)

Arthur Moreira de Deus7765441c9beb
diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.py
index c2b7d5f81305..ea713aa818e7 100644
--- a/products/customer_analytics/backend/logic/account_property_sync.py
+++ b/products/customer_analytics/backend/logic/account_property_sync.py
@@ -13,6 +13,7 @@ from uuid import UUID
import pyarrow as pa
import structlog
import pyarrow.parquet as pq
+from structlog.typing import FilteringBoundLogger
from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async
@@ -21,6 +22,7 @@ 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.data_warehouse.backend.facade.api import aget_s3_client
from products.warehouse_sources.backend.facade.hooks import WarehouseBinding
@@ -42,6 +44,15 @@ class AccountPropertySyncSegment(StrEnum):
IGNORED = "ignored"
+class AccountPropertySyncPhase(StrEnum):
+ LOAD_STATE = "load_state"
+ READ_STAGED_ROWS = "read_staged_rows"
+ DIFF_VALUES = "diff_values"
+ MATCH_ACCOUNTS = "match_accounts"
+ APPLY_VALUES = "apply_values"
+ PERSIST_STATE = "persist_state"
+
+
class AccountPropertySourceValueError(Exception):
pass
@@ -61,6 +72,27 @@ class SourceSyncState:
failed: bool = False
+def _record_phase_duration(
+ log: FilteringBoundLogger,
+ segment: AccountPropertySyncSegment,
+ phase: AccountPropertySyncPhase,
+ started_at: float,
+ details: dict[str, bool | float | int | str],
+) -> None:
+ duration_seconds = asyncio.get_running_loop().time() - started_at
+ log.info(
+ "Account-property sync phase completed",
+ phase=phase.value,
+ duration_seconds=duration_seconds,
+ **details,
+ )
+ record_account_property_sync_phase_duration(
+ phase=phase.value,
+ segment=segment.value,
+ duration_seconds=duration_seconds,
+ )
+
+
def _json_safe(value: Any) -> Any:
if value is None or isinstance(value, (str, bool, int, float)):
return value
@@ -281,9 +313,16 @@ async def run_account_property_segment_sync(
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)
+ log = logger.bind(
+ team_id=team_id,
+ saved_query_id=binding.id,
+ job_id=job_id,
+ segment=segment.value,
+ )
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:
@@ -294,14 +333,37 @@ async def run_account_property_segment_sync(
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)},
+ )
- async for rows in _iter_parquet_row_batches(team_id, binding, job_id):
+ batch_index = 0
+ batches = aiter(_iter_parquet_row_batches(team_id, binding, job_id))
+ while True:
+ phase_started_at = asyncio.get_running_loop().time()
+ try:
+ rows = await anext(batches)
+ except StopAsyncIteration:
+ break
+ _record_phase_duration(
+ log,
+ segment,
+ AccountPropertySyncPhase.READ_STAGED_ROWS,
+ phase_started_at,
+ {"batch_index": batch_index, "batch_rows": len(rows)},
+ )
counts["rows_read"] += len(rows)
for state in states:
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)
@@ -314,12 +376,36 @@ async def run_account_property_segment_sync(
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),
+ }
+ _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)
)
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
)
@@ -327,7 +413,22 @@ async def run_account_property_segment_sync(
state.failed = state.failed or applied.failed
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()
+ persisted_hashes = 0
for state in states:
if state.failed:
counts["source_errors"] += 1
@@ -339,6 +440,14 @@ async def run_account_property_segment_sync(
job_id,
state.applied_hashes,
)
+ persisted_hashes += len(state.applied_hashes)
+ _record_phase_duration(
+ log,
+ segment,
+ AccountPropertySyncPhase.PERSIST_STATE,
+ phase_started_at,
+ {"source_count": len(states), "persisted_hashes": persisted_hashes},
+ )
if counts["source_errors"]:
raise AccountPropertySourceValueError(
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 1e5d7136586d..046ff2239ecd 100644
--- a/products/customer_analytics/backend/logic/account_property_sync_test.py
+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py
@@ -8,7 +8,9 @@ import pyarrow as pa
import pyarrow.parquet as pq
from products.customer_analytics.backend.logic.account_property_sync import (
+ AccountPropertySyncPhase,
AccountPropertySyncSegment,
+ AppliedSourceValues,
_iter_parquet_row_batches,
_mark_completed_and_maybe_cleanup,
_matching_account_ids,
@@ -94,6 +96,44 @@ async def test_each_staged_batch_is_shared_across_sources() -> None:
assert batch_calls == 1
+async def test_sync_records_each_phase_duration() -> None:
+ binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
+ source = MagicMock()
+ source.id = "source-1"
+ source.key_column = "organization_id"
+ source.source_column = "value"
+ phase_duration_recorder = MagicMock()
+
+ async def batches(*args):
+ yield [{"organization_id": "org-1", "value": 1}]
+
+ 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}._apply_source_values",
+ return_value=AppliedSourceValues(written=1, hashes={"org-1": "hash"}, failed=False),
+ ),
+ patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),
+ patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),
+ 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,
+ )
+
+ assert [call.kwargs["phase"] for call in phase_duration_recorder.call_args_list] == [
+ phase.value for phase in AccountPropertySyncPhase
+ ]
+
+
@pytest.mark.asyncio
async def test_staged_parquet_is_decoded_in_bounded_batches() -> None:
binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")
diff --git a/products/customer_analytics/backend/metrics.py b/products/customer_analytics/backend/metrics.py
index 9a0032d99ed2..c89084ed0f6a 100644
--- a/products/customer_analytics/backend/metrics.py
+++ b/products/customer_analytics/backend/metrics.py
@@ -46,8 +46,23 @@ _ACCOUNT_TRACK_RULE_OLDEST_SUCCESS_AGE_SECONDS = Gauge(
"customer_analytics_account_track_rule_oldest_success_age_seconds",
"Oldest success, first-attempt, or enablement age among enabled Account Track Rule teams",
)
+_ACCOUNT_PROPERTY_SYNC_PHASE_DURATION_SECONDS = Histogram(
+ "customer_analytics_account_property_sync_phase_duration_seconds",
+ "Account property sync operation duration by phase and segment",
+ labelnames=["phase", "segment"],
+ buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 15, 30, 60, 120, 300, 600, 1_800, 3_600),
+)
_otel = OtelInstrumentFactory("customer-analytics-account-track-rules")
+_account_property_sync_otel = OtelInstrumentFactory("customer-analytics-account-property-sync")
+
+
+def record_account_property_sync_phase_duration(*, phase: str, segment: str, duration_seconds: float) -> None:
+ labels = {"phase": phase, "segment": segment}
+ _ACCOUNT_PROPERTY_SYNC_PHASE_DURATION_SECONDS.labels(**labels).observe(duration_seconds)
+ _account_property_sync_otel.record_histogram_twin(
+ _ACCOUNT_PROPERTY_SYNC_PHASE_DURATION_SECONDS, duration_seconds, labels
+ )
def record_account_track_rule_run(