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.

feat(logs): make batched alert predicate hoisting unconditional (#81981)

Jon McCallum15886f43b9c3
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index 5bc50404b6b4..2340b9357b61 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -25,7 +25,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
-from products.logs.backend.alert_utils import HOIST_BATCHED_ALERT_PREDICATES, MAX_BYTES_TO_READ
+from products.logs.backend.alert_utils import MAX_BYTES_TO_READ
from products.logs.backend.logs_query_runner import LIVE_LOGS_CHECKPOINT_QUERY, LogsFilterBuilder
from products.logs.backend.models import LogsAlertConfiguration
@@ -349,9 +349,9 @@ class BatchedAlertCheckQuery:
[tmp/logs-alerting/per-team-batching-test.sql](../../../tmp/logs-alerting/per-team-batching-test.sql)
for cost validation.
- The outer WHERE also carries the OR of all per-alert predicates (behind
- `HOIST_BATCHED_ALERT_PREDICATES`), so rows matching no alert are pruned via
- the primary key and skip indexes before any countIf column is evaluated.
+ The outer WHERE also carries the OR of all per-alert predicates, so rows
+ matching no alert are pruned via the primary key and skip indexes before
+ any countIf column is evaluated.
"""
SETTINGS = AlertCheckQuery.SETTINGS
@@ -386,9 +386,8 @@ class BatchedAlertCheckQuery:
)
# Outer WHERE owns the pruning so CH can skip parts/granules before
- # evaluating any countIf: the time bounds always, plus (behind
- # HOIST_BATCHED_ALERT_PREDICATES) the OR of every alert's predicate.
- # The disjunction is
+ # evaluating any countIf: the time bounds, plus the OR of every alert's
+ # predicate. The disjunction is
# result-equivalent because a row matching no alert's predicate
# contributes to no countIf, but it lets CH prune with the primary key
# (service_name) and the attributes bloom-filter skip indexes, which
@@ -406,21 +405,20 @@ class BatchedAlertCheckQuery:
"date_to": ast.Constant(value=date_to),
},
)
- if HOIST_BATCHED_ALERT_PREDICATES:
- # The hoisted copies must differ from the countIf copies in two ways.
- # They must be fresh instances, because the resolver annotates nodes
- # in place and sharing one instance at two positions in the query
- # tree is an aliasing hazard. And they must not carry indexHint(...)
- # wrappers: ClickHouse dedupes an expression that appears in both
- # the WHERE clause and a countIf argument, and when that shared
- # expression contains indexHint the filter step constant-folds one
- # use but not the other and the query fails with ILLEGAL_COLUMN
- # ("non constant in source stream but must be constant in result").
- # Dropping the hint loses nothing here: the real predicate sits in
- # the WHERE clause where the planner can use it directly.
- hoisted_exprs = [_strip_index_hints(e) for e in self._alert_where_exprs]
- hoisted = hoisted_exprs[0] if len(hoisted_exprs) == 1 else ast.Or(exprs=hoisted_exprs)
- self._outer_where = ast.And(exprs=[self._outer_where, hoisted])
+ # The hoisted copies must differ from the countIf copies in two ways.
+ # They must be fresh instances, because the resolver annotates nodes
+ # in place and sharing one instance at two positions in the query
+ # tree is an aliasing hazard. And they must not carry indexHint(...)
+ # wrappers: ClickHouse dedupes an expression that appears in both
+ # the WHERE clause and a countIf argument, and when that shared
+ # expression contains indexHint the filter step constant-folds one
+ # use but not the other and the query fails with ILLEGAL_COLUMN
+ # ("non constant in source stream but must be constant in result").
+ # Dropping the hint loses nothing here: the real predicate sits in
+ # the WHERE clause where the planner can use it directly.
+ hoisted_exprs = [_strip_index_hints(e) for e in self._alert_where_exprs]
+ hoisted = hoisted_exprs[0] if len(hoisted_exprs) == 1 else ast.Or(exprs=hoisted_exprs)
+ self._outer_where = ast.And(exprs=[self._outer_where, hoisted])
def execute_bucketed(self, interval_minutes: int, *, limit: int = 10_000) -> BatchedBucketedResult:
"""Run the batched query and split results back per-alert.
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index d4c60d7797a1..dda290f90663 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -12,7 +12,6 @@ from products.alerts.backend.scheduling import (
)
__all__ = [
- "HOIST_BATCHED_ALERT_PREDICATES",
"MAX_BYTES_TO_READ",
"SCHEDULE_INTERVAL_SECONDS",
"advance_next_check_at",
@@ -35,16 +34,6 @@ SCHEDULE_INTERVAL_SECONDS = 60
# a circular import via `temporal/__init__.py` to activities to alert_check_query.
MAX_BYTES_TO_READ = int(os.environ.get("LOGS_ALERTING_MAX_BYTES_TO_READ", "5368709120"))
-# Hoists the OR of per-alert predicates into the batched alert query's outer
-# WHERE so ClickHouse can prune the scan with them. Results are identical
-# either way; the flag changes only how much data each check reads. Default
-# off for a staged rollout, because a planner regression on the hoisted shape
-# (e.g. pathological KeyCondition analysis on a large OR chain) would hit
-# every batched check at once: enable per environment with
-# LOGS_ALERTING_HOIST_BATCHED_ALERT_PREDICATES=1, then flip this default once
-# both regions have soaked.
-HOIST_BATCHED_ALERT_PREDICATES = os.environ.get("LOGS_ALERTING_HOIST_BATCHED_ALERT_PREDICATES", "0") == "1"
-
def compute_shard_offset_seconds(alert_id: UUID, check_interval_minutes: int) -> int:
return shared_compute_shard_offset_seconds(
diff --git a/products/logs/backend/test/test_alert_check_query.py b/products/logs/backend/test/test_alert_check_query.py
index ae0c57030a0f..0a69437fe1ae 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -1361,7 +1361,6 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
)
@freeze_time("2025-12-16T11:00:00Z")
- @patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
def test_per_alert_results_match_single_query_across_random_inputs(self):
# Generative property test: the batched query must produce the same
# per-alert bucket counts as running each alert through `AlertCheckQuery`
@@ -1669,7 +1668,6 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand([("bucketed",), ("periods",), ("rolling",)])
@freeze_time("2025-12-16T10:33:00Z")
- @patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
def test_heterogeneous_cohort_matches_single_alert_results(self, path: str):
# Cohort mixing a match-everything alert (its predicate is ~always true),
# a service alert, an attribute alert, and a zero-match alert. Guards the
@@ -1699,7 +1697,6 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert got == single, f"alert={alert.name} path={path}"
@freeze_time("2025-12-16T13:30:00Z")
- @patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
def test_max_cohort_size_query_builds_and_matches(self):
# A full-size cohort duplicates every predicate into the hoisted OR
# chain on top of its countIf copy: guards the doubled predicate text
@@ -1729,11 +1726,10 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
# Predicate hoisting: the batched query's outer WHERE carries the OR of
-# per-alert predicates (behind HOIST_BATCHED_ALERT_PREDICATES) so ClickHouse
-# can prune with the primary key and skip indexes. The redundant-looking OR
-# is the point: removing it reverts to scanning the whole time window, the
-# shape that made attribute-filter alerts exceed the 5 GiB read cap and
-# auto-disable in production.
+# per-alert predicates so ClickHouse can prune with the primary key and skip
+# indexes. The redundant-looking OR is the point: removing it reverts to
+# scanning the whole time window, the shape that made attribute-filter alerts
+# exceed the 5 GiB read cap and auto-disable in production.
class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
ATTR_KEY = "job_kind"
ATTR_VALUE = "usage-rollup"
@@ -1743,15 +1739,6 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
- def setUp(self):
- super().setUp()
- # HOIST_BATCHED_ALERT_PREDICATES defaults off (staged rollout); these
- # tests guard the hoisted behavior, so force it on. The kill-switch and
- # planner tests re-patch it per assertion.
- patcher = patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
@classmethod
def setUpTestData(cls):
super().setUpTestData()
@@ -1934,27 +1921,12 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
assert "service_name" in where
assert not re.search(r"(?<![a-zA-Z0-9_])or\(", where), where
- def test_hoisting_disabled_by_kill_switch(self):
- # The env kill switch must actually restore the old time-only WHERE;
- # if it silently stops applying, prod has no rollback lever.
+ def _explain_index_usage(self) -> tuple[set[str], set[str]]:
alert = self._make_alert(filters=self._incident_filters(self.ATTR_VALUE))
date_from = self.NCA - dt.timedelta(minutes=15)
- with patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", False):
- query = BatchedAlertCheckQuery(
- team=self.team, alerts=[alert], date_from=date_from, date_to=self.NCA, projection_eligible=False
- )
- sql, _ = self._print_query(query._build_count_per_range_query(_rolling_check_ranges(self.NCA, 5, 5, 3)))
- where = self._outer_where_sql(sql)
- assert "service_name" not in where
- assert "attributes_map_str" not in where
-
- def _explain_index_usage(self, *, hoist: bool) -> tuple[set[str], set[str]]:
- alert = self._make_alert(filters=self._incident_filters(self.ATTR_VALUE))
- date_from = self.NCA - dt.timedelta(minutes=15)
- with patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", hoist):
- query = BatchedAlertCheckQuery(
- team=self.team, alerts=[alert], date_from=date_from, date_to=self.NCA, projection_eligible=False
- )
+ query = BatchedAlertCheckQuery(
+ team=self.team, alerts=[alert], date_from=date_from, date_to=self.NCA, projection_eligible=False
+ )
sql, values = self._print_query(query._build_count_per_range_query(_rolling_check_ranges(self.NCA, 5, 5, 3)))
# Apply the runtime CH settings; index selection can diverge from real
# queries without them (same recipe as posthog/hogql/test/test_property_skip_indexes.py).
@@ -1991,9 +1963,8 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
def test_hoisted_predicates_visible_to_planner(self):
# Plan-level check, because the SQL can contain the predicate in a form
- # the planner cannot use: with hoisting on, the primary key prunes on
- # service_name and the mapValues(attributes_map_str) bloom filter is
- # consulted; with the kill switch off, neither engages.
+ # the planner cannot use: the primary key must prune on service_name
+ # and the mapValues(attributes_map_str) bloom filter must be consulted.
# `logs` is a Distributed wrapper; the skip indexes live on whichever
# MergeTree backs it, so look them up by expression instead of by name
# or table (index names differ between logs schema generations).
@@ -2004,13 +1975,10 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
attr_indexes = {row[0] for row in attr_index_rows}
assert attr_indexes, "expected the logs tables to define skip indexes over attributes_map_str"
- hoisted_skips, hoisted_pk = self._explain_index_usage(hoist=True)
- plain_skips, plain_pk = self._explain_index_usage(hoist=False)
+ hoisted_skips, hoisted_pk = self._explain_index_usage()
assert "service_name" in hoisted_pk
assert hoisted_skips & attr_indexes, f"skip indexes in plan: {hoisted_skips}"
- assert "service_name" not in plain_pk
- assert not (plain_skips & attr_indexes)
@parameterized.expand(
[
@@ -2174,7 +2142,6 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
# a shard has no matching parts for the check window.
class TestBatchedQueryPredicateHoistingEmptyScan(ClickhouseTestMixin, APIBaseTest):
@freeze_time("2026-02-03T10:05:00Z")
- @patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
def test_body_and_resource_filter_with_no_matching_logs(self):
alert = LogsAlertConfiguration.objects.create(
team=self.team,
diff --git a/products/logs/backend/test/test_alert_hoisting_sweep.py b/products/logs/backend/test/test_alert_hoisting_sweep.py
index 61d21ac0a024..04710f5bfc10 100644
--- a/products/logs/backend/test/test_alert_hoisting_sweep.py
+++ b/products/logs/backend/test/test_alert_hoisting_sweep.py
@@ -19,7 +19,6 @@ from datetime import UTC, datetime
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from unittest.mock import patch
from parameterized import parameterized
@@ -135,12 +134,6 @@ class _HoistingSweepBase(ClickhouseTestMixin, APIBaseTest):
class Meta:
abstract = True
- def setUp(self):
- super().setUp()
- patcher = patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
- patcher.start()
- self.addCleanup(patcher.stop)
-
def _assert_batched_matches_per_alert(self, alerts: list[LogsAlertConfiguration]) -> dict[str, int]:
batched = BatchedAlertCheckQuery(
team=self.team, alerts=alerts, date_from=DATE_FROM, date_to=NCA, projection_eligible=False
@@ -397,10 +390,9 @@ if os.environ.get("RUN_PBT"):
# predicate) and execution can raise; either counts, as long as the
# batched path fails whenever the per-alert path does.
def run_batched():
- with patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True):
- query = BatchedAlertCheckQuery(
- team=self.team, alerts=alerts, date_from=DATE_FROM, date_to=NCA, projection_eligible=False
- )
+ query = BatchedAlertCheckQuery(
+ team=self.team, alerts=alerts, date_from=DATE_FROM, date_to=NCA, projection_eligible=False
+ )
return query.execute_rolling_checks(nca=NCA, window_minutes=5, cadence_minutes=5, period_count=3)
if per_alert_error is not None:
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 3e701a298162..112949b3b635 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -609,11 +609,10 @@ class TestRunCohortQueryFallbackEndToEnd(ClickhouseTestMixin, APIBaseTest):
assert bad_prefetch.query_duration_ms is not None and bad_prefetch.query_duration_ms >= 0
@freeze_time("2026-01-01T10:05:00Z")
- @patch("products.logs.backend.alert_check_query.HOIST_BATCHED_ALERT_PREDICATES", True)
def test_attribute_filter_single_alert_cohort_succeeds_end_to_end(self):
# The shape that broke in production: a size-1, projection-ineligible
# cohort whose alert filters on a log attribute. Runs the real batched
- # query via _run_cohort_query with predicate hoisting enabled, so it
+ # query via _run_cohort_query, so it
# catches wiring drift between the activity call site and
# BatchedAlertCheckQuery that tests constructing the query class
# directly cannot.