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): gate series-bands grain on bucket density and pick it when omitted (#95932)

Jon McCallum39e5d14d5a81
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.py
index f38205ccfaa0..3cc3a5691221 100644
--- a/products/logs/backend/presentation/views/anomalies_api.py
+++ b/products/logs/backend/presentation/views/anomalies_api.py
@@ -22,12 +22,15 @@ from posthog.rate_limit import (
from products.logs.backend.anomaly_scan import MAX_EVAL_DAYS, ScanBudgetExceeded, floor_to_bucket, run_scan
from products.logs.backend.series_bands import (
+ ALIVE_SLOT_FRACTION,
BASELINE_WEEKS,
+ BUCKET_TARGET,
INTERVAL_LADDER_MINUTES,
MAX_BUCKETS_PER_SERIES,
MAX_WINDOW_DAYS,
MAX_WINDOW_START_AGE_DAYS,
MIN_BASELINE_WEEKS_FOR_BAND,
+ MIN_MEAN_PER_ALIVE_BUCKET,
SeriesBandsFetchTruncated,
SeriesBandsWindowInvalid,
resolve_window,
@@ -56,6 +59,7 @@ class LogsAnomalyVerdict(models.TextChoices):
_VERDICT_CHOICES = list(LogsAnomalyVerdict.values)
_TIER_CHOICES = ["a", "b", "c", "d"]
+_COARSENED_REASON_CHOICES = ["sparse", "quiet"]
_CONSTRAINT_CHOICES = ["team_retention", "byte_budget"]
@@ -242,11 +246,15 @@ class LogsSeriesBandsRequestSerializer(serializers.Serializer):
)
intervalMinutes = serializers.ChoiceField(
choices=list(INTERVAL_LADDER_MINUTES),
- default=60,
+ required=False,
+ allow_null=True,
help_text=(
f"Display grain in minutes for buckets and bands. One of {', '.join(map(str, INTERVAL_LADDER_MINUTES))}. "
f"The window may hold at most {MAX_BUCKETS_PER_SERIES} buckets per series at the chosen grain, "
- f"so a finer grain needs a shorter window."
+ f"so a finer grain needs a shorter window. Omit it to let the window pick its grain, the coarsest "
+ f"that still cuts it into about {BUCKET_TARGET} buckets. "
+ f"A series too sparse to read at this grain is returned at a coarser one; see each series' "
+ f"interval_minutes."
),
)
@@ -294,9 +302,29 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):
"When this series gains its band, so a learning series can count down to it. Null once the band is drawn."
),
)
+ interval_minutes = serializers.IntegerField(
+ help_text=(
+ "Grain of this series' buckets, in minutes. Equals the response interval_minutes unless the series "
+ "was too sparse at that grain and was coarsened to the next rung it is dense enough to read at."
+ ),
+ )
+ coarsened_reason = serializers.ChoiceField(
+ choices=_COARSENED_REASON_CHOICES,
+ allow_null=True,
+ help_text=(
+ f"Why this series was too thin to read at the requested grain, or null when it was not. sparse: fewer "
+ f"than {ALIVE_SLOT_FRACTION:.0%} of its buckets held any records. quiet: its non-empty buckets averaged "
+ f"under {MIN_MEAN_PER_ALIVE_BUCKET:g} records. A series that fails every rung is returned at the "
+ f"coarsest one. A series that a coarser rung has no rows for, or that the request's time budget "
+ f"cannot refetch, keeps the requested grain and still carries its reason."
+ ),
+ )
buckets = LogsSeriesBandBucketSerializer(
many=True,
- help_text="One entry per display bucket across the whole window, oldest first, zero-filled.",
+ help_text=(
+ "One entry per display bucket across the window at this series' interval_minutes, oldest first, "
+ "zero-filled. A coarsened series' window is snapped to its grain, so it can end short of window_end."
+ ),
)
@@ -304,7 +332,12 @@ class LogsSeriesBandsResponseSerializer(serializers.Serializer):
service_name = serializers.CharField(help_text="Service the series belong to.")
window_start = serializers.DateTimeField(help_text="Start of the observed window (UTC, inclusive).")
window_end = serializers.DateTimeField(help_text="End of the observed window (UTC, exclusive).")
- interval_minutes = serializers.IntegerField(help_text="Display grain of the buckets, in minutes.")
+ interval_minutes = serializers.IntegerField(
+ help_text=(
+ f"Display grain requested, or picked to cut the window into about {BUCKET_TARGET} buckets when the "
+ f"request left it out."
+ ),
+ )
series_truncated = serializers.BooleanField(
help_text="True when the service has more series than the response carries; the quietest were dropped."
)
@@ -412,16 +445,16 @@ class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
def series_bands(self, request: ValidatedRequest, **kwargs: Any) -> Response:
data = request.validated_data
service_name: str = data["serviceName"]
- interval_minutes: int = int(data["intervalMinutes"])
date_range: dict[str, Any] = data.get("dateRange") or {}
try:
window = resolve_window(
date_range.get("date_from"),
date_range.get("date_to"),
- interval_minutes=interval_minutes,
+ interval_minutes=data.get("intervalMinutes"),
)
except SeriesBandsWindowInvalid as err:
return Response({"error": str(err)}, status=status.HTTP_400_BAD_REQUEST)
+ interval_minutes = window.interval_minutes
cache_key = (
"logs_series_bands/"
diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.py
index 2316d37a96d6..0693b60365f8 100644
--- a/products/logs/backend/series_bands.py
+++ b/products/logs/backend/series_bands.py
@@ -11,7 +11,11 @@ gating, widening) where the arithmetic is cheap and unit-testable.
import os
import math
+import time
import datetime as dt
+from collections.abc import Collection
+from dataclasses import replace
+from typing import Literal
from zoneinfo import ZoneInfo
from posthog.schema import HogQLQueryModifiers
@@ -46,17 +50,29 @@ MAX_SERIES = int(os.environ.get("LOGS_SERIES_BANDS_MAX_SERIES", "100"))
# aligned with the weekly fold, and 5 is the bucket size of logs_volume_buckets.
INTERVAL_LADDER_MINUTES = (5, 15, 30, 60)
MAX_BUCKETS_PER_SERIES = int(os.environ.get("LOGS_SERIES_BANDS_MAX_BUCKETS_PER_SERIES", "500"))
+# How many buckets a window aims for when the caller leaves the grain out. The
+# grain snaps up to the ladder rung at or above window / BUCKET_TARGET, so a
+# 7 day window keeps its hourly look and a 6 hour window reads at 5 minutes.
+BUCKET_TARGET = int(os.environ.get("LOGS_SERIES_BANDS_BUCKET_TARGET", "168"))
# A series' lifetime starts at the first slot followed by sustained traffic: at
# least this fraction of the slots after it are non-empty, over the day and over
# the week. A stray row before the real start would otherwise date the lifetime
# and turn every empty week between them into a baseline of zeros.
ALIVE_SLOT_FRACTION = float(os.environ.get("LOGS_SERIES_BANDS_ALIVE_SLOT_FRACTION", "0.2"))
+# A series keeps a grain only where it is dense enough to read there: at least
+# ALIVE_SLOT_FRACTION of its window buckets are non-empty, and those buckets
+# average at least this many records. Below that the band floor, which scales
+# with the grain, sits under most observed values and nearly every bucket marks.
+MIN_MEAN_PER_ALIVE_BUCKET = float(os.environ.get("LOGS_SERIES_BANDS_MIN_MEAN_PER_ALIVE_BUCKET", "5"))
# Widening keeps the envelope from reading as a hairline on quiet series: the
# fraction scales both edges, the floor lifts the upper edge by a per-hour
# count so a band exists even where every baseline week saw the same value.
BAND_WIDEN_FRACTION = 0.1
BAND_FLOOR_PER_HOUR = 2.0
+# ClickHouse time one request may spend, shared across its passes. The
+# coarsening walk costs one pass per rung, so a per-pass cap would let a
+# request against a sparse service spend the whole cap once per rung.
MAX_EXECUTION_SECONDS = int(os.environ.get("LOGS_SERIES_BANDS_MAX_EXECUTION_SECONDS", "30"))
@@ -68,6 +84,9 @@ class SeriesBandsWindowInvalid(Exception):
pass
+CoarsenedReason = Literal["sparse", "quiet"]
+
+
@frozen
class BandBucket:
time: dt.datetime
@@ -85,6 +104,8 @@ class BandSeries:
baseline_weeks: int
history_start: dt.datetime
band_ready_at: dt.datetime | None
+ interval_minutes: int
+ coarsened_reason: CoarsenedReason | None
buckets: list[BandBucket]
@@ -102,6 +123,7 @@ class SeriesBandsResult:
class SeriesBandsWindow:
start: dt.datetime
end: dt.datetime
+ interval_minutes: int
@frozen
@@ -137,6 +159,8 @@ def fetch_series_slot_rows(
window_start: dt.datetime,
window_end: dt.datetime,
interval_minutes: int,
+ series_keys: Collection[_SeriesKey] | None = None,
+ max_execution_seconds: int = MAX_EXECUTION_SECONDS,
) -> dict[_SeriesKey, _SeriesRows]:
"""One ClickHouse pass: interval rollup over the window plus baseline, folded
by time-of-week onto the display window's slots, plus each series' lifetime
@@ -145,7 +169,8 @@ def fetch_series_slot_rows(
Rows are sparse — a (series, slot) with no observed and no baseline data has
no row. Missing baseline weeks are reconstructed in Python from
baseline_samples vs the weeks the series existed. Baseline samples only
- count slots at or after the lifetime start."""
+ count slots at or after the lifetime start. With series_keys the pass reads
+ only those series and skips the volume ranking."""
tag_queries(product=Product.LOGS, feature=Feature.QUERY, source="logs_series_bands", team_id=str(team.id))
baseline_start = window_start - dt.timedelta(weeks=BASELINE_WEEKS)
@@ -158,11 +183,38 @@ def fetch_series_slot_rows(
# same fraction over the day after the slot leaves only slots that carry
# traffic of their own.
alive_day_slots = max(1, math.ceil(ALIVE_SLOT_FRACTION * SECONDS_PER_DAY / (interval_minutes * 60)))
- # The series cap ranks over the whole 42d, not the display window: a series
- # that went silent this week has zero window volume, and ranking on the
- # window alone would drop exactly the series a silence should surface. The
- # subquery fetches one series past the cap so the caller can tell a full
- # response from a truncated one.
+ series_filter: ast.Expr
+ if series_keys is None:
+ # The series cap ranks over the whole 42d, not the display window: a series
+ # that went silent this week has zero window volume, and ranking on the
+ # window alone would drop exactly the series a silence should surface. The
+ # subquery fetches one series past the cap so the caller can tell a full
+ # response from a truncated one.
+ series_filter = parse_select(
+ """
+ SELECT namespace, environment, severity_text
+ FROM posthog.logs_volume_buckets
+ WHERE service_name = {service_name}
+ AND time_bucket >= {baseline_start}
+ AND time_bucket < {window_end}
+ GROUP BY namespace, environment, severity_text
+ ORDER BY sum(log_count) DESC
+ LIMIT {max_series_plus_probe}
+ """,
+ placeholders={
+ "service_name": ast.Constant(value=service_name),
+ "window_end": ast.Constant(value=window_end),
+ "baseline_start": ast.Constant(value=baseline_start),
+ "max_series_plus_probe": ast.Constant(value=MAX_SERIES + 1),
+ },
+ )
+ else:
+ series_filter = ast.Tuple(
+ exprs=[
+ ast.Tuple(exprs=[ast.Constant(value=part) for part in (key.namespace, key.environment, key.severity)])
+ for key in series_keys
+ ]
+ )
query = parse_select(
"""
WITH slots AS (
@@ -176,16 +228,7 @@ def fetch_series_slot_rows(
WHERE service_name = {service_name}
AND time_bucket >= {baseline_start}
AND time_bucket < {window_end}
- AND (namespace, environment, severity_text) IN (
- SELECT namespace, environment, severity_text
- FROM posthog.logs_volume_buckets
- WHERE service_name = {service_name}
- AND time_bucket >= {baseline_start}
- AND time_bucket < {window_end}
- GROUP BY namespace, environment, severity_text
- ORDER BY sum(log_count) DESC
- LIMIT {max_series_plus_probe}
- )
+ AND (namespace, environment, severity_text) IN {series_filter}
GROUP BY namespace, environment, severity_text, slot
),
lifetimes AS (
@@ -235,7 +278,7 @@ def fetch_series_slot_rows(
"alive_slots": ast.Constant(value=alive_slots),
"alive_day_slots": ast.Constant(value=alive_day_slots),
"day_seconds": ast.Constant(value=SECONDS_PER_DAY),
- "max_series_plus_probe": ast.Constant(value=MAX_SERIES + 1),
+ "series_filter": series_filter,
"row_limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),
},
)
@@ -246,7 +289,7 @@ def fetch_series_slot_rows(
query=query,
team=team,
workload=Workload.LOGS,
- settings=HogQLGlobalSettings(max_execution_time=MAX_EXECUTION_SECONDS),
+ settings=HogQLGlobalSettings(max_execution_time=max_execution_seconds),
limit_context=LimitContext.QUERY,
# Constants above are UTC; without this the printer emits them against
# the project timezone and the weekly fold lands on the wrong slots.
@@ -348,10 +391,96 @@ def _build_series(
baseline_weeks=baseline_weeks,
history_start=lifetime_start,
band_ready_at=band_ready_at,
+ interval_minutes=interval_minutes,
+ coarsened_reason=None,
buckets=buckets,
)
+def _density_shortfall(series: BandSeries) -> CoarsenedReason | None:
+ alive = [bucket.observed for bucket in series.buckets if bucket.observed > 0]
+ if len(alive) < ALIVE_SLOT_FRACTION * len(series.buckets):
+ return "sparse"
+ if sum(alive) / len(alive) < MIN_MEAN_PER_ALIVE_BUCKET:
+ return "quiet"
+ return None
+
+
+def _series_key(series: BandSeries) -> _SeriesKey:
+ return _SeriesKey(namespace=series.namespace, environment=series.environment, severity=series.severity)
+
+
+def _remaining_execution_seconds(deadline: float) -> int | None:
+ """Whole seconds left in the request's ClickHouse budget, or None once it is spent."""
+ remaining = int(deadline - time.monotonic())
+ return remaining if remaining > 0 else None
+
+
+def _coarsen_sparse_series(
+ team: Team,
+ service_name: str,
+ series: list[BandSeries],
+ window_start: dt.datetime,
+ window_end: dt.datetime,
+ interval_minutes: int,
+ deadline: float,
+) -> list[BandSeries]:
+ """Move each series that is too sparse at the requested grain up the ladder
+ to the first rung where it is dense enough, or to the top rung.
+
+ Every rung is one ClickHouse pass scoped to the series still failing, so the
+ worst case costs one pass per rung above the requested grain. The passes
+ share the request's execution budget, so that worst case costs the same
+ ClickHouse time as a single pass, and the walk stops at the rung reached when
+ the budget runs out. Every series that fails the gate keeps the reason from
+ the requested grain, because that is the grain the caller asked for and did
+ not get. A series the walk cannot reach, because a rung has no rows for it
+ or the budget is spent first, returns at the requested grain with that same
+ reason."""
+ settled: list[BandSeries] = []
+ pending: dict[_SeriesKey, BandSeries] = {}
+ for candidate in series:
+ shortfall = _density_shortfall(candidate)
+ if shortfall is None:
+ settled.append(candidate)
+ continue
+ pending[_series_key(candidate)] = replace(candidate, coarsened_reason=shortfall)
+
+ for rung in (rung for rung in INTERVAL_LADDER_MINUTES if rung > interval_minutes):
+ if not pending:
+ break
+ remaining = _remaining_execution_seconds(deadline)
+ if remaining is None:
+ break
+ rung_start = floor_to_interval(window_start, rung)
+ rung_end = floor_to_interval(window_end, rung)
+ rows = fetch_series_slot_rows(
+ team,
+ service_name,
+ rung_start,
+ rung_end,
+ rung,
+ series_keys=list(pending),
+ max_execution_seconds=remaining,
+ )
+ still_failing: dict[_SeriesKey, BandSeries] = {}
+ for key, fallback in pending.items():
+ if key not in rows:
+ settled.append(fallback)
+ continue
+ candidate = replace(
+ _build_series(key, rows[key], rung_start, rung_end, rung), coarsened_reason=fallback.coarsened_reason
+ )
+ if _density_shortfall(candidate) is None:
+ settled.append(candidate)
+ else:
+ still_failing[key] = candidate
+ pending = still_failing
+
+ settled.extend(pending.values())
+ return settled
+
+
_UTC_ZONE = ZoneInfo("UTC")
@@ -361,14 +490,26 @@ def _parse_bound(value: str, *, now: dt.datetime) -> dt.datetime:
return ensure_utc(relative_date_parse(value, _UTC_ZONE, now=now))
+def pick_interval_minutes(window_start: dt.datetime, window_end: dt.datetime) -> int:
+ """The first ladder rung at or above the step that cuts the window into BUCKET_TARGET buckets, capped at the coarsest.
+
+ The span is measured on bounds floored to the finest rung, as the query at that rung would see them."""
+ finest = INTERVAL_LADDER_MINUTES[0]
+ span = floor_to_interval(window_end, finest) - floor_to_interval(window_start, finest)
+ step_minutes = span.total_seconds() / 60 / BUCKET_TARGET
+ return next((grain for grain in INTERVAL_LADDER_MINUTES if grain >= step_minutes), INTERVAL_LADDER_MINUTES[-1])
+
+
def resolve_window(
date_from: str | None,
date_to: str | None,
*,
- interval_minutes: int = 60,
+ interval_minutes: int | None = 60,
now: dt.datetime | None = None,
) -> SeriesBandsWindow:
- """Turn a request date range into the snapped window to chart, defaulting to the last WINDOW_DAYS."""
+ """Turn a request date range into the snapped window to chart, defaulting to the last WINDOW_DAYS.
+
+ Without a grain the window picks its own, aiming for BUCKET_TARGET buckets."""
# Wall clock, never max(time_bucket): prod carries future buckets from
# device clock skew (ingest clamps at +24h), and the exclusive window_end
# bound is what keeps them out of the observed line.
@@ -377,6 +518,8 @@ def resolve_window(
window_end = _parse_bound(date_to, now=now) if date_to else now
window_end = min(window_end, now)
window_start = _parse_bound(date_from, now=now) if date_from else window_end - dt.timedelta(days=WINDOW_DAYS)
+ if interval_minutes is None:
+ interval_minutes = pick_interval_minutes(window_start, window_end)
# Snapping can move either bound by up to one interval, so every check runs
# on the snapped values the query will actually see.
window_start = floor_to_interval(window_start, interval_minutes)
@@ -397,7 +540,7 @@ def resolve_window(
)
_check_bucket_cap(window_start, window_end, interval_minutes)
- return SeriesBandsWindow(start=window_start, end=window_end)
+ return SeriesBandsWindow(start=window_start, end=window_end, interval_minutes=interval_minutes)
def _bucket_count(window_start: dt.datetime, window_end: dt.datetime, interval_minutes: int) -> int:
@@ -434,11 +577,15 @@ def run_series_bands(
window_start = floor_to_interval(window_start, interval_minutes)
window_end = floor_to_interval(window_end, interval_minutes)
+ deadline = time.monotonic() + MAX_EXECUTION_SECONDS
slot_rows = fetch_series_slot_rows(team, service_name, window_start, window_end, interval_minutes)
series = [_build_series(key, rows, window_start, window_end, interval_minutes) for key, rows in slot_rows.items()]
series.sort(key=lambda s: (-s.total_count, s.namespace, s.environment, s.severity))
series_truncated = len(series) > MAX_SERIES
- series = series[:MAX_SERIES]
+ series = _coarsen_sparse_series(
+ team, service_name, series[:MAX_SERIES], window_start, window_end, interval_minutes, deadline
+ )
+ series.sort(key=lambda s: (-s.total_count, s.namespace, s.environment, s.severity))
return SeriesBandsResult(
service_name=service_name,
diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.py
index 4af91990af0e..d06f33c537c7 100644
--- a/products/logs/backend/test/test_anomalies_api.py
+++ b/products/logs/backend/test/test_anomalies_api.py
@@ -66,6 +66,32 @@ def _scan_result(**overrides) -> ScanResult:
return ScanResult(**defaults)
+def _bands_result(**overrides) -> SeriesBandsResult:
+ defaults: dict = {
+ "service_name": "svc",
+ "window_start": T0 - dt.timedelta(days=7),
+ "window_end": T0,
+ "interval_minutes": 60,
+ "series_truncated": False,
+ "series": [
+ BandSeries(
+ namespace="ns",
+ environment="prod",
+ severity="error",
+ total_count=25,
+ baseline_weeks=5,
+ history_start=T0 - dt.timedelta(weeks=5),
+ band_ready_at=None,
+ interval_minutes=60,
+ coarsened_reason="sparse",
+ buckets=[BandBucket(time=T0 - dt.timedelta(hours=1), observed=25, lower=9.0, upper=57.0)],
+ )
+ ],
+ }
+ defaults.update(overrides)
+ return SeriesBandsResult(**defaults)
+
+
class TestScanRequestValidation(SimpleTestCase):
@parameterized.expand(
[
@@ -174,13 +200,18 @@ class TestLogsAnomalyScanAPI(APIBaseTest):
class TestSeriesBandsRequestValidation(SimpleTestCase):
- @parameterized.expand([(5, True), (15, True), (30, True), (60, True), (7, False), (120, False)])
- def test_interval_must_sit_on_the_ladder(self, interval_minutes: int, valid: bool) -> None:
+ @parameterized.expand([(5, True), (15, True), (30, True), (60, True), (None, True), (7, False), (120, False)])
+ def test_interval_must_sit_on_the_ladder_or_be_null(self, interval_minutes: int | None, valid: bool) -> None:
serializer = LogsSeriesBandsRequestSerializer(data={"serviceName": "svc", "intervalMinutes": interval_minutes})
assert serializer.is_valid() is valid, serializer.errors
if valid:
assert serializer.validated_data["intervalMinutes"] == interval_minutes
+ def test_interval_may_be_omitted(self) -> None:
+ serializer = LogsSeriesBandsRequestSerializer(data={"serviceName": "svc"})
+ assert serializer.is_valid(), serializer.errors
+ assert "intervalMinutes" not in serializer.validated_data
+
class TestLogsSeriesBandsAPI(APIBaseTest):
def setUp(self):
@@ -197,27 +228,8 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
run.assert_not_called()
def test_response_shape(self):
- result = SeriesBandsResult(
- service_name="svc",
- window_start=T0 - dt.timedelta(days=7),
- window_end=T0,
- interval_minutes=60,
- series_truncated=False,
- series=[
- BandSeries(
- namespace="ns",
- environment="prod",
- severity="error",
- total_count=25,
- baseline_weeks=5,
- history_start=T0 - dt.timedelta(weeks=5),
- band_ready_at=None,
- buckets=[BandBucket(time=T0 - dt.timedelta(hours=1), observed=25, lower=9.0, upper=57.0)],
- )
- ],
- )
with patch(
- "products.logs.backend.presentation.views.anomalies_api.run_series_bands", return_value=result
+ "products.logs.backend.presentation.views.anomalies_api.run_series_bands", return_value=_bands_result()
) as run:
response = self.client.post(self.url, {"serviceName": "svc"}, format="json")
@@ -235,6 +247,8 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
assert series["baseline_weeks"] == 5
assert series["history_start"] == (T0 - dt.timedelta(weeks=5)).isoformat().replace("+00:00", "Z")
assert series["band_ready_at"] is None
+ assert series["interval_minutes"] == 60
+ assert series["coarsened_reason"] == "sparse"
assert series["buckets"][0] == {
"time": (T0 - dt.timedelta(hours=1)).isoformat().replace("+00:00", "Z"),
"observed": 25,
@@ -242,6 +256,19 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
"upper": 57.0,
}
+ @parameterized.expand([("-7d", 60), ("-1d", 15)])
+ def test_omitted_interval_is_picked_from_the_window(self, date_from: str, expected_interval: int):
+ with patch(
+ "products.logs.backend.presentation.views.anomalies_api.run_series_bands",
+ return_value=_bands_result(interval_minutes=expected_interval),
+ ) as run:
+ response = self.client.post(
+ self.url, {"serviceName": "svc", "dateRange": {"date_from": date_from}}, format="json"
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert run.call_args.kwargs["interval_minutes"] == expected_interval
+ assert response.json()["interval_minutes"] == expected_interval
+
@parameterized.expand(
[
("span_over_seven_days", {"dateRange": {"date_from": "-14d"}}, "at most 7 days"),
diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.py
index ab7d92040899..38ebe8850632 100644
--- a/products/logs/backend/test/test_series_bands.py
+++ b/products/logs/backend/test/test_series_bands.py
@@ -2,6 +2,7 @@ import datetime as dt
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from django.test import SimpleTestCase
@@ -9,6 +10,7 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
+from products.logs.backend import series_bands
from products.logs.backend.series_bands import (
SeriesBandsWindow,
SeriesBandsWindowInvalid,
@@ -86,6 +88,12 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
rows.append((self.team.pk, slot, service, "ns", "prod", "error", 5))
rows.append((self.team.pk, slot, service, "ns", "prod", "error", 5))
rows.append((self.team.pk, slot + dt.timedelta(minutes=5), service, "ns", "prod", "error", 15))
+ # Steady traffic in every other bucket keeps the series dense at the grain.
+ bucket_count = window_days * 24 * 60 // interval_minutes
+ for i in range(bucket_count):
+ bucket_time = window_start + i * step
+ if bucket_time not in (slot, slot + step):
+ rows.append((self.team.pk, bucket_time, service, "ns", "prod", "error", 10))
# Excluded: future bucket, other service, other team.
rows.append((self.team.pk, NOW + dt.timedelta(hours=2), service, "ns", "prod", "error", 999))
rows.append((self.team.pk, slot, "svc-other", "ns", "prod", "error", 999))
@@ -105,8 +113,9 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
assert (series.namespace, series.environment, series.severity) == ("ns", "prod", "error")
assert series.baseline_weeks == 5
assert series.band_ready_at is None
- assert series.total_count == 25
- bucket_count = window_days * 24 * 60 // interval_minutes
+ assert series.interval_minutes == interval_minutes
+ assert series.coarsened_reason is None
+ assert series.total_count == 25 + 10 * (bucket_count - 2)
assert [bucket.time for bucket in series.buckets] == [window_start + i * step for i in range(bucket_count)]
by_time = {bucket.time: bucket for bucket in series.buckets}
@@ -122,6 +131,96 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
assert quiet.lower == 0
assert quiet.upper == quiet_upper
+ @parameterized.expand(
+ [
+ # (name, quiet_every_n_buckets, quiet_count, expected_interval, expected_reason)
+ # Six records in one 5 minute bucket an hour: 8% of 5 minute buckets are
+ # non-empty, but a quarter of the 15 minute ones are, averaging 6.
+ ("sparse_settles_at_15", 12, 6, 15, "sparse"),
+ # One record in every 5 minute bucket: alive everywhere, but the mean
+ # only reaches 5 once six buckets fold into a 30 minute one.
+ ("quiet_settles_at_30", 1, 1, 30, "quiet"),
+ # One record an hour never passes; the series stops at the top rung.
+ ("too_thin_stops_at_60", 12, 1, 60, "sparse"),
+ ]
+ )
+ def test_sparse_series_is_coarsened_next_to_a_dense_one(
+ self, _name: str, quiet_every_n_buckets: int, quiet_count: int, expected_interval: int, expected_reason: str
+ ):
+ service = f"svc-density-{_name}"
+ window_start = WINDOW_END - dt.timedelta(days=1)
+ five = dt.timedelta(minutes=5)
+ rows = []
+ for i in range(24 * 12):
+ slot = window_start + i * five
+ rows.append((self.team.pk, slot, service, "ns", "prod", "info", 10))
+ if i % quiet_every_n_buckets == 0:
+ rows.append((self.team.pk, slot, service, "ns", "prod", "warn", quiet_count))
+ self._insert(rows)
+
+ result = run_series_bands(
+ self.team, service, window_start=window_start, window_end=WINDOW_END, interval_minutes=5
+ )
+
+ assert result.interval_minutes == 5
+ dense, quiet = result.series
+ assert (dense.severity, dense.interval_minutes, dense.coarsened_reason) == ("info", 5, None)
+ assert len(dense.buckets) == 24 * 12
+ assert (quiet.severity, quiet.interval_minutes, quiet.coarsened_reason) == (
+ "warn",
+ expected_interval,
+ expected_reason,
+ )
+ step = dt.timedelta(minutes=expected_interval)
+ assert [bucket.time for bucket in quiet.buckets] == [
+ window_start + i * step for i in range(24 * 60 // expected_interval)
+ ]
+ assert quiet.total_count == quiet_count * (24 * 12 // quiet_every_n_buckets)
+ assert quiet.buckets[0].observed == quiet_count * max(1, expected_interval // 5 // quiet_every_n_buckets)
+
+ def test_series_only_in_the_trailing_partial_bucket_keeps_the_requested_grain_and_its_reason(self):
+ service = "svc-trailing"
+ # A grain above 5 minutes floors this window end back to WINDOW_END, so the
+ # records below sit outside every coarser rung's window.
+ window_end = WINDOW_END + dt.timedelta(minutes=5)
+ window_start = window_end - dt.timedelta(days=1)
+ self._insert([(self.team.pk, WINDOW_END, service, "ns", "prod", "info", 3)])
+
+ result = run_series_bands(
+ self.team, service, window_start=window_start, window_end=window_end, interval_minutes=5
+ )
+
+ assert len(result.series) == 1
+ series = result.series[0]
+ assert (series.interval_minutes, series.coarsened_reason) == (5, "sparse")
+ assert len(series.buckets) == 24 * 12
+ assert series.total_count == 3
+ # Nothing to coarsen towards, and no band to under-read either: the series
+ # has no history, so it draws as still learning rather than as anomalous.
+ assert series.baseline_weeks == 0
+ assert series.band_ready_at is not None
+ assert all(bucket.lower is None and bucket.upper is None for bucket in series.buckets)
+
+ def test_a_spent_execution_budget_stops_the_walk_and_keeps_the_reason(self):
+ service = "svc-budget"
+ window_start = WINDOW_END - dt.timedelta(days=1)
+ self._insert(
+ [
+ (self.team.pk, window_start + i * dt.timedelta(hours=1), service, "ns", "prod", "info", 1)
+ for i in range(24)
+ ]
+ )
+
+ with patch.object(series_bands, "MAX_EXECUTION_SECONDS", 0):
+ result = run_series_bands(
+ self.team, service, window_start=window_start, window_end=WINDOW_END, interval_minutes=5
+ )
+
+ assert len(result.series) == 1
+ series = result.series[0]
+ assert (series.interval_minutes, series.coarsened_reason) == (5, "sparse")
+ assert len(series.buckets) == 24 * 12
+
@parameterized.expand(
[
# A stray row two weeks before the sustained start does not date the lifetime.
@@ -266,15 +365,31 @@ NOW_FIXED = dt.datetime(2026, 6, 17, 15, 30, tzinfo=UTC)
class TestResolveWindow(SimpleTestCase):
- def _resolve(self, date_from: str | None, date_to: str | None, interval_minutes: int = 60) -> SeriesBandsWindow:
+ def _resolve(
+ self, date_from: str | None, date_to: str | None, interval_minutes: int | None = 60
+ ) -> SeriesBandsWindow:
return resolve_window(date_from, date_to, interval_minutes=interval_minutes, now=NOW_FIXED)
def test_exactly_seven_days_is_accepted(self):
assert self._resolve("2026-06-08T00:00:00Z", "2026-06-15T00:00:00Z") == SeriesBandsWindow(
start=dt.datetime(2026, 6, 8, tzinfo=UTC),
end=dt.datetime(2026, 6, 15, tzinfo=UTC),
+ interval_minutes=60,
)
+ @parameterized.expand(
+ [
+ # (date_from, expected_interval): the rung at or above window / 168 buckets.
+ ("-7d", 60),
+ ("-1d", 15),
+ ("-6h", 5),
+ ]
+ )
+ def test_omitted_grain_aims_for_the_bucket_target(self, date_from: str, expected_interval: int) -> None:
+ window = self._resolve(date_from, None, interval_minutes=None)
+ assert window.interval_minutes == expected_interval
+ assert window.end == NOW_FIXED.replace(minute=30 // expected_interval * expected_interval)
+
def test_window_that_collapses_after_snapping_is_rejected(self):
# Both bounds floor into the same hourly bucket, so the window holds no bucket at all.
with pytest.raises(SeriesBandsWindowInvalid, match="empty"):
@@ -285,6 +400,7 @@ class TestResolveWindow(SimpleTestCase):
assert self._resolve("2026-06-17T15:05:00Z", "2026-06-17T15:20:00Z", interval_minutes=5) == SeriesBandsWindow(
start=dt.datetime(2026, 6, 17, 15, 5, tzinfo=UTC),
end=dt.datetime(2026, 6, 17, 15, 20, tzinfo=UTC),
+ interval_minutes=5,
)
def test_thirty_days_back_is_accepted(self):
@@ -294,6 +410,7 @@ class TestResolveWindow(SimpleTestCase):
assert self._resolve(None, None) == SeriesBandsWindow(
start=NOW_FIXED.replace(minute=0) - dt.timedelta(days=7),
end=NOW_FIXED.replace(minute=0),
+ interval_minutes=60,
)
def test_day_offset_keeps_its_time_of_day(self):
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index cb10628ceaf4..e6950606a663 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1275,15 +1275,26 @@ export interface LogsSeriesBandsRequestApi {
serviceName: string
/** Window to chart. Defaults to the last 7 days. It may span at most 7 days and start at most 35 days ago, past which the volume rollup no longer reaches. */
dateRange?: _SeriesBandsDateRangeApi
- /** Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window.
+ /** Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window. Omit it to let the window pick its grain, the coarsest that still cuts it into about 168 buckets. A series too sparse to read at this grain is returned at a coarser one; see each series' interval_minutes.
*
* * `5` - 5
* * `15` - 15
* * `30` - 30
* * `60` - 60 */
- intervalMinutes?: IntervalMinutesEnumApi
+ intervalMinutes?: IntervalMinutesEnumApi | null
}
+/**
+ * * `sparse` - sparse
+ * * `quiet` - quiet
+ */
+export type CoarsenedReasonEnumApi = (typeof CoarsenedReasonEnumApi)[keyof typeof CoarsenedReasonEnumApi]
+
+export const CoarsenedReasonEnumApi = {
+ Sparse: 'sparse',
+ Quiet: 'quiet',
+} as const
+
export interface LogsSeriesBandBucketApi {
/** Start of the display bucket (UTC). */
time: string
@@ -1319,7 +1330,14 @@ export interface LogsSeriesBandSeriesApi {
* @nullable
*/
band_ready_at: string | null
- /** One entry per display bucket across the whole window, oldest first, zero-filled. */
+ /** Grain of this series' buckets, in minutes. Equals the response interval_minutes unless the series was too sparse at that grain and was coarsened to the next rung it is dense enough to read at. */
+ interval_minutes: number
+ /** Why this series was too thin to read at the requested grain, or null when it was not. sparse: fewer than 20% of its buckets held any records. quiet: its non-empty buckets averaged under 5 records. A series that fails every rung is returned at the coarsest one. A series that a coarser rung has no rows for, or that the request's time budget cannot refetch, keeps the requested grain and still carries its reason.
+ *
+ * * `sparse` - sparse
+ * * `quiet` - quiet */
+ coarsened_reason: CoarsenedReasonEnumApi | null
+ /** One entry per display bucket across the window at this series' interval_minutes, oldest first, zero-filled. A coarsened series' window is snapped to its grain, so it can end short of window_end. */
buckets: LogsSeriesBandBucketApi[]
}
@@ -1330,7 +1348,7 @@ export interface LogsSeriesBandsResponseApi {
window_start: string
/** End of the observed window (UTC, exclusive). */
window_end: string
- /** Display grain of the buckets, in minutes. */
+ /** Display grain requested, or picked to cut the window into about 168 buckets when the request left it out. */
interval_minutes: number
/** True when the service has more series than the response carries; the quietest were dropped. */
series_truncated: boolean
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index b76cbfbc4cfb..abf56becac6f 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -509,8 +509,6 @@ export const LogsAnomaliesScanCreateBody = /* @__PURE__ */ zod.object({
* Returns log volume over the requested window for every (namespace, environment, severity) series of one service, with a time-of-week expected band derived from the prior weeks of the volume rollup. The window defaults to the last 7 days and may span at most 7 days. Synchronous and read only.
* @summary Per-series log volume with expected bands
*/
-export const logsAnomaliesSeriesBandsCreateBodyIntervalMinutesDefault = 60
-
export const LogsAnomaliesSeriesBandsCreateBody = /* @__PURE__ */ zod.object({
serviceName: zod.string().describe("Service whose per-series volume to chart (the log record's service_name)."),
dateRange: zod
@@ -531,11 +529,15 @@ export const LogsAnomaliesSeriesBandsCreateBody = /* @__PURE__ */ zod.object({
'Window to chart. Defaults to the last 7 days. It may span at most 7 days and start at most 35 days ago, past which the volume rollup no longer reaches.'
),
intervalMinutes: zod
- .union([zod.literal(5), zod.literal(15), zod.literal(30), zod.literal(60)])
- .describe('\* `5` - 5\n\* `15` - 15\n\* `30` - 30\n\* `60` - 60')
- .default(logsAnomaliesSeriesBandsCreateBodyIntervalMinutesDefault)
+ .union([
+ zod
+ .union([zod.literal(5), zod.literal(15), zod.literal(30), zod.literal(60)])
+ .describe('\* `5` - 5\n\* `15` - 15\n\* `30` - 30\n\* `60` - 60'),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window.\n\n\* `5` - 5\n\* `15` - 15\n\* `30` - 30\n\* `60` - 60'
+ "Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window. Omit it to let the window pick its grain, the coarsest that still cuts it into about 168 buckets. A series too sparse to read at this grain is returned at a coarser one; see each series' interval_minutes.\n\n\* `5` - 5\n\* `15` - 15\n\* `30` - 30\n\* `60` - 60"
),
})
diff --git a/products/logs/frontend/logsAnomaliesLogic.test.ts b/products/logs/frontend/logsAnomaliesLogic.test.ts
index 9ceb6e5a4ed3..65f59814699e 100644
--- a/products/logs/frontend/logsAnomaliesLogic.test.ts
+++ b/products/logs/frontend/logsAnomaliesLogic.test.ts
@@ -25,6 +25,8 @@ function seriesBandsResponse(seriesCount: number): LogsSeriesBandsResponseApi {
baseline_weeks: 5,
history_start: '2026-07-13T10:00:00Z',
band_ready_at: null,
+ interval_minutes: 60,
+ coarsened_reason: null,
buckets: [],
})),
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 25cf1385d201..d92a73e24c79 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17829,6 +17829,18 @@ export namespace Schemas {
clustering_job_id?: string | null;
}
+ /**
+ * * `sparse` - sparse
+ * * `quiet` - quiet
+ */
+ export type CoarsenedReasonEnum = typeof CoarsenedReasonEnum[keyof typeof CoarsenedReasonEnum];
+
+
+ export const CoarsenedReasonEnum = {
+ Sparse: 'sparse',
+ Quiet: 'quiet',
+ } as const;
+
/**
* * `dataset_archived` - dataset_archived
* * `dataset_name_conflict` - dataset_name_conflict
@@ -49889,7 +49901,14 @@ export namespace Schemas {
* @nullable
*/
band_ready_at: string | null;
- /** One entry per display bucket across the whole window, oldest first, zero-filled. */
+ /** Grain of this series' buckets, in minutes. Equals the response interval_minutes unless the series was too sparse at that grain and was coarsened to the next rung it is dense enough to read at. */
+ interval_minutes: number;
+ /** Why this series was too thin to read at the requested grain, or null when it was not. sparse: fewer than 20% of its buckets held any records. quiet: its non-empty buckets averaged under 5 records. A series that fails every rung is returned at the coarsest one. A series that a coarser rung has no rows for, or that the request's time budget cannot refetch, keeps the requested grain and still carries its reason.
+ *
+ * * `sparse` - sparse
+ * * `quiet` - quiet */
+ coarsened_reason: CoarsenedReasonEnum | null;
+ /** One entry per display bucket across the window at this series' interval_minutes, oldest first, zero-filled. A coarsened series' window is snapped to its grain, so it can end short of window_end. */
buckets: LogsSeriesBandBucket[];
}
@@ -49916,13 +49935,13 @@ export namespace Schemas {
serviceName: string;
/** Window to chart. Defaults to the last 7 days. It may span at most 7 days and start at most 35 days ago, past which the volume rollup no longer reaches. */
dateRange?: _SeriesBandsDateRange;
- /** Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window.
+ /** Display grain in minutes for buckets and bands. One of 5, 15, 30, 60. The window may hold at most 500 buckets per series at the chosen grain, so a finer grain needs a shorter window. Omit it to let the window pick its grain, the coarsest that still cuts it into about 168 buckets. A series too sparse to read at this grain is returned at a coarser one; see each series' interval_minutes.
*
* * `5` - 5
* * `15` - 15
* * `30` - 30
* * `60` - 60 */
- intervalMinutes?: IntervalMinutesEnum;
+ intervalMinutes?: IntervalMinutesEnum | null;
}
export interface LogsSeriesBandsResponse {
@@ -49932,7 +49951,7 @@ export namespace Schemas {
window_start: string;
/** End of the observed window (UTC, exclusive). */
window_end: string;
- /** Display grain of the buckets, in minutes. */
+ /** Display grain requested, or picked to cut the window into about 168 buckets when the request left it out. */
interval_minutes: number;
/** True when the service has more series than the response carries; the quietest were dropped. */
series_truncated: boolean;