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.

fix(experiments): clamp precompute job claims to the build's as_of (#97251)

Juraj Majerik8f9bac1f4fce
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index d610bccf75e8..00139bdb76b1 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -722,19 +722,28 @@ def find_missing_contiguous_windows(
If no jobs exist for Jan 1-4, it returns: [(Jan 1, Jan 4)]
"""
+ # Some callers pass naive datetimes; window bounds and job rows are aware UTC.
+ if end_timestamp.tzinfo is None:
+ end_timestamp = end_timestamp.replace(tzinfo=UTC)
+
# Step 1: Generate daily windows for the range
daily_windows = get_daily_windows(start_timestamp, end_timestamp)
# Step 2: Find missing daily windows
missing = []
for window_start, window_end in daily_windows:
+ # The final window is rounded up to a full day, but the query reads only
+ # up to end_timestamp. A claim clamped to the data horizon (see
+ # clamp_ranges_to_data_horizon) must count as covering, or every read at
+ # the same `end` would rebuild the same window.
+ required_end = min(window_end, end_timestamp)
# Check if this window is covered by any READY or PENDING job
is_covered = False
for job in existing_jobs:
if (
job.status in (PreaggregationJob.Status.READY, PreaggregationJob.Status.PENDING)
and job.time_range_start <= window_start
- and job.time_range_end >= window_end
+ and job.time_range_end >= required_end
):
is_covered = True
break
@@ -766,6 +775,55 @@ def find_missing_contiguous_windows(
return merged
+@frozen
+class BuildRange:
+ """One contiguous span a single job's INSERT fills, with its band TTL."""
+
+ start: datetime
+ end: datetime
+ ttl_seconds: int
+
+
+def clamp_ranges_to_data_horizon(
+ ttl_ranges: list[tuple[datetime, datetime, int]],
+ horizon: datetime | None,
+) -> list[BuildRange]:
+ """
+ Clamp build ranges so no created job claims time past `horizon`, the point
+ up to which the INSERT stores data. A None horizon only wraps the ranges.
+
+ Daily windows round the final day up to midnight, so a historical mid-day
+ horizon would otherwise create a job that claims hours it never stored, and
+ every later read would treat the unstored tail as covered until the job
+ expires (up to 60 days in the frozen band).
+
+ A range that crosses the horizon splits at the horizon's day boundary: the
+ complete days keep a full-day claim and the partial tail becomes its own
+ job. Split jobs tile, so a later full-day rebuild replaces only the tail.
+ A single clamped multi-day job would partially overlap that rebuild and be
+ evicted whole by `filter_overlapping_jobs`, dropping its complete days.
+
+ Callers must not pass a horizon on the current UTC day: the same-day TTL
+ already refreshes today's window, and a clamped claim would force a
+ rebuild on every read.
+ """
+ if horizon is None:
+ return [BuildRange(start=s, end=e, ttl_seconds=ttl) for s, e, ttl in ttl_ranges]
+
+ clamped: list[BuildRange] = []
+ horizon_day_start = datetime(horizon.year, horizon.month, horizon.day, tzinfo=UTC)
+ for range_start, range_end, ttl in ttl_ranges:
+ if range_end <= horizon:
+ clamped.append(BuildRange(start=range_start, end=range_end, ttl_seconds=ttl))
+ continue
+ split = max(range_start, horizon_day_start)
+ if split > range_start:
+ clamped.append(BuildRange(start=range_start, end=split, ttl_seconds=ttl))
+ if horizon > split:
+ clamped.append(BuildRange(start=split, end=horizon, ttl_seconds=ttl))
+ return clamped
+
+
def create_lazy_computation_job(
team: Team,
query_hash: str,
@@ -995,6 +1053,7 @@ class LazyComputationExecutor:
start: datetime,
end: datetime,
run_insert: Callable[[Team, PreaggregationJob], int | None] | None = None,
+ end_is_data_horizon: bool = False,
) -> LazyComputationResult:
"""
Execute computation jobs for the given query and time range.
@@ -1011,6 +1070,12 @@ class LazyComputationExecutor:
default AST-based run_computation_insert with query_info. Returns the
number of rows it wrote, or None when it can't report one — see the
empty-insert branch below for what a 0 buys.
+ end_is_data_horizon: True when the caller's INSERT stores no rows past
+ `end` (it bakes `end` into its own filters), so the final
+ day's job must not claim past it. Leave False when the
+ INSERT fills whole daily windows regardless of `end`,
+ because clamping those would create a new partial-tail job
+ for every distinct `end` a user submits.
"""
insert_fn = run_insert or (lambda t, j: run_lazy_computation_insert(t, j, query_info))
query_hash = compute_query_hash(query_info)
@@ -1028,6 +1093,15 @@ class LazyComputationExecutor:
had_ready_at_start: bool | None = None
+ # Set when `end` is a data horizon on a past UTC day; the create loop then
+ # clamps job claims to it so a truncated build cannot mark unstored hours
+ # as covered. Some callers pass a naive `end`; treat it as UTC like the
+ # window math does.
+ now_utc = django_timezone.now()
+ today_start_utc = datetime(now_utc.year, now_utc.month, now_utc.day, tzinfo=UTC)
+ end_utc = end if end.tzinfo is not None else end.replace(tzinfo=UTC)
+ historical_end = end_utc if end_is_data_horizon and end_utc < today_start_utc else None
+
def _log_execution(outcome: str, result: LazyComputationResult) -> None:
if outcome == "check_miss":
# Check-only misses return before any job is created or waited on,
@@ -1081,7 +1155,9 @@ class LazyComputationExecutor:
# The filter can also hide a window covered only by an older
# PENDING job; recomputing it costs at most one duplicate build.
missing_ranges = find_missing_contiguous_windows(filter_overlapping_jobs(fresh_jobs), start, end)
- ttl_ranges = split_ranges_by_ttl(missing_ranges, self.ttl_schedule)
+ build_ranges = clamp_ranges_to_data_horizon(
+ split_ranges_by_ttl(missing_ranges, self.ttl_schedule), historical_end
+ )
if had_ready_at_start is None:
had_ready_at_start = any(j.status == PreaggregationJob.Status.READY for j in fresh_jobs)
@@ -1091,7 +1167,7 @@ class LazyComputationExecutor:
# fully cover the range, return them immediately — complete-but-stale beats
# blocking. Whoever refreshes (the warmer, or a request after the grace)
# replaces the data; `filter_overlapping_jobs` always prefers newer jobs.
- if self.stale_while_revalidate_seconds is not None and (ttl_ranges or pending_jobs):
+ if self.stale_while_revalidate_seconds is not None and (build_ranges or pending_jobs):
graced = find_existing_jobs(
team, query_hash, start, end, expired_grace_seconds=self.stale_while_revalidate_seconds
)
@@ -1116,7 +1192,7 @@ class LazyComputationExecutor:
# jobs (the stale-serve above would have returned), and this request
# must not compute inline or block on someone else's pending job —
# report the miss so the caller serves live and warms in background.
- if not self.run_inserts and (ttl_ranges or pending_jobs):
+ if not self.run_inserts and (build_ranges or pending_jobs):
result = LazyComputationResult(
ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded
)
@@ -1126,8 +1202,8 @@ class LazyComputationExecutor:
# Step 3: Insert missing ranges
did_work = False
lost_create_race = False
- if ttl_ranges and failures <= self.max_retries:
- for range_start, range_end, ttl in ttl_ranges:
+ if build_ranges and failures <= self.max_retries:
+ for build_range in build_ranges:
# Each insert runs inline and is bounded only by the ClickHouse
# max_execution_time, which is larger than our wait budget. A capped
# (narrow) window can produce many ranges; stop before starting another
@@ -1141,13 +1217,13 @@ class LazyComputationExecutor:
_log_execution("timeout", result)
return result
- # `ttl` is the band TTL used for merging; the job's real expiry adds the jitter
+ # `ttl_seconds` 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),
+ build_range.start,
+ build_range.end,
+ self.ttl_schedule.get_ttl(build_range.start, jittered=True),
)
if new_job is None:
# Another executor created a PENDING job for this range; the
@@ -1160,10 +1236,10 @@ class LazyComputationExecutor:
team_id=team.id,
query_hash=query_hash,
table=str(query_info.table),
- time_range_start=str(range_start),
- time_range_end=str(range_end),
+ time_range_start=str(build_range.start),
+ time_range_end=str(build_range.end),
)
- if self._try_fail_expired_pending_job(team, query_hash, range_start, range_end):
+ if self._try_fail_expired_pending_job(team, query_hash, build_range.start, build_range.end):
LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
outcome="expired", table=str(query_info.table)
).inc()
@@ -1172,8 +1248,8 @@ class LazyComputationExecutor:
team_id=team.id,
query_hash=query_hash,
table=str(query_info.table),
- time_range_start=str(range_start),
- time_range_end=str(range_end),
+ time_range_start=str(build_range.start),
+ time_range_end=str(build_range.end),
)
lost_create_race = True
continue
@@ -1202,7 +1278,7 @@ class LazyComputationExecutor:
new_job.computed_at = django_timezone.now()
if wrote_nothing and new_job.expires_at is not None:
empty_expires_at = self.ttl_schedule.empty_result_expires_at(
- new_job.computed_at, range_end
+ new_job.computed_at, build_range.end
)
if empty_expires_at is not None:
new_job.expires_at = min(new_job.expires_at, empty_expires_at)
@@ -1218,9 +1294,9 @@ class LazyComputationExecutor:
job_id=str(new_job.id),
query_hash=query_hash,
table=str(query_info.table),
- time_range_start=str(range_start),
- time_range_end=str(range_end),
- ttl_seconds=ttl,
+ time_range_start=str(build_range.start),
+ time_range_end=str(build_range.end),
+ ttl_seconds=build_range.ttl_seconds,
insert_duration_ms=round(insert_elapsed * 1000),
rows_written=rows_written,
expires_at=str(new_job.expires_at),
@@ -1241,9 +1317,9 @@ class LazyComputationExecutor:
job_id=str(new_job.id),
query_hash=query_hash,
table=str(query_info.table),
- time_range_start=str(range_start),
- time_range_end=str(range_end),
- ttl_seconds=ttl,
+ time_range_start=str(build_range.start),
+ time_range_end=str(build_range.end),
+ ttl_seconds=build_range.ttl_seconds,
insert_duration_ms=round(insert_elapsed * 1000),
error=str(e)[:500],
error_type=type(e).__name__,
@@ -1267,7 +1343,7 @@ class LazyComputationExecutor:
return result
did_work = True
- if ttl_ranges and failures > self.max_retries:
+ if build_ranges and failures > self.max_retries:
errors.append("Max retries exceeded for computation")
result = LazyComputationResult(
ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded
@@ -1482,6 +1558,7 @@ def ensure_precomputed(
run_inserts: bool = True,
empty_result_ttl_seconds: int | None = None,
empty_result_max_age_seconds: int | None = None,
+ end_is_data_horizon: bool = False,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1547,6 +1624,10 @@ def ensure_precomputed(
hash covers only the substituted AST — so modifiers must never
change what the query computes, only how it executes (e.g.
`sessionIdPushdown`, which is semantics-preserving by design).
+ end_is_data_horizon: Set True when the insert query bakes `time_range_end`
+ into its own filters, so it stores no rows past it. Job claims
+ then clamp to a historical end instead of claiming the full
+ final day. See LazyComputationExecutor.execute.
Returns:
ComputationResult with job_ids that can be used to query the data
@@ -1652,7 +1733,14 @@ def ensure_precomputed(
stale_while_revalidate_seconds=stale_while_revalidate_seconds,
run_inserts=run_inserts,
)
- return executor.execute(team, query_info, time_range_start, time_range_end, run_insert=_run_manual_insert)
+ return executor.execute(
+ team,
+ query_info,
+ time_range_start,
+ time_range_end,
+ run_insert=_run_manual_insert,
+ end_is_data_horizon=end_is_data_horizon,
+ )
def _resolve_insert_query(insert_query: str | ast.SelectQuery, placeholders: dict[str, ast.Expr]) -> ast.SelectQuery:
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.py
index 131e4775f928..964cc3ca110a 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
@@ -7,6 +7,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import patch
from django.db import IntegrityError
+from django.test import SimpleTestCase
from django.utils import timezone as django_timezone
from clickhouse_driver.errors import ServerException
@@ -35,6 +36,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
NON_RETRYABLE_CLICKHOUSE_ERROR_CODES,
PREAGGREGATION_INSERT_QUORUM,
PREAGGREGATION_INSERT_QUORUM_TIMEOUT_MS,
+ BuildRange,
LazyComputationExecutor,
LazyComputationQuery,
LazyComputationResult,
@@ -44,6 +46,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
_get_insert_settings,
_written_rows,
build_lazy_computation_insert_sql,
+ clamp_ranges_to_data_horizon,
compute_query_hash,
create_lazy_computation_job,
ensure_precomputed,
@@ -226,6 +229,89 @@ class TestFindMissingContiguousWindows(BaseTest):
assert missing[0] == (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 2, tzinfo=UTC))
assert missing[1] == (datetime(2024, 1, 3, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC))
+ @parameterized.expand(
+ [
+ ("same_end_covered", datetime(2024, 1, 3, 12, tzinfo=UTC), []),
+ (
+ "later_end_rebuilds_final_day",
+ datetime(2024, 1, 4, tzinfo=UTC),
+ [(datetime(2024, 1, 3, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC))],
+ ),
+ ]
+ )
+ def test_final_window_only_requires_coverage_up_to_requested_end(self, _name, end, expected_missing):
+ start = datetime(2024, 1, 1, tzinfo=UTC)
+ full_days_job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash="test_hash",
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 3, tzinfo=UTC),
+ status=PreaggregationJob.Status.READY,
+ )
+ tail_job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash="test_hash",
+ time_range_start=datetime(2024, 1, 3, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 3, 12, tzinfo=UTC),
+ status=PreaggregationJob.Status.READY,
+ )
+
+ missing = find_missing_contiguous_windows([full_days_job, tail_job], start, end)
+
+ assert missing == expected_missing
+
+
+class TestClampRangesToDataHorizon(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "no_horizon_wraps_unchanged",
+ [(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC), 60)],
+ None,
+ [
+ BuildRange(
+ start=datetime(2024, 1, 1, tzinfo=UTC), end=datetime(2024, 1, 4, tzinfo=UTC), ttl_seconds=60
+ )
+ ],
+ ),
+ (
+ "crossing_multi_day_range_splits_at_day_boundary",
+ [(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC), 60)],
+ datetime(2024, 1, 3, 12, tzinfo=UTC),
+ [
+ BuildRange(
+ start=datetime(2024, 1, 1, tzinfo=UTC), end=datetime(2024, 1, 3, tzinfo=UTC), ttl_seconds=60
+ ),
+ BuildRange(
+ start=datetime(2024, 1, 3, tzinfo=UTC), end=datetime(2024, 1, 3, 12, tzinfo=UTC), ttl_seconds=60
+ ),
+ ],
+ ),
+ (
+ "crossing_single_day_range_clamps_without_split",
+ [(datetime(2024, 1, 3, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC), 60)],
+ datetime(2024, 1, 3, 12, tzinfo=UTC),
+ [
+ BuildRange(
+ start=datetime(2024, 1, 3, tzinfo=UTC), end=datetime(2024, 1, 3, 12, tzinfo=UTC), ttl_seconds=60
+ )
+ ],
+ ),
+ (
+ "midnight_horizon_is_noop",
+ [(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC), 60)],
+ datetime(2024, 1, 3, tzinfo=UTC),
+ [
+ BuildRange(
+ start=datetime(2024, 1, 1, tzinfo=UTC), end=datetime(2024, 1, 3, tzinfo=UTC), ttl_seconds=60
+ )
+ ],
+ ),
+ ]
+ )
+ def test_clamps_and_splits(self, _name, ttl_ranges, horizon, expected):
+ assert clamp_ranges_to_data_horizon(ttl_ranges, horizon) == expected
+
class TestFilterOverlappingJobs(BaseTest):
def test_empty_list(self):
@@ -654,6 +740,107 @@ class TestExecuteComputationJobs(ClickhouseTestMixin, BaseTest):
assert ch_results[1][4] == 1 # Jan 2: user2
assert ch_results[2][4] == 1 # Jan 3: user3
+ def test_historical_mid_day_end_claims_only_stored_hours_then_heals(self):
+ self._create_pageview_events()
+ query_info = LazyComputationQuery(
+ query=self._make_computation_query(), table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
+ )
+ mid_day_end = datetime(2024, 1, 3, 12, tzinfo=UTC)
+
+ first = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=mid_day_end,
+ end_is_data_horizon=True,
+ )
+
+ assert first.ready is True
+ first_claims = sorted(
+ (j.time_range_start, j.time_range_end) for j in PreaggregationJob.objects.filter(id__in=first.job_ids)
+ )
+ assert first_claims == [
+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC)),
+ (datetime(2024, 1, 3, tzinfo=UTC), mid_day_end),
+ ]
+
+ second = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=mid_day_end,
+ end_is_data_horizon=True,
+ )
+
+ assert second.ready is True
+ assert set(second.job_ids) == set(first.job_ids)
+
+ third = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 4, tzinfo=UTC),
+ end_is_data_horizon=True,
+ )
+
+ assert third.ready is True
+ third_claims = sorted(
+ (j.time_range_start, j.time_range_end) for j in PreaggregationJob.objects.filter(id__in=third.job_ids)
+ )
+ assert third_claims == [
+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC)),
+ (datetime(2024, 1, 3, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC)),
+ ]
+ ch_results = self._query_computation_results(third.job_ids)
+ assert len(ch_results) == 3
+
+ def test_current_day_end_keeps_full_day_claim(self):
+ query_info = LazyComputationQuery(
+ query=self._make_computation_query(), table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
+ )
+
+ with time_machine.travel(datetime(2024, 1, 3, 12, tzinfo=UTC), tick=False):
+ result = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 3, 12, tzinfo=UTC),
+ end_is_data_horizon=True,
+ )
+
+ assert result.ready is True
+ assert len(result.job_ids) == 1
+ job = PreaggregationJob.objects.get(id=result.job_ids[0])
+ assert job.time_range_end == datetime(2024, 1, 4, tzinfo=UTC)
+
+ def test_historical_mid_day_end_without_horizon_flag_keeps_full_day_claim(self):
+ query_info = LazyComputationQuery(
+ query=self._make_computation_query(), table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
+ )
+
+ first = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 3, 12, tzinfo=UTC),
+ )
+ second = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 3, 12, 30, tzinfo=UTC),
+ )
+
+ assert first.ready is True
+ assert second.ready is True
+ # Whole-day inserts stay valid for any end inside the day, so a varied
+ # user-supplied end must reuse the full-day job instead of creating a
+ # new partial-tail job per distinct end.
+ assert len(first.job_ids) == 1
+ assert second.job_ids == first.job_ids
+ job = PreaggregationJob.objects.get(id=first.job_ids[0])
+ assert job.time_range_end == datetime(2024, 1, 4, tzinfo=UTC)
+
def test_takes_over_expired_pending_job(self):
self._create_pageview_events()
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index 8a17c4bd0efc..29303ab59641 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -141,6 +141,7 @@ class ExperimentExposuresQueryRunner(QueryRunner):
table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
placeholders=placeholders,
sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
spill_to_disk=True,
)
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 7fc82c83a782..4727dfcca1fa 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -366,6 +366,7 @@ class ExperimentQueryRunner(QueryRunner):
table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
placeholders=placeholders,
sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
# High-volume teams' builds OOM even at capped window widths; spilling the
# GROUP BY to disk degrades gracefully instead of failing the build.
spill_to_disk=True,
@@ -403,6 +404,7 @@ class ExperimentQueryRunner(QueryRunner):
table=LazyComputationTable.EXPERIMENT_METRIC_EVENTS_PREAGGREGATED,
placeholders=placeholders,
sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
spill_to_disk=True,
)
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py
index 29b7048e4d91..1e80b7f9733a 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py
@@ -167,8 +167,13 @@ class TestExperimentFunnelMetricEventsPreaggregation(ExperimentQueryRunnerBaseTe
assert first_result.ready is True
assert second_result.ready is True
- assert first_result.job_ids == second_result.job_ids
- assert mock_sync_execute.call_count == len(first_result.job_ids)
+ # The stable hash shares the complete day-aligned jobs across as_of values;
+ # only the final partial day, claimed up to each as_of, is rebuilt.
+ first_jobs = set(first_result.job_ids)
+ second_jobs = set(second_result.job_ids)
+ assert len(second_jobs) == len(first_jobs)
+ assert len(first_jobs & second_jobs) == len(first_jobs) - 1
+ assert mock_sync_execute.call_count == len(first_jobs) + 1
@patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
def test_metric_events_precomputation_for_stopped_experiment_uses_end_date(self, mock_sync_execute):
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py
index db5a85e54db4..64e313e933ed 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py
@@ -171,8 +171,13 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTest
assert first_result.ready is True
assert second_result.ready is True
- assert first_result.job_ids == second_result.job_ids
- assert mock_sync_execute.call_count == len(first_result.job_ids)
+ # The stable hash shares the complete day-aligned jobs across as_of values;
+ # only the final partial day, claimed up to each as_of, is rebuilt.
+ first_jobs = set(first_result.job_ids)
+ second_jobs = set(second_result.job_ids)
+ assert len(second_jobs) == len(first_jobs)
+ assert len(first_jobs & second_jobs) == len(first_jobs) - 1
+ assert mock_sync_execute.call_count == len(first_jobs) + 1
@patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
def test_dau_metric_shares_precompute_jobs_with_count_metric(self, mock_sync_execute):
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py
index 849b25f502a4..40305e647c61 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py
@@ -284,8 +284,13 @@ class TestExperimentRetentionMetricEventsPreaggregation(ExperimentQueryRunnerBas
assert first_result.ready is True
assert second_result.ready is True
- assert first_result.job_ids == second_result.job_ids
- assert mock_sync_execute.call_count == len(first_result.job_ids)
+ # The stable hash shares the complete day-aligned jobs across as_of values;
+ # only the final partial day, claimed up to each as_of, is rebuilt.
+ first_jobs = set(first_result.job_ids)
+ second_jobs = set(second_result.job_ids)
+ assert len(second_jobs) == len(first_jobs)
+ assert len(first_jobs & second_jobs) == len(first_jobs) - 1
+ assert mock_sync_execute.call_count == len(first_jobs) + 1
@patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
def test_retention_metric_events_precomputation_hash_tracks_retention_window(self, mock_sync_execute):
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index 69871e7646b1..51dc1804d449 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -466,6 +466,7 @@ def _resolve_exposure_read(team: Team, experiment: Experiment, context: Experime
table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
placeholders=placeholders,
sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
spill_to_disk=True,
)
except Exception: