: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
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.pyindex 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.pyindex 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 uuidimport datetime as dtfrom typing import castfrom zoneinfo import ZoneInfo+from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patchfrom django.test import SimpleTestCase@@ -9,6 +12,7 @@ from django.test import SimpleTestCaseimport numpy as npfrom parameterized import parameterized+from posthog.clickhouse.client import sync_executefrom posthog.errors import CHQueryErrorTooManyBytesfrom 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 Noneassert issue.last_anomalous_at <= issue.resolved_atassert 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},+ }