:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(marketing-analytics): time the precompute warmer phases (#106302)
Lucas Ricoy7995d25ab1f9
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex fa512fc9a827..0ae92253fca4 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -1753,6 +1753,7 @@ def ensure_precomputed()def _run_manual_insert(t: Team, job: PreaggregationJob) -> int:+ print_start = time.monotonic()insert_sql, values = _build_manual_insert_sql(team=t,job=job,@@ -1761,6 +1762,7 @@ def ensure_precomputed(base_placeholders=base_placeholders,modifiers=modifiers,)+ print_end = time.monotonic()set_ch_query_started(job.id)tag_kwargs: dict = {"client_query_id": str(job.id),@@ -1770,14 +1772,27 @@ def ensure_precomputed(}if query_type:tag_kwargs["query_type"] = query_type+ execute_start = time.monotonic()with tags_context(**tag_kwargs):- return _written_rows(+ rows_written = _written_rows(sync_execute(insert_sql,values,settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk, read_after_write=read_after_write),))+ # Splits the job's insert_duration_ms: printing builds the team's HogQL database, which can cost+ # as much as the ClickHouse INSERT itself.+ logger.info(+ "lazy_computation.insert_phases",+ team_id=t.id,+ job_id=str(job.id),+ table=str(table),+ print_ms=round((print_end - print_start) * 1000),+ setup_ms=round((execute_start - print_end) * 1000),+ execute_ms=round((time.monotonic() - execute_start) * 1000),+ )+ return rows_written# A caller can hand in a fully-built TtlSchedule (e.g. one carrying a max_window_days# cap) to bound job width — "switch the schedule"; otherwise parse int/dict as usual.diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.pyindex 47f1a90b50e6..631b785609eb 100644--- a/products/marketing_analytics/dags/marketing_precompute.py+++ b/products/marketing_analytics/dags/marketing_precompute.py@@ -32,8 +32,9 @@ only. `MARKETING_PRECOMPUTE_ACTIVE_DAYS` tunes the `auto` activity window."""import os+import timefrom collections.abc import Callable-from concurrent.futures import ThreadPoolExecutor+from concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import UTC, datetime, timedeltafrom functools import partialfrom typing import NamedTuple@@ -241,10 +242,18 @@ def _ensure_chunks("""table_label = table.valuefailures = 0+ chunks = 0+ build_seconds = 0.0+ ensure_seconds = 0.0+ started = time.monotonic()for chunk_start, chunk_end in chunk_ranges(start, end, chunk_days):+ chunks += 1+ build_started = time.monotonic()insert_query = build_insert_query()+ build_seconds += time.monotonic() - build_startedif insert_query is None:continue # source can't materialize this chunk (deterministic) — nothing to warm+ ensure_started = time.monotonic()try:result = ensure_precomputed(team=team,@@ -255,12 +264,14 @@ def _ensure_chunks(table=table,)except Exception:+ ensure_seconds += time.monotonic() - ensure_startedMARKETING_PRECOMPUTE_CHUNK_FAILED.labels(table=table_label, error_type="exception").inc()context.log.exception(f"marketing_precompute_failed team={team.pk} table={table_label} chunk=[{chunk_start}, {chunk_end})")failures += 1continue+ ensure_seconds += time.monotonic() - ensure_startedif result.ready:MARKETING_PRECOMPUTE_CHUNK_DONE.labels(table=table_label).inc()@@ -271,6 +282,11 @@ def _ensure_chunks(f"chunk=[{chunk_start}, {chunk_end}) errors={result.errors}")failures += 1+ context.log.info(+ f"marketing_precompute_table_timing team={team.pk} table={table_label} chunks={chunks} "+ f"failures={failures} wall_ms={round((time.monotonic() - started) * 1000)} "+ f"build_query_ms={round(build_seconds * 1000)} ensure_ms={round(ensure_seconds * 1000)}"+ )return failures@@ -483,6 +499,7 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: daconversion_teams = 0costs_teams = 0failures = 0+ started = time.monotonic()try:# Conversions and costs are independent products behind independent flags — isolate each so a# failure in one (e.g. Database.create_for on a broken warehouse source) still lets the other run.@@ -529,6 +546,10 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: dafailures += 1finally:connections.close_all()+ context.log.info(+ f"marketing_precompute_team_timing team={team.pk} goals={len(plan.conversion_goals)} "+ f"warm_costs={plan.warm_costs} failures={failures} wall_ms={round((time.monotonic() - started) * 1000)}"+ )return _WarmCounts(conversion_teams, costs_teams, failures)@@ -572,6 +593,7 @@ def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[# threads do only ClickHouse warming (no Django ORM). Setup failures are counted here.failures = 0plans: list[_TeamWarmPlan] = []+ plan_started = time.monotonic()for team in teams:plan = _plan_team(team)if plan is None:@@ -580,14 +602,25 @@ def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[plans.append(plan)concurrency = int(os.getenv(TEAM_CONCURRENCY_ENV_VAR, str(DEFAULT_TEAM_CONCURRENCY)))+ context.log.info(+ f"marketing_precompute_planned plans={len(plans)} concurrency={concurrency} "+ f"plan_ms={round((time.monotonic() - plan_started) * 1000)}"+ )conversion_teams = 0costs_teams = 0if plans:+ warm_started = time.monotonic()with ThreadPoolExecutor(max_workers=max(1, min(concurrency, len(plans))), thread_name_prefix="ma_warm") as pool:- for conv_inc, costs_inc, fail_inc in pool.map(lambda plan: _warm_team(context, plan, end), plans):+ futures = [pool.submit(_warm_team, context, plan, end) for plan in plans]+ for done, future in enumerate(as_completed(futures), start=1):+ conv_inc, costs_inc, fail_inc = future.result()conversion_teams += conv_inccosts_teams += costs_incfailures += fail_inc+ context.log.info(+ f"marketing_precompute_progress done={done}/{len(plans)} "+ f"elapsed_s={round(time.monotonic() - warm_started)}"+ )context.log.info(f"marketing_precompute_complete teams={len(teams)} conversion_teams={conversion_teams} "