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): add per-series volume band endpoint for anomalies tab (#87684)

Jon McCallum894c8804f958
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 08086f4ebdfe..bb2c37f1abe0 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -613,6 +613,19 @@ class LogsAnomalyScanSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "60/hour"
+# Series band charts read a 6-week window of the logs_volume_buckets rollup — a few orders of
+# magnitude cheaper than the anomaly scan above, but still a browse surface that fires on every
+# service pick, so a team bucket keeps a click-happy session from stacking ClickHouse reads.
+class LogsSeriesBandsBurstRateThrottle(_TeamBucketRateThrottle):
+ scope = "logs_series_bands_burst"
+ rate = "30/minute"
+
+
+class LogsSeriesBandsSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "logs_series_bands_sustained"
+ rate = "600/hour"
+
+
# The experiment session-bucket endpoint scans every session in an experiment's recent run
# window rather than a known id list, so one call is heavier than a session-context batch. Same
# project-wide bucketing and same session-authenticated caller as those, at a lower rate: the UI
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.py
index 2be4f42a024a..c601399a6575 100644
--- a/products/logs/backend/presentation/views/anomalies_api.py
+++ b/products/logs/backend/presentation/views/anomalies_api.py
@@ -12,11 +12,23 @@ from rest_framework.response import Response
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.permissions import PostHogFeatureFlagPermission
-from posthog.rate_limit import LogsAnomalyScanBurstRateThrottle, LogsAnomalyScanSustainedRateThrottle
+from posthog.rate_limit import (
+ LogsAnomalyScanBurstRateThrottle,
+ LogsAnomalyScanSustainedRateThrottle,
+ LogsSeriesBandsBurstRateThrottle,
+ LogsSeriesBandsSustainedRateThrottle,
+)
from products.logs.backend.anomaly_scan import MAX_EVAL_DAYS, ScanBudgetExceeded, floor_to_bucket, run_scan
+from products.logs.backend.series_bands import (
+ BASELINE_WEEKS,
+ MIN_BASELINE_WEEKS_FOR_BAND,
+ SeriesBandsFetchTruncated,
+ run_series_bands,
+)
SCAN_CACHE_TTL_SECONDS = 60
+SERIES_BANDS_CACHE_TTL_SECONDS = 60
_STAGE_CHOICES = ["insufficient", "cold_start", "developing", "mature"]
_VERDICT_CHOICES = ["spike", "drop", "silence"]
@@ -180,11 +192,77 @@ class LogsAnomalyScanErrorSerializer(serializers.Serializer):
error = serializers.CharField(help_text="Human readable description of why the scan could not run.")
+class LogsSeriesBandsRequestSerializer(serializers.Serializer):
+ serviceName = serializers.CharField(
+ help_text="Service whose per-series volume to chart (the log record's service_name).",
+ )
+ intervalMinutes = serializers.ChoiceField(
+ choices=[60],
+ default=60,
+ help_text="Display grain in minutes for buckets and bands. Only hourly is supported today.",
+ )
+
+
+class LogsSeriesBandBucketSerializer(serializers.Serializer):
+ time = serializers.DateTimeField(help_text="Start of the display bucket (UTC).")
+ observed = serializers.IntegerField(help_text="Log count observed in this bucket.")
+ lower = serializers.FloatField(
+ allow_null=True,
+ help_text="Lower edge of the expected band. Null while the series has too little history to band.",
+ )
+ upper = serializers.FloatField(
+ allow_null=True,
+ help_text="Upper edge of the expected band. Null while the series has too little history to band.",
+ )
+
+
+class LogsSeriesBandSeriesSerializer(serializers.Serializer):
+ namespace = serializers.CharField(
+ allow_blank=True, help_text="Namespace of the emitting resource; empty when the logs carry none."
+ )
+ environment = serializers.CharField(
+ allow_blank=True, help_text="Deployment environment of the emitting resource; empty when the logs carry none."
+ )
+ severity = serializers.CharField(help_text="Lowercased log severity of this series (for example info, error).")
+ total_count = serializers.IntegerField(
+ help_text="Total observed log count over the window. Series are ordered by this, descending."
+ )
+ baseline_weeks = serializers.IntegerField(
+ help_text=(
+ f"Full weeks of history behind the band, 0 to {BASELINE_WEEKS}. "
+ f"Below {MIN_BASELINE_WEEKS_FOR_BAND} the series is still learning and its buckets carry no band."
+ )
+ )
+ buckets = LogsSeriesBandBucketSerializer(
+ many=True,
+ help_text="One entry per display bucket across the whole window, oldest first, zero-filled.",
+ )
+
+
+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.")
+ series_truncated = serializers.BooleanField(
+ help_text="True when the service has more series than the response carries; the quietest were dropped."
+ )
+ series = LogsSeriesBandSeriesSerializer(
+ many=True,
+ help_text="One entry per (namespace, environment, severity) series, ordered by observed volume descending.",
+ )
+
+
+class LogsSeriesBandsErrorSerializer(serializers.Serializer):
+ error = serializers.CharField(help_text="Human readable description of why the series could not be charted.")
+
+
class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
- """On-demand anomaly scan over one service's log volume.
+ """Anomaly surfaces over one service's log volume.
- Experimental, behind the logs-anomalies feature flag. Computes everything
- per request from raw logs; nothing is persisted.
+ Experimental, behind the logs-anomalies feature flag. `scan` computes
+ everything per request from raw logs; `series_bands` reads the volume
+ rollup. Neither persists anything.
"""
scope_object = "logs"
@@ -238,3 +316,51 @@ class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
response_data = LogsAnomalyScanResponseSerializer(result).data
cache.set(cache_key, response_data, SCAN_CACHE_TTL_SECONDS)
return Response(response_data)
+
+ @validated_request(
+ request_serializer=LogsSeriesBandsRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=LogsSeriesBandsResponseSerializer,
+ description="Observed volume and expected band per series of the service.",
+ ),
+ 422: OpenApiResponse(
+ response=LogsSeriesBandsErrorSerializer,
+ description="The service has too many series to chart in one response.",
+ ),
+ },
+ summary="Per-series log volume with expected bands",
+ description=(
+ "Returns the last 7 days of log volume 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. Synchronous and read only."
+ ),
+ )
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["logs:read"],
+ url_path="series_bands",
+ throttle_classes=[LogsSeriesBandsBurstRateThrottle, LogsSeriesBandsSustainedRateThrottle],
+ )
+ def series_bands(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ data = request.validated_data
+ service_name: str = data["serviceName"]
+ interval_minutes: int = int(data["intervalMinutes"])
+
+ cache_key = (
+ "logs_series_bands/"
+ + hashlib.sha256(f"{self.team.id}/{service_name}/{interval_minutes}".encode()).hexdigest()
+ )
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return Response(cached)
+
+ try:
+ result = run_series_bands(self.team, service_name, interval_minutes=interval_minutes)
+ except SeriesBandsFetchTruncated as err:
+ return Response({"error": str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
+
+ response_data = LogsSeriesBandsResponseSerializer(result).data
+ cache.set(cache_key, response_data, SERIES_BANDS_CACHE_TTL_SECONDS)
+ return Response(response_data)
diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.py
new file mode 100644
index 000000000000..d880e93fb3a4
--- /dev/null
+++ b/products/logs/backend/series_bands.py
@@ -0,0 +1,288 @@
+"""Per-series log volume band charts for one service, read from logs_volume_buckets.
+
+The observed line is the last WINDOW_DAYS of volume per (namespace, environment,
+severity) series. The expected band is a time-of-week aligned min/max envelope
+over the BASELINE_WEEKS weeks before the window: each display slot's band comes
+from the same weekly slot in prior weeks. ClickHouse folds the baseline weeks
+onto the display window; Python finishes the envelope (zero-fill, maturity
+gating, widening) where the arithmetic is cheap and unit-testable.
+"""
+
+import os
+import datetime as dt
+
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.hogql import ast
+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, HogQLGlobalSettings, LimitContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models import Team
+from posthog.utils import ensure_utc
+
+WINDOW_DAYS = 7
+BASELINE_WEEKS = 5
+# Below this many full prior weeks the band rests on too little history to draw.
+MIN_BASELINE_WEEKS_FOR_BAND = 2
+SECONDS_PER_WEEK = 7 * 24 * 3600
+
+MAX_SERIES = int(os.environ.get("LOGS_SERIES_BANDS_MAX_SERIES", "100"))
+# 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
+
+MAX_EXECUTION_SECONDS = int(os.environ.get("LOGS_SERIES_BANDS_MAX_EXECUTION_SECONDS", "30"))
+
+
+class SeriesBandsFetchTruncated(Exception):
+ pass
+
+
+@frozen
+class BandBucket:
+ time: dt.datetime
+ observed: int
+ lower: float | None
+ upper: float | None
+
+
+@frozen
+class BandSeries:
+ namespace: str
+ environment: str
+ severity: str
+ total_count: int
+ baseline_weeks: int
+ buckets: list[BandBucket]
+
+
+@frozen
+class SeriesBandsResult:
+ service_name: str
+ window_start: dt.datetime
+ window_end: dt.datetime
+ interval_minutes: int
+ series_truncated: bool
+ series: list[BandSeries]
+
+
+@frozen
+class _SeriesKey:
+ namespace: str
+ environment: str
+ severity: str
+
+
+@frozen
+class _SlotRow:
+ target_time: dt.datetime
+ observed: int
+ baseline_samples: int
+ baseline_min: int
+ baseline_max: int
+ earliest_slot: dt.datetime
+
+
+def floor_to_interval(value: dt.datetime, interval_minutes: int) -> dt.datetime:
+ seconds = interval_minutes * 60
+ return dt.datetime.fromtimestamp(int(value.timestamp()) // seconds * seconds, tz=dt.UTC)
+
+
+def fetch_series_slot_rows(
+ team: Team,
+ service_name: str,
+ window_start: dt.datetime,
+ window_end: dt.datetime,
+ interval_minutes: int,
+) -> dict[_SeriesKey, list[_SlotRow]]:
+ """One ClickHouse pass: hourly rollup over the window plus baseline, folded
+ by time-of-week onto the display window's slots.
+
+ 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."""
+ 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)
+ # 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.
+ query = parse_select(
+ """
+ SELECT
+ namespace,
+ environment,
+ severity_text,
+ {window_start} + toIntervalSecond(
+ (toUnixTimestamp(slot) - toUnixTimestamp({window_start}) + {baseline_seconds}) % {week_seconds}
+ ) AS target_time,
+ sumIf(slot_count, slot >= {window_start}) AS observed,
+ countIf(slot < {window_start}) AS baseline_samples,
+ minIf(slot_count, slot < {window_start}) AS baseline_min,
+ maxIf(slot_count, slot < {window_start}) AS baseline_max,
+ min(slot) AS earliest_slot
+ FROM (
+ SELECT
+ namespace,
+ environment,
+ severity_text,
+ toStartOfInterval(time_bucket, {interval}, 'UTC') AS slot,
+ sum(log_count) AS slot_count
+ FROM posthog.logs_volume_buckets
+ 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}
+ )
+ GROUP BY namespace, environment, severity_text, slot
+ )
+ GROUP BY namespace, environment, severity_text, target_time
+ LIMIT {row_limit}
+ """,
+ placeholders={
+ "service_name": ast.Constant(value=service_name),
+ "window_start": ast.Constant(value=window_start),
+ "window_end": ast.Constant(value=window_end),
+ "baseline_start": ast.Constant(value=baseline_start),
+ "interval": ast.Call(name="toIntervalMinute", args=[ast.Constant(value=interval_minutes)]),
+ "baseline_seconds": ast.Constant(value=BASELINE_WEEKS * SECONDS_PER_WEEK),
+ "week_seconds": ast.Constant(value=SECONDS_PER_WEEK),
+ "max_series_plus_probe": ast.Constant(value=MAX_SERIES + 1),
+ "row_limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+
+ response = execute_hogql_query(
+ query_type="logs_series_bands",
+ query=query,
+ team=team,
+ workload=Workload.LOGS,
+ 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.
+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
+ )
+
+ if len(response.results) >= MAX_SELECT_RETURNED_ROWS:
+ raise SeriesBandsFetchTruncated(f"series bands fetch returned {len(response.results)} rows, at the row limit")
+
+ rows: dict[_SeriesKey, list[_SlotRow]] = {}
+ for row in response.results:
+ key = _SeriesKey(namespace=row[0], environment=row[1], severity=row[2])
+ rows.setdefault(key, []).append(
+ _SlotRow(
+ target_time=ensure_utc(row[3]),
+ observed=int(row[4]),
+ baseline_samples=int(row[5]),
+ baseline_min=int(row[6]),
+ baseline_max=int(row[7]),
+ earliest_slot=ensure_utc(row[8]),
+ )
+ )
+ return rows
+
+
+def _baseline_weeks_available(later: dt.datetime, earliest_slot: dt.datetime) -> int:
+ """Whole weeks of series lifetime before `later`, capped at the baseline depth.
+
+ Against the window start this is the series' maturity; against one display
+ slot it is how many of that slot's weekly samples carry information. A week
+ whose sample slot predates the series says nothing; a week inside the
+ lifetime with no row was a real zero.
+ """
+ weeks = int((later - earliest_slot).total_seconds()) // SECONDS_PER_WEEK
+ return min(BASELINE_WEEKS, max(0, weeks))
+
+
+def _build_series(
+ key: _SeriesKey,
+ slot_rows: list[_SlotRow],
+ window_start: dt.datetime,
+ window_end: dt.datetime,
+ interval_minutes: int,
+) -> BandSeries:
+ by_time = {row.target_time: row for row in slot_rows}
+ earliest_slot = min(row.earliest_slot for row in slot_rows)
+ baseline_weeks = _baseline_weeks_available(window_start, earliest_slot)
+ banded = baseline_weeks >= MIN_BASELINE_WEEKS_FOR_BAND
+ floor = BAND_FLOOR_PER_HOUR * interval_minutes / 60
+
+ buckets: list[BandBucket] = []
+ total_count = 0
+ step = dt.timedelta(minutes=interval_minutes)
+ slot = window_start
+ while slot < window_end:
+ row = by_time.get(slot)
+ observed = row.observed if row else 0
+ total_count += observed
+ lower: float | None = None
+ upper: float | None = None
+ if banded:
+ # Every slot sits at or after window_start, so a banded series has at
+ # least MIN_BASELINE_WEEKS_FOR_BAND samples to expect at every slot.
+ expected = _baseline_weeks_available(slot, earliest_slot)
+ samples = row.baseline_samples if row else 0
+ # A lifetime week with no row at this slot was a real zero, so any
+ # missing sample drags the envelope floor to zero.
+ low = row.baseline_min if row and samples >= expected else 0
+ high = row.baseline_max if row else 0
+ lower = low * (1 - BAND_WIDEN_FRACTION)
+ upper = high * (1 + BAND_WIDEN_FRACTION) + floor
+ buckets.append(BandBucket(time=slot, observed=observed, lower=lower, upper=upper))
+ slot += step
+
+ return BandSeries(
+ namespace=key.namespace,
+ environment=key.environment,
+ severity=key.severity,
+ total_count=total_count,
+ baseline_weeks=baseline_weeks,
+ buckets=buckets,
+ )
+
+
+def run_series_bands(
+ team: Team,
+ service_name: str,
+ interval_minutes: int = 60,
+ now: dt.datetime | None = None,
+) -> SeriesBandsResult:
+ # 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.
+ now = now or dt.datetime.now(dt.UTC)
+ window_end = floor_to_interval(now, interval_minutes)
+ window_start = window_end - dt.timedelta(days=WINDOW_DAYS)
+
+ 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]
+
+ return SeriesBandsResult(
+ service_name=service_name,
+ window_start=window_start,
+ window_end=window_end,
+ interval_minutes=interval_minutes,
+ series_truncated=series_truncated,
+ series=series,
+ )
diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.py
index 8cb7fde3b811..eddcff86368a 100644
--- a/products/logs/backend/test/test_anomalies_api.py
+++ b/products/logs/backend/test/test_anomalies_api.py
@@ -11,6 +11,7 @@ from rest_framework import status
from products.apm.backend.facade.api import BaselineStage, Direction, IssueState, TrafficTier, VerdictType
from products.logs.backend.anomaly_scan import ScanBucket, ScanBudgetExceeded, ScanIssue, ScanResult, ScanSeries
from products.logs.backend.presentation.views.anomalies_api import LogsAnomalyScanRequestSerializer
+from products.logs.backend.series_bands import BandBucket, BandSeries, SeriesBandsFetchTruncated, SeriesBandsResult
UTC = dt.UTC
T0 = dt.datetime(2026, 6, 1, 12, 0, tzinfo=UTC)
@@ -167,3 +168,65 @@ class TestLogsAnomalyScanAPI(APIBaseTest):
):
response = self.client.post(self.url, self._payload(), format="json")
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
+
+
+class TestLogsSeriesBandsAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.url = f"/api/projects/{self.team.pk}/logs/anomalies/series_bands/"
+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ self._ff_patcher.start()
+ self.addCleanup(self._ff_patcher.stop)
+
+ def test_invalid_body_is_rejected_before_querying(self):
+ with patch("products.logs.backend.presentation.views.anomalies_api.run_series_bands") as run:
+ response = self.client.post(self.url, {}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ 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,
+ 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
+ ) as run:
+ response = self.client.post(self.url, {"serviceName": "svc"}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ run.assert_called_once_with(self.team, "svc", interval_minutes=60)
+ data = response.json()
+ assert data["service_name"] == "svc"
+ assert data["interval_minutes"] == 60
+ assert data["series_truncated"] is False
+ series = data["series"][0]
+ assert (series["namespace"], series["environment"], series["severity"]) == ("ns", "prod", "error")
+ assert series["baseline_weeks"] == 5
+ assert series["buckets"][0] == {
+ "time": (T0 - dt.timedelta(hours=1)).isoformat().replace("+00:00", "Z"),
+ "observed": 25,
+ "lower": 9.0,
+ "upper": 57.0,
+ }
+
+ def test_truncated_fetch_returns_422(self):
+ with patch(
+ "products.logs.backend.presentation.views.anomalies_api.run_series_bands",
+ side_effect=SeriesBandsFetchTruncated("too many rows"),
+ ):
+ response = self.client.post(self.url, {"serviceName": "svc"}, format="json")
+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.py
new file mode 100644
index 000000000000..b8e31c92da7a
--- /dev/null
+++ b/products/logs/backend/test/test_series_bands.py
@@ -0,0 +1,117 @@
+import datetime as dt
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from posthog.clickhouse.client import sync_execute
+
+from products.logs.backend.series_bands import run_series_bands
+
+UTC = dt.UTC
+# The scan clock sits ahead of real time so the whole 6-week fixture range stays
+# inside the table's 42-day TTL, which ClickHouse enforces against the real clock.
+# Fixed calendar dates age out of retention and lose their oldest baseline rows.
+NOW = (dt.datetime.now(UTC) + dt.timedelta(days=20)).replace(minute=30, second=0, microsecond=0)
+WINDOW_END = NOW.replace(minute=0)
+WINDOW_START = WINDOW_END - dt.timedelta(days=7)
+BASELINE_START = WINDOW_START - dt.timedelta(weeks=5)
+# A display slot a few days into the window, so its weekly samples spread across it.
+SLOT = WINDOW_START + dt.timedelta(days=3, hours=4)
+
+
+class TestSeriesBands(ClickhouseTestMixin, BaseTest):
+ def _insert(self, rows: list[tuple]) -> None:
+ sync_execute(
+ "INSERT INTO logs_volume_buckets "
+ "(team_id, time_bucket, service_name, namespace, environment, severity_text, log_count) VALUES",
+ [
+ (team_id, ts.astimezone(UTC).replace(tzinfo=None), service, ns, env, sev, count)
+ for team_id, ts, service, ns, env, sev, count in rows
+ ],
+ )
+
+ def test_observed_line_and_band_from_prior_weeks(self):
+ service = "svc-banded"
+ rows = [
+ # Anchors the series' lifetime at the full 5-week baseline.
+ (self.team.pk, BASELINE_START, service, "ns", "prod", "error", 1),
+ ]
+ for week, value in enumerate([10, 20, 30, 40, 50], start=1):
+ rows.append((self.team.pk, SLOT - dt.timedelta(weeks=week), service, "ns", "prod", "error", value))
+ # Partial rows within one display bucket, including a repeated 5-minute key.
+ 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))
+ # 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))
+ rows.append((self.team.pk + 1, SLOT, service, "ns", "prod", "error", 999))
+ self._insert(rows)
+
+ result = run_series_bands(self.team, service, now=NOW)
+
+ assert result.window_start == WINDOW_START
+ assert result.window_end == WINDOW_END
+ assert not result.series_truncated
+ assert len(result.series) == 1
+ series = result.series[0]
+ assert (series.namespace, series.environment, series.severity) == ("ns", "prod", "error")
+ assert series.baseline_weeks == 5
+ assert series.total_count == 25
+ assert len(series.buckets) == 7 * 24
+
+ by_time = {bucket.time: bucket for bucket in series.buckets}
+ # Band folds the five weekly samples 10..50 into a 10% widened envelope,
+ # then lifts the upper edge by the 2-per-hour floor.
+ banded = by_time[SLOT]
+ assert banded.observed == 25
+ assert banded.lower == pytest.approx(9.0)
+ assert banded.upper == pytest.approx(57.0)
+
+ quiet = by_time[SLOT + dt.timedelta(hours=1)]
+ assert quiet.observed == 0
+ assert quiet.lower == 0
+ assert quiet.upper == 2.0
+
+ def test_learning_series_carries_no_band(self):
+ service = "svc-learning"
+ self._insert(
+ [
+ (self.team.pk, WINDOW_START - dt.timedelta(weeks=1), service, "", "", "info", 10),
+ (self.team.pk, SLOT, service, "", "", "info", 12),
+ ]
+ )
+
+ result = run_series_bands(self.team, service, now=NOW)
+
+ assert len(result.series) == 1
+ series = result.series[0]
+ assert series.baseline_weeks == 1
+ assert all(bucket.lower is None and bucket.upper is None for bucket in series.buckets)
+ assert series.total_count == 12
+
+ def test_missing_baseline_week_drags_floor_to_zero(self):
+ service = "svc-gappy"
+ rows = [(self.team.pk, BASELINE_START, service, "ns", "prod", "warn", 1)]
+ for week, value in enumerate([100, 110, 120], start=1):
+ rows.append((self.team.pk, SLOT - dt.timedelta(weeks=week), service, "ns", "prod", "warn", value))
+ self._insert(rows)
+
+ result = run_series_bands(self.team, service, now=NOW)
+
+ bucket = {b.time: b for b in result.series[0].buckets}[SLOT]
+ assert bucket.lower == 0
+ assert bucket.upper == pytest.approx(134.0)
+
+ def test_series_ordered_by_observed_volume(self):
+ service = "svc-ordered"
+ self._insert(
+ [
+ (self.team.pk, SLOT, service, "ns", "prod", "info", 5),
+ (self.team.pk, SLOT, service, "ns", "prod", "error", 300),
+ ]
+ )
+
+ result = run_series_bands(self.team, service, now=NOW)
+
+ assert [(s.severity, s.total_count) for s in result.series] == [("error", 300), ("info", 5)]
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index c50ee852b244..2cd73c1b38ec 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1065,6 +1065,76 @@ export interface LogsAnomalyScanErrorApi {
error: string
}
+/**
+ * * `60` - 60
+ */
+export type IntervalMinutesEnumApi = (typeof IntervalMinutesEnumApi)[keyof typeof IntervalMinutesEnumApi]
+
+export const IntervalMinutesEnumApi = {
+ Number60: 60,
+} as const
+
+export interface LogsSeriesBandsRequestApi {
+ /** Service whose per-series volume to chart (the log record's service_name). */
+ serviceName: string
+ /** Display grain in minutes for buckets and bands. Only hourly is supported today.
+ *
+ * * `60` - 60 */
+ intervalMinutes?: IntervalMinutesEnumApi
+}
+
+export interface LogsSeriesBandBucketApi {
+ /** Start of the display bucket (UTC). */
+ time: string
+ /** Log count observed in this bucket. */
+ observed: number
+ /**
+ * Lower edge of the expected band. Null while the series has too little history to band.
+ * @nullable
+ */
+ lower: number | null
+ /**
+ * Upper edge of the expected band. Null while the series has too little history to band.
+ * @nullable
+ */
+ upper: number | null
+}
+
+export interface LogsSeriesBandSeriesApi {
+ /** Namespace of the emitting resource; empty when the logs carry none. */
+ namespace: string
+ /** Deployment environment of the emitting resource; empty when the logs carry none. */
+ environment: string
+ /** Lowercased log severity of this series (for example info, error). */
+ severity: string
+ /** Total observed log count over the window. Series are ordered by this, descending. */
+ total_count: number
+ /** Full weeks of history behind the band, 0 to 5. Below 2 the series is still learning and its buckets carry no band. */
+ baseline_weeks: number
+ /** One entry per display bucket across the whole window, oldest first, zero-filled. */
+ buckets: LogsSeriesBandBucketApi[]
+}
+
+export interface LogsSeriesBandsResponseApi {
+ /** Service the series belong to. */
+ service_name: string
+ /** Start of the observed window (UTC, inclusive). */
+ window_start: string
+ /** End of the observed window (UTC, exclusive). */
+ window_end: string
+ /** Display grain of the buckets, in minutes. */
+ interval_minutes: number
+ /** True when the service has more series than the response carries; the quietest were dropped. */
+ series_truncated: boolean
+ /** One entry per (namespace, environment, severity) series, ordered by observed volume descending. */
+ series: LogsSeriesBandSeriesApi[]
+}
+
+export interface LogsSeriesBandsErrorApi {
+ /** Human readable description of why the series could not be charted. */
+ error: string
+}
+
export interface _DateRangeApi {
/**
* Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 26d0e6ef82a4..6e1bfcafaf7b 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -36,6 +36,8 @@ import type {
LogsSamplingRuleSimulateResponseApi,
LogsSamplingRulesListParams,
LogsSamplingRulesReorderCreateParams,
+ LogsSeriesBandsRequestApi,
+ LogsSeriesBandsResponseApi,
LogsValuesRetrieveParams,
LogsViewApi,
LogsViewsListParams,
@@ -327,6 +329,27 @@ export const logsAnomaliesScanCreate = async (
})
}
+export const getLogsAnomaliesSeriesBandsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/logs/anomalies/series_bands/`
+}
+
+/**
+ * Returns the last 7 days of log volume 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. Synchronous and read only.
+ * @summary Per-series log volume with expected bands
+ */
+export const logsAnomaliesSeriesBandsCreate = async (
+ projectId: string,
+ logsSeriesBandsRequestApi: LogsSeriesBandsRequestApi,
+ options?: RequestInit
+): Promise<LogsSeriesBandsResponseApi> => {
+ return apiMutator<LogsSeriesBandsResponseApi>(getLogsAnomaliesSeriesBandsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(logsSeriesBandsRequestApi),
+ })
+}
+
export const getLogsAttributesRetrieveUrl = (projectId: string, params?: LogsAttributesRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index da579f046c71..e565b8d141c2 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -507,6 +507,21 @@ export const LogsAnomaliesScanCreateBody = /* @__PURE__ */ zod.object({
.describe('Evaluation window to scan for anomalies. May span at most 7 days.'),
})
+/**
+ * Returns the last 7 days of log volume 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. 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)."),
+ intervalMinutes: zod
+ .literal(60)
+ .describe('\* `60` - 60')
+ .default(logsAnomaliesSeriesBandsCreateBodyIntervalMinutesDefault)
+ .describe('Display grain in minutes for buckets and bands. Only hourly is supported today.\n\n\* `60` - 60'),
+})
+
export const LogsCountCreateBody = /* @__PURE__ */ zod.object({
query: zod
.object({
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index ca59b4641526..152e78806473 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -298,6 +298,9 @@ tools:
response:
exclude:
- series.*.buckets
+ logs-anomalies-series-bands-create:
+ operation: logs_anomalies_series_bands_create
+ enabled: false
logs-attribute-values-list:
operation: logs_values_retrieve
enabled: true
diff --git a/pyproject.toml b/pyproject.toml
index f3e01d20b755..07ef347c33e2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -606,6 +606,7 @@ ignore_imports = [
"products.logs.backend.presentation.views.sampling_api -> products.logs.backend.models",
"products.logs.backend.presentation.views.views_api -> products.logs.backend.models",
"products.logs.backend.presentation.views.anomalies_api -> products.logs.backend.anomaly_scan",
+ "products.logs.backend.presentation.views.anomalies_api -> products.logs.backend.series_bands",
# logs presentation isolation (temporary): cross-product imports the moved viewsets
# still make directly. These resolve once cdp/exports expose the needed facades, so
# they outlive the in-product cleanup above.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2b4dbd1e9b7b..26a39524ccc1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44779,6 +44779,16 @@ export namespace Schemas {
line_refs: string;
}
+ /**
+ * * `60` - 60
+ */
+ export type IntervalMinutesEnum = typeof IntervalMinutesEnum[keyof typeof IntervalMinutesEnum];
+
+
+ export const IntervalMinutesEnum = {
+ Number60: 60,
+ } as const;
+
export interface InterviewInviteResult {
/** The original identifier (email or distinct ID) from the topic targeting. */
interviewee_identifier: string;
@@ -46791,6 +46801,67 @@ export namespace Schemas {
notes: string;
}
+ export interface LogsSeriesBandBucket {
+ /** Start of the display bucket (UTC). */
+ time: string;
+ /** Log count observed in this bucket. */
+ observed: number;
+ /**
+ * Lower edge of the expected band. Null while the series has too little history to band.
+ * @nullable
+ */
+ lower: number | null;
+ /**
+ * Upper edge of the expected band. Null while the series has too little history to band.
+ * @nullable
+ */
+ upper: number | null;
+ }
+
+ export interface LogsSeriesBandSeries {
+ /** Namespace of the emitting resource; empty when the logs carry none. */
+ namespace: string;
+ /** Deployment environment of the emitting resource; empty when the logs carry none. */
+ environment: string;
+ /** Lowercased log severity of this series (for example info, error). */
+ severity: string;
+ /** Total observed log count over the window. Series are ordered by this, descending. */
+ total_count: number;
+ /** Full weeks of history behind the band, 0 to 5. Below 2 the series is still learning and its buckets carry no band. */
+ baseline_weeks: number;
+ /** One entry per display bucket across the whole window, oldest first, zero-filled. */
+ buckets: LogsSeriesBandBucket[];
+ }
+
+ export interface LogsSeriesBandsError {
+ /** Human readable description of why the series could not be charted. */
+ error: string;
+ }
+
+ export interface LogsSeriesBandsRequest {
+ /** Service whose per-series volume to chart (the log record's service_name). */
+ serviceName: string;
+ /** Display grain in minutes for buckets and bands. Only hourly is supported today.
+ *
+ * * `60` - 60 */
+ intervalMinutes?: IntervalMinutesEnum;
+ }
+
+ export interface LogsSeriesBandsResponse {
+ /** Service the series belong to. */
+ service_name: string;
+ /** Start of the observed window (UTC, inclusive). */
+ window_start: string;
+ /** End of the observed window (UTC, exclusive). */
+ window_end: string;
+ /** Display grain of the buckets, in minutes. */
+ interval_minutes: number;
+ /** True when the service has more series than the response carries; the quietest were dropped. */
+ series_truncated: boolean;
+ /** One entry per (namespace, environment, severity) series, ordered by observed volume descending. */
+ series: LogsSeriesBandSeries[];
+ }
+
/**
* Filter criteria — subset of LogsViewerFilters. May contain severityLevels, serviceNames, searchTerm, filterGroup, dateRange, and other keys.
*/