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): compare anomaly scan day pruning as Date for ClickHouse IN (#79426)

Jon McCallum3e705e7995db
diff --git a/products/logs/backend/anomaly_scan.py b/products/logs/backend/anomaly_scan.py
index 8093329014a9..acf89d572fa7 100644
--- a/products/logs/backend/anomaly_scan.py
+++ b/products/logs/backend/anomaly_scan.py
@@ -262,12 +262,12 @@ def _scan_settings(max_execution_seconds: int) -> HogQLGlobalSettings:
)
-def _covered_days(ranges: list[TimeRange]) -> list[dt.datetime]:
- days: set[dt.datetime] = set()
+def _covered_days(ranges: list[TimeRange]) -> list[dt.date]:
+ days: set[dt.date] = set()
for r in ranges:
day = r.start.astimezone(dt.UTC).replace(hour=0, minute=0, second=0, microsecond=0)
while day < r.end:
- days.add(day)
+ days.add(day.date())
day += dt.timedelta(days=1)
return sorted(days)
@@ -292,9 +292,12 @@ def fetch_bucket_counts(
# Day-level primary-key pruning: the logs table sorts on time_bucket
# (day-truncated). Pin the truncation to UTC — convertToProjectTimezone is
# off, so the constants are UTC and an unpinned toStartOfDay would compare
- # against server-local day boundaries.
+ # against server-local day boundaries. Both sides must be Date: HogQL
+ # prints datetime constants as DateTime64, and ClickHouse's IN section
+ # refuses to coerce DateTime64 elements against a DateTime left side
+ # (ordered comparisons coerce; IN does not).
day_prune = parse_expr(
- "toStartOfDay(time_bucket, 'UTC') IN {days}",
+ "toDate(toStartOfDay(time_bucket, 'UTC')) IN {days}",
placeholders={"days": ast.Tuple(exprs=[ast.Constant(value=day) for day in _covered_days(ranges)])},
)
where = ast.And(
diff --git a/products/logs/backend/test/test_anomaly_scan.py b/products/logs/backend/test/test_anomaly_scan.py
index 2139bbb0799e..5dcfad3c3e26 100644
--- a/products/logs/backend/test/test_anomaly_scan.py
+++ b/products/logs/backend/test/test_anomaly_scan.py
@@ -1,7 +1,10 @@
+import json
+import uuid
import datetime as dt
from typing import cast
from zoneinfo import ZoneInfo
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
from django.test import SimpleTestCase
@@ -9,6 +12,7 @@ from django.test import SimpleTestCase
import numpy as np
from parameterized import parameterized
+from posthog.clickhouse.client import sync_execute
from posthog.errors import CHQueryErrorTooManyBytes
from posthog.models import Team
@@ -29,6 +33,7 @@ from products.logs.backend.anomaly_scan import (
TimeRange,
baseline_slice_ranges,
degradation_ladder,
+ fetch_bucket_counts,
floor_to_bucket,
merge_ranges,
run_scan,
@@ -280,3 +285,45 @@ class TestRunScan(SimpleTestCase):
assert issue.resolved_at is not None
assert issue.last_anomalous_at <= issue.resolved_at
assert all(t <= issue.resolved_at for t in issue.anomalous_bucket_times)
+
+
+class TestFetchBucketCountsClickhouse(ClickhouseTestMixin, APIBaseTest):
+ def test_query_executes_against_clickhouse_and_prunes_days(self):
+ base = dt.datetime(2026, 8, 6, 10, 2, tzinfo=UTC)
+ rows: list[tuple[dt.datetime, str, str]] = [
+ # Two error rows in one 5-minute bucket, one info row in the next.
+ (base, "error", "checkout"),
+ (base + dt.timedelta(minutes=1), "error", "checkout"),
+ (base + dt.timedelta(minutes=5), "info", "checkout"),
+ # Outside the fetched ranges: a different day, and a different service.
+ (base - dt.timedelta(days=2), "error", "checkout"),
+ (base, "error", "other-svc"),
+ ]
+ payload = "\n".join(
+ json.dumps(
+ {
+ "uuid": str(uuid.uuid4()),
+ "team_id": self.team.id,
+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "observed_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "body": "scan fixture",
+ "severity_text": severity,
+ "severity_number": 9,
+ "service_name": service,
+ "resource_attributes": {},
+ "instrumentation_scope": "",
+ "event_name": "",
+ }
+ )
+ for timestamp, severity, service in rows
+ )
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow {payload}")
+
+ window = TimeRange(start=base.replace(minute=0), end=base.replace(minute=0) + dt.timedelta(hours=1))
+ counts = fetch_bucket_counts(self.team, "checkout", [window])
+
+ bucket_0 = base.replace(minute=0)
+ assert counts == {
+ "error": {bucket_0: 2},
+ "info": {bucket_0 + dt.timedelta(minutes=5): 1},
+ }