: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(experiments): spread frozen precompute chunk expiries with jitter (#96576)
Juraj Majerik125e00683650
diff --git a/.agents/skills/analyzing-experiment-query-performance/SKILL.md b/.agents/skills/analyzing-experiment-query-performance/SKILL.mdindex af3805569906..96fb4ca784ac 100644--- a/.agents/skills/analyzing-experiment-query-performance/SKILL.md+++ b/.agents/skills/analyzing-experiment-query-performance/SKILL.md@@ -154,6 +154,8 @@ Both tables are partitioned by `toYYYYMMDD(expires_at)` with TTL-driven part droso each partition id is the **day that data expires** —the partition list doubles as a TTL/growth timeline(a bulge N days out means a large recent build; a missing near-term partition means little recent activity).+Frozen-band chunks get a per-chunk expiry jitter (`PRECOMPUTE_TTL_JITTER_SECONDS`, 14 days),+so a big build shows up as data spread over up to 14 expiry partitions, not as one large partition.### Not available via PATdiff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex eb931e0033a2..d4d2e6a1f27c 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -35,6 +35,7 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.preaggregation.sql import DISTRIBUTED_PREAGGREGATION_RESULTS_TABLEfrom posthog.clickhouse.query_tagging import tags_context+from posthog.dataclasses import frozenfrom posthog.models.team import Teamfrom posthog.settings import DEBUG, HOGQL_INCREASED_MAX_EXECUTION_TIME, TESTfrom posthog.utils import relative_date_parse_with_delta_mapping@@ -204,7 +205,17 @@ def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False) -> dict:return settings-@dataclass+def _ttl_jitter_offset(window_start: datetime, jitter_seconds: int) -> int:+ """Stable offset in [0, jitter_seconds) for a window, from its start date.++ sha256, not hash(): hash() is salted per process, and the offset must come out the same+ everywhere.+ """+ digest = hashlib.sha256(window_start.date().isoformat().encode()).digest()+ return int.from_bytes(digest[:8], "big") % jitter_seconds+++@frozenclass TtlSchedule:"""Maps time windows to TTL values based on their recency.@@ -247,6 +258,16 @@ class TtlSchedule:long warmer window). Windows older than this keep their full band TTL. `None` caps everyempty window regardless of age.+ `default_ttl_jitter_seconds` spreads out when default-band (frozen) windows expire. A+ backfill builds every chunk on the same day, so with one uniform TTL the whole history+ expires at once and the next read must rebuild all of it. The jitter adds a stable+ per-window offset in [0, jitter) to the default TTL, so chunks expire days apart and a read+ only finds a chunk or two missing. The offset comes from the window's start date, not from+ randomness, so a rebuild gives each chunk the same offset again and chunks do not go back+ to expiring together. Rule-matched (recent) windows never get jitter. Opt in only for+ frozen, immutable data: jitter keeps data longer, which is safe only when the data cannot+ change. `None` disables it.+Use parse_ttl_schedule() to create from user-facing dict format."""@@ -256,12 +277,22 @@ class TtlSchedule:settling_period_seconds: int | None = Noneempty_result_ttl_seconds: int | None = Noneempty_result_max_age_seconds: int | None = None+ default_ttl_jitter_seconds: int | None = None++ def get_ttl(self, window_start: datetime, *, jittered: bool = False) -> int:+ """TTL for a window. `jittered=True` adds the default-band jitter offset.- def get_ttl(self, window_start: datetime) -> int:+ Job creation and the freshness check must both pass `jittered=True`, or jobs get+ recomputed before they expire. `split_ranges_by_ttl` must not: it merges windows by+ comparing TTLs, and per-window offsets would break the merging.+ """for cutoff, ttl in self.rules:if window_start >= cutoff:return ttl- return self.default_ttl_seconds+ ttl = self.default_ttl_seconds+ if jittered and self.default_ttl_jitter_seconds:+ ttl += _ttl_jitter_offset(window_start, self.default_ttl_jitter_seconds)+ return ttldef empty_result_expires_at(self, computed_at: datetime, window_end: datetime) -> datetime | None:"""When a zero-row job for this window should expire, or None to keep the band TTL.@@ -303,6 +334,7 @@ def parse_ttl_schedule(settling_period_seconds: int | None = None,empty_result_ttl_seconds: int | None = None,empty_result_max_age_seconds: int | None = None,+ default_ttl_jitter_seconds: int | None = None,) -> TtlSchedule:"""Parse a TTL specification into a TtlSchedule.@@ -326,6 +358,8 @@ def parse_ttl_schedule(raise ValueError(f"empty_result_ttl_seconds must be positive, got {empty_result_ttl_seconds}")if empty_result_max_age_seconds is not None and empty_result_max_age_seconds <= 0:raise ValueError(f"empty_result_max_age_seconds must be positive, got {empty_result_max_age_seconds}")+ if default_ttl_jitter_seconds is not None and default_ttl_jitter_seconds <= 0:+ raise ValueError(f"default_ttl_jitter_seconds must be positive, got {default_ttl_jitter_seconds}")if isinstance(ttl, int):if ttl <= 0:@@ -337,6 +371,7 @@ def parse_ttl_schedule(settling_period_seconds=settling_period_seconds,empty_result_ttl_seconds=empty_result_ttl_seconds,empty_result_max_age_seconds=empty_result_max_age_seconds,+ default_ttl_jitter_seconds=default_ttl_jitter_seconds,)tz = ZoneInfo(team_timezone)@@ -367,6 +402,7 @@ def parse_ttl_schedule(settling_period_seconds=settling_period_seconds,empty_result_ttl_seconds=empty_result_ttl_seconds,empty_result_max_age_seconds=empty_result_max_age_seconds,+ default_ttl_jitter_seconds=default_ttl_jitter_seconds,)@@ -1099,7 +1135,14 @@ class LazyComputationExecutor:_log_execution("timeout", result)return result- new_job = create_lazy_computation_job(team, query_hash, range_start, range_end, ttl)+ # `ttl` is the band TTL used for merging; the job's real expiry adds the jitter+ new_job = create_lazy_computation_job(+ team,+ query_hash,+ range_start,+ range_end,+ self.ttl_schedule.get_ttl(range_start, jittered=True),+ )if new_job is None:# Another executor created a PENDING job for this range; the# rescan at the top of the loop will pick it up. The log keeps@@ -1401,7 +1444,7 @@ class LazyComputationExecutor:if job.status == PreaggregationJob.Status.PENDING:result.append(job)continue- desired_ttl = self.ttl_schedule.get_ttl(job.time_range_start)+ desired_ttl = self.ttl_schedule.get_ttl(job.time_range_start, jittered=True)fresh_until = job.created_at + timedelta(seconds=desired_ttl + grace_seconds)if settling_period is not None:settled_at = job.time_range_end + timedelta(seconds=settling_period)diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.pyindex 9995e93a400e..58989d26fadb 100644--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py@@ -2,6 +2,7 @@ import time as time_modfrom datetime import UTC, datetime, timedeltaimport pytest+from freezegun import freeze_timefrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_eventfrom unittest.mock import patch@@ -1418,9 +1419,11 @@ class TestParseTtlSchedule(BaseTest):("negative_empty_ttl", {"empty_result_ttl_seconds": -60}),("zero_max_age", {"empty_result_max_age_seconds": 0}),("negative_max_age", {"empty_result_max_age_seconds": -60}),+ ("zero_jitter", {"default_ttl_jitter_seconds": 0}),+ ("negative_jitter", {"default_ttl_jitter_seconds": -60}),])- def test_rejects_non_positive_empty_result_settings(self, name, kwargs):+ def test_rejects_non_positive_optional_settings(self, name, kwargs):# Validated like every sibling TTL: 0 would expire a job the moment it is created.with pytest.raises(ValueError, match="must be positive"):parse_ttl_schedule(3600, **kwargs)@@ -1436,6 +1439,33 @@ class TestParseTtlSchedule(BaseTest):assert uncapped.empty_result_ttl_seconds is Noneassert uncapped.empty_result_max_age_seconds is None+ def test_carries_default_ttl_jitter(self):+ schedule = parse_ttl_schedule({"default": 3600}, "UTC", default_ttl_jitter_seconds=600)+ assert schedule.default_ttl_jitter_seconds == 600+ assert parse_ttl_schedule(3600, default_ttl_jitter_seconds=600).default_ttl_jitter_seconds == 600+ assert parse_ttl_schedule(3600).default_ttl_jitter_seconds is None++ def test_jittered_ttl_is_deterministic_and_spread_within_the_default_band(self):+ now = django_timezone.now()+ jitter = 14 * 24 * 60 * 60+ schedule = TtlSchedule(+ rules=[(now - timedelta(days=1), 60)],+ default_ttl_seconds=86400,+ default_ttl_jitter_seconds=jitter,+ )+ windows = [now - timedelta(days=30 + i) for i in range(20)]+ first = [schedule.get_ttl(w, jittered=True) for w in windows]+ second = [schedule.get_ttl(w, jittered=True) for w in windows]+ assert first == second+ assert all(86400 <= ttl < 86400 + jitter for ttl in first)+ assert len(set(first)) > 1+ assert schedule.get_ttl(now, jittered=True) == 60+ assert all(schedule.get_ttl(w) == 86400 for w in windows)++ def test_jittered_ttl_without_jitter_configured_is_the_band_ttl(self):+ schedule = TtlSchedule(rules=[], default_ttl_seconds=86400)+ assert schedule.get_ttl(django_timezone.now() - timedelta(days=30), jittered=True) == 86400+class TestSplitRangesByTtl(BaseTest):def test_single_range_uniform_ttl(self):@@ -2167,6 +2197,34 @@ class TestComputationExecutorExecute(BaseTest):ttl = (j.expires_at - j.created_at).total_seconds()assert ttl > 80000 # ~1 day+ def test_jittered_jobs_survive_past_the_base_ttl(self):+ # If the freshness check used the base TTL while creation used the jittered one,+ # this job would be judged stale before its expiry and recomputed on every read.+ query_info, _ = self._make_query_info()+ schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, default_ttl_jitter_seconds=14 * 24 * 60 * 60)+ executor = LazyComputationExecutor(ttl_schedule=schedule)++ with freeze_time("2026-01-15T12:00:00Z") as frozen:+ start = datetime(2026, 1, 5, tzinfo=UTC)+ end = datetime(2026, 1, 6, tzinfo=UTC)+ result = executor.execute(+ team=self.team, query_info=query_info, start=start, end=end, run_insert=lambda t, j: None+ )+ assert result.ready is True+ [job] = PreaggregationJob.objects.filter(id__in=result.job_ids)+ assert job.expires_at is not None+ jittered_ttl = (job.expires_at - job.created_at).total_seconds()+ # This window's deterministic offset is nonzero, so the job outlives the base TTL+ assert jittered_ttl > 3600++ frozen.tick(timedelta(seconds=(3600 + jittered_ttl) / 2))+ result = executor.execute(+ team=self.team, query_info=query_info, start=start, end=end, run_insert=lambda t, j: None+ )+ assert result.ready is True+ assert result.job_ids == [job.id]+ assert PreaggregationJob.objects.count() == 1+def test_timezone_aware_ttl_creates_jobs_with_correct_expiry(self):query_info, _ = self._make_query_info()@@ -3325,6 +3383,16 @@ class TestMaxWindowDaysCap(BaseTest):(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC), 3600)]+ def test_jitter_does_not_affect_merging(self):+ # If jitter leaked into the TTLs this function merges on, every daily window would+ # get a distinct TTL and this backfill would split into 14 daily jobs, not two.+ schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, max_window_days=7, default_ttl_jitter_seconds=86400)+ ranges = [(datetime(2020, 1, 1, tzinfo=UTC), datetime(2020, 1, 15, tzinfo=UTC))]+ assert split_ranges_by_ttl(ranges, schedule) == [+ (datetime(2020, 1, 1, tzinfo=UTC), datetime(2020, 1, 8, tzinfo=UTC), 3600),+ (datetime(2020, 1, 8, tzinfo=UTC), datetime(2020, 1, 15, tzinfo=UTC), 3600),+ ]+class TestExecuteOOMAndBudget(ClickhouseTestMixin, BaseTest):def _query_info(self) -> LazyComputationQuery:diff --git a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.mdindex 4066182df1af..5794c1bedc93 100644--- a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md+++ b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md@@ -262,8 +262,10 @@ GROUP BY variant4. **Job width cap**: Missing ranges are split into jobs of at most `PRECOMPUTE_MAX_WINDOW_DAYS` (7) days via `TtlSchedule.max_window_days` (see `experiment_precompute_ttl_schedule`). Without the cap, the frozen band (everything older than 4 days shares one TTL) merges into a single INSERT, so a cold or expired long-running experiment would scan its entire history in one query and hit the per-query bytes-to-read cap, timeout, or memory limit on high-volume teams. Completed chunk jobs persist even when a later chunk fails, so wide backfills converge across successive runs.-5. **Fallback**: If precomputation fails or isn't ready, the query falls back to scanning the events table directly.+5. **Frozen-band expiry jitter**: A backfill builds all frozen chunks on the same day, so with a uniform 60-day TTL the whole history would expire at once, and the next read would rebuild everything while its fallback scan exceeds the per-query read cap on high-volume teams. `PRECOMPUTE_TTL_JITTER_SECONDS` (14 days) adds a stable per-chunk offset to the frozen TTL, derived from the chunk's window start date, so chunks expire days apart and a read only finds a chunk or two missing. Frozen data never changes, so the longer lifetime changes no results. The offset comes from the window date, not from randomness, so a rebuild gives each chunk the same offset again and chunks do not go back to expiring together.-6. **Future: GROUP BY (entity_id, variant)**: Currently the query groups by entity_id only and resolves the variant during precomputation (e.g., argMin for first-seen). This bakes the variant handling strategy into the stored data, so switching between "first seen" and "exclude multiple" requires recomputation. A better approach is to GROUP BY (entity_id, variant) so we store one row per user-variant pair, then resolve multiple variants at query time.+6. **Fallback**: If precomputation fails or isn't ready, the query falls back to scanning the events table directly.-7. **Metric events**: The same lazy computation system also precomputes the metric_events half into `experiment_metric_events_preaggregated`, for ordered funnel metrics (one row per matching event with step indicators in `steps`), count/sum mean metrics (one row per matching event with its value in `numeric_value`), and retention metrics (one row per event matching the start or completion predicate, flagged as `steps[1]`/`steps[2]`; start anchoring, the retention window, and maturity stay read-time). Eligibility is gated by `_metric_events_precompute_applicable()` in `experiment_query_runner.py`; breakdowns, CUPED, and data warehouse sources fall back to a direct scan of the metric_events CTE. Retention is additionally gated behind the default-off `experiments-retention-metric-events-preaggregation` flag so it can be disabled without turning off funnel/mean. The scan extends past the experiment end by the conversion window — plus, for retention, `retention_window_end`, since a completion can land that much after a start event.+7. **Future: GROUP BY (entity_id, variant)**: Currently the query groups by entity_id only and resolves the variant during precomputation (e.g., argMin for first-seen). This bakes the variant handling strategy into the stored data, so switching between "first seen" and "exclude multiple" requires recomputation. A better approach is to GROUP BY (entity_id, variant) so we store one row per user-variant pair, then resolve multiple variants at query time.++8. **Metric events**: The same lazy computation system also precomputes the metric_events half into `experiment_metric_events_preaggregated`, for ordered funnel metrics (one row per matching event with step indicators in `steps`), count/sum mean metrics (one row per matching event with its value in `numeric_value`), and retention metrics (one row per event matching the start or completion predicate, flagged as `steps[1]`/`steps[2]`; start anchoring, the retention window, and maturity stay read-time). Eligibility is gated by `_metric_events_precompute_applicable()` in `experiment_query_runner.py`; breakdowns, CUPED, and data warehouse sources fall back to a direct scan of the metric_events CTE. Retention is additionally gated behind the default-off `experiments-retention-metric-events-preaggregation` flag so it can be disabled without turning off funnel/mean. The scan extends past the experiment end by the conversion window — plus, for retention, `retention_window_end`, since a completion can land that much after a start event.diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex cb066518c533..97473a4529ab 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -109,6 +109,11 @@ DEFAULT_EXPOSURE_TTL_SECONDS = {# instead of failing atomically on every attempt.PRECOMPUTE_MAX_WINDOW_DAYS = 7+# Spread frozen chunk expiries so an experiment's history does not expire all at once+# (see TtlSchedule.default_ttl_jitter_seconds). 14 days means roughly one chunk expiry+# per day for a months-long experiment; a larger value would only keep data on disk longer.+PRECOMPUTE_TTL_JITTER_SECONDS = 14 * 24 * 60 * 60+# Upper bound on how far past the experiment end a metric-events build may scan.# retention_window_end is an unrestricted user-supplied integer; without a cap, a huge# window would stretch the precompute horizon into thousands of daily jobs before the@@ -122,6 +127,7 @@ def experiment_precompute_ttl_schedule(team_timezone: str) -> TtlSchedule:DEFAULT_EXPOSURE_TTL_SECONDS,team_timezone,max_window_days=PRECOMPUTE_MAX_WINDOW_DAYS,+ default_ttl_jitter_seconds=PRECOMPUTE_TTL_JITTER_SECONDS,)