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(web-analytics): add dedicated eager backfill job with 24h budget (#70592)

Lucas Ricoybe1ac16d8817
diff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.py
index 9e8b252e44e4..fe023a9abe35 100644
--- a/posthog/dags/locations/web_analytics.py
+++ b/posthog/dags/locations/web_analytics.py
@@ -56,6 +56,7 @@ defs = dagster.Definitions(
web_analytics_watchdog.web_analytics_watchdog_job,
cache_warming.web_analytics_cache_warming_job,
eager_web_analytics_precompute.web_analytics_eager_baseline_warming_job,
+ eager_web_analytics_precompute.web_analytics_eager_backfill_job,
web_dimensional_precompute.web_dimensional_precompute_job,
marketing_precompute.marketing_precompute_job,
cache_favicons.cache_authorized_domain_favicons_job,
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.py
index c49562f95cc0..5d15921793ed 100644
--- a/products/web_analytics/dags/eager_web_analytics_precompute.py
+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py
@@ -82,6 +82,7 @@ from django.db.models import Max
import dagster
import pydantic
import structlog
+from dagster import DagsterRunStatus, RunsFilter
from prometheus_client import Counter
from posthog.schema import WebAnalyticsPreComputeStrategy, WebStatsBreakdown
@@ -198,12 +199,11 @@ EAGER_PRECOMPUTE_BASELINE_NOT_PRECOMPUTED = Counter(
)
-ACTIVE_AUDIENCE_LOOKBACK_HOURS = 24
# Sanity ceiling on the active-team fetch; ~9k teams open the dashboard daily.
ACTIVE_AUDIENCE_MAX_TEAMS = 20000
-def _fetch_active_wa_team_ids(limit: int) -> list[int]:
+def _fetch_active_wa_team_ids(limit: int, lookback_hours: int = 24) -> list[int]:
"""Top teams by deliberate WA dashboard activity (stats-table tile queries),
most active first. Powers the warm-audience ramp experiment via the job's
run config (`active_teams_pct`).
@@ -228,7 +228,7 @@ def _fetch_active_wa_team_ids(limit: int) -> list[int]:
ORDER BY n DESC
LIMIT %(limit)s
""",
- {"cluster": "posthog", "hours": ACTIVE_AUDIENCE_LOOKBACK_HOURS, "limit": limit},
+ {"cluster": "posthog", "hours": lookback_hours, "limit": limit},
)
return [int(row[0]) for row in rows]
except Exception:
@@ -236,7 +236,7 @@ def _fetch_active_wa_team_ids(limit: int) -> list[int]:
return []
-def _resolve_eager_audience(active_teams_pct: int = 0) -> tuple[list[int], str, dict]:
+def _resolve_eager_audience(active_teams_pct: int = 0, active_lookback_hours: int = 24) -> tuple[list[int], str, dict]:
"""Resolve the audience and return a structured trace of which gate
fired. Returns `(team_ids, gate_reason, diagnostics)`.
@@ -255,7 +255,7 @@ def _resolve_eager_audience(active_teams_pct: int = 0) -> tuple[list[int], str,
# dict.fromkeys preserves order and dedupes teams in both lists.
active_team_ids: list[int] = []
if active_teams_pct > 0:
- all_active = _fetch_active_wa_team_ids(ACTIVE_AUDIENCE_MAX_TEAMS)
+ all_active = _fetch_active_wa_team_ids(ACTIVE_AUDIENCE_MAX_TEAMS, lookback_hours=active_lookback_hours)
take = max(1, len(all_active) * min(active_teams_pct, 100) // 100) if all_active else 0
active_team_ids = all_active[:take]
@@ -431,159 +431,183 @@ class EagerWarmConfig(dagster.Config):
# 0 = static lists only; set in the run config when launching manually to ramp
# the warm-audience experiment (e.g. 5 -> 25 -> 100).
active_teams_pct: int = pydantic.Field(default=0, ge=0, le=100)
+ # Activity window used to rank/select the ramp audience. The backfill job pins a
+ # 7-day window so a run terminated at its runtime cap can be relaunched against a
+ # stable team set - a 24h window shifts between chunks and can drop the unwarmed
+ # tail of the previous run.
+ active_lookback_hours: int = pydantic.Field(default=24, ge=1, le=168)
@dagster.op
def warm_eager_baseline_op(context: dagster.OpExecutionContext, config: EagerWarmConfig) -> dict[str, int]:
"""Run the baseline tile matrix against every team in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` setting."""
started = time.monotonic()
- team_ids, gate_reason, diagnostics = _resolve_eager_audience(active_teams_pct=config.active_teams_pct)
+ # `job_name` raises DagsterInvalidPropertyError on direct op invocation (tests);
+ # only real job runs need the backfill concurrency guard anyway.
+ try:
+ job_name = context.job_name
+ except Exception:
+ job_name = None
+ if job_name == "web_analytics_eager_backfill":
+ _fail_on_concurrent_run(context)
+ team_ids, gate_reason, diagnostics = _resolve_eager_audience(
+ active_teams_pct=config.active_teams_pct, active_lookback_hours=config.active_lookback_hours
+ )
# Captured before the ramp enrollment below mutates the setting — this set is
# what "statically enrolled" means for the priority sort further down.
static_ids = {
*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,
*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,
}
+ original_enrollment = settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS
if config.active_teams_pct > 0:
- # Enroll the ramp audience for the lifetime of this run's process: the warm
- # queries route through `is_precompute_enabled_for_team`, whose org-flag
- # fallback fails closed in Dagster — without this, ramp teams would silently
- # take the RAW path and the experiment would fan heavy live queries across
- # thousands of teams instead of building precompute windows.
+ # Enroll the ramp audience for the duration of this run: the warm queries
+ # route through `is_precompute_enabled_for_team`, whose org-flag fallback
+ # fails closed in Dagster — without this, ramp teams would silently take
+ # the RAW path and the experiment would fan heavy live queries across
+ # thousands of teams instead of building precompute windows. Restored in
+ # the finally below so the enrollment can't leak into later runs if the
+ # executor ever reuses this process.
settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS = list(
dict.fromkeys([*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS, *team_ids])
)
- diag_str = " ".join(f"{k}={v}" for k, v in diagnostics.items())
- context.log.info(
- f"eager_baseline_warming_start teams={len(team_ids)} gate_reason={gate_reason} {diag_str}".rstrip()
- )
- # Mirror lifecycle events to structlog so the run is queryable in Loki /
- # PostHog. `context.log` only reaches the Dagster UI — PostHog's Dagster
- # has no python_logs sink wiring it to stdout.
- logger.info("eager_baseline_warming_start", teams=len(team_ids), gate_reason=gate_reason, **diagnostics)
+ try:
+ diag_str = " ".join(f"{k}={v}" for k, v in diagnostics.items())
+ context.log.info(
+ f"eager_baseline_warming_start teams={len(team_ids)} gate_reason={gate_reason} {diag_str}".rstrip()
+ )
+ # Mirror lifecycle events to structlog so the run is queryable in Loki /
+ # PostHog. `context.log` only reaches the Dagster UI — PostHog's Dagster
+ # has no python_logs sink wiring it to stdout.
+ logger.info("eager_baseline_warming_start", teams=len(team_ids), gate_reason=gate_reason, **diagnostics)
+
+ # Bulk-load teams once instead of N+1 per-team get().
+ teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids).select_related("organization")}
+
+ warmed = 0
+ failed = 0
+ skipped = 0
+
+ # Resolve the eligible teams up front (cheap Postgres/flag checks), then warm
+ # them with a small thread pool. Each team's tile matrix still runs
+ # sequentially inside `_warm_baseline_for_team`, so we never fire concurrent
+ # INSERTs into one team's buckets — the pool just runs several *different*
+ # teams at once to spread the ClickHouse load and cut total wall-clock.
+ eligible: list[Team] = []
+ for team_id in team_ids:
+ team = teams_by_id.get(team_id)
+ if team is None:
+ context.log.warning(f"eager_baseline_warming_team_missing team_id={team_id}")
+ logger.warning("eager_baseline_warming_team_missing", team_id=team_id)
+ skipped += 1
+ continue
+
+ # Eligibility pre-check. The audience IS the precompute team list, so a
+ # team reaching here should always be eligible. If it isn't, the gate
+ # and the warmer audience have drifted and every tile would silently
+ # warm via the raw path — skip loudly rather than burn compute on it.
+ if not is_precompute_enabled_for_team(team):
+ EAGER_PRECOMPUTE_NOT_LAZY_ELIGIBLE.inc()
+ context.log.error(
+ f"eager_baseline_warming_not_lazy_eligible team={team_id} — "
+ f"skipping; the lazy gate would route every tile through the raw path"
+ )
+ logger.error("eager_baseline_warming_not_lazy_eligible", team_id=team_id)
+ skipped += 1
+ continue
+
+ eligible.append(team)
+
+ # Warm the least-recently-computed teams first, so a run cut short by
+ # `max_runtime` still makes progress on the teams that need it most. Teams
+ # that have never been warmed (no qualifying `PreaggregationJob` row) sort to
+ # the front. One indexed aggregate, not per-team.
+ #
+ # Scope the freshness signal to READY jobs whose coverage falls inside the
+ # baseline window this DAG actually warms. `PreaggregationJob` is a shared
+ # lazy-precompute table (web analytics, marketing analytics, experiments all
+ # write it) with no product column, so this can't perfectly isolate this
+ # warmer's own jobs — but restricting to READY + the trailing window drops
+ # the bulk of the noise (old one-off date ranges, pending/failed/stale rows)
+ # that would otherwise make a team with a stale baseline look freshly warmed.
+ window_start = datetime.now(UTC) - timedelta(days=BASELINE_WINDOW_DAYS)
+ last_computed: dict[int, datetime | None] = dict(
+ PreaggregationJob.objects.filter(
+ team_id__in=[t.pk for t in eligible],
+ status=PreaggregationJob.Status.READY,
+ time_range_end__gte=window_start,
+ )
+ .values("team_id")
+ .annotate(last=Max("computed_at"))
+ .values_list("team_id", "last")
+ )
+ never_computed = datetime.min.replace(tzinfo=UTC)
+ # Two tiers: statically enrolled teams first (stalest first within the tier),
+ # then the ramp audience. A large `active_teams_pct` audience is mostly
+ # never-warmed, and a flat staleness sort would push the always-enrolled teams
+ # behind thousands of ramp teams whenever a run hits `max_runtime`.
+ # `static_ids` was captured before the ramp enrollment mutated the setting.
+ eligible.sort(key=lambda t: (t.pk not in static_ids, last_computed.get(t.pk) or never_computed))
+
+ # Running progress counter for the pool — `itertools.count.__next__` is
+ # atomic under the GIL, so it's safe to call from the worker threads. Each
+ # team's completion log carries `processed/total` as a live progress signal.
+ total = len(eligible)
+ progress = itertools.count(1)
+
+ def _warm(team: Team) -> tuple[int, int]:
+ team_started = time.monotonic()
+ team_warmed = team_failed = 0
+ try:
+ team_warmed, team_failed = _warm_baseline_for_team(context, team)
+ except Exception:
+ # `_warm_baseline_for_team` guards each tile, but a failure *outside*
+ # that loop (e.g. building the tile matrix) would otherwise propagate
+ # out of `pool.map`, abort the teams not yet iterated, and discard the
+ # counts of teams that already warmed. Contain it so the pool drains.
+ logger.exception("eager_baseline_warming_team_errored", team_id=team.pk)
+ finally:
+ # Each pool thread holds its own Django DB connections; close them on
+ # the way out so the run doesn't leak one connection per team.
+ connections.close_all()
+ logger.info(
+ "eager_baseline_warming_team",
+ team_id=team.pk,
+ warmed=team_warmed,
+ failed=team_failed,
+ processed=next(progress),
+ total=total,
+ duration_ms=round((time.monotonic() - team_started) * 1000),
+ )
+ return team_warmed, team_failed
- # Bulk-load teams once instead of N+1 per-team get().
- teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids).select_related("organization")}
+ with ThreadPoolExecutor(max_workers=WARM_TEAM_CONCURRENCY) as pool:
+ for team_warmed, team_failed in pool.map(_warm, eligible):
+ warmed += team_warmed
+ failed += team_failed
- warmed = 0
- failed = 0
- skipped = 0
-
- # Resolve the eligible teams up front (cheap Postgres/flag checks), then warm
- # them with a small thread pool. Each team's tile matrix still runs
- # sequentially inside `_warm_baseline_for_team`, so we never fire concurrent
- # INSERTs into one team's buckets — the pool just runs several *different*
- # teams at once to spread the ClickHouse load and cut total wall-clock.
- eligible: list[Team] = []
- for team_id in team_ids:
- team = teams_by_id.get(team_id)
- if team is None:
- context.log.warning(f"eager_baseline_warming_team_missing team_id={team_id}")
- logger.warning("eager_baseline_warming_team_missing", team_id=team_id)
- skipped += 1
- continue
-
- # Eligibility pre-check. The audience IS the precompute team list, so a
- # team reaching here should always be eligible. If it isn't, the gate
- # and the warmer audience have drifted and every tile would silently
- # warm via the raw path — skip loudly rather than burn compute on it.
- if not is_precompute_enabled_for_team(team):
- EAGER_PRECOMPUTE_NOT_LAZY_ELIGIBLE.inc()
- context.log.error(
- f"eager_baseline_warming_not_lazy_eligible team={team_id} — "
- f"skipping; the lazy gate would route every tile through the raw path"
- )
- logger.error("eager_baseline_warming_not_lazy_eligible", team_id=team_id)
- skipped += 1
- continue
-
- eligible.append(team)
-
- # Warm the least-recently-computed teams first, so a run cut short by
- # `max_runtime` still makes progress on the teams that need it most. Teams
- # that have never been warmed (no qualifying `PreaggregationJob` row) sort to
- # the front. One indexed aggregate, not per-team.
- #
- # Scope the freshness signal to READY jobs whose coverage falls inside the
- # baseline window this DAG actually warms. `PreaggregationJob` is a shared
- # lazy-precompute table (web analytics, marketing analytics, experiments all
- # write it) with no product column, so this can't perfectly isolate this
- # warmer's own jobs — but restricting to READY + the trailing window drops
- # the bulk of the noise (old one-off date ranges, pending/failed/stale rows)
- # that would otherwise make a team with a stale baseline look freshly warmed.
- window_start = datetime.now(UTC) - timedelta(days=BASELINE_WINDOW_DAYS)
- last_computed: dict[int, datetime | None] = dict(
- PreaggregationJob.objects.filter(
- team_id__in=[t.pk for t in eligible],
- status=PreaggregationJob.Status.READY,
- time_range_end__gte=window_start,
+ duration_ms = round((time.monotonic() - started) * 1000)
+ context.log.info(
+ f"eager_baseline_warming_complete teams={len(team_ids)} warmed={warmed} failed={failed} "
+ f"skipped={skipped} gate_reason={gate_reason} duration_ms={duration_ms}"
)
- .values("team_id")
- .annotate(last=Max("computed_at"))
- .values_list("team_id", "last")
- )
- never_computed = datetime.min.replace(tzinfo=UTC)
- # Two tiers: statically enrolled teams first (stalest first within the tier),
- # then the ramp audience. A large `active_teams_pct` audience is mostly
- # never-warmed, and a flat staleness sort would push the always-enrolled teams
- # behind thousands of ramp teams whenever a run hits `max_runtime`.
- # `static_ids` was captured before the ramp enrollment mutated the setting.
- eligible.sort(key=lambda t: (t.pk not in static_ids, last_computed.get(t.pk) or never_computed))
-
- # Running progress counter for the pool — `itertools.count.__next__` is
- # atomic under the GIL, so it's safe to call from the worker threads. Each
- # team's completion log carries `processed/total` as a live progress signal.
- total = len(eligible)
- progress = itertools.count(1)
-
- def _warm(team: Team) -> tuple[int, int]:
- team_started = time.monotonic()
- team_warmed = team_failed = 0
- try:
- team_warmed, team_failed = _warm_baseline_for_team(context, team)
- except Exception:
- # `_warm_baseline_for_team` guards each tile, but a failure *outside*
- # that loop (e.g. building the tile matrix) would otherwise propagate
- # out of `pool.map`, abort the teams not yet iterated, and discard the
- # counts of teams that already warmed. Contain it so the pool drains.
- logger.exception("eager_baseline_warming_team_errored", team_id=team.pk)
- finally:
- # Each pool thread holds its own Django DB connections; close them on
- # the way out so the run doesn't leak one connection per team.
- connections.close_all()
logger.info(
- "eager_baseline_warming_team",
- team_id=team.pk,
- warmed=team_warmed,
- failed=team_failed,
- processed=next(progress),
- total=total,
- duration_ms=round((time.monotonic() - team_started) * 1000),
+ "eager_baseline_warming_complete",
+ teams=len(team_ids),
+ warmed=warmed,
+ failed=failed,
+ skipped=skipped,
+ gate_reason=gate_reason,
+ duration_ms=duration_ms,
)
- return team_warmed, team_failed
-
- with ThreadPoolExecutor(max_workers=WARM_TEAM_CONCURRENCY) as pool:
- for team_warmed, team_failed in pool.map(_warm, eligible):
- warmed += team_warmed
- failed += team_failed
-
- duration_ms = round((time.monotonic() - started) * 1000)
- context.log.info(
- f"eager_baseline_warming_complete teams={len(team_ids)} warmed={warmed} failed={failed} "
- f"skipped={skipped} gate_reason={gate_reason} duration_ms={duration_ms}"
- )
- logger.info(
- "eager_baseline_warming_complete",
- teams=len(team_ids),
- warmed=warmed,
- failed=failed,
- skipped=skipped,
- gate_reason=gate_reason,
- duration_ms=duration_ms,
- )
- result = {"teams": len(team_ids), "warmed": warmed, "failed": failed, "skipped": skipped}
- context.add_output_metadata({**result, "gate_reason": gate_reason, "duration_ms": duration_ms, **diagnostics})
- return result
+ result = {"teams": len(team_ids), "warmed": warmed, "failed": failed, "skipped": skipped}
+ context.add_output_metadata({**result, "gate_reason": gate_reason, "duration_ms": duration_ms, **diagnostics})
+ return result
+ finally:
+ # Undo the in-run ramp enrollment so it cannot leak into later runs if
+ # the executor ever reuses this process (the hourly warmer must stay
+ # scoped to the static lists).
+ settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS = original_enrollment
@dagster.job(
@@ -611,6 +635,61 @@ def web_analytics_eager_baseline_warming_job():
warm_eager_baseline_op()
+def _fail_on_concurrent_run(context: dagster.OpExecutionContext) -> None:
+ """Fail fast when another run of the same job is already in flight.
+
+ The hourly warmer gets this from its schedule's `check_for_concurrent_runs`
+ skip, but manual launches bypass schedule evaluation entirely - two
+ simultaneous backfills would not double-insert (the pending-job unique index
+ dedupes windows) yet would burn duplicate audience fetches and coordination
+ for zero extra coverage."""
+ in_flight = context.instance.get_run_records(
+ RunsFilter(
+ job_name=context.job_name,
+ statuses=[
+ DagsterRunStatus.QUEUED,
+ DagsterRunStatus.NOT_STARTED,
+ DagsterRunStatus.STARTING,
+ DagsterRunStatus.STARTED,
+ ],
+ )
+ )
+ ours = next((r for r in in_flight if r.dagster_run.run_id == context.run_id), None)
+ # Older run wins: if two launches race, only the newer one fails, instead of
+ # both seeing each other and mutually aborting.
+ older = [
+ r
+ for r in in_flight
+ if r.dagster_run.run_id != context.run_id and (ours is None or r.create_timestamp <= ours.create_timestamp)
+ ]
+ if older:
+ raise dagster.Failure(
+ f"Another {context.job_name} run is already in flight ({older[0].dagster_run.run_id}); "
+ "wait for it or terminate it first - a concurrent backfill adds no coverage."
+ )
+
+
+ name="web_analytics_eager_backfill",
+ description=(
+ "Manual backfill of the eager baseline across the active WA audience. Same op and "
+ "per-team concurrency as the hourly warmer (WARM_TEAM_CONCURRENCY caps instantaneous "
+ "cluster pressure regardless of audience size — a bigger audience only runs longer), "
+ "but defaults to active_teams_pct=100 and gets a 24h runtime budget instead of 90min. "
+ "Fully resumable: windows built before a termination persist via their TTLs, so "
+ "relaunching skips them and continues the tail. Safe to run alongside the hourly "
+ "schedule — the pending-job unique index dedupes concurrent window builds."
+ ),
+ config={"ops": {"warm_eager_baseline_op": {"config": {"active_teams_pct": 100, "active_lookback_hours": 168}}}},
+ tags={
+ "owner": JobOwners.TEAM_WEB_ANALYTICS.value,
+ "dagster/max_runtime": str(24 * 60 * 60),
+ },
+)
+def web_analytics_eager_backfill_job():
+ warm_eager_baseline_op()
+
+
@dagster.schedule(
# DEPRECATED: being wound down — see module docstring. The plan is to stop
# this schedule and validate teams on the lazy-on-read path alone; once that