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(logs): hoist per-alert predicates into batched alert check WHERE (#78985)

Jon McCallum36638ee6a175
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index d5f604b77f00..6e6824c49733 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -18,13 +18,14 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.visitor import clone_expr
from posthog.clickhouse.client.connection import Workload
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 MAX_BYTES_TO_READ
+from products.logs.backend.alert_utils import HOIST_BATCHED_ALERT_PREDICATES, MAX_BYTES_TO_READ
from products.logs.backend.logs_query_runner import LIVE_LOGS_CHECKPOINT_QUERY, LogsFilterBuilder
from products.logs.backend.models import LogsAlertConfiguration
@@ -329,6 +330,10 @@ class BatchedAlertCheckQuery:
scan, not by the predicate count. See
[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.
"""
SETTINGS = AlertCheckQuery.SETTINGS
@@ -362,10 +367,17 @@ class BatchedAlertCheckQuery:
else all(is_projection_eligible(a.filters) for a in self.alerts)
)
- # Outer WHERE owns the time-based pruning so CH can skip parts/granules
- # before evaluating any countIf. Per-alert exprs include redundant
- # time/timestamp clauses inside countIf — harmless but worth noting if
- # you're reading EXPLAIN output and counting predicate evaluations.
+ # 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
+ # 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
+ # cannot see predicates inside countIf. Per-alert exprs therefore appear
+ # redundantly both here and inside their countIf, which is deliberate
+ # and worth remembering when reading EXPLAIN output and counting
+ # predicate evaluations.
self._outer_where = parse_expr(
"toStartOfDay(time_bucket) >= toStartOfDay({date_from})"
" AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})"
@@ -376,6 +388,17 @@ class BatchedAlertCheckQuery:
"date_to": ast.Constant(value=date_to),
},
)
+ if HOIST_BATCHED_ALERT_PREDICATES:
+ # clone_expr is required: the same expr instances sit inside the
+ # countIf select columns of the same query tree, and the resolver
+ # annotates nodes in place, so sharing one instance at two positions
+ # is an aliasing hazard.
+ hoisted = (
+ clone_expr(self._alert_where_exprs[0])
+ if len(self._alert_where_exprs) == 1
+ else ast.Or(exprs=[clone_expr(e) for e in self._alert_where_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.
@@ -386,37 +409,7 @@ class BatchedAlertCheckQuery:
"""
self._tag()
- time_field = (
- ast.Call(name="toStartOfMinute", args=[ast.Field(chain=["timestamp"])])
- if self._all_projection_eligible
- else ast.Field(chain=["timestamp"])
- )
-
- select_columns: list[ast.Expr] = [
- ast.Alias(
- alias="bucket",
- expr=ast.Call(
- name="toStartOfInterval",
- args=[time_field, ast.Call(name="toIntervalMinute", args=[ast.Constant(value=interval_minutes)])],
- ),
- ),
- ]
- for i, alert_expr in enumerate(self._alert_where_exprs):
- select_columns.append(
- ast.Alias(
- alias=f"alert_{i}",
- expr=ast.Call(name="countIf", args=[alert_expr]),
- )
- )
-
- query = ast.SelectQuery(
- select=select_columns,
- select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),
- where=self._outer_where,
- group_by=[ast.Field(chain=["bucket"])],
- order_by=[ast.OrderExpr(expr=ast.Field(chain=["bucket"]), order="ASC")],
- limit=ast.Constant(value=limit),
- )
+ query = self._build_bucketed_query(interval_minutes, limit)
start_ms = time.monotonic_ns() // 1_000_000
response = self._run_query(query)
@@ -448,23 +441,7 @@ class BatchedAlertCheckQuery:
return self._execute_count_per_range(ranges)
def _execute_count_per_range(self, ranges: list[tuple[dt.datetime, dt.datetime]]) -> BatchedBucketedResult:
- select_columns: list[ast.Expr] = [
- ast.Alias(
- alias=f"alert_{alert_i}_period_{period_i}",
- expr=ast.Call(
- name="countIf",
- args=[ast.And(exprs=[alert_expr, _timestamp_in_range(start, end)])],
- ),
- )
- for alert_i, alert_expr in enumerate(self._alert_where_exprs)
- for period_i, (start, end) in enumerate(ranges)
- ]
-
- query = ast.SelectQuery(
- select=select_columns,
- select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),
- where=self._outer_where,
- )
+ query = self._build_count_per_range_query(ranges)
start_ms = time.monotonic_ns() // 1_000_000
response = self._run_query(query)
@@ -482,6 +459,58 @@ class BatchedAlertCheckQuery:
]
return BatchedBucketedResult(per_alert=per_alert, query_duration_ms=duration_ms)
+ def _build_bucketed_query(self, interval_minutes: int, limit: int) -> ast.SelectQuery:
+ time_field = (
+ ast.Call(name="toStartOfMinute", args=[ast.Field(chain=["timestamp"])])
+ if self._all_projection_eligible
+ else ast.Field(chain=["timestamp"])
+ )
+
+ select_columns: list[ast.Expr] = [
+ ast.Alias(
+ alias="bucket",
+ expr=ast.Call(
+ name="toStartOfInterval",
+ args=[time_field, ast.Call(name="toIntervalMinute", args=[ast.Constant(value=interval_minutes)])],
+ ),
+ ),
+ ]
+ for i, alert_expr in enumerate(self._alert_where_exprs):
+ select_columns.append(
+ ast.Alias(
+ alias=f"alert_{i}",
+ expr=ast.Call(name="countIf", args=[alert_expr]),
+ )
+ )
+
+ return ast.SelectQuery(
+ select=select_columns,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),
+ where=self._outer_where,
+ group_by=[ast.Field(chain=["bucket"])],
+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["bucket"]), order="ASC")],
+ limit=ast.Constant(value=limit),
+ )
+
+ def _build_count_per_range_query(self, ranges: list[tuple[dt.datetime, dt.datetime]]) -> ast.SelectQuery:
+ select_columns: list[ast.Expr] = [
+ ast.Alias(
+ alias=f"alert_{alert_i}_period_{period_i}",
+ expr=ast.Call(
+ name="countIf",
+ args=[ast.And(exprs=[alert_expr, _timestamp_in_range(start, end)])],
+ ),
+ )
+ for alert_i, alert_expr in enumerate(self._alert_where_exprs)
+ for period_i, (start, end) in enumerate(ranges)
+ ]
+
+ return ast.SelectQuery(
+ select=select_columns,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),
+ where=self._outer_where,
+ )
+
def _run_query(self, query: ast.SelectQuery) -> HogQLQueryResponse:
return execute_hogql_query(
query_type="alert_check",
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index dda290f90663..d4c60d7797a1 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -12,6 +12,7 @@ from products.alerts.backend.scheduling import (
)
__all__ = [
+ "HOIST_BATCHED_ALERT_PREDICATES",
"MAX_BYTES_TO_READ",
"SCHEDULE_INTERVAL_SECONDS",
"advance_next_check_at",
@@ -34,6 +35,16 @@ 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 e9e5c5b8011c..3ff83f924853 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -1,4 +1,5 @@
import os
+import re
import json
import datetime as dt
from datetime import UTC, datetime
@@ -10,6 +11,15 @@ from unittest.mock import patch
from parameterized import parameterized
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.filters import replace_filters
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.printer import prepare_and_print_ast
+
from posthog.clickhouse.client import sync_execute
from products.logs.backend.alert_check_query import (
@@ -25,6 +35,7 @@ from products.logs.backend.alert_check_query import (
resolve_alert_date_to,
)
from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.temporal.constants import MAX_ALERT_COHORT_SIZE
def _seed_log_rows(
@@ -40,22 +51,64 @@ def _seed_log_rows(
for log_idx in range(count):
ts = minute_start + dt.timedelta(seconds=10 + log_idx)
rows.append(
- {
- "uuid": f"{uuid_prefix}-{minute_idx:03d}-{log_idx:03d}",
- "team_id": team_id,
- "timestamp": ts.strftime("%Y-%m-%d %H:%M:%S.%f"),
- "body": "",
- "severity_text": "info",
- "severity_number": 9,
- "service_name": service,
- "resource_attributes": {},
- "attributes_map_str": {},
- }
+ _log_row(
+ team_id,
+ f"{uuid_prefix}-{minute_idx:03d}-{log_idx:03d}",
+ ts.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ service,
+ )
)
if rows:
sync_execute("INSERT INTO logs FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in rows))
+def _log_row(
+ team_id: int,
+ uuid: str,
+ timestamp: str,
+ service: str,
+ *,
+ severity: str = "info",
+ attributes: dict[str, str] | None = None,
+) -> dict:
+ return {
+ "uuid": uuid,
+ "team_id": team_id,
+ "timestamp": timestamp,
+ "body": "",
+ "severity_text": severity,
+ "severity_number": 9,
+ "service_name": service,
+ "resource_attributes": {},
+ "attributes_map_str": attributes or {},
+ }
+
+
+def _attribute_filters(
+ key: str,
+ value: str,
+ *,
+ services: list[str] | None = None,
+ severities: list[str] | None = None,
+) -> dict:
+ filters: dict = {
+ "filterGroup": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"key": key, "value": value, "operator": "exact", "type": "log_attribute"}],
+ }
+ ],
+ }
+ }
+ if services is not None:
+ filters["serviceNames"] = services
+ if severities is not None:
+ filters["severityLevels"] = severities
+ return filters
+
+
class TestIsProjectionEligible(unittest.TestCase):
@parameterized.expand(
[
@@ -1306,12 +1359,15 @@ 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`
# individually. We seed several services worth of logs at random
- # timestamps, build one alert per service, run them as a batched cohort,
- # and assert each alert's per_alert slice matches the single-alert result.
+ # timestamps (a random subset carrying a log attribute), build one alert
+ # per service (alternating service-only and service+attribute filters),
+ # run them as a batched cohort, and assert each alert's per_alert slice
+ # matches the single-alert result.
# Sparse buckets (count=0 in batched, absent in single) are reconciled by
# filtering count>0 before comparison — same convention as the single
# query test suite.
@@ -1320,6 +1376,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
rng = _random.Random(7)
base = datetime(2025, 12, 16, 9, 0, 0, tzinfo=UTC)
range_seconds = 2 * 3600
+ attr_values = ["alpha", "beta", "gamma"]
# Build N services, each with a random log distribution.
n_services = 6
@@ -1331,23 +1388,30 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
n_logs = rng.randint(0, 150) # include 0 so we exercise sparse alerts
for i in range(n_logs):
off = rng.randint(0, range_seconds - 1)
+ attributes = {"job_kind__str": rng.choice(attr_values)} if rng.random() < 0.5 else {}
all_rows.append(
- {
- "uuid": f"batched-equiv-{trial}-{i}",
- "team_id": self.team.id,
- "timestamp": (base + dt.timedelta(seconds=off)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- "body": "",
- "severity_text": "info",
- "severity_number": 9,
- "service_name": service_name,
- "resource_attributes": {},
- "attributes_map_str": {},
- }
+ _log_row(
+ self.team.id,
+ f"batched-equiv-{trial}-{i}",
+ (base + dt.timedelta(seconds=off)).strftime("%Y-%m-%d %H:%M:%S.%f"),
+ service_name,
+ attributes=attributes,
+ )
)
if all_rows:
sync_execute("INSERT INTO logs FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in all_rows))
- alerts = [self._make_alert(name=svc, filters={"serviceNames": [svc]}) for svc in services]
+ # Attribute alerts read the attributes_map_str map, the filter class
+ # whose predicate placement caused the production incident.
+ alerts = [
+ self._make_alert(name=svc, filters={"serviceNames": [svc]})
+ if trial % 2 == 0
+ else self._make_alert(
+ name=f"{svc}-attr",
+ filters=_attribute_filters("job_kind", attr_values[trial % len(attr_values)], services=[svc]),
+ )
+ for trial, svc in enumerate(services)
+ ]
date_from = base
date_to = base + dt.timedelta(seconds=range_seconds)
@@ -1601,6 +1665,378 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
f"alert={alert.name}\nbatched (non-zero): {non_zero_batched}\nsingle: {single}"
)
+ @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
+ # hoisted OR of predicates against a future "simplification" when one
+ # disjunct is trivially true, across all three execute paths.
+ alerts = [
+ self._make_alert(name="everything", filters={}),
+ self._make_alert(name="service", filters={"serviceNames": ["argo-rollouts"]}),
+ self._make_alert(name="attribute", filters=_attribute_filters("log.iostream", "stderr")),
+ self._make_alert(name="nothing", filters={"serviceNames": ["no-such-service"]}),
+ ]
+ date_from, date_to = self._date_range()
+
+ def run(query):
+ if path == "bucketed":
+ return query.execute_bucketed(interval_minutes=5)
+ if path == "periods":
+ return query.execute_periods(period_minutes=5, period_count=3)
+ return query.execute_rolling_checks(nca=date_to, window_minutes=5, cadence_minutes=5, period_count=3)
+
+ batched = run(BatchedAlertCheckQuery(team=self.team, alerts=alerts, date_from=date_from, date_to=date_to))
+ for alert in alerts:
+ single = run(AlertCheckQuery(team=self.team, alert=alert, date_from=date_from, date_to=date_to))
+ got = batched.per_alert[str(alert.id)]
+ if path == "bucketed":
+ got = [b for b in got if b.count > 0]
+ 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
+ # against query-size/printer limits at the production cohort cap, with
+ # spot-checked equivalence.
+ nca = datetime(2025, 12, 16, 12, 30, tzinfo=UTC)
+ date_from = nca - dt.timedelta(minutes=15)
+ sampled = (0, MAX_ALERT_COHORT_SIZE // 2, MAX_ALERT_COHORT_SIZE - 1)
+ for i in sampled:
+ _seed_log_rows(self.team.id, f"batched_cap_{i}", date_from, [1] * 15, f"cap-{i}")
+
+ alerts = [
+ self._make_alert(name=f"cap-{i}", filters={"serviceNames": [f"batched_cap_{i}"]})
+ for i in range(MAX_ALERT_COHORT_SIZE)
+ ]
+ batched = BatchedAlertCheckQuery(
+ team=self.team, alerts=alerts, date_from=date_from, date_to=nca
+ ).execute_rolling_checks(nca=nca, window_minutes=5, cadence_minutes=5, period_count=3)
+
+ assert set(batched.per_alert.keys()) == {str(a.id) for a in alerts}
+ for i in sampled:
+ single = AlertCheckQuery(
+ team=self.team, alert=alerts[i], date_from=date_from, date_to=nca
+ ).execute_rolling_checks(nca=nca, window_minutes=5, cadence_minutes=5, period_count=3)
+ assert batched.per_alert[str(alerts[i].id)] == single, f"alert index {i}"
+ assert sum(b.count for b in single) > 0
+
+
+# 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.
+class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
+ ATTR_KEY = "job_kind"
+ ATTR_VALUE = "usage-rollup"
+ TARGET_SERVICE = "hoist_usage_reporter"
+ NOISY_SERVICES = ("hoist_noisy_api", "hoist_noisy_worker", "hoist_noisy_web")
+ NCA = datetime(2026, 2, 3, 10, 5, 0, tzinfo=UTC)
+
+ 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()
+ # Bulk of the team's volume comes from services the target alert does
+ # not match, mirroring the production incident's data shape.
+ base = datetime(2026, 2, 3, 9, 50, 0, tzinfo=UTC)
+ for svc in cls.NOISY_SERVICES:
+ _seed_log_rows(cls.team.id, svc, base, [3] * 15, f"hoist-noise-{svc}")
+ attrs = {f"{cls.ATTR_KEY}__str": cls.ATTR_VALUE}
+ rows = [
+ _log_row(
+ cls.team.id,
+ "hoist-target-1",
+ "2026-02-03 10:01:10",
+ cls.TARGET_SERVICE,
+ severity="error",
+ attributes=attrs,
+ ),
+ _log_row(
+ cls.team.id,
+ "hoist-target-2",
+ "2026-02-03 10:02:20",
+ cls.TARGET_SERVICE,
+ severity="error",
+ attributes=attrs,
+ ),
+ # Same service and attribute but wrong severity: must be excluded
+ # by the severity leg of the predicate.
+ _log_row(
+ cls.team.id,
+ "hoist-target-3",
+ "2026-02-03 10:03:30",
+ cls.TARGET_SERVICE,
+ severity="info",
+ attributes=attrs,
+ ),
+ # Same service and severity but no attribute: must be excluded by
+ # the attribute leg.
+ _log_row(cls.team.id, "hoist-target-4", "2026-02-03 10:04:40", cls.TARGET_SERVICE, severity="error"),
+ ]
+ sync_execute("INSERT INTO logs FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in rows))
+
+ def _make_alert(self, **kwargs) -> LogsAlertConfiguration:
+ defaults = {
+ "team": self.team,
+ "name": "Hoisting test",
+ "threshold_count": 0,
+ "threshold_operator": "above",
+ "window_minutes": 5,
+ "evaluation_periods": 3,
+ "filters": {},
+ }
+ defaults.update(kwargs)
+ return LogsAlertConfiguration.objects.create(**defaults)
+
+ def _incident_filters(self, attr_value: str) -> dict:
+ return _attribute_filters(
+ self.ATTR_KEY, attr_value, services=[self.TARGET_SERVICE], severities=["error", "fatal"]
+ )
+
+ def _print_query(self, query: ast.SelectQuery) -> tuple[str, dict]:
+ # Same modifier resolution and {filters} placeholder handling as
+ # `execute_hogql_query`, so the printed SQL is the production query text.
+ query = replace_filters(query, None, self.team)
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_team(self.team, HogQLQueryModifiers(convertToProjectTimezone=False)),
+ )
+ sql, _ = prepare_and_print_ast(query, context, "clickhouse")
+ return sql, context.values
+
+ @staticmethod
+ def _outer_where_sql(sql: str) -> str:
+ # The countIf predicates live in the SELECT list, before the WHERE
+ # keyword, so everything after it (minus trailing clauses) is the
+ # outer WHERE.
+ _, sep, after = sql.partition(" WHERE ")
+ assert sep, f"no WHERE clause in: {sql}"
+ for terminator in (" GROUP BY ", " ORDER BY ", " LIMIT "):
+ cut = after.find(terminator)
+ if cut != -1:
+ after = after[:cut]
+ return after
+
+ def _build_two_alert_query(self, builder: str) -> ast.SelectQuery:
+ service_alert = self._make_alert(name="svc", filters={"serviceNames": [self.NOISY_SERVICES[0]]})
+ attr_alert = self._make_alert(name="attr", filters=self._incident_filters(self.ATTR_VALUE))
+ date_from = self.NCA - dt.timedelta(minutes=15)
+ query = BatchedAlertCheckQuery(
+ team=self.team,
+ alerts=[service_alert, attr_alert],
+ date_from=date_from,
+ date_to=self.NCA,
+ projection_eligible=False,
+ )
+ builders = {
+ "bucketed": lambda: query._build_bucketed_query(5, 10_000),
+ "count_per_range": lambda: query._build_count_per_range_query(_rolling_check_ranges(self.NCA, 5, 5, 3)),
+ }
+ return builders[builder]()
+
+ @parameterized.expand(
+ [
+ ("matches_rows", "usage-rollup", 2),
+ ("matches_nothing", "no-such-kind", 0),
+ ]
+ )
+ @freeze_time("2026-02-03T10:05:00Z")
+ def test_single_alert_attribute_filter_cohort_matches_per_alert_path(
+ self, _name: str, attr_value: str, expected_total: int
+ ):
+ # The production incident shape: a size-1 cohort whose alert filters on
+ # a log attribute (projection-ineligible), checked as 3 rolling 5-minute
+ # windows while other services carry the bulk of the team's volume.
+ alert = self._make_alert(filters=self._incident_filters(attr_value))
+ date_from = self.NCA - dt.timedelta(minutes=15)
+
+ batched = BatchedAlertCheckQuery(
+ team=self.team, alerts=[alert], date_from=date_from, date_to=self.NCA, projection_eligible=False
+ ).execute_rolling_checks(nca=self.NCA, window_minutes=5, cadence_minutes=5, period_count=3)
+ single = AlertCheckQuery(
+ team=self.team, alert=alert, date_from=date_from, date_to=self.NCA
+ ).execute_rolling_checks(nca=self.NCA, window_minutes=5, cadence_minutes=5, period_count=3)
+
+ assert batched.per_alert[str(alert.id)] == single
+ assert sum(b.count for b in single) == expected_total
+
+ @parameterized.expand([("bucketed",), ("count_per_range",)])
+ def test_alert_predicates_hoisted_into_outer_where(self, builder: str):
+ # If a refactor drops the "redundant" OR from the outer WHERE, every
+ # equivalence test still passes (the predicates survive inside countIf)
+ # and the scan just quietly stops pruning. Pin the placement.
+ sql, _ = self._print_query(self._build_two_alert_query(builder))
+ where = self._outer_where_sql(sql)
+ assert "service_name" in where
+ assert "attributes_map_str" in where
+
+ def test_single_alert_outer_where_has_bare_predicate(self):
+ # A size-1 cohort must produce the same WHERE shape as AlertCheckQuery:
+ # the predicate itself, not a one-armed or(...) wrapper.
+ alert = self._make_alert(filters={"serviceNames": [self.TARGET_SERVICE]})
+ date_from = self.NCA - dt.timedelta(minutes=15)
+ query = BatchedAlertCheckQuery(team=self.team, alerts=[alert], date_from=date_from, date_to=self.NCA)
+ 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" 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.
+ 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
+ )
+ 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).
+ settings = {
+ k: "1" if v is True else "0" if v is False else str(v)
+ for k, v in HogQLGlobalSettings().model_dump().items()
+ if v is not None
+ }
+ [[raw]] = sync_execute(f"EXPLAIN indexes = 1, json = 1 {sql}", values, settings=settings)
+ plan = json.loads(raw)
+
+ skip_indexes: set[str] = set()
+ primary_key_columns: set[str] = set()
+
+ def walk(obj) -> None:
+ if isinstance(obj, dict):
+ indexes = obj.get("Indexes")
+ if isinstance(indexes, list):
+ for idx in indexes:
+ if not isinstance(idx, dict):
+ continue
+ if idx.get("Type") == "Skip" and isinstance(idx.get("Name"), str):
+ skip_indexes.add(idx["Name"])
+ if idx.get("Type") == "PrimaryKey":
+ primary_key_columns.update(k for k in idx.get("Keys", []) if isinstance(k, str))
+ for value in obj.values():
+ walk(value)
+ elif isinstance(obj, list):
+ for item in obj:
+ walk(item)
+
+ walk(plan)
+ return skip_indexes, primary_key_columns
+
+ 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.
+ # `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).
+ attr_index_rows = sync_execute(
+ "SELECT DISTINCT name FROM system.data_skipping_indices"
+ " WHERE database = currentDatabase() AND expr LIKE '%attributes_map_str%'"
+ )
+ 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)
+
+ 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(
+ [
+ (
+ "midnight_boundary",
+ ["2026-02-02 23:59:59.999999", "2026-02-03 00:00:00.000000"],
+ datetime(2026, 2, 2, 23, 50, 0, tzinfo=UTC),
+ datetime(2026, 2, 3, 0, 10, 0, tzinfo=UTC),
+ 2,
+ ),
+ (
+ "subsecond_bucket_edge",
+ ["2026-02-02 10:04:59.999999", "2026-02-02 10:05:00.000000"],
+ datetime(2026, 2, 2, 10, 0, 0, tzinfo=UTC),
+ datetime(2026, 2, 2, 10, 10, 0, tzinfo=UTC),
+ 2,
+ ),
+ (
+ "exact_date_to_excluded",
+ ["2026-02-02 10:09:59.999999", "2026-02-02 10:10:00.000000"],
+ datetime(2026, 2, 2, 10, 0, 0, tzinfo=UTC),
+ datetime(2026, 2, 2, 10, 10, 0, tzinfo=UTC),
+ 1,
+ ),
+ ]
+ )
+ @freeze_time("2026-02-03T10:05:00Z")
+ def test_boundary_rows_with_attribute_filter(
+ self, name: str, timestamps: list[str], date_from: datetime, date_to: datetime, expected_total: int
+ ):
+ # The existing boundary tests use service filters only; with hoisting,
+ # an attribute predicate and the time bounds meet in the outer WHERE
+ # for the first time, so pin batched == single at the same edges.
+ service = f"hoist_bnd_{name}"
+ rows = [
+ _log_row(
+ self.team.id,
+ f"bnd-{name}-{i}",
+ ts,
+ service,
+ attributes={f"{self.ATTR_KEY}__str": self.ATTR_VALUE},
+ )
+ for i, ts in enumerate(timestamps)
+ ]
+ # A row without the attribute keeps the attribute leg non-trivial.
+ rows.append(_log_row(self.team.id, f"bnd-{name}-decoy", timestamps[0], service))
+ sync_execute("INSERT INTO logs FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in rows))
+
+ alert = self._make_alert(filters=_attribute_filters(self.ATTR_KEY, self.ATTR_VALUE, services=[service]))
+ batched = BatchedAlertCheckQuery(
+ team=self.team, alerts=[alert], date_from=date_from, date_to=date_to, projection_eligible=False
+ ).execute_bucketed(interval_minutes=5)
+ single = AlertCheckQuery(team=self.team, alert=alert, date_from=date_from, date_to=date_to).execute_bucketed(
+ interval_minutes=5
+ )
+
+ non_zero = [b for b in batched.per_alert[str(alert.id)] if b.count > 0]
+ assert non_zero == single
+ assert sum(b.count for b in single) == expected_total
+
class TestFetchLiveLogsCheckpoint(APIBaseTest):
@patch("products.logs.backend.alert_check_query.execute_hogql_query")
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index d483a5d9e161..3e701a298162 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -608,6 +608,79 @@ class TestRunCohortQueryFallbackEndToEnd(ClickhouseTestMixin, APIBaseTest):
assert "simulated per-alert query failure" in str(bad_prefetch.error)
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
+ # catches wiring drift between the activity call site and
+ # BatchedAlertCheckQuery that tests constructing the query class
+ # directly cannot.
+ from products.logs.backend.temporal.activities import _AlertCohort, _run_cohort_query
+
+ rows = [
+ {
+ "uuid": f"incident-{i}",
+ "team_id": self.team.id,
+ "timestamp": ts,
+ "body": "",
+ "severity_text": "error",
+ "severity_number": 17,
+ "service_name": "incident_usage_reporter",
+ "resource_attributes": {},
+ "attributes_map_str": attributes,
+ }
+ for i, (ts, attributes) in enumerate(
+ [
+ ("2026-01-01 10:01:10", {"job_kind__str": "usage-rollup"}),
+ ("2026-01-01 10:02:20", {"job_kind__str": "usage-rollup"}),
+ ("2026-01-01 10:03:30", {}),
+ ]
+ )
+ ]
+ sync_execute("INSERT INTO logs FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in rows))
+
+ alert = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="incident shape",
+ threshold_count=0,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=3,
+ filters={
+ "serviceNames": ["incident_usage_reporter"],
+ "filterGroup": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": "job_kind",
+ "value": "usage-rollup",
+ "operator": "exact",
+ "type": "log_attribute",
+ }
+ ],
+ }
+ ],
+ },
+ },
+ )
+ cohort = _AlertCohort(
+ alerts=(alert,),
+ date_to=datetime(2026, 1, 1, 10, 5, 0, tzinfo=UTC),
+ projection_eligible=False,
+ )
+
+ result = _run_cohort_query(cohort)
+
+ prefetched = result.per_alert[str(alert.id)]
+ assert prefetched.error is None
+ assert prefetched.buckets is not None
+ assert sum(b.count for b in prefetched.buckets) == 2
+
class TestEvaluateSingleAlert(APIBaseTest):
def setUp(self):