: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
fix(web-analytics): complete large conversion achievement scans (#112762)
Vasco de Krijger02eb0a975794
diff --git a/products/web_analytics/backend/achievements/backfill.py b/products/web_analytics/backend/achievements/backfill.pyindex d6e8f8e378d9..a8451c8eac87 100644--- a/products/web_analytics/backend/achievements/backfill.py+++ b/products/web_analytics/backend/achievements/backfill.py@@ -1,3 +1,4 @@+from django.db import transactionfrom django.utils import timezoneimport structlog@@ -14,6 +15,7 @@ from products.web_analytics.backend.achievements.tasks import (persist_progress,team_local_today,)+from products.web_analytics.backend.models import WebAnalyticsAchievementProgresslogger = structlog.get_logger(__name__)@@ -61,18 +63,34 @@ def _backfill_track(ctx: EvalContext, track: TrackDefinition) -> bool:except Exception:logger.warning("wa_achievements_backfill_failed", track=str(track.key), team_id=ctx.team.id, exc_info=True)return False- value = max(evaluation.value, progress.progress_value)- stage = track.stage_for_value(value, None)- seeded_at = timezone.now().isoformat()- state = dict(progress.state or {})- unlocked_stages = dict(state.get("unlocked_stages", {}))- for unlocked_stage in range(1, stage + 1):- unlocked_stages.setdefault(str(unlocked_stage), seeded_at)- state["unlocked_stages"] = unlocked_stages- state.setdefault("pending_celebrations", [])- if evaluation.checkpoint is not None:- state["checkpoint"] = evaluation.checkpoint- # Leave last_computed_at untouched so the next live recompute still runs the same day a team is- # backfilled — backfilling must not suppress real-time unlocks.- persist_progress(progress, value, max(progress.current_stage, stage), state, bump_last_computed_at=False)+ if not evaluation.complete and evaluation.checkpoint is None:+ return False+ with transaction.atomic():+ current = WebAnalyticsAchievementProgress.objects.for_team(ctx.team.id).select_for_update().get(pk=progress.pk)+ if evaluation.checkpoint is not None and (+ current.last_computed_at != progress.last_computed_at+ or (current.state or {}).get("checkpoint") != (progress.state or {}).get("checkpoint")+ ):+ return False+ if not evaluation.complete:+ state = dict(current.state or {})+ state["checkpoint"] = evaluation.checkpoint+ state["backfill_pending"] = True+ persist_progress(current, current.progress_value, current.current_stage, state, bump_last_computed_at=False)+ return True+ value = max(evaluation.value, current.progress_value)+ stage = track.stage_for_value(value, None)+ seeded_at = timezone.now().isoformat()+ state = dict(current.state or {})+ state.pop("backfill_pending", None)+ unlocked_stages = dict(state.get("unlocked_stages", {}))+ for unlocked_stage in range(1, stage + 1):+ unlocked_stages.setdefault(str(unlocked_stage), seeded_at)+ state["unlocked_stages"] = unlocked_stages+ state.setdefault("pending_celebrations", [])+ if evaluation.checkpoint is not None:+ state["checkpoint"] = evaluation.checkpoint+ # Leave last_computed_at untouched so the next live recompute still runs the same day a team is+ # backfilled — backfilling must not suppress real-time unlocks.+ persist_progress(current, value, max(current.current_stage, stage), state, bump_last_computed_at=False)return Truediff --git a/products/web_analytics/backend/achievements/evaluators.py b/products/web_analytics/backend/achievements/evaluators.pyindex ef52bb9dd4e4..414c71ce7b01 100644--- a/products/web_analytics/backend/achievements/evaluators.py+++ b/products/web_analytics/backend/achievements/evaluators.py@@ -7,12 +7,15 @@ from datetime import UTC, date, datetime, time, timedeltafrom django.utils import timezonefrom posthog.hogql import ast+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, HogQLGlobalSettingsfrom posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_stringfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.property import action_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.dataclasses import frozen+from posthog.errors import CHQueryErrorTooManyBytes+from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, ClickHouseQueryTimeOutfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -42,6 +45,7 @@ class PriorProgress:class TrackEvaluation:value: intcheckpoint: dict[str, object] | None = None+ complete: bool = Truedef _week_monday(day: date) -> date:@@ -123,7 +127,13 @@ INGESTION_LAG = timedelta(hours=1)LATE_ARRIVAL_LOOKBACK = timedelta(days=3)-def _ingestion_window_expr(since: datetime | None, until: datetime, earliest_timestamp: datetime | None) -> ast.Expr:+def _ingestion_window_expr(+ since: datetime | None,+ until: datetime,+ earliest_timestamp: datetime | None,+ latest_timestamp: datetime | None = None,+ latest_inclusive: bool = False,+) -> ast.Expr:exprs: list[ast.Expr] = [ast.CompareOperation(op=ast.CompareOperationOp.Lt, left=ast.Field(chain=["created_at"]), right=ast.Constant(value=until)@@ -143,6 +153,14 @@ def _ingestion_window_expr(since: datetime | None, until: datetime, earliest_timright=ast.Constant(value=earliest_timestamp),))+ if latest_timestamp is not None:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq if latest_inclusive else ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=latest_timestamp),+ )+ )return ast.And(exprs=exprs)@@ -167,6 +185,24 @@ def evaluate_cumulative_pageviews(ctx: EvalContext, prior: PriorProgress) -> TraCONVERSIONS_LOOKBACK_DAYS = 90+CONVERSIONS_BOOTSTRAP_CHUNK_DAYS = 7+CONVERSIONS_MAX_TIMESTAMP = datetime(2299, 12, 31, 23, 59, 59, 999999, tzinfo=UTC)+CONVERSIONS_FUTURE_CHUNK_MAX_HOURS = 24 * 365 * 50+CONVERSIONS_SCAN_LIMITS = (+ CHQueryErrorTooManyBytes,+ ClickHouseQueryTimeOut,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+)+++@frozen+class ConversionBootstrap:+ next_start: datetime+ end: datetime+ created_until: datetime+ phase: str = "initial"+ created_since: datetime | None = None+ chunk_hours: int = CONVERSIONS_BOOTSTRAP_CHUNK_DAYS * 24def _action_event_filter_expr(actions: list[Action]) -> ast.Expr:@@ -204,6 +240,255 @@ def _daily_buckets(checkpoint: dict[str, object], fingerprints: list[list[objectreturn None+def _conversion_bootstrap_state(checkpoint: dict[str, object]) -> ConversionBootstrap | None:+ bootstrap = checkpoint.get("bootstrap")+ if not isinstance(bootstrap, dict):+ return None+ next_start = parse_zoned_datetime_string(bootstrap.get("next_start"))+ end = parse_zoned_datetime_string(bootstrap.get("end"))+ created_until = parse_zoned_datetime_string(bootstrap.get("created_until"))+ phase = bootstrap.get("phase", "initial")+ created_since = parse_zoned_datetime_string(bootstrap.get("created_since"))+ chunk_hours = bootstrap.get("chunk_hours", CONVERSIONS_BOOTSTRAP_CHUNK_DAYS * 24)+ if (+ next_start is None+ or end is None+ or created_until is None+ or phase not in ("initial", "initial_future", "catchup", "catchup_future", "tail")+ or (phase in ("initial_future", "catchup_future") and not end <= next_start < CONVERSIONS_MAX_TIMESTAMP)+ or (phase not in ("initial_future", "catchup_future") and next_start >= end)+ or (phase in ("catchup", "catchup_future", "tail") and created_since is None)+ or not isinstance(chunk_hours, int)+ or not 1+ <= chunk_hours+ <= (+ CONVERSIONS_FUTURE_CHUNK_MAX_HOURS+ if phase in ("initial_future", "catchup_future")+ else CONVERSIONS_BOOTSTRAP_CHUNK_DAYS * 24+ )+ ):+ return None+ return ConversionBootstrap(+ next_start=next_start,+ end=end,+ created_until=created_until,+ phase=phase,+ created_since=created_since,+ chunk_hours=chunk_hours,+ )+++def _add_conversion_counts(+ ctx: EvalContext,+ actions: list[Action],+ daily: dict[str, list[int]],+ since: datetime | None,+ until: datetime,+ earliest_timestamp: datetime,+ latest_timestamp: datetime | None = None,+ latest_inclusive: bool = False,+) -> bool:+ chunk_daily: dict[str, list[int]] = {}+ for team in _project_environment_teams(ctx.team):+ query = parse_select(+ "SELECT toDate(toTimeZone(timestamp, 'UTC')) AS day FROM events WHERE and({window}, {events}, {test}) GROUP BY day",+ placeholders={+ "window": _ingestion_window_expr(since, until, earliest_timestamp, latest_timestamp, latest_inclusive),+ "events": _action_event_filter_expr(actions),+ "test": _test_account_filter_expr(team),+ },+ )+ if not isinstance(query, ast.SelectQuery):+ raise TypeError(f"evaluate_conversions: expected SelectQuery, got {type(query)}")+ query.select = [+ query.select[0],+ *(ast.Call(name="countIf", args=[action_to_expr(action)]) for action in actions),+ ]+ # Future slices can group more than the default 100 days; the largest bounded slice is 50 years.+ query.limit = ast.Constant(value=MAX_SELECT_RETURNED_ROWS)+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type="web_achievements_conversions",+ settings=HogQLGlobalSettings(timeout_overflow_mode="throw", read_overflow_mode="throw"),+ )+ for row in response.results or []:+ day_counts = chunk_daily.setdefault(row[0].isoformat(), [0] * len(actions))+ for index, value in enumerate(row[1:]):+ day_counts[index] += int(value or 0)+ for day, counts in chunk_daily.items():+ day_counts = daily.setdefault(day, [0] * len(actions))+ for index, value in enumerate(counts):+ day_counts[index] += value+ return bool(chunk_daily)+++def _advance_conversion_future(+ ctx: EvalContext,+ actions: list[Action],+ daily: dict[str, list[int]],+ bootstrap: ConversionBootstrap,+ window_start: datetime,+ until: datetime,+) -> ConversionBootstrap | None:+ next_start = bootstrap.next_start+ chunk_hours = bootstrap.chunk_hours+ # Empty timestamp ranges are cheap to skip with the event timestamp index. Grow those+ # ranges so a scan with no future-dated events does not take hundreds of daily sweeps.+ for _ in range(20):+ chunk_end = min(next_start + timedelta(hours=chunk_hours), CONVERSIONS_MAX_TIMESTAMP)+ try:+ has_rows = _add_conversion_counts(+ ctx,+ actions,+ daily,+ bootstrap.created_since,+ bootstrap.created_until,+ next_start,+ chunk_end,+ latest_inclusive=chunk_end == CONVERSIONS_MAX_TIMESTAMP,+ )+ except CONVERSIONS_SCAN_LIMITS:+ if chunk_hours <= 1:+ raise+ return ConversionBootstrap(+ next_start=next_start,+ end=bootstrap.end,+ created_since=bootstrap.created_since,+ created_until=bootstrap.created_until,+ phase=bootstrap.phase,+ chunk_hours=max(1, chunk_hours // 2),+ )+ if chunk_end == CONVERSIONS_MAX_TIMESTAMP:+ if bootstrap.phase == "initial_future" and bootstrap.created_until < until:+ return ConversionBootstrap(+ next_start=window_start,+ end=bootstrap.end,+ created_since=bootstrap.created_until,+ created_until=bootstrap.created_until,+ phase="tail",+ )+ return None+ next_start = chunk_end+ if has_rows:+ break+ chunk_hours = min(chunk_hours * 2, CONVERSIONS_FUTURE_CHUNK_MAX_HOURS)+ return ConversionBootstrap(+ next_start=next_start,+ end=bootstrap.end,+ created_since=bootstrap.created_since,+ created_until=bootstrap.created_until,+ phase=bootstrap.phase,+ chunk_hours=chunk_hours,+ )+++def _advance_conversion_bootstrap(+ ctx: EvalContext,+ actions: list[Action],+ daily: dict[str, list[int]],+ bootstrap: ConversionBootstrap,+ window_start: datetime,+ until: datetime,+) -> ConversionBootstrap | None:+ if bootstrap.phase == "tail":+ try:+ _add_conversion_counts(ctx, actions, daily, bootstrap.created_since, until, window_start)+ except CONVERSIONS_SCAN_LIMITS:+ return ConversionBootstrap(+ next_start=window_start,+ end=bootstrap.end,+ created_since=bootstrap.created_since,+ created_until=until,+ phase="catchup",+ )+ return None++ if bootstrap.phase in ("initial_future", "catchup_future"):+ return _advance_conversion_future(ctx, actions, daily, bootstrap, window_start, until)++ next_start = max(bootstrap.next_start, window_start)+ end = bootstrap.end+ if bootstrap.phase == "catchup":+ # Events ingested after the first scan can have timestamps on later days.+ # Freeze a finite timestamp horizon for this catch-up interval.+ end = max(+ end,+ datetime.combine(bootstrap.created_until.astimezone(UTC).date() + timedelta(days=1), time.min, tzinfo=UTC),+ )+ if next_start >= end:+ daily.clear()+ bootstrap = ConversionBootstrap(+ next_start=window_start,+ end=window_start + timedelta(days=CONVERSIONS_LOOKBACK_DAYS),+ created_until=until,+ )+ next_start = window_start+ end = bootstrap.end++ chunk_hours = bootstrap.chunk_hours+ chunk_end = min(next_start + timedelta(hours=chunk_hours), end)+ try:+ _add_conversion_counts(+ ctx,+ actions,+ daily,+ bootstrap.created_since,+ bootstrap.created_until,+ next_start,+ chunk_end,+ )+ except CONVERSIONS_SCAN_LIMITS:+ if chunk_hours <= 1:+ raise+ return ConversionBootstrap(+ next_start=next_start,+ end=end,+ created_until=bootstrap.created_until,+ phase=bootstrap.phase,+ created_since=bootstrap.created_since,+ chunk_hours=max(1, chunk_hours // 2),+ )++ if chunk_end < end:+ return ConversionBootstrap(+ next_start=chunk_end,+ end=end,+ created_until=bootstrap.created_until,+ phase=bootstrap.phase,+ created_since=bootstrap.created_since,+ chunk_hours=chunk_hours,+ )++ if bootstrap.phase == "catchup":+ if bootstrap.created_since is None or bootstrap.created_since >= bootstrap.created_until:+ return None+ return ConversionBootstrap(+ next_start=end,+ end=end,+ created_since=bootstrap.created_since,+ created_until=bootstrap.created_until,+ phase="catchup_future",+ chunk_hours=CONVERSIONS_BOOTSTRAP_CHUNK_DAYS * 24,+ )+ if bootstrap.phase == "initial":+ return ConversionBootstrap(+ next_start=end,+ end=end,+ created_until=bootstrap.created_until,+ phase="initial_future",+ )+ if bootstrap.created_until < until:+ return ConversionBootstrap(+ next_start=window_start,+ end=bootstrap.end,+ created_since=bootstrap.created_until,+ created_until=bootstrap.created_until,+ phase="tail",+ )+ return None++def evaluate_conversions(ctx: EvalContext, prior: PriorProgress) -> TrackEvaluation:actions = list(Action.objects.filter(team__project_id=ctx.team.project_id, deleted=False)@@ -220,39 +505,54 @@ def evaluate_conversions(ctx: EvalContext, prior: PriorProgress) -> TrackEvaluatfingerprints = _action_fingerprints(actions)daily = _daily_buckets(prior.checkpoint, fingerprints)since = parse_zoned_datetime_string(prior.checkpoint.get("counted_through"))- if daily is None or since is None:- daily, since, earliest_timestamp = {}, None, window_start- else:- earliest_timestamp = max(window_start, since - LATE_ARRIVAL_LOOKBACK)-+ bootstrap = _conversion_bootstrap_state(prior.checkpoint) if daily is not None and since is None else None+ if daily is None:+ daily = {}+ since = None+ if since is None and bootstrap is None:+ daily = {}++ started_bootstrap = False+ completed_through = untilwith achievement_query_scope(ctx.team.id):- for team in _project_environment_teams(ctx.team):- query = parse_select(- "SELECT toDate(toTimeZone(timestamp, 'UTC')) AS day FROM events WHERE and({window}, {events}, {test}) GROUP BY day",- placeholders={- "window": _ingestion_window_expr(since, until, earliest_timestamp),- "events": _action_event_filter_expr(actions),- "test": _test_account_filter_expr(team),- },- )- if not isinstance(query, ast.SelectQuery):- raise TypeError(f"evaluate_conversions: expected SelectQuery, got {type(query)}")- query.select = [- query.select[0],- *(ast.Call(name="countIf", args=[action_to_expr(action)]) for action in actions),- ]- response = execute_hogql_query(query=query, team=team, query_type="web_achievements_conversions")- for row in response.results or []:- day_counts = daily.setdefault(row[0].isoformat(), [0] * len(actions))- for index, value in enumerate(row[1:]):- day_counts[index] += int(value or 0)+ if bootstrap is None:+ earliest_timestamp = max(window_start, since - LATE_ARRIVAL_LOOKBACK) if since is not None else window_start+ try:+ _add_conversion_counts(ctx, actions, daily, since, until, earliest_timestamp)+ except CONVERSIONS_SCAN_LIMITS:+ if since is not None:+ raise+ daily = {}+ bootstrap = ConversionBootstrap(+ next_start=window_start,+ end=window_start + timedelta(days=CONVERSIONS_LOOKBACK_DAYS),+ created_until=until,+ )+ started_bootstrap = True+ if bootstrap is not None and not started_bootstrap:+ if bootstrap.phase in ("catchup", "catchup_future"):+ completed_through = bootstrap.created_until+ bootstrap = _advance_conversion_bootstrap(ctx, actions, daily, bootstrap, window_start, until)oldest_kept_day = window_start.date().isoformat()daily = {day: counts for day, counts in daily.items() if day >= oldest_kept_day and any(counts)}per_action_totals = [sum(counts[index] for counts in daily.values()) for index in range(len(actions))]+ checkpoint: dict[str, object] = {"actions": fingerprints, "daily": daily}+ if bootstrap is not None:+ checkpoint["bootstrap"] = {+ "next_start": bootstrap.next_start.isoformat(),+ "end": bootstrap.end.isoformat(),+ "created_until": bootstrap.created_until.isoformat(),+ "phase": bootstrap.phase,+ "created_since": bootstrap.created_since.isoformat() if bootstrap.created_since is not None else None,+ "chunk_hours": bootstrap.chunk_hours,+ }+ else:+ checkpoint["counted_through"] = completed_through.isoformat()return TrackEvaluation(value=max(len(actions), max(per_action_totals, default=0)),- checkpoint={"actions": fingerprints, "daily": daily, "counted_through": until.isoformat()},+ checkpoint=checkpoint,+ complete="bootstrap" not in checkpoint,)diff --git a/products/web_analytics/backend/achievements/tasks.py b/products/web_analytics/backend/achievements/tasks.pyindex 9d0c56984657..a8dfa4718c43 100644--- a/products/web_analytics/backend/achievements/tasks.py+++ b/products/web_analytics/backend/achievements/tasks.py@@ -251,6 +251,13 @@ def _apply_progress(or (progress.state or {}).get("checkpoint") != (evaluated_progress.state or {}).get("checkpoint")):return []+ if not evaluation.complete:+ state = dict(progress.state or {})+ state["checkpoint"] = evaluation.checkpoint+ persist_progress(+ progress, progress.progress_value, progress.current_stage, state, bump_last_computed_at=False+ )+ return []new_value = evaluation.valueis_cumulative = track.evaluator_key != "streak"value = max(new_value, progress.progress_value) if is_cumulative else new_value@@ -258,6 +265,7 @@ def _apply_progress(new_stage = max(progress.current_stage, track.stage_for_value(value, arm))state = dict(progress.state or {})+ backfill_pending = bool(state.pop("backfill_pending", False))unlocked_stages = dict(state.get("unlocked_stages", {}))pending_celebrations = list(state.get("pending_celebrations", []))newly_unlocked: list[int] = []@@ -265,8 +273,9 @@ def _apply_progress(now_iso = timezone.now().isoformat()for stage in range(progress.current_stage + 1, new_stage + 1):unlocked_stages[str(stage)] = now_iso- pending_celebrations.append(stage)- newly_unlocked.append(stage)+ if not backfill_pending:+ pending_celebrations.append(stage)+ newly_unlocked.append(stage)state["unlocked_stages"] = unlocked_stagesstate["pending_celebrations"] = pending_celebrationsif track.evaluator_key == "streak":diff --git a/products/web_analytics/backend/test/test_achievements_backfill.py b/products/web_analytics/backend/test/test_achievements_backfill.pyindex d02cdb22c7e0..74e791644c24 100644--- a/products/web_analytics/backend/test/test_achievements_backfill.py+++ b/products/web_analytics/backend/test/test_achievements_backfill.py@@ -1,7 +1,13 @@+from datetime import date+from posthog.test.base import BaseTestfrom unittest.mock import patch+from parameterized import parameterized+from products.web_analytics.backend.achievements import backfill, tasks+from products.web_analytics.backend.achievements.definitions import TRACKS, TrackKey+from products.web_analytics.backend.achievements.evaluators import EvalContext, TrackEvaluationfrom products.web_analytics.backend.models import WebAnalyticsAchievementProgressfrom products.web_analytics.backend.test.achievements_test_utils import make_evaluators, make_incremental_evaluators@@ -43,3 +49,94 @@ class TestBackfill(BaseTest):loyal = WebAnalyticsAchievementProgress.objects.for_team(self.team.id).get(user=self.user, track_key="loyalty")self.assertEqual(loyal.current_stage, 1)self.assertIsNone(loyal.last_computed_at)++ def test_backfill_keeps_partial_conversion_value_private(self) -> None:+ checkpoint: dict[str, object] = {"bootstrap": {"next_start": "2026-01-09T00:00:00+00:00"}}+ evaluation = TrackEvaluation(value=1000, checkpoint=checkpoint, complete=False)+ with patch.object(backfill, "evaluate_track", return_value=evaluation):+ touched = backfill._backfill_track(+ EvalContext(team=self.team, user=None, today=date.today(), arm=None),+ TRACKS[TrackKey.CONVERSIONS],+ )++ progress = WebAnalyticsAchievementProgress.objects.for_team(self.team.id).get(+ user__isnull=True, track_key="conversions"+ )+ self.assertTrue(touched)+ self.assertEqual(progress.progress_value, 0)+ self.assertEqual(progress.current_stage, 0)+ self.assertEqual(progress.state["checkpoint"], checkpoint)++ def test_partial_backfill_finishes_without_celebrations_then_allows_new_unlocks(self) -> None:+ track = TRACKS[TrackKey.CONVERSIONS]+ ctx = EvalContext(team=self.team, user=None, today=date.today(), arm=None)+ partial_checkpoint: dict[str, object] = {"bootstrap": {"next_start": "2026-01-09T00:00:00+00:00"}}+ next_checkpoint: dict[str, object] = {"bootstrap": {"next_start": "2026-01-10T00:00:00+00:00"}}+ completed_checkpoint: dict[str, object] = {"counted_through": "2026-01-10T00:00:00+00:00"}+ with patch.object(+ backfill,+ "evaluate_track",+ return_value=TrackEvaluation(value=3, checkpoint=partial_checkpoint, complete=False),+ ):+ self.assertTrue(backfill._backfill_track(ctx, track))++ with (+ patch.object(+ tasks,+ "evaluate_track",+ side_effect=[+ TrackEvaluation(value=3, checkpoint=next_checkpoint, complete=False),+ TrackEvaluation(value=3, checkpoint=completed_checkpoint),+ ],+ ),+ patch.object(tasks, "_send_unlock_notifications") as notify,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ tasks._recompute_track(ctx, track)+ notify.assert_not_called()+ progress = tasks.get_or_create_progress(ctx, track)+ self.assertTrue(progress.state["backfill_pending"])++ with self.captureOnCommitCallbacks(execute=True):+ tasks._recompute_track(ctx, track)+ notify.assert_not_called()++ progress = tasks.get_or_create_progress(ctx, track)+ self.assertEqual(progress.current_stage, 2)+ self.assertEqual(sorted(progress.state["unlocked_stages"]), ["1", "2"])+ self.assertEqual(progress.state["pending_celebrations"], [])+ self.assertNotIn("backfill_pending", progress.state)++ with self.captureOnCommitCallbacks(execute=True):+ tasks._apply_progress(ctx, track, progress, TrackEvaluation(value=5, checkpoint=completed_checkpoint))+ notify.assert_called_once()+ progress.refresh_from_db()+ self.assertEqual(progress.state["pending_celebrations"], [3])++ @parameterized.expand([("incomplete", False), ("complete", True)])+ def test_backfill_does_not_overwrite_a_newer_conversion_checkpoint(self, _name: str, complete: bool) -> None:+ track = TRACKS[TrackKey.CONVERSIONS]+ ctx = EvalContext(team=self.team, user=None, today=date.today(), arm=None)+ progress = tasks.get_or_create_progress(ctx, track)+ winning_checkpoint = {"counted_through": "2026-01-02T00:05:00+00:00"}++ def evaluate_racing_recompute(_ctx: EvalContext, _track: object, _progress: object) -> TrackEvaluation:+ WebAnalyticsAchievementProgress.objects.for_team(self.team.id).filter(pk=progress.pk).update(+ progress_value=5,+ current_stage=3,+ state={"checkpoint": winning_checkpoint},+ )+ return TrackEvaluation(+ value=4,+ checkpoint={"counted_through": "2026-01-02T00:01:00+00:00"},+ complete=complete,+ )++ with patch.object(backfill, "evaluate_track", side_effect=evaluate_racing_recompute):+ touched = backfill._backfill_track(ctx, track)++ progress.refresh_from_db()+ self.assertFalse(touched)+ self.assertEqual(progress.progress_value, 5)+ self.assertEqual(progress.current_stage, 3)+ self.assertEqual(progress.state["checkpoint"], winning_checkpoint)diff --git a/products/web_analytics/backend/test/test_achievements_evaluators.py b/products/web_analytics/backend/test/test_achievements_evaluators.pyindex 481ed704085b..0581f2dd58e2 100644--- a/products/web_analytics/backend/test/test_achievements_evaluators.py+++ b/products/web_analytics/backend/test/test_achievements_evaluators.py@@ -1,11 +1,17 @@-from datetime import date, datetime, timedelta+from datetime import UTC, date, datetime, time, timedeltafrom posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patchfrom django.utils import timezonefrom parameterized import parameterized+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.query import execute_hogql_query++from posthog.errors import CHQueryErrorTooManyBytes+from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, ClickHouseQueryTimeOutfrom posthog.models import Element, Team, Userfrom products.actions.backend.models.action import Action@@ -13,6 +19,8 @@ from products.web_analytics.backend.achievements.definitions import STREAK_ARM_Dfrom products.web_analytics.backend.achievements.evaluators import (EvalContext,PriorProgress,+ _action_fingerprints,+ _add_conversion_counts,evaluate_conversions,evaluate_cumulative_pageviews,evaluate_data_events,@@ -86,9 +94,11 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):steps_json=[{"event": event, "tag_name": "button", "text": "Pay $10"}],)- def _pay_click(self, timestamp: datetime | None = None, created_at: datetime | None = None) -> None:+ def _pay_click(+ self, timestamp: datetime | None = None, created_at: datetime | None = None, team: Team | None = None+ ) -> None:_create_event(- team=self.team,+ team=team or self.team,event="$autocapture",distinct_id="d1",elements=[Element(nth_of_type=1, nth_child=0, tag_name="button", text="Pay $10")],@@ -147,11 +157,328 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):self._pay_action("$autocapture")self.assertEqual(evaluate_conversions(self._ctx(), EMPTY_PRIOR).value, 1)+ @parameterized.expand(+ [+ ("byte_limit", CHQueryErrorTooManyBytes("read limit", code=307)),+ ("timeout", ClickHouseQueryTimeOut()),+ ("estimated_timeout", ClickHouseEstimatedQueryExecutionTimeTooLong()),+ ]+ )+ def test_conversions_resume_a_bounded_initial_scan_after_limit(self, _name: str, failure: Exception) -> None:+ self._pay_action("$autocapture")+ first_now = timezone.now()+ old_timestamp = first_now - timedelta(days=10)+ recent_timestamp = first_now - timedelta(days=2)+ future_timestamp = first_now + timedelta(days=1)+ self._pay_click(timestamp=old_timestamp, created_at=old_timestamp)+ self._pay_click(timestamp=recent_timestamp, created_at=recent_timestamp)+ self._pay_click(timestamp=future_timestamp, created_at=first_now - timedelta(hours=2))+ flush_persons_and_events()++ attempts = 0++ def fail_full_window_once(*args: object, **kwargs: object):+ nonlocal attempts+ settings = kwargs["settings"]+ assert isinstance(settings, HogQLGlobalSettings)+ self.assertEqual(settings.timeout_overflow_mode, "throw")+ self.assertEqual(settings.read_overflow_mode, "throw")+ attempts += 1+ if attempts == 1:+ raise failure+ return execute_hogql_query(*args, **kwargs)++ with (+ patch("products.web_analytics.backend.achievements.evaluators.CONVERSIONS_LOOKBACK_DAYS", 14),+ patch(+ "products.web_analytics.backend.achievements.evaluators.execute_hogql_query",+ side_effect=fail_full_window_once,+ ),+ ):+ with patch("products.web_analytics.backend.achievements.evaluators.timezone.now", return_value=first_now):+ first = evaluate_conversions(self._ctx(), EMPTY_PRIOR)+ self.assertEqual(first.value, 1)+ self.assertFalse(first.complete)+ assert first.checkpoint is not None+ self.assertNotIn("counted_through", first.checkpoint)+ self.assertEqual(attempts, 1)++ self._pay_click(timestamp=old_timestamp, created_at=first_now)+ flush_persons_and_events()+ saw_tail_checkpoint = False+ final = first+ for sweep in range(40):+ with patch(+ "products.web_analytics.backend.achievements.evaluators.timezone.now",+ return_value=first_now + timedelta(hours=2, minutes=5 * sweep),+ ):+ assert final.checkpoint is not None+ final = evaluate_conversions(+ self._ctx(),+ PriorProgress(value=final.value, last_computed_at=None, checkpoint=final.checkpoint),+ )+ assert final.checkpoint is not None+ if "bootstrap" in final.checkpoint:+ bootstrap = final.checkpoint["bootstrap"]+ assert isinstance(bootstrap, dict)+ saw_tail_checkpoint |= bootstrap["phase"] == "tail"+ if final.complete:+ break++ self.assertTrue(saw_tail_checkpoint)+ self.assertEqual(final.value, 4)+ self.assertTrue(final.complete)+ assert final.checkpoint is not None+ self.assertIn("counted_through", final.checkpoint)+ self.assertNotIn("bootstrap", final.checkpoint)++ self._pay_click(+ timestamp=first_now + timedelta(hours=2),+ created_at=first_now + timedelta(hours=2, minutes=30),+ )+ flush_persons_and_events()+ with patch(+ "products.web_analytics.backend.achievements.evaluators.timezone.now",+ return_value=first_now + timedelta(hours=4),+ ):+ incremental = evaluate_conversions(+ self._ctx(), PriorProgress(value=final.value, last_computed_at=None, checkpoint=final.checkpoint)+ )+ self.assertEqual(incremental.value, 5)+ self.assertTrue(incremental.complete)++ def test_conversions_initial_future_slice_recovers_from_a_limit(self) -> None:+ action = self._pay_action("$autocapture")+ now = timezone.now()+ self._pay_click(timestamp=now + timedelta(days=2), created_at=now - timedelta(hours=2))+ self._pay_click(timestamp=now + timedelta(days=20), created_at=now - timedelta(hours=2))+ flush_persons_and_events()++ created_until = now - timedelta(hours=1)+ window_start = datetime.combine((created_until - timedelta(days=13)).date(), time.min, tzinfo=UTC)+ initial_end = window_start + timedelta(days=14)+ checkpoint: dict[str, object] = {+ "actions": _action_fingerprints([action]),+ "daily": {},+ "bootstrap": {+ "next_start": window_start.isoformat(),+ "end": initial_end.isoformat(),+ "created_since": None,+ "created_until": created_until.isoformat(),+ "phase": "initial",+ "chunk_hours": 24,+ },+ }+ split_future_slice = False++ def fail_unbounded_or_wide_future_slice(+ ctx: EvalContext,+ actions: list[Action],+ daily: dict[str, list[int]],+ since: datetime | None,+ until: datetime,+ earliest_timestamp: datetime,+ latest_timestamp: datetime | None = None,+ latest_inclusive: bool = False,+ ) -> bool:+ nonlocal split_future_slice+ if latest_timestamp is None:+ raise CHQueryErrorTooManyBytes("read limit", code=307)+ if (+ earliest_timestamp >= initial_end+ and earliest_timestamp <= now + timedelta(days=20) < latest_timestamp+ and latest_timestamp - earliest_timestamp > timedelta(days=1)+ ):+ split_future_slice = True+ raise CHQueryErrorTooManyBytes("read limit", code=307)+ return _add_conversion_counts(+ ctx, actions, daily, since, until, earliest_timestamp, latest_timestamp, latest_inclusive+ )++ with (+ patch("products.web_analytics.backend.achievements.evaluators.CONVERSIONS_LOOKBACK_DAYS", 14),+ patch("products.web_analytics.backend.achievements.evaluators.timezone.now", return_value=now),+ patch(+ "products.web_analytics.backend.achievements.evaluators._add_conversion_counts",+ side_effect=fail_unbounded_or_wide_future_slice,+ ),+ ):+ for _ in range(80):+ evaluation = evaluate_conversions(+ self._ctx(), PriorProgress(value=1, last_computed_at=None, checkpoint=checkpoint)+ )+ assert evaluation.checkpoint is not None+ checkpoint = evaluation.checkpoint+ if evaluation.complete:+ break++ self.assertTrue(evaluation.complete)+ self.assertTrue(split_future_slice)+ self.assertEqual(evaluation.value, 2)+ self.assertEqual(checkpoint["counted_through"], created_until.isoformat())++ def test_conversions_future_slice_keeps_more_than_default_query_limit_days(self) -> None:+ action = self._pay_action("$autocapture")+ now = timezone.now()+ for offset in range(1, 102):+ self._pay_click(timestamp=now + timedelta(days=offset), created_at=now - timedelta(hours=2))+ flush_persons_and_events()++ daily: dict[str, list[int]] = {}+ has_rows = _add_conversion_counts(+ self._ctx(),+ [action],+ daily,+ None,+ now - timedelta(hours=1),+ now,+ now + timedelta(days=224),+ )++ self.assertTrue(has_rows)+ self.assertEqual(len(daily), 101)+ self.assertEqual(sum(counts[0] for counts in daily.values()), 101)++ def test_conversions_catchup_bounds_later_days_and_preserves_future_timestamps(self) -> None:+ action = self._pay_action("$autocapture")+ first_now = timezone.now()+ later = first_now + timedelta(days=4)+ self._pay_click(timestamp=first_now - timedelta(days=2), created_at=first_now + timedelta(days=1))+ self._pay_click(timestamp=first_now + timedelta(days=3), created_at=first_now + timedelta(days=3))+ self._pay_click(timestamp=first_now + timedelta(days=20), created_at=first_now + timedelta(days=3))+ flush_persons_and_events()++ created_since = first_now - timedelta(hours=2)+ created_until = later - timedelta(hours=1)+ catchup_end = datetime.combine(created_until.date() + timedelta(days=1), time.min, tzinfo=UTC)+ initial_window_start = datetime.combine((first_now - timedelta(days=13)).date(), time.min, tzinfo=UTC)+ checkpoint: dict[str, object] = {+ "actions": _action_fingerprints([action]),+ "daily": {},+ "bootstrap": {+ "next_start": initial_window_start.isoformat(),+ "end": (initial_window_start + timedelta(days=14)).isoformat(),+ "created_since": created_since.isoformat(),+ "created_until": created_until.isoformat(),+ "phase": "catchup",+ "chunk_hours": 24,+ },+ }++ split_final_slice = False++ split_future_slice = False++ def fail_wide_timestamp_slice(+ ctx: EvalContext,+ actions: list[Action],+ daily: dict[str, list[int]],+ since: datetime | None,+ until: datetime,+ earliest_timestamp: datetime,+ latest_timestamp: datetime | None = None,+ latest_inclusive: bool = False,+ ) -> bool:+ nonlocal split_final_slice, split_future_slice+ if latest_timestamp is None and since is not None and until - since > timedelta(days=1):+ raise CHQueryErrorTooManyBytes("read limit", code=307)+ if (+ latest_timestamp is not None+ and latest_timestamp == catchup_end+ and latest_timestamp - earliest_timestamp > timedelta(hours=1)+ ):+ split_final_slice = True+ raise CHQueryErrorTooManyBytes("read limit", code=307)+ if (+ earliest_timestamp >= catchup_end+ and latest_timestamp is not None+ and earliest_timestamp <= first_now + timedelta(days=20) < latest_timestamp+ and latest_timestamp - earliest_timestamp > timedelta(days=1)+ ):+ split_future_slice = True+ raise CHQueryErrorTooManyBytes("read limit", code=307)+ return _add_conversion_counts(+ ctx, actions, daily, since, until, earliest_timestamp, latest_timestamp, latest_inclusive+ )++ with (+ patch("products.web_analytics.backend.achievements.evaluators.CONVERSIONS_LOOKBACK_DAYS", 14),+ patch("products.web_analytics.backend.achievements.evaluators.timezone.now", return_value=later),+ patch(+ "products.web_analytics.backend.achievements.evaluators._add_conversion_counts",+ side_effect=fail_wide_timestamp_slice,+ ),+ ):+ for _ in range(80):+ evaluation = evaluate_conversions(+ self._ctx(), PriorProgress(value=1, last_computed_at=None, checkpoint=checkpoint)+ )+ assert evaluation.checkpoint is not None+ checkpoint = evaluation.checkpoint+ if evaluation.complete:+ break++ self.assertTrue(evaluation.complete)+ self.assertTrue(split_final_slice)+ self.assertTrue(split_future_slice)+ self.assertEqual(evaluation.value, 3)+ self.assertEqual(checkpoint["counted_through"], created_until.isoformat())++ @parameterized.expand(+ [+ ("byte_limit", CHQueryErrorTooManyBytes("read limit", code=307)),+ ("estimated_timeout", ClickHouseEstimatedQueryExecutionTimeTooLong()),+ ]+ )+ def test_conversions_split_a_failed_chunk_without_duplicate_environment_counts(+ self, _name: str, failure: Exception+ ) -> None:+ self._pay_action("$autocapture")+ second_env = Team.objects.create(organization=self.organization, project=self.team.project, name="env 2")+ now = timezone.now()+ timestamp = now - timedelta(days=10)+ self._pay_click(timestamp=timestamp, created_at=timestamp)+ self._pay_click(timestamp=timestamp, created_at=timestamp, team=second_env)+ flush_persons_and_events()++ attempts = 0++ def fail_second_environment_twice(*args: object, **kwargs: object):+ nonlocal attempts+ attempts += 1+ if attempts in (2, 4):+ raise failure+ return execute_hogql_query(*args, **kwargs)++ with (+ patch("products.web_analytics.backend.achievements.evaluators.CONVERSIONS_LOOKBACK_DAYS", 14),+ patch(+ "products.web_analytics.backend.achievements.evaluators.execute_hogql_query",+ side_effect=fail_second_environment_twice,+ ),+ patch("products.web_analytics.backend.achievements.evaluators.timezone.now", return_value=now),+ ):+ prior = EMPTY_PRIOR+ for _ in range(30):+ evaluation = evaluate_conversions(self._ctx(), prior)+ assert evaluation.checkpoint is not None+ if evaluation.complete:+ break+ prior = PriorProgress(value=evaluation.value, last_computed_at=None, checkpoint=evaluation.checkpoint)+ if attempts == 4:+ bootstrap = evaluation.checkpoint["bootstrap"]+ assert isinstance(bootstrap, dict)+ self.assertEqual(bootstrap["chunk_hours"], 84)++ self.assertTrue(evaluation.complete)+ self.assertEqual(evaluation.value, 2)+ self.assertGreater(attempts, 6)+@parameterized.expand([("unchanged_actions_add_new_arrivals", "unchanged", 5),- ("edited_steps_rebuild", "edited_steps", 3),- ("other_actions_rebuild", "other_actions", 3),+ ("edited_steps_rebuild", "edited_steps", 4),+ ("other_actions_rebuild", "other_actions", 4),])def test_conversions_keep_a_rolling_ninety_day_window(self, _name: str, change: str, expected: int) -> None:@@ -171,6 +498,8 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):self._pay_click()self._pay_click()self._pay_click(timestamp=now - timedelta(days=2), created_at=now - timedelta(hours=2))+ if change != "unchanged":+ self._pay_click(timestamp=now - timedelta(days=10), created_at=now - timedelta(days=10))flush_persons_and_events()prior = PriorProgress(value=0,diff --git a/products/web_analytics/backend/test/test_achievements_tasks.py b/products/web_analytics/backend/test/test_achievements_tasks.pyindex b4f08ab32154..c9940cbcbfdd 100644--- a/products/web_analytics/backend/test/test_achievements_tasks.py+++ b/products/web_analytics/backend/test/test_achievements_tasks.py@@ -101,6 +101,26 @@ class TestRecomputeTask(BaseTest):self.assertEqual(progress.current_stage, 1)self.assertEqual(progress.state["checkpoint"], checkpoint)+ def test_partial_conversion_checkpoint_stays_due_for_next_sweep(self) -> None:+ checkpoint: dict[str, object] = {"bootstrap": {"next_start": "2026-01-09T00:00:00+00:00"}}+ calls = 0++ def conversions(_ctx: EvalContext, _prior: PriorProgress) -> TrackEvaluation:+ nonlocal calls+ calls += 1+ return TrackEvaluation(value=calls, checkpoint=checkpoint, complete=False)++ evaluators = {**make_incremental_evaluators(), "conversions": conversions}+ self._run_team(evaluators)+ self._run_team(evaluators)++ progress = self._team_progress("conversions")+ self.assertEqual(calls, 2)+ self.assertEqual(progress.progress_value, 0)+ self.assertEqual(progress.current_stage, 0)+ self.assertEqual(progress.state["checkpoint"], checkpoint)+ self.assertIsNone(progress.last_computed_at)+@parameterized.expand([("racing_recompute", True), ("racing_backfill", False)])def test_overlapping_team_recompute_keeps_the_first_checkpoint(self, _name: str, bumps_last_computed_at: bool