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): cap anomaly scan fetch explicitly and degrade on row truncation (#79548)

Jon McCallumcdf3bd29efb0
diff --git a/products/logs/backend/anomaly_scan.py b/products/logs/backend/anomaly_scan.py
index acf89d572fa7..0ef6205b433d 100644
--- a/products/logs/backend/anomaly_scan.py
+++ b/products/logs/backend/anomaly_scan.py
@@ -29,7 +29,7 @@ import numpy as np
from posthog.schema import HogQLQueryModifiers
from posthog.hogql import ast
-from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, HogQLGlobalSettings, LimitContext
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -85,6 +85,11 @@ class ScanBudgetExceeded(Exception):
"""Every degradation rung blew the byte budget or the scan deadline."""
+class ScanFetchTruncated(Exception):
+ """The bucket fetch hit its row limit, so the history would be silently
+ incomplete. Degradable: fewer lookback buckets means fewer rows."""
+
+
class BindingConstraint(StrEnum):
"""What limited the scan's baseline, scan-wide."""
@@ -321,8 +326,16 @@ def fetch_bucket_counts(
WHERE {where}
GROUP BY bucket, severity_text
ORDER BY bucket ASC
+ LIMIT {row_limit}
""",
- placeholders={"bucket_minutes": ast.Constant(value=BUCKET_MINUTES), "where": where},
+ placeholders={
+ "bucket_minutes": ast.Constant(value=BUCKET_MINUTES),
+ "where": where,
+ # Without an explicit LIMIT, HogQL applies the context default of
+ # 100 rows, and ClickHouse returns buckets in primary-key order —
+ # the scan would silently see only the oldest sliver of history.
+ "row_limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),
+ },
)
assert isinstance(query, ast.SelectQuery)
@@ -336,6 +349,11 @@ def fetch_bucket_counts(
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
)
+ # A full page may be complete-but-exactly-full; treating it as truncated is
+ # the conservative read — degrading beats scoring against partial history.
+ if len(response.results) >= MAX_SELECT_RETURNED_ROWS:
+ raise ScanFetchTruncated(f"bucket fetch returned {len(response.results)} rows, at the row limit")
+
counts: dict[str, dict[dt.datetime, int]] = {}
for row in response.results:
bucket_time, severity, total = row[0], row[1] or "unknown", row[2]
@@ -547,7 +565,7 @@ def run_scan(
ranges = baseline_slice_ranges(attempt.eval_start, attempt.eval_end, attempt.lookback_buckets, config_probe)
try:
counts = fetch_bucket_counts(team, service_name, ranges, max_execution_seconds=remaining_seconds)
- except (CHQueryErrorTooManyBytes, ClickHouseQueryTimeOut) as err:
+ except (CHQueryErrorTooManyBytes, ClickHouseQueryTimeOut, ScanFetchTruncated) as err:
last_error = err
continue
diff --git a/products/logs/backend/test/test_anomaly_scan.py b/products/logs/backend/test/test_anomaly_scan.py
index 5dcfad3c3e26..b080f6c1e0b8 100644
--- a/products/logs/backend/test/test_anomaly_scan.py
+++ b/products/logs/backend/test/test_anomaly_scan.py
@@ -1,6 +1,7 @@
import json
import uuid
import datetime as dt
+from types import SimpleNamespace
from typing import cast
from zoneinfo import ZoneInfo
@@ -12,6 +13,8 @@ from django.test import SimpleTestCase
import numpy as np
from parameterized import parameterized
+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS
+
from posthog.clickhouse.client import sync_execute
from posthog.errors import CHQueryErrorTooManyBytes
from posthog.models import Team
@@ -30,6 +33,7 @@ from products.apm.backend.facade.api import (
from products.logs.backend.anomaly_scan import (
BindingConstraint,
ScanBudgetExceeded,
+ ScanFetchTruncated,
TimeRange,
baseline_slice_ranges,
degradation_ladder,
@@ -170,13 +174,19 @@ class TestRunScan(SimpleTestCase):
def _now(self) -> dt.datetime:
return T0 + BUCKETS_PER_DAY * BUCKET
- def test_degrades_on_byte_budget_and_reports_constraint(self) -> None:
+ @parameterized.expand(
+ [
+ ("byte_budget", CHQueryErrorTooManyBytes("too many bytes", code=307)),
+ ("row_truncation", ScanFetchTruncated("bucket fetch returned 50000 rows, at the row limit")),
+ ]
+ )
+ def test_degrades_on_fetch_failure_and_reports_constraint(self, _name: str, error: Exception) -> None:
calls: list[int] = []
def fake_fetch(team, service_name, ranges, max_execution_seconds=60):
calls.append(len(ranges))
if len(calls) == 1:
- raise CHQueryErrorTooManyBytes("too many bytes", code=307)
+ raise error
return {"info": {T0: 100}}
with patch("products.logs.backend.anomaly_scan.fetch_bucket_counts", side_effect=fake_fetch):
@@ -187,6 +197,13 @@ class TestRunScan(SimpleTestCase):
assert BindingConstraint.BYTE_BUDGET in result.binding_constraints
assert result.lookback_buckets < 6 * BUCKETS_PER_WEEK
+ def test_fetch_raises_on_full_result_page(self) -> None:
+ full_page = [(T0 + i * BUCKET, "info", 1) for i in range(MAX_SELECT_RETURNED_ROWS)]
+ response = SimpleNamespace(results=full_page)
+ with patch("products.logs.backend.anomaly_scan.execute_hogql_query", return_value=response):
+ with self.assertRaises(ScanFetchTruncated):
+ fetch_bucket_counts(_team(), "svc", [TimeRange(start=T0, end=T0 + BUCKET)])
+
def test_retention_clamps_lookback_and_reports_constraint(self) -> None:
with patch("products.logs.backend.anomaly_scan.fetch_bucket_counts", return_value={}) as fetch:
result = run_scan(_team(retention_days=14), "svc", T0, T0 + 12 * BUCKET, now=self._now())