: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
perf(lazy-precompute): pin per-team insert window to 1 day after an OOM (#64394)
Lucas Ricoy87739e7b743c
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 8fa84cd32b28..2f58175477c6 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -177,11 +177,17 @@ class TtlSchedule:A window matches the first rule where window_start >= cutoff. If no rulematches, default_ttl_seconds is used.+ `max_window_days` optionally caps how wide `split_ranges_by_ttl` will merge a+ single job, independent of TTL boundaries — so a caller bounds a high-cardinality+ team's GROUP BY by handing in a schedule with a tight cap, regardless of how old+ the requested window is. `None` leaves it uncapped.+Use parse_ttl_schedule() to create from user-facing dict format."""rules: list[tuple[datetime, int]]default_ttl_seconds: int+ max_window_days: int | None = Nonedef get_ttl(self, window_start: datetime) -> int:for cutoff, ttl in self.rules:@@ -200,6 +206,7 @@ DEFAULT_TTL_SCHEDULE = TtlSchedule.from_seconds(DEFAULT_TTL_SECONDS)def parse_ttl_schedule(ttl: int | dict[str, int],team_timezone: str = "UTC",+ max_window_days: int | None = None,) -> TtlSchedule:"""Parse a TTL specification into a TtlSchedule.@@ -213,12 +220,14 @@ def parse_ttl_schedule(example, {"0d": 900, "7d": 86400, "default": 604800} means today's datagets 15 min TTL, last week gets 1 day, everything else gets 7 days.+ `max_window_days` is carried onto the resulting schedule to cap job width.+Raises ValueError for unrecognized keys or non-positive TTL values."""if isinstance(ttl, int):if ttl <= 0:raise ValueError(f"TTL must be positive, got {ttl}")- return TtlSchedule.from_seconds(ttl)+ return TtlSchedule(rules=[], default_ttl_seconds=ttl, max_window_days=max_window_days)tz = ZoneInfo(team_timezone)rules: list[tuple[datetime, int]] = []@@ -241,7 +250,7 @@ def parse_ttl_schedule(rules.append((cutoff, value))rules.sort(key=lambda r: r[0], reverse=True)- return TtlSchedule(rules=rules, default_ttl_seconds=default_ttl)+ return TtlSchedule(rules=rules, default_ttl_seconds=default_ttl, max_window_days=max_window_days)def split_ranges_by_ttl(@@ -253,7 +262,13 @@ def split_ranges_by_ttl(Re-expands each range into daily windows, assigns a TTL per window, andmerges consecutive windows with the same TTL. This prevents a single jobfrom covering days with different TTL requirements.++ `schedule.max_window_days` additionally caps the merged job width: a merge+ also breaks when adding the next day would exceed it. This bounds a job's+ GROUP BY (independent of TTL and of how old the window is) so its hash table+ stays under the memory limit."""+ max_window_days = schedule.max_window_daysresult: list[tuple[datetime, datetime, int]] = []for range_start, range_end in ranges:@@ -266,7 +281,8 @@ def split_ranges_by_ttl(for window_start, window_end in windows[1:]:ttl = schedule.get_ttl(window_start)- if ttl == current_ttl:+ exceeds_cap = max_window_days is not None and (window_end - current_start) > timedelta(days=max_window_days)+ if ttl == current_ttl and not exceeds_cap:current_end = window_endelse:result.append((current_start, current_end, current_ttl))@@ -295,6 +311,10 @@ NON_RETRYABLE_CLICKHOUSE_ERROR_CODES = {# Too many simultaneous queries means the cluster is overloaded.# Rather than adding to the load with retries, surface the error.202, # TOO_MANY_SIMULTANEOUS_QUERIES+ # An OOM won't succeed on an immediate retry with the same window — retrying just+ # adds memory pressure to a cluster that already signaled it's out of memory. Fail+ # fast so the caller can react (e.g. cap the team's window) and fall back.+ 241, # MEMORY_LIMIT_EXCEEDED}@@ -330,6 +350,21 @@ def is_non_retryable_error(error: Exception) -> bool:return False+# ClickHouse MEMORY_LIMIT_EXCEEDED. Surfaced on the result so callers can react to an OOM+# (e.g. cap a high-cardinality team's future inserts) instead of parsing error text.+MEMORY_LIMIT_EXCEEDED_CODE = 241+++def is_memory_limit_error(error: Exception) -> bool:+ """True if the error (or any wrapped cause) is a ClickHouse MEMORY_LIMIT_EXCEEDED."""+ current: BaseException | None = error+ while current is not None:+ if isinstance(current, ServerException) and current.code == MEMORY_LIMIT_EXCEEDED_CODE:+ return True+ current = current.__cause__+ return False++class LazyComputationTable(StrEnum):"""Allowed target tables for lazy-computed results."""@@ -385,6 +420,9 @@ class LazyComputationResult:ready: booljob_ids: list[uuid.UUID]errors: list[str] = field(default_factory=list)+ # True if any insert failed with ClickHouse MEMORY_LIMIT_EXCEEDED. Lets callers react+ # to an OOM (e.g. cap a high-cardinality team's future inserts) without parsing errors.+ memory_exceeded: bool = Falsedef compute_query_hash(query_info: QueryInfo) -> str:@@ -755,6 +793,7 @@ class LazyComputationExecutor:errors: list[str] = []failures = 0+ memory_exceeded = Falsestart_time = time.monotonic()interval = self.poll_interval_secondssubscribed_ids: set[uuid.UUID] = set()@@ -794,7 +833,9 @@ class LazyComputationExecutor:while True:if time.monotonic() - start_time >= self.wait_timeout_seconds:errors.append("Timeout waiting for computation jobs")- result = LazyComputationResult(ready=False, job_ids=[], errors=errors)+ result = LazyComputationResult(+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded+ )_log_execution("timeout", result)return result@@ -814,6 +855,19 @@ class LazyComputationExecutor:did_work = Falseif ttl_ranges and failures <= self.max_retries:for range_start, range_end, ttl in ttl_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+ # insert once the budget is spent rather than running the whole set+ # back-to-back and blowing well past wait_timeout_seconds.+ if time.monotonic() - start_time >= self.wait_timeout_seconds:+ errors.append("Timeout waiting for computation jobs")+ result = LazyComputationResult(+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded+ )+ _log_execution("timeout", result)+ return result+try:with transaction.atomic():new_job = create_lazy_computation_job(team, query_hash, range_start, range_end, ttl)@@ -855,6 +909,7 @@ class LazyComputationExecutor:)except Exception as e:insert_elapsed = time.monotonic() - insert_start+ memory_exceeded = memory_exceeded or is_memory_limit_error(e)new_job.status = PreaggregationJob.Status.FAILEDnew_job.error = str(e)new_job.save()@@ -879,20 +934,26 @@ class LazyComputationExecutor:)if is_non_retryable_error(e):errors.append(str(e))- result = LazyComputationResult(ready=False, job_ids=[], errors=errors)+ result = LazyComputationResult(+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded+ )_log_execution("non_retryable_error", result)return resultfailures += 1if failures > self.max_retries:errors.append(f"Max retries ({self.max_retries}) exceeded: {e}")- result = LazyComputationResult(ready=False, job_ids=[], errors=errors)+ result = LazyComputationResult(+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded+ )_log_execution("max_retries_exceeded", result)return resultdid_work = Trueif ttl_ranges and failures > self.max_retries:errors.append("Max retries exceeded for computation")- result = LazyComputationResult(ready=False, job_ids=[], errors=errors)+ result = LazyComputationResult(+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded+ )_log_execution("max_retries_exceeded", result)return result@@ -1019,7 +1080,7 @@ def ensure_precomputed(insert_query: str | ast.SelectQuery,time_range_start: datetime,time_range_end: datetime,- ttl_seconds: int | dict[str, int] = DEFAULT_TTL_SECONDS,+ ttl_seconds: int | dict[str, int] | TtlSchedule = DEFAULT_TTL_SECONDS,table: LazyComputationTable = LazyComputationTable.PREAGGREGATION_RESULTS,placeholders: dict[str, ast.Expr] | None = None,sentinel_placeholders: set[str] | None = None,@@ -1142,7 +1203,11 @@ def ensure_precomputed(settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk),)- ttl_schedule = parse_ttl_schedule(ttl_seconds, team.timezone)+ # 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)+ )executor = LazyComputationExecutor(ttl_schedule=ttl_schedule)return executor.execute(team, query_info, time_range_start, time_range_end, run_insert=_run_manual_insert)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 1ed530139db8..3d8f567ea800 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@@ -2650,6 +2650,9 @@ class TestIsNonRetryableError(BaseTest):("no_such_column", 16, "No such column"),("timeout", 159, "Timeout exceeded"),("too_many_queries", 202, "Too many simultaneous queries"),+ # An OOM won't succeed on an immediate retry — retrying just re-pressures the+ # cluster. Fail fast so the caller can react (e.g. cap the team's window).+ ("memory_limit", 241, "Memory limit exceeded"),])def test_clickhouse_non_retryable_error_codes(self, name, code, message):@@ -2659,7 +2662,7 @@ class TestIsNonRetryableError(BaseTest):@parameterized.expand([- ("memory_limit", 241, "Memory limit exceeded"),+ ("network_error", 210, "Network error"),])def test_clickhouse_retryable_error_codes(self, name, code, message):@@ -2749,3 +2752,108 @@ class TestInsertSettingsAppliedToInserts(BaseTest):assert mock_execute.call_count == 1assert mock_execute.call_args.kwargs["settings"] == _get_insert_settings(self.team.pk)+++class TestMaxWindowDaysCap(BaseTest):+ def test_parse_carries_max_window_days(self):+ assert parse_ttl_schedule(3600, max_window_days=2).max_window_days == 2+ assert parse_ttl_schedule({"default": 3600}, "UTC", max_window_days=1).max_window_days == 1+ assert parse_ttl_schedule(3600).max_window_days is None++ def test_cap_splits_merged_range_at_any_age(self):+ schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, max_window_days=1)+ # an OLD 7-day range (uniform default TTL) must still split into 7 one-day jobs+ ranges = [(datetime(2020, 1, 1, tzinfo=UTC), datetime(2020, 1, 8, tzinfo=UTC))]+ result = split_ranges_by_ttl(ranges, schedule)+ assert len(result) == 7+ assert all((end - start) == timedelta(days=1) for start, end, _ in result)+ assert result[0][0] == datetime(2020, 1, 1, tzinfo=UTC)+ assert result[-1][1] == datetime(2020, 1, 8, tzinfo=UTC)+ for prev, nxt in zip(result, result[1:]):+ assert prev[1] == nxt[0]++ def test_no_cap_merges_whole_range(self):+ schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, max_window_days=None)+ ranges = [(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC))]+ assert split_ranges_by_ttl(ranges, schedule) == [+ (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC), 3600)+ ]+++class TestExecuteOOMAndBudget(ClickhouseTestMixin, BaseTest):+ def _query_info(self) -> QueryInfo:+ s = parse_select(+ """+ SELECT toStartOfDay(timestamp) as time_window_start, [] as breakdown_value,+ uniqExactState(person_id) as uniq_exact_state+ FROM events WHERE event = '$pageview' GROUP BY time_window_start+ """+ )+ assert isinstance(s, ast.SelectQuery)+ return QueryInfo(query=s, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC")++ def test_surfaces_memory_exceeded_on_oom(self):+ def oom_insert(_t, _j) -> None:+ raise ServerException(message="Memory limit (total) exceeded", code=241)++ result = LazyComputationExecutor().execute(+ team=self.team,+ query_info=self._query_info(),+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 2, tzinfo=UTC),+ run_insert=oom_insert,+ )+ assert result.ready is False+ assert result.memory_exceeded is True++ def test_oom_is_not_retried(self):+ calls: list = []++ def oom_insert(_t, job) -> None:+ calls.append(job.id)+ raise ServerException(message="Memory limit (total) exceeded", code=241)++ LazyComputationExecutor(max_retries=1).execute(+ team=self.team,+ query_info=self._query_info(),+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 2, tzinfo=UTC),+ run_insert=oom_insert,+ )+ # 241 is non-retryable → exactly one attempt, no second OOM+ assert len(calls) == 1++ def test_memory_exceeded_false_for_non_oom(self):+ def syntax_insert(_t, _j) -> None:+ raise ServerException(message="Syntax error", code=62)++ result = LazyComputationExecutor().execute(+ team=self.team,+ query_info=self._query_info(),+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 2, tzinfo=UTC),+ run_insert=syntax_insert,+ )+ assert result.ready is False+ assert result.memory_exceeded is False++ def test_bails_mid_loop_when_budget_exhausted(self):+ # max_window_days=1 over a 7-day range → 7 one-day inline inserts; a spent wait+ # budget must stop the loop before running the whole set back-to-back.+ calls: list = []++ def slow_insert(_t, job) -> None:+ calls.append(job.id)+ time_mod.sleep(0.02)++ schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, max_window_days=1)+ result = LazyComputationExecutor(wait_timeout_seconds=0.01, ttl_schedule=schedule).execute(+ team=self.team,+ query_info=self._query_info(),+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 8, tzinfo=UTC),+ run_insert=slow_insert,+ )+ assert result.ready is False+ assert any("Timeout" in e for e in result.errors)+ assert 1 <= len(calls) < 7diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.pyindex 8f958c0453d6..d724759339d2 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py@@ -19,19 +19,29 @@ from posthog.schema import (from posthog.hogql import ast+from posthog import redisfrom posthog.clickhouse.query_tagging import get_query_tag_valuefrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ TtlSchedule,+)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ OOM_PIN_TTL_SECONDS,PerQueryOptedOut,PerQueryOptInNotSet,TooManyFilters,UnsupportedFilterKey,+ _oom_pin_key,check_common_eligibility,compute_filters_eligibility_hash,host_filter_expr,is_precompute_enabled_for_team,is_precompute_unrestricted_for_team,+ is_team_oom_pinned,+ pin_team_oom,+ web_ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner@@ -350,3 +360,74 @@ class TestFiltersEligibilityHashContextvarBinding(ClickhouseTestMixin, APIBaseTerunner.calculate()assert captured["query_tag"] is None+++class TestTeamOomPin(BaseTest):+ def tearDown(self):+ redis.get_client().delete(_oom_pin_key(self.team.pk))+ super().tearDown()++ def test_unpinned_team(self):+ assert is_team_oom_pinned(self.team.pk) is False++ def test_pin_then_read_with_ttl(self):+ pin_team_oom(self.team.pk)+ assert is_team_oom_pinned(self.team.pk) is True+ ttl = redis.get_client().ttl(_oom_pin_key(self.team.pk))+ assert 0 < ttl <= OOM_PIN_TTL_SECONDS++ @mock.patch(f"{_COMMON}.redis.get_client", side_effect=Exception("redis down"))+ def test_redis_failure_reads_as_unpinned(self, _client):+ assert is_team_oom_pinned(self.team.pk) is False+++class TestWebEnsurePrecomputed(BaseTest):+ def tearDown(self):+ redis.get_client().delete(_oom_pin_key(self.team.pk))+ super().tearDown()++ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_pins_team_on_oom_and_runs_uncapped_first(self, mock_ensure):+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=True)+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ # ran with the caller's raw schedule this time (not yet pinned), then pinned for next time+ assert mock_ensure.call_args.kwargs["ttl_seconds"] == {"default": 3600}+ assert is_team_oom_pinned(self.team.pk) is True++ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_pinned_team_gets_width_capped_schedule(self, mock_ensure):+ pin_team_oom(self.team.pk)+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ passed = mock_ensure.call_args.kwargs["ttl_seconds"]+ assert isinstance(passed, TtlSchedule)+ assert passed.max_window_days == 1++ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_already_pinned_oom_refreshes_ttl(self, mock_ensure):+ pin_team_oom(self.team.pk)+ # expire-soon, then a re-OOM should refresh the TTL back to full+ redis.get_client().expire(_oom_pin_key(self.team.pk), 5)+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=True)+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ ttl = redis.get_client().ttl(_oom_pin_key(self.team.pk))+ assert ttl > 5++ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_no_pin_on_success(self, mock_ensure):+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ assert is_team_oom_pinned(self.team.pk) is False++ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_pinned_team_restamps_prebuilt_schedule(self, mock_ensure):+ # A caller may pass an already-built TtlSchedule (ensure_precomputed accepts one);+ # the pin must stamp the cap onto it, not crash by re-parsing it.+ pin_team_oom(self.team.pk)+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)+ prebuilt = TtlSchedule(rules=[], default_ttl_seconds=3600, max_window_days=None)+ web_ensure_precomputed(team=self.team, ttl_seconds=prebuilt, table=None)+ passed = mock_ensure.call_args.kwargs["ttl_seconds"]+ assert isinstance(passed, TtlSchedule)+ assert passed.max_window_days == 1+ assert passed.default_ttl_seconds == 3600diff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.pyindex 08c252586f0e..0152a91066cf 100644--- a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py@@ -37,7 +37,6 @@ from products.actions.backend.models.action import Actionfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (LAZY_TTL_SECONDS,@@ -49,6 +48,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imphost_filter_expr,log_eligibility_outcome,test_account_filter_expr,+ web_ensure_precomputed,)if TYPE_CHECKING:@@ -297,7 +297,7 @@ def ensure_web_goals_precomputed(placeholders[f"action_{n}_expr"] = action_to_expr(action)placeholders[f"action_{n}_id"] = ast.Constant(value=int(action.id))- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=_build_insert_query(actions),time_range_start=time_range_start,diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.pyindex d622d51a5e9d..5147ebd9b1a6 100644--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py@@ -11,6 +11,7 @@ the two paths drifting apart.import jsonimport hashlibfrom collections.abc import Callable+from dataclasses import replacefrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional@@ -25,10 +26,78 @@ from posthog.hogql import astfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone+from posthog import redisfrom posthog.models import Team+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ TtlSchedule,+ ensure_precomputed,+ parse_ttl_schedule,+)+logger = structlog.get_logger(__name__)+# Reactive per-team OOM cap. A very high-cardinality team's wide-window GROUP BY+# (session, breakdown) can OOM the precompute INSERT. We run uncapped until that happens;+# on an OOM we pin the team (one Redis key per team, self-healing TTL) so its later requests+# build their TTL schedule with a 1-day `max_window_days` cap — bounding each insert's GROUP+# BY by job *width*, at any window age (so a year-over-year compare's old previous period is+# capped too), while keeping the team's normal TTL grading. The capping lives entirely in the+# schedule handed to `ensure_precomputed`, so the executor needs no per-team knowledge.+OOM_PIN_WINDOW_DAYS = 1+TEAM_OOM_PIN_REDIS_PREFIX = "preagg:oom_pinned:"+OOM_PIN_TTL_SECONDS = 14 * 24 * 60 * 60+++def _oom_pin_key(team_id: int) -> str:+ return f"{TEAM_OOM_PIN_REDIS_PREFIX}{team_id}"+++def is_team_oom_pinned(team_id: int) -> bool:+ """Whether the team has hit an OOM recently and should cap its insert windows.++ Best-effort: a Redis failure reads as not-pinned (uncapped default) — never blocks the insert."""+ try:+ return redis.get_client().get(_oom_pin_key(team_id)) is not None+ except Exception:+ return False+++def pin_team_oom(team_id: int) -> None:+ """Pin (or refresh) a team's OOM cap after an OOM. Best-effort; self-healing TTL."""+ try:+ redis.get_client().set(_oom_pin_key(team_id), "1", ex=OOM_PIN_TTL_SECONDS)+ except Exception:+ logger.warning("web_precompute.oom_pin_failed", team_id=team_id, exc_info=True)+++def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResult:+ """`ensure_precomputed` for web analytics, with reactive per-team OOM capping.++ A team runs uncapped until one of its precompute inserts OOMs; that pins it so later+ requests build their TTL schedule with a 1-day `max_window_days` cap (job width bounded+ at any window age). The request that hits the OOM still fails here and falls back to the+ live query — the cap only takes effect next time.+ """+ pinned = is_team_oom_pinned(team.id)+ if pinned and "ttl_seconds" in kwargs:+ existing = kwargs["ttl_seconds"]+ # Stamp the width cap onto whatever schedule the caller passed: an int/dict gets+ # parsed with the cap; an already-built TtlSchedule (also accepted by+ # ensure_precomputed) just gets the cap re-stamped — parse_ttl_schedule can't take one.+ if isinstance(existing, TtlSchedule):+ kwargs["ttl_seconds"] = replace(existing, max_window_days=OOM_PIN_WINDOW_DAYS)+ else:+ kwargs["ttl_seconds"] = parse_ttl_schedule(existing, team.timezone, max_window_days=OOM_PIN_WINDOW_DAYS)+ result = ensure_precomputed(team=team, **kwargs)+ if result.memory_exceeded:+ pin_team_oom(team.id) # set or refresh the cap so a still-OOMing team stays pinned+ if not pinned:+ logger.warning("web_precompute.oom_pinned_team", team_id=team.id, table=str(kwargs.get("table")))+ return result++# Fields stripped from the query payload before hashing.# These don't influence which precompute job_id a query would map to —# `useWebAnalyticsPrecompute` is just the opt-in toggle, `modifiers` isdiff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.pyindex f9d58f29f7e4..abfd62c566e2 100644--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py@@ -16,7 +16,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (LAZY_TTL_SECONDS,@@ -31,6 +30,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed_FAMILY = "web_overview"@@ -116,7 +116,7 @@ def ensure_web_overview_precomputed("pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),}- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=INSERT_QUERY_TEMPLATE,time_range_start=time_range_start,diff --git a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.pyindex c3f5215532ed..ad8317c1f739 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py@@ -27,7 +27,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (LAZY_TTL_SECONDS,@@ -39,6 +38,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imphost_filter_expr,log_eligibility_outcome,test_account_filter_expr,+ web_ensure_precomputed,)if TYPE_CHECKING:@@ -263,7 +263,7 @@ def ensure_web_stats_frustration_precomputed("pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),}- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=INSERT_QUERY_TEMPLATE,time_range_start=time_range_start,diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.pyindex 80a858cca6d8..07f4e3fdedb2 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py@@ -23,7 +23,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (LAZY_TTL_SECONDS,@@ -39,6 +38,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed_FAMILY = "web_stats"@@ -274,7 +274,7 @@ def ensure_web_stats_precomputed("pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),}- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=INSERT_QUERY_TEMPLATE,time_range_start=time_range_start,diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.pyindex 6a66b583109d..9da65765eb4d 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py@@ -28,7 +28,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (LAZY_TTL_SECONDS,@@ -40,6 +39,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imphost_filter_expr,log_eligibility_outcome,test_account_filter_expr,+ web_ensure_precomputed,)if TYPE_CHECKING:@@ -290,7 +290,7 @@ def ensure_web_stats_paths_precomputed("pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),}- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=INSERT_QUERY_TEMPLATE,time_range_start=time_range_start,diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.pyindex 8ef9d5a47e4e..ec3bd06c22b3 100644--- a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py@@ -29,7 +29,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (LAZY_TTL_SECONDS,@@ -43,6 +42,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed_FAMILY = "web_vitals_paths"@@ -203,7 +203,7 @@ def ensure_web_vitals_paths_precomputed("team_tz": ast.Constant(value=runner.team.timezone),}- return ensure_precomputed(+ return web_ensure_precomputed(team=runner.team,insert_query=INSERT_QUERY_TEMPLATE,time_range_start=time_range_start,