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(marketing-analytics): stop empty cost precompute jobs serving $0 days (#77835)

Javier Bahamondes6b6549c98eef
diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.md
index cd9aea9a47a9..17ddc18f6371 100644
--- a/products/analytics_platform/backend/lazy_computation/README.md
+++ b/products/analytics_platform/backend/lazy_computation/README.md
@@ -193,10 +193,13 @@ Jobs run synchronously inside `execute()` — there is no background queue, so P
`outcome` values:
-- `ready` — INSERT succeeded, PENDING → READY.
+- `ready` — INSERT succeeded and wrote rows, PENDING → READY.
+- `ready_empty` — INSERT succeeded but wrote no rows, PENDING → READY. Still a success; split out because an empty window is only provisionally computed (see `TtlSchedule.empty_result_ttl_seconds`), so a climbing share here points at a lagging source rather than a broken query.
- `failed` — INSERT raised (retryable or non-retryable), PENDING → FAILED.
- `stale` — a waiter detected the owning executor crashed (`_try_mark_stale_job_as_failed`) and the atomic update flipped the row to FAILED.
+Sum `ready` and `ready_empty` for total successes, and prefer `outcome=~"failed|stale"` over `outcome!="ready"` when alerting — the latter counts empty-but-successful jobs as problems.
+
Net job throughput (positive = backlog growing, expected ~0 in steady state):
```promql
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 a50ca42fb02c..a9f540598dbc 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -131,10 +131,15 @@ LAZY_COMPUTATION_EXECUTIONS_TOTAL = Counter(
# to get average jobs per miss execution (i.e. average miss window size).
#
# `finished` outcomes:
-# - `ready` → INSERT succeeded, row moved PENDING → READY.
-# - `failed` → INSERT raised (retryable or non-retryable), row moved PENDING → FAILED.
-# - `stale` → another waiter detected the owning executor crashed and marked
-# the row FAILED via `_try_mark_stale_job_as_failed`.
+# - `ready` → INSERT succeeded and wrote rows, row moved PENDING → READY.
+# - `ready_empty` → INSERT succeeded but wrote no rows, row moved PENDING → READY. Split out
+# from `ready` because an empty window is only provisionally computed (see
+# `TtlSchedule.empty_result_ttl_seconds`); a climbing share here means a
+# source is lagging. Alert on `outcome=~"failed|stale"` rather than
+# `outcome!="ready"`, and sum both ready labels for total successes.
+# - `failed` → INSERT raised (retryable or non-retryable), row moved PENDING → FAILED.
+# - `stale` → another waiter detected the owning executor crashed and marked
+# the row FAILED via `_try_mark_stale_job_as_failed`.
LAZY_COMPUTATION_JOBS_CREATED_TOTAL = Counter(
"lazy_computation_jobs_created_total",
"PreaggregationJob rows inserted in PENDING status (one per missing range, per executor).",
@@ -209,6 +214,26 @@ class TtlSchedule:
non-UTC teams, whose UTC-aligned edge windows can land in a long-TTL band while
still settling. `None` disables the check.
+ `empty_result_ttl_seconds` caps the TTL of a job that wrote no rows. A zero-row insert is
+ indistinguishable from a productive one at the SQL level, but it leaves the window only
+ *provisionally* computed: either the source genuinely had no activity, or it hadn't been
+ synced through the window yet (a paused or failed warehouse sync, a source that resumes
+ after a billing limit). Coverage keys on the job existing rather than on rows existing (see
+ `find_missing_contiguous_windows`), so an empty job holding a long band TTL freezes the
+ window at zero for that whole TTL even once the data lands. Opt in when a caller reads from
+ a source that can lag — data warehouse tables — and leave it `None` when empty genuinely
+ means empty (event tables), since the cap trades recompute work for freshness. Note the cap
+ bounds when the window is *recomputed*, not when a reader stops seeing zero: a caller serving
+ stale within a grace (`stale_while_revalidate_seconds`) can hand back the empty window for up
+ to the cap plus that grace.
+
+ `empty_result_max_age_seconds` bounds *which* empty windows get that cap, measured from
+ `time_range_end` to now. The cap only buys something while a sync could still deliver the
+ window; past that, empty almost certainly means empty, and re-capping forever turns a 7-day
+ band TTL into a 6-hourly rescan of history that will never change (~28x the insert work on a
+ long warmer window). Windows older than this keep their full band TTL. `None` caps every
+ empty window regardless of age.
+
Use parse_ttl_schedule() to create from user-facing dict format.
"""
@@ -216,6 +241,8 @@ class TtlSchedule:
default_ttl_seconds: int
max_window_days: int | None = None
settling_period_seconds: int | None = None
+ empty_result_ttl_seconds: int | None = None
+ empty_result_max_age_seconds: int | None = None
def get_ttl(self, window_start: datetime) -> int:
for cutoff, ttl in self.rules:
@@ -223,9 +250,34 @@ class TtlSchedule:
return ttl
return self.default_ttl_seconds
+ def 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.
+
+ A ceiling, never a floor: the caller takes `min` with the band expiry, so a short band
+ (today's window) still comes back sooner than the cap.
+ """
+ if self.empty_result_ttl_seconds is None:
+ return None
+ if (
+ self.empty_result_max_age_seconds is not None
+ and (computed_at - window_end).total_seconds() > self.empty_result_max_age_seconds
+ ):
+ return None
+ return computed_at + timedelta(seconds=self.empty_result_ttl_seconds)
+
@classmethod
- def from_seconds(cls, ttl_seconds: int) -> "TtlSchedule":
- return cls(rules=[], default_ttl_seconds=ttl_seconds)
+ def from_seconds(
+ cls,
+ ttl_seconds: int,
+ empty_result_ttl_seconds: int | None = None,
+ empty_result_max_age_seconds: int | None = None,
+ ) -> "TtlSchedule":
+ return cls(
+ rules=[],
+ default_ttl_seconds=ttl_seconds,
+ empty_result_ttl_seconds=empty_result_ttl_seconds,
+ empty_result_max_age_seconds=empty_result_max_age_seconds,
+ )
DEFAULT_TTL_SCHEDULE = TtlSchedule.from_seconds(DEFAULT_TTL_SECONDS)
@@ -236,6 +288,8 @@ def parse_ttl_schedule(
team_timezone: str = "UTC",
max_window_days: int | None = None,
settling_period_seconds: int | None = None,
+ empty_result_ttl_seconds: int | None = None,
+ empty_result_max_age_seconds: int | None = None,
) -> TtlSchedule:
"""Parse a TTL specification into a TtlSchedule.
@@ -253,6 +307,13 @@ def parse_ttl_schedule(
Raises ValueError for unrecognized keys or non-positive TTL values.
"""
+ # Validated like every other TTL on the schedule: 0 would expire a job the instant it is
+ # created, leaving the executor to lean on its own no-infinite-loop guard instead.
+ if empty_result_ttl_seconds is not None and empty_result_ttl_seconds <= 0:
+ 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 isinstance(ttl, int):
if ttl <= 0:
raise ValueError(f"TTL must be positive, got {ttl}")
@@ -261,6 +322,8 @@ def parse_ttl_schedule(
default_ttl_seconds=ttl,
max_window_days=max_window_days,
settling_period_seconds=settling_period_seconds,
+ empty_result_ttl_seconds=empty_result_ttl_seconds,
+ empty_result_max_age_seconds=empty_result_max_age_seconds,
)
tz = ZoneInfo(team_timezone)
@@ -289,6 +352,8 @@ def parse_ttl_schedule(
default_ttl_seconds=default_ttl,
max_window_days=max_window_days,
settling_period_seconds=settling_period_seconds,
+ empty_result_ttl_seconds=empty_result_ttl_seconds,
+ empty_result_max_age_seconds=empty_result_max_age_seconds,
)
@@ -754,12 +819,26 @@ def build_lazy_computation_insert_sql(
return sql, context.values
+def _written_rows(insert_result: object) -> int:
+ """How many rows an INSERT wrote, or 0.
+
+ `sync_execute` swaps an INSERT's result for the ClickHouse `written_rows` progress counter,
+ but only when that counter is nonzero — otherwise it passes the driver's (empty) result
+ through. So "not an int" is precisely the zero-row case.
+ """
+ return insert_result if isinstance(insert_result, int) else 0
+
+
def run_lazy_computation_insert(
team: Team,
job: PreaggregationJob,
query_info: QueryInfo,
-) -> None:
- """Run the INSERT query to populate lazy-computed results in ClickHouse."""
+) -> int:
+ """Run the INSERT query to populate lazy-computed results in ClickHouse.
+
+ Returns the number of rows written, which the executor uses to tell a genuinely computed
+ window from an empty one.
+ """
ch_expires_at = _get_ch_expires_at(job, LazyComputationTable.PREAGGREGATION_RESULTS)
insert_sql, values = build_lazy_computation_insert_sql(
@@ -778,10 +857,12 @@ def run_lazy_computation_insert(
precompute_window_start=str(job.time_range_start),
precompute_window_end=str(job.time_range_end),
):
- sync_execute(
- insert_sql,
- values,
- settings=_get_insert_settings(team.id),
+ return _written_rows(
+ sync_execute(
+ insert_sql,
+ values,
+ settings=_get_insert_settings(team.id),
+ )
)
@@ -845,7 +926,7 @@ class LazyComputationExecutor:
query_info: QueryInfo,
start: datetime,
end: datetime,
- run_insert: Callable[[Team, PreaggregationJob], None] | None = None,
+ run_insert: Callable[[Team, PreaggregationJob], int | None] | None = None,
) -> LazyComputationResult:
"""
Execute computation jobs for the given query and time range.
@@ -859,7 +940,9 @@ class LazyComputationExecutor:
Args:
run_insert: Optional custom insert function. If not provided, uses the
- default AST-based run_computation_insert with query_info.
+ 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.
"""
insert_fn = run_insert or (lambda t, j: run_lazy_computation_insert(t, j, query_info))
query_hash = compute_query_hash(query_info)
@@ -1001,14 +1084,28 @@ class LazyComputationExecutor:
try:
insert_start = time.monotonic()
- insert_fn(team, new_job)
+ rows_written = insert_fn(team, new_job)
insert_elapsed = time.monotonic() - insert_start
+ # An empty window is only provisionally computed — see
+ # `TtlSchedule.empty_result_ttl_seconds` for why, and note this only
+ # applies to callers that opted in. `rows_written is None` means the
+ # insert function can't report a count, which is not a claim of
+ # emptiness. `min` because the cap is a ceiling, never a floor: a short
+ # band (today's window) already comes back sooner than the cap.
+ wrote_nothing = rows_written == 0
new_job.status = PreaggregationJob.Status.READY
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
+ )
+ if empty_expires_at is not None:
+ new_job.expires_at = min(new_job.expires_at, empty_expires_at)
new_job.save()
publish_job_completion(new_job.id, "ready")
LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
- outcome="ready", table=str(query_info.table)
+ outcome="ready_empty" if wrote_nothing else "ready",
+ table=str(query_info.table),
).inc()
jobs_created += 1
logger.info(
@@ -1020,6 +1117,8 @@ class LazyComputationExecutor:
time_range_end=str(range_end),
ttl_seconds=ttl,
insert_duration_ms=round(insert_elapsed * 1000),
+ rows_written=rows_written,
+ expires_at=str(new_job.expires_at),
)
except Exception as e:
insert_elapsed = time.monotonic() - insert_start
@@ -1218,6 +1317,8 @@ def ensure_precomputed(
stale_while_revalidate_seconds: float | None = None,
modifiers: HogQLQueryModifiers | None = None,
run_inserts: bool = True,
+ empty_result_ttl_seconds: int | None = None,
+ empty_result_max_age_seconds: int | None = None,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1249,6 +1350,13 @@ def ensure_precomputed(
- dict: maps date strings to TTL values. Keys are parsed using
relative_date_parse (e.g. "7d", "24h", "2026-02-15"). The
"default" key sets the fallback TTL. Uses team timezone.
+ empty_result_ttl_seconds: Caps the TTL of a job that wrote no rows, so a window the
+ source hadn't synced yet doesn't stay cached as zero for the full band
+ TTL. See TtlSchedule.empty_result_ttl_seconds. Ignored when `ttl_seconds`
+ is already a built TtlSchedule — set it on the schedule instead.
+ empty_result_max_age_seconds: Bounds which empty windows get that cap, measured from
+ `time_range_end`. See TtlSchedule.empty_result_max_age_seconds. Same
+ caveat: ignored when `ttl_seconds` is already a built TtlSchedule.
table: The target computation table (default "preaggregation_results")
placeholders: Additional placeholder values to substitute into the query.
time_window_min and time_window_max are added automatically.
@@ -1336,7 +1444,7 @@ def ensure_precomputed(
timezone=team.timezone,
)
- def _run_manual_insert(t: Team, job: PreaggregationJob) -> None:
+ def _run_manual_insert(t: Team, job: PreaggregationJob) -> int:
insert_sql, values = _build_manual_insert_sql(
team=t,
job=job,
@@ -1355,16 +1463,25 @@ def ensure_precomputed(
if query_type:
tag_kwargs["query_type"] = query_type
with tags_context(**tag_kwargs):
- sync_execute(
- insert_sql,
- values,
- settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk),
+ return _written_rows(
+ sync_execute(
+ insert_sql,
+ values,
+ settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk),
+ )
)
# A caller can hand in a fully-built TtlSchedule (e.g. one carrying a max_window_days
# cap) to bound job width — "switch the schedule"; otherwise parse int/dict as usual.
ttl_schedule = (
- ttl_seconds if isinstance(ttl_seconds, TtlSchedule) else parse_ttl_schedule(ttl_seconds, team.timezone)
+ ttl_seconds
+ if isinstance(ttl_seconds, TtlSchedule)
+ else parse_ttl_schedule(
+ ttl_seconds,
+ team.timezone,
+ empty_result_ttl_seconds=empty_result_ttl_seconds,
+ empty_result_max_age_seconds=empty_result_max_age_seconds,
+ )
)
executor = LazyComputationExecutor(
ttl_schedule=ttl_schedule,
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 a2268c9259d3..0290f1d83eff 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
@@ -42,6 +42,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
TtlSchedule,
_build_manual_insert_sql,
_get_insert_settings,
+ _written_rows,
build_lazy_computation_insert_sql,
compute_query_hash,
create_lazy_computation_job,
@@ -1312,6 +1313,30 @@ class TestParseTtlSchedule(BaseTest):
with pytest.raises(ValueError, match="must be positive"):
parse_ttl_schedule(ttl)
+ @parameterized.expand(
+ [
+ ("zero_empty_ttl", {"empty_result_ttl_seconds": 0}),
+ ("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}),
+ ]
+ )
+ def test_rejects_non_positive_empty_result_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)
+
+ def test_carries_empty_result_settings(self):
+ schedule = parse_ttl_schedule(
+ {"default": 3600}, "UTC", empty_result_ttl_seconds=600, empty_result_max_age_seconds=86400
+ )
+ assert schedule.empty_result_ttl_seconds == 600
+ assert schedule.empty_result_max_age_seconds == 86400
+
+ uncapped = parse_ttl_schedule(3600)
+ assert uncapped.empty_result_ttl_seconds is None
+ assert uncapped.empty_result_max_age_seconds is None
+
class TestSplitRangesByTtl(BaseTest):
def test_single_range_uniform_ttl(self):
@@ -1356,6 +1381,18 @@ class TestSplitRangesByTtl(BaseTest):
assert result[1] == (datetime(2024, 1, 5, tzinfo=UTC), datetime(2024, 1, 7, tzinfo=UTC), 3600)
+class TestWrittenRows(BaseTest):
+ """`sync_execute` only swaps an INSERT's result for the `written_rows` counter when that
+ counter is nonzero, so the driver's passthrough result is how a zero-row insert shows up."""
+
+ def test_int_result_is_the_row_count(self):
+ assert _written_rows(42) == 42
+
+ def test_passthrough_driver_result_means_zero_rows(self):
+ assert _written_rows([]) == 0
+ assert _written_rows(None) == 0
+
+
class TestComputationExecutor(BaseTest):
def test_executor_with_custom_settings(self):
default_executor = LazyComputationExecutor()
@@ -1634,6 +1671,125 @@ class TestComputationExecutorExecute(BaseTest):
time_diff = (job.expires_at - django_timezone.now()).total_seconds()
assert one_hour - 100 < time_diff < one_hour + 100
+ # --- Empty inserts ---
+ #
+ # A job that writes no rows is only provisionally computed: the source may have had no
+ # activity, or it may not have been synced through the window yet. Coverage keys on the job
+ # existing rather than on rows existing, so an empty job holding a full band TTL freezes the
+ # window at zero even after the data lands. Callers that read a source which can lag opt into
+ # a capped TTL for that case.
+
+ LONG_TTL = 7 * 24 * 60 * 60
+ EMPTY_TTL = 6 * 60 * 60
+
+ def _expires_in_seconds(self, job_id) -> float:
+ job = PreaggregationJob.objects.get(id=job_id)
+ assert job.expires_at is not None
+ return (job.expires_at - django_timezone.now()).total_seconds()
+
+ def _execute_with_insert(self, run_insert, ttl_schedule) -> LazyComputationResult:
+ query_info, _ = self._make_query_info()
+ return LazyComputationExecutor(ttl_schedule=ttl_schedule).execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 2, tzinfo=UTC),
+ run_insert=run_insert,
+ )
+
+ def test_zero_row_insert_caps_ttl_when_opted_in(self):
+ result = self._execute_with_insert(
+ lambda t, j: 0,
+ TtlSchedule.from_seconds(self.LONG_TTL, empty_result_ttl_seconds=self.EMPTY_TTL),
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.EMPTY_TTL) < 100
+
+ def test_zero_row_insert_keeps_band_ttl_when_not_opted_in(self):
+ # Shared infrastructure: a caller whose source can't lag (event tables) is unaffected.
+ result = self._execute_with_insert(lambda t, j: 0, TtlSchedule.from_seconds(self.LONG_TTL))
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.LONG_TTL) < 100
+
+ def test_zero_row_insert_does_not_lengthen_a_shorter_ttl(self):
+ one_hour = 60 * 60
+ result = self._execute_with_insert(
+ lambda t, j: 0,
+ TtlSchedule.from_seconds(one_hour, empty_result_ttl_seconds=self.EMPTY_TTL),
+ )
+
+ assert result.ready is True
+ # The cap is a ceiling, not a floor — today's short band must still come back sooner.
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - one_hour) < 100
+
+ def test_productive_insert_keeps_the_band_ttl(self):
+ result = self._execute_with_insert(
+ lambda t, j: 42,
+ TtlSchedule.from_seconds(self.LONG_TTL, empty_result_ttl_seconds=self.EMPTY_TTL),
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.LONG_TTL) < 100
+
+ def test_insert_that_cannot_report_a_row_count_keeps_the_band_ttl(self):
+ # Returning None isn't a claim that the window was empty, so leave the TTL alone.
+ result = self._execute_with_insert(
+ lambda t, j: None,
+ TtlSchedule.from_seconds(self.LONG_TTL, empty_result_ttl_seconds=self.EMPTY_TTL),
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.LONG_TTL) < 100
+
+ def test_empty_window_older_than_the_max_age_keeps_the_band_ttl(self):
+ # Past the horizon a sync could deliver in, empty means empty. Re-capping forever would
+ # turn the long band into a rescan of history that will never change. The fixed 2024
+ # window the helper uses is far outside any sane max age.
+ result = self._execute_with_insert(
+ lambda t, j: 0,
+ TtlSchedule.from_seconds(
+ self.LONG_TTL,
+ empty_result_ttl_seconds=self.EMPTY_TTL,
+ empty_result_max_age_seconds=14 * 24 * 60 * 60,
+ ),
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.LONG_TTL) < 100
+
+ def test_empty_window_inside_the_max_age_is_still_capped(self):
+ query_info, _ = self._make_query_info()
+ # A window that ended an hour ago is well inside the horizon.
+ end = django_timezone.now()
+ result = LazyComputationExecutor(
+ ttl_schedule=TtlSchedule.from_seconds(
+ self.LONG_TTL,
+ empty_result_ttl_seconds=self.EMPTY_TTL,
+ empty_result_max_age_seconds=14 * 24 * 60 * 60,
+ )
+ ).execute(
+ team=self.team,
+ query_info=query_info,
+ start=end - timedelta(hours=1),
+ end=end,
+ run_insert=lambda t, j: 0,
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.EMPTY_TTL) < 100
+
+ def test_max_age_alone_does_not_cap_anything(self):
+ # The horizon only bounds an opt-in that must still be made explicitly.
+ result = self._execute_with_insert(
+ lambda t, j: 0,
+ TtlSchedule.from_seconds(self.LONG_TTL, empty_result_max_age_seconds=14 * 24 * 60 * 60),
+ )
+
+ assert result.ready is True
+ assert abs(self._expires_in_seconds(result.job_ids[0]) - self.LONG_TTL) < 100
+
def test_short_ttl_does_not_infinite_loop(self):
query_info, _ = self._make_query_info()
@@ -2947,6 +3103,70 @@ class TestInsertSettingsAppliedToInserts(BaseTest):
assert mock_execute.call_args.kwargs["settings"] == _get_insert_settings(self.team.pk)
+class TestInsertsReportRowsWritten(BaseTest):
+ """Both insert wrappers must hand `sync_execute`'s row count back to the executor.
+
+ The empty-window cap keys entirely on this return value, and `None` is deliberately read as
+ "no claim of emptiness" — so a wrapper that stopped returning would disable the cap silently,
+ with no exception and no failing assertion anywhere else.
+ """
+
+ INSERT_QUERY = TestInsertSettingsAppliedToInserts.INSERT_QUERY
+
+ def _pending_job(self) -> PreaggregationJob:
+ return 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, 2, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+
+ def _query_info(self) -> QueryInfo:
+ query = parse_select(
+ self.INSERT_QUERY,
+ placeholders={
+ "time_window_min": ast.Constant(value=datetime(2024, 1, 1, tzinfo=UTC)),
+ "time_window_max": ast.Constant(value=datetime(2024, 1, 2, tzinfo=UTC)),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS)
+
+ @parameterized.expand([("productive", 42, 42), ("empty_passthrough", [], 0), ("empty_none", None, 0)])
+ def test_ast_insert_returns_rows_written(self, _name, sync_execute_result, expected):
+ with patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute",
+ return_value=sync_execute_result,
+ ):
+ assert run_lazy_computation_insert(self.team, self._pending_job(), self._query_info()) == expected
+
+ @parameterized.expand([("productive", 42, 42), ("empty_passthrough", [], 0), ("empty_none", None, 0)])
+ def test_manual_insert_returns_rows_written(self, _name, sync_execute_result, expected):
+ # `_run_manual_insert` is a closure inside ensure_precomputed, so drive it the way the
+ # executor does and read the count back off the capped TTL.
+ with patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute",
+ return_value=sync_execute_result,
+ ):
+ result = ensure_precomputed(
+ team=self.team,
+ insert_query=self.INSERT_QUERY,
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ ttl_seconds=7 * 24 * 60 * 60,
+ empty_result_ttl_seconds=60 * 60,
+ )
+
+ assert result.ready is True
+ job = PreaggregationJob.objects.get(id=result.job_ids[0])
+ assert job.expires_at is not None
+ expires_in = (job.expires_at - django_timezone.now()).total_seconds()
+ # Only a reported 0 caps the TTL; 42 and None must leave the 7-day band alone.
+ assert abs(expires_in - (60 * 60 if expected == 0 else 7 * 24 * 60 * 60)) < 100
+
+
class TestMaxWindowDaysCap(BaseTest):
def test_parse_carries_max_window_days(self):
assert parse_ttl_schedule(3600, max_window_days=2).max_window_days == 2
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index 28e0da18a010..decd43ce93be 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -31,9 +31,13 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryResponseProtocol, A
from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
-from posthog.models.team.team import DEFAULT_CURRENCY
+from posthog.models.team.team import DEFAULT_CURRENCY, Team
-from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationTable
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationTable,
+ TtlSchedule,
+ parse_ttl_schedule,
+)
from products.analytics_platform.backend.lazy_computation.stale_policy import is_background_warming_request
from products.marketing_analytics.backend.hogql_queries.constants import (
CHANNEL_SESSIONS_CTE_NAME,
@@ -84,6 +88,45 @@ COMPARE_PERIOD_PREVIOUS = "previous"
# SAME freshness the read path expects — a mismatch would warm jobs the read then treats as stale.
COSTS_PRECOMPUTE_TTL_SECONDS = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}
+# Cap for a cost window that materialized zero rows. Short enough that a source which was mid-sync
+# heals the same day, long enough that a genuinely empty window isn't re-scanned on every read.
+# This bounds recomputation, not what a reader sees: the read path serves stale within
+# STALE_WHILE_REVALIDATE_SECONDS, so a $0 window can still be handed back for up to the sum of both.
+COSTS_EMPTY_RESULT_TTL_SECONDS = 6 * 60 * 60 # 6 hours
+
+# How far back the cap above applies, measured from the window's end. A warehouse sync that is going
+# to deliver a window does so within days; past that, empty means empty, and re-capping forever would
+# turn the 7-day band into a 6-hourly rescan of history that will never change.
+COSTS_EMPTY_RESULT_MAX_AGE_SECONDS = 14 * 24 * 60 * 60 # 14 days
+
+# One day per job. `split_ranges_by_ttl` otherwise merges every window sharing a TTL band into a
+# single job, so the whole `default` band (everything older than yesterday) becomes one job — and
+# emptiness is only observable per job. A 10-day sync gap inside a 30-day read would sit in a job
+# that also covered productive days, report rows written, and keep the full 7-day TTL: exactly the
+# stuck-$0 window this schedule exists to prevent. Day-granular jobs make the signal per-day, and
+# match the warmer, which already chunks a day at a time (MARKETING_PRECOMPUTE_CHUNK_DAYS). The cost
+# is more, narrower inserts on a cold read rather than one wide one.
+COSTS_PRECOMPUTE_MAX_WINDOW_DAYS = 1
+
+
+def costs_precompute_ttl_schedule(team: Team) -> TtlSchedule:
+ """The freshness contract for native cost materialization. Both the read path and the Dagster
+ warmer build their schedule here so the two can't drift.
+
+ Costs are materialized from data warehouse tables, which lag: a window computed while its source
+ was mid-sync — or paused by a billing limit — writes no rows and looks like a successful compute.
+ Coverage keys on the job existing rather than on rows existing, so without `empty_result_ttl_seconds`
+ that empty window would stay authoritative for the whole band TTL (up to 7 days of a $0 chart)
+ even once the source catches up.
+ """
+ return parse_ttl_schedule(
+ COSTS_PRECOMPUTE_TTL_SECONDS,
+ team.timezone,
+ max_window_days=COSTS_PRECOMPUTE_MAX_WINDOW_DAYS,
+ empty_result_ttl_seconds=COSTS_EMPTY_RESULT_TTL_SECONDS,
+ empty_result_max_age_seconds=COSTS_EMPTY_RESULT_MAX_AGE_SECONDS,
+ )
+
_INFINITY_SENTINELS = {float(InfinityValue.NUMBER_999999), float(InfinityValue.NUMBER__999999)}
@@ -323,7 +366,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
)
return None
- ttl_seconds = COSTS_PRECOMPUTE_TTL_SECONDS
+ ttl_seconds = costs_precompute_ttl_schedule(self.team)
# Per source: read the native table when it materializes, otherwise keep that one source on the
# live S3 union. A single unmaterializable/syncing source must not force every source back to S3.
materialized_source_ids: list = []
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
index 81877948d9e8..fdfb2a20e3cd 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
@@ -1,3 +1,8 @@
+from datetime import UTC, datetime, timedelta
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+
from parameterized import parameterized
from posthog.schema import (
@@ -9,6 +14,11 @@ from posthog.schema import (
)
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner import (
+ COSTS_EMPTY_RESULT_MAX_AGE_SECONDS,
+ COSTS_EMPTY_RESULT_TTL_SECONDS,
+ COSTS_PRECOMPUTE_MAX_WINDOW_DAYS,
+ COSTS_PRECOMPUTE_TTL_SECONDS,
+ costs_precompute_ttl_schedule,
strip_infinity_sentinels,
)
@@ -24,6 +34,49 @@ def _item(change_pct: float | None) -> MarketingAnalyticsItem:
)
+@freeze_time("2026-06-15T12:00:00Z")
+class TestCostsPrecomputeTtlSchedule(BaseTest):
+ """The read path and the Dagster warmer both build their schedule here.
+
+ Nothing else pins that the cost path actually opts into the empty-window cap, which is the
+ gap that let an unsynced window stay cached as $0 in the first place — a refactor that dropped
+ the opt-in would leave every test green.
+
+ Frozen because the band cutoffs are resolved when the schedule is *built* (`parse_ttl_schedule`
+ runs `relative_date_parse("0d")` eagerly) while the assertions pass a separately-sampled `now`.
+ Midday UTC keeps the two on the same side of every boundary.
+ """
+
+ def test_opts_into_the_empty_result_cap(self):
+ schedule = costs_precompute_ttl_schedule(self.team)
+
+ assert schedule.empty_result_ttl_seconds == COSTS_EMPTY_RESULT_TTL_SECONDS
+ assert schedule.empty_result_max_age_seconds == COSTS_EMPTY_RESULT_MAX_AGE_SECONDS
+
+ def test_jobs_are_day_granular(self):
+ # Emptiness is only observable per job, so a merged multi-day job would hide a sync gap
+ # that sat next to productive days.
+ assert costs_precompute_ttl_schedule(self.team).max_window_days == COSTS_PRECOMPUTE_MAX_WINDOW_DAYS == 1
+
+ def test_keeps_the_band_ttls(self):
+ schedule = costs_precompute_ttl_schedule(self.team)
+
+ assert schedule.default_ttl_seconds == COSTS_PRECOMPUTE_TTL_SECONDS["default"]
+ assert schedule.get_ttl(datetime.now(UTC)) == COSTS_PRECOMPUTE_TTL_SECONDS["0d"]
+
+ def test_recent_empty_window_is_capped_but_old_one_is_not(self):
+ schedule = costs_precompute_ttl_schedule(self.team)
+ now = datetime.now(UTC)
+
+ recent = schedule.empty_result_expires_at(now, now - timedelta(hours=1))
+ assert recent is not None
+ assert abs((recent - now).total_seconds() - COSTS_EMPTY_RESULT_TTL_SECONDS) < 1
+
+ # Past the horizon, empty means empty — keep the band TTL instead of rescanning history.
+ old_window_end = now - timedelta(seconds=COSTS_EMPTY_RESULT_MAX_AGE_SECONDS + 60)
+ assert schedule.empty_result_expires_at(now, old_window_end) is None
+
+
class TestStripInfinitySentinels:
@parameterized.expand(
[
diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.py
index c83a6d2f3d5b..19ba3a8e0147 100644
--- a/products/marketing_analytics/dags/marketing_precompute.py
+++ b/products/marketing_analytics/dags/marketing_precompute.py
@@ -55,6 +55,7 @@ from posthog.settings import TEST
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationTable,
+ TtlSchedule,
ensure_precomputed,
)
from products.marketing_analytics.backend.hogql_queries.adapters.base import QueryContext
@@ -65,7 +66,7 @@ from products.marketing_analytics.backend.hogql_queries.conversion_goal_processo
build_touchpoints_precompute_query,
)
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner import (
- COSTS_PRECOMPUTE_TTL_SECONDS,
+ costs_precompute_ttl_schedule,
)
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
from products.marketing_analytics.backend.hogql_queries.utils import convert_team_conversion_goals_to_objects
@@ -145,7 +146,7 @@ def _ensure_chunks(
team: Team,
table: LazyComputationTable,
build_insert_query: Callable[[], ast.SelectQuery | None],
- ttl_seconds: dict[str, int],
+ ttl_seconds: dict[str, int] | TtlSchedule,
start: datetime,
end: datetime,
chunk_days: int,
@@ -293,7 +294,7 @@ def _ensure_costs_for_team(
team,
LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,
partial(adapter.build_materialization_query, source_id),
- COSTS_PRECOMPUTE_TTL_SECONDS,
+ costs_precompute_ttl_schedule(team),
start,
end,
chunk_days,