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 fast when worker threads wedge instead of hanging forever (#75551)

Lucas Ricoy8694164f540f
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index dc9925114aa1..ee45de069c03 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -1,3 +1,4 @@
+import os
import re
import gzip
import json
@@ -6,7 +7,7 @@ import zlib
import random
import threading
import statistics
-from concurrent.futures import ThreadPoolExecutor, as_completed
+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Optional
@@ -619,6 +620,30 @@ WARMING_PROGRESS_LOG_INTERVAL_SECONDS = 120
# identity churn re-warming old days, one team's pathological filters).
WARMING_SLOW_SHAPE_SECONDS = 15
+# A ClickHouse node dying mid-pass can leave every worker thread blocked in a
+# socket read that never returns: no futures complete, the heartbeat (which
+# lives in the consumption loop) goes silent, and because pool threads are
+# non-daemon the process cannot even exit — the run wedges indefinitely,
+# mutual exclusion then blocks every subsequent scheduled tick, and the fleet
+# goes stale until a human terminates the run. If nothing has completed for
+# this long WHILE there is still queued work beyond the in-flight set (threads
+# should be turning over constantly), the pass is presumed wedged and the
+# process hard-exits so Dagster records a step failure and the next tick runs.
+# A quiet tail (pending <= concurrency, e.g. one slow deep-range straggler) is
+# legitimate and only logs.
+WARMING_STALL_TIMEOUT_SECONDS = 1800
+
+# A quiet tail (pending <= concurrency) gets this many consecutive stall
+# windows before it is also presumed wedged: a legitimately slow straggler is
+# bounded by ClickHouse-side execution timeouts at minutes, so zero completions
+# among only in-flight shapes for this long has no innocent explanation.
+WARMING_TAIL_STALL_WINDOWS = 3
+
+# 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
+
+
# The warmer shares its per-user ClickHouse query budget with every other
# Dagster job (the `dagster` CH user has a hard simultaneous-query cap on the
# sessions cluster), so a co-tenant burst surfaces here as 202/AtCapacity even
@@ -912,16 +937,49 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
started_at = time.monotonic()
last_log_at = started_at
context.log.info(f"Warming {total} shapes across {len(teams)} teams (mode={mode}, concurrency={concurrency})")
- with ThreadPoolExecutor(max_workers=concurrency) as pool:
+ # No `with` block: the context manager's exit calls shutdown(wait=True),
+ # which joins worker threads — on the exceptional paths below that would
+ # re-block on the very wedged threads this code exists to escape.
+ pool = ThreadPoolExecutor(max_workers=concurrency)
+ pending: set = set()
+ try:
# Futures are consumed by completion, not input order: with pool.map one
# slow early shape would block this loop — and the heartbeat — while later
# workers finish thousands of shapes. Consuming on the op thread also keeps
# context.log here safe, unlike the worker-thread logging inside _warm_one.
futures = [pool.submit(_warm_one, query_info) for query_info in queries]
- for future in as_completed(futures):
- outcome = future.result()
- outcomes[outcome] = outcomes.get(outcome, 0) + 1
- processed += 1
+ pending = set(futures)
+ empty_waits = 0
+ while pending:
+ done, pending = wait(pending, timeout=WARMING_STALL_TIMEOUT_SECONDS, return_when=FIRST_COMPLETED)
+ if not done:
+ empty_waits += 1
+ # Queued work beyond the in-flight set means threads should be
+ # turning over constantly — one silent window is definitive. A
+ # quiet tail gets WARMING_TAIL_STALL_WINDOWS before the same
+ # verdict, so a single slow straggler isn't killed but a fully
+ # wedged tail cannot spin forever.
+ if len(pending) > concurrency or empty_waits >= WARMING_TAIL_STALL_WINDOWS:
+ context.log.error(
+ f"No shape completed in {empty_waits * WARMING_STALL_TIMEOUT_SECONDS}s with {len(pending)} "
+ f"shapes pending — presuming worker threads wedged on dead connections; exiting so the "
+ f"step fails and the next scheduled run takes over"
+ )
+ pool.shutdown(wait=False, cancel_futures=True)
+ # Blocked pool threads are non-daemon: a raise would still hang
+ # at interpreter shutdown joining them. Hard exit is the only
+ # way out of a wedged process; Dagster records a step failure.
+ os._exit(1)
+ context.log.warning(
+ f"No shape completed in {WARMING_STALL_TIMEOUT_SECONDS}s with only {len(pending)} in flight "
+ f"— slow tail (window {empty_waits}/{WARMING_TAIL_STALL_WINDOWS}), still waiting"
+ )
+ continue
+ empty_waits = 0
+ for future in done:
+ outcome = future.result()
+ outcomes[outcome] = outcomes.get(outcome, 0) + 1
+ processed += 1
now = time.monotonic()
if now - last_log_at >= WARMING_PROGRESS_LOG_INTERVAL_SECONDS:
elapsed = now - started_at
@@ -933,6 +991,26 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
f"at {rate:.0f}/s, ETA ~{eta_min:.0f}m — {breakdown}"
)
last_log_at = now
+ pool.shutdown(wait=False)
+ except BaseException:
+ # Cancellation or a crash must not drain the queued backlog (observed as
+ # a cancelled run that kept warming for hours), and must not block on a
+ # wedged in-flight thread either. Cancel the queue, give healthy
+ # in-flight shapes a bounded grace to finish, then exit hard if any
+ # remain — re-raising with blocked threads alive would just hang again
+ # at the interpreter's exit join.
+ pool.shutdown(wait=False, cancel_futures=True)
+ if pending:
+ _, still_pending = wait(pending, timeout=WARMING_CANCEL_GRACE_SECONDS)
+ if still_pending:
+ # Not log.exception: the interesting fact is the wedged threads,
+ # not the (expected) cancellation traceback.
+ context.log.error( # noqa: TRY400
+ f"{len(still_pending)} in-flight shapes still running {WARMING_CANCEL_GRACE_SECONDS}s "
+ f"after cancellation — exiting hard instead of hanging on the thread join"
+ )
+ os._exit(1)
+ raise
queries_warmed = outcomes.get("warmed", 0)
queries_skipped = outcomes.get("skipped_fresh", 0)
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index 6e65e90216e3..90b9953286d9 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -1,5 +1,6 @@
import gzip
import json
+import threading
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -15,6 +16,7 @@ from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_background_warming_request
+from products.web_analytics.dags import cache_warming
from products.web_analytics.dags.cache_warming import (
WarmQueriesConfig,
build_replay_runner,
@@ -607,6 +609,71 @@ class TestWarmQueriesOp(BaseTest):
self.assertEqual(runner.run.call_count, expected_runs)
+ @parameterized.expand(
+ [
+ # A dead ClickHouse node can block every pool thread in a socket
+ # read forever: nothing completes, the run wedges, and mutual
+ # exclusion starves every later scheduled tick (observed in prod as
+ # a silent pod needing manual termination). With queued work beyond
+ # the in-flight set the pass must hard-exit so Dagster records a
+ # failure and the next tick recovers. A quiet tail with only the
+ # in-flight remainder pending is a legitimate slow straggler and
+ # must NOT exit.
+ # One silent window with queued work is definitive; a quiet tail
+ # gets WARMING_TAIL_STALL_WINDOWS before the same verdict — a
+ # single slow straggler survives, a fully wedged tail cannot spin
+ # forever (greptile P1: the old tail branch looped indefinitely).
+ ("stall_with_queued_work_exits", 10, 1, True),
+ ("slow_tail_one_window_keeps_waiting", 3, 1, False),
+ ("wedged_tail_exits_after_windows", 3, cache_warming.WARMING_TAIL_STALL_WINDOWS, True),
+ ]
+ )
+ def test_stalled_pass_fails_fast_instead_of_wedging(
+ self, _name: str, n_shapes: int, empty_windows: int, expect_exit: bool
+ ) -> None:
+ 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
+ calls = {"n": 0}
+
+ def fake_wait(
+ pending: set, timeout: float | None = None, return_when: str = "ALL_COMPLETED"
+ ) -> tuple[set, set]:
+ calls["n"] += 1
+ if calls["n"] <= empty_windows:
+ return set(), pending
+ return real_wait(pending, timeout=5, return_when=return_when)
+
+ 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.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(n_shapes)
+ ]
+ if expect_exit:
+ with self.assertRaises(_Exited):
+ warm_queries_op(dagster.build_op_context(), WarmQueriesConfig(), shapes)
+ else:
+ warm_queries_op(dagster.build_op_context(), WarmQueriesConfig(), shapes)
+
+ self.assertEqual(mock_exit.called, expect_exit)
+ if not expect_exit:
+ self.assertEqual(runner.run.call_count, n_shapes)
+
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
@@ -648,6 +715,59 @@ class TestWarmQueriesOp(BaseTest):
# the early warm into a silent no-op.
self.assertEqual(runner.run.call_args.kwargs.get("execution_mode"), ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ def test_cancellation_drains_or_exits_within_grace(self) -> None:
+ # Cancellation mid-pass must not hand the executor a queue to drain nor
+ # hang joining a wedged thread (codex/greptile P1: the with-block exit
+ # called shutdown(wait=True) after cancel_futures). Healthy in-flight
+ # shapes finish within the grace and the interrupt propagates; wedged
+ # ones trigger the hard exit.
+ class _Exited(BaseException):
+ pass
+
+ release = threading.Event()
+ runner = MagicMock()
+ runner.get_cache_key.side_effect = lambda: f"key-{runner.get_cache_key.call_count}"
+ runner.run.side_effect = lambda **kwargs: release.wait(10)
+
+ real_wait = cache_warming.wait
+ calls = {"n": 0}
+
+ def interrupting_wait(pending: set, timeout: float | None = None, return_when: str = "") -> tuple[set, set]:
+ calls["n"] += 1
+ if calls["n"] == 1 and return_when:
+ raise KeyboardInterrupt()
+ # The grace-period wait (no return_when) runs for real, shortened.
+ return real_wait(pending, timeout=0.2)
+
+ try:
+ 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=interrupting_wait),
+ patch("products.web_analytics.dags.cache_warming.os._exit", side_effect=_Exited) as mock_exit,
+ ):
+ mock_cm.return_value.lookup.return_value.entry = None
+ with self.assertRaises(_Exited):
+ warm_queries_op(
+ dagster.build_op_context(),
+ WarmQueriesConfig(),
+ [
+ {
+ "team_id": self.team.pk,
+ "query_json": {"kind": "WebOverviewQuery", "properties": []},
+ "query_count": 5,
+ "representative_query_count": 5,
+ "normalized_query_hash": "h",
+ }
+ ],
+ )
+ assert mock_exit.called
+ finally:
+ release.set()
+
def test_team_ids_and_limit_scope_the_run(self) -> None:
# A Launchpad run scoped to one team must not warm the fleet: launches
# are mutually exclusive with the hourly schedule, so an unscoped manual