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(web-analytics): fail warmer pass at a 3h deadline instead of crawling forever (#77743)

Lucas Ricoy8cfcdabbf385
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 5cdbde347b88..e70589ec5359 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -700,6 +700,15 @@ WARMING_STALL_TIMEOUT_SECONDS = 1800
# among only in-flight shapes for this long has no innocent explanation.
WARMING_TAIL_STALL_WINDOWS = 3
+# The no-progress guard above cannot catch a pass that crawls: a poisoned
+# shard completing a handful of shapes per window keeps resetting it while
+# holding the job's single run slot, so every scheduled tick is skipped and
+# the fleet goes stale until a human terminates the run (observed as one shard
+# at ~70 shapes/hour blocking all warming for two days). A healthy full pass
+# finishes well inside an hour; one still running after this long is not
+# serving its purpose, so it fails and the next tick starts fresh.
+WARMING_PASS_DEADLINE_SECONDS = 3 * 3600
+
# After cancellation/crash, how long healthy in-flight shapes get to finish
# before the process exits hard rather than hanging on a blocked thread join.
WARMING_CANCEL_GRACE_SECONDS = 60
@@ -1012,7 +1021,29 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
pending = set(futures)
empty_waits = 0
while pending:
- done, pending = wait(pending, timeout=WARMING_STALL_TIMEOUT_SECONDS, return_when=FIRST_COMPLETED)
+ # The wait is truncated to the remaining deadline so a quiet window
+ # cannot overshoot it by a full stall timeout. A truncated empty
+ # wait lands in the deadline raise below before the stall guard, so
+ # the shortened window never counts as a stall observation.
+ remaining = WARMING_PASS_DEADLINE_SECONDS - (time.monotonic() - started_at)
+ done, pending = wait(
+ pending,
+ timeout=min(WARMING_STALL_TIMEOUT_SECONDS, max(1.0, remaining)),
+ return_when=FIRST_COMPLETED,
+ )
+ if pending and time.monotonic() - started_at > WARMING_PASS_DEADLINE_SECONDS:
+ # Raising (not os._exit) routes through the cancellation path
+ # below: the backlog is cancelled, healthy in-flight shapes get
+ # the bounded grace, and only truly wedged threads hard-exit.
+ # Non-retryable: the op's retry policy would reset the clock and
+ # hold the schedule slot for another full deadline per attempt;
+ # the next scheduled run resumes incrementally instead.
+ raise dagster.Failure(
+ f"Warming pass still running after {WARMING_PASS_DEADLINE_SECONDS // 3600}h with "
+ f"{len(pending)} shapes left ({processed}/{total} processed) — failing the pass so "
+ f"the next scheduled run takes over instead of holding the schedule slot",
+ allow_retries=False,
+ )
if not done:
empty_waits += 1
# Queued work beyond the in-flight set means threads should be
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index 7dd9cb647f8f..d7a57f84e45e 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -1,6 +1,7 @@
import gzip
import json
import threading
+from types import SimpleNamespace
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -813,6 +814,63 @@ class TestWarmQueriesOp(BaseTest):
if not expect_exit:
self.assertEqual(runner.run.call_count, n_shapes)
+ def test_crawling_pass_fails_at_deadline(self) -> None:
+ # A pass that completes one shape per stall window never trips the
+ # no-progress guard, but crawling like that holds the job's single run
+ # slot indefinitely and blocks every scheduled tick. It must fail at
+ # the pass deadline via a clean dagster.Failure (in-flight shapes are
+ # healthy, so no hard exit).
+ class _Exited(BaseException):
+ pass
+
+ runner = MagicMock()
+ runner.get_cache_key.side_effect = lambda: f"key-{runner.get_cache_key.call_count}"
+ real_wait = cache_warming.wait
+ fake_time = SimpleNamespace(now=0.0)
+ fake_time.monotonic = lambda: fake_time.now
+ fake_time.sleep = lambda _s: None
+ wait_timeouts: list[float | None] = []
+
+ def fake_wait(
+ pending: set, timeout: float | None = None, return_when: str = "ALL_COMPLETED"
+ ) -> tuple[set, set]:
+ wait_timeouts.append(timeout)
+ fake_time.now += 10000.0
+ first = next(iter(pending))
+ real_wait({first}, timeout=5)
+ return {first}, pending - {first}
+
+ with (
+ patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),
+ patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,
+ patch("products.web_analytics.dags.cache_warming.wait", side_effect=fake_wait),
+ patch("products.web_analytics.dags.cache_warming.time", new=fake_time),
+ patch("products.web_analytics.dags.cache_warming.os._exit", side_effect=_Exited) as mock_exit,
+ ):
+ mock_cm.return_value.lookup.return_value.entry = None
+ shapes = [
+ {
+ "team_id": self.team.pk,
+ "query_json": {"kind": "WebOverviewQuery", "properties": [], "n": i},
+ "query_count": 5,
+ "representative_query_count": 5,
+ "normalized_query_hash": f"h{i}",
+ }
+ for i in range(3)
+ ]
+ with self.assertRaises(dagster.Failure) as raised:
+ warm_queries_op(dagster.build_op_context(), WarmQueriesConfig(), shapes)
+
+ self.assertFalse(mock_exit.called)
+ # Retrying would reset the deadline clock and hold the schedule slot
+ # for another full deadline per attempt.
+ self.assertIs(raised.exception.allow_retries, False)
+ # The wait is truncated to the remaining deadline (second window has
+ # only 800s left of the 10800s budget), so a quiet window cannot
+ # overshoot the deadline by a full stall timeout.
+ self.assertEqual(wait_timeouts[0], cache_warming.WARMING_STALL_TIMEOUT_SECONDS)
+ self.assertEqual(wait_timeouts[1], 800.0)
+
def test_staleness_evaluated_on_jitter_aged_entry(self) -> None:
# Shapes warmed together go stale together (fixed threshold), so a bulk
# pass turns into a synchronized expiry storm hours later. The warmer