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): accept a 5 to 60 minute interval ladder on series-bands (#95910)

Jon McCallume04da21b9b12
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.py
index 6ba127682911..cdacc20f76e5 100644
--- a/products/logs/backend/presentation/views/anomalies_api.py
+++ b/products/logs/backend/presentation/views/anomalies_api.py
@@ -23,6 +23,8 @@ 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 (
BASELINE_WEEKS,
+ INTERVAL_LADDER_MINUTES,
+ MAX_BUCKETS_PER_SERIES,
MAX_WINDOW_DAYS,
MAX_WINDOW_START_AGE_DAYS,
MIN_BASELINE_WEEKS_FOR_BAND,
@@ -239,9 +241,13 @@ class LogsSeriesBandsRequestSerializer(serializers.Serializer):
),
)
intervalMinutes = serializers.ChoiceField(
- choices=[60],
+ choices=list(INTERVAL_LADDER_MINUTES),
default=60,
- help_text="Display grain in minutes for buckets and bands. Only hourly is supported today.",
+ 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."
+ ),
)
diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.py
index 689faa0016c7..b395e0891192 100644
--- a/products/logs/backend/series_bands.py
+++ b/products/logs/backend/series_bands.py
@@ -40,6 +40,10 @@ MIN_BASELINE_WEEKS_FOR_BAND = 2
SECONDS_PER_WEEK = 7 * 24 * 3600
MAX_SERIES = int(os.environ.get("LOGS_SERIES_BANDS_MAX_SERIES", "100"))
+# Display grains a caller may pick. Every rung divides an hour so slots stay
+# 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"))
# 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.
@@ -122,7 +126,7 @@ def fetch_series_slot_rows(
window_end: dt.datetime,
interval_minutes: int,
) -> dict[_SeriesKey, list[_SlotRow]]:
- """One ClickHouse pass: hourly rollup over the window plus baseline, folded
+ """One ClickHouse pass: interval 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
@@ -341,10 +345,34 @@ def resolve_window(
f"Log volume history does not reach that far back. The window may start at most "
f"{MAX_WINDOW_START_AGE_DAYS} days ago."
)
+ _check_bucket_cap(window_start, window_end, interval_minutes)
return SeriesBandsWindow(start=window_start, end=window_end)
+def _bucket_count(window_start: dt.datetime, window_end: dt.datetime, interval_minutes: int) -> int:
+ return int((window_end - window_start).total_seconds()) // (interval_minutes * 60)
+
+
+def _check_bucket_cap(window_start: dt.datetime, window_end: dt.datetime, interval_minutes: int) -> None:
+ buckets = _bucket_count(window_start, window_end, interval_minutes)
+ if buckets <= MAX_BUCKETS_PER_SERIES:
+ return
+ fitting = next(
+ (
+ grain
+ for grain in INTERVAL_LADDER_MINUTES
+ if _bucket_count(window_start, window_end, grain) <= MAX_BUCKETS_PER_SERIES
+ ),
+ None,
+ )
+ remedy = f"Use a {fitting} minute grain or a shorter window." if fitting else "Pick a shorter window."
+ raise SeriesBandsWindowInvalid(
+ f"The window spans {buckets} buckets at the {interval_minutes} minute grain, "
+ f"over the cap of {MAX_BUCKETS_PER_SERIES} buckets per series. {remedy}"
+ )
+
+
def run_series_bands(
team: Team,
service_name: str,
diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.py
index 98b17d235ca9..4af91990af0e 100644
--- a/products/logs/backend/test/test_anomalies_api.py
+++ b/products/logs/backend/test/test_anomalies_api.py
@@ -10,7 +10,10 @@ 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.presentation.views.anomalies_api import (
+ LogsAnomalyScanRequestSerializer,
+ LogsSeriesBandsRequestSerializer,
+)
from products.logs.backend.series_bands import BandBucket, BandSeries, SeriesBandsFetchTruncated, SeriesBandsResult
UTC = dt.UTC
@@ -170,6 +173,15 @@ class TestLogsAnomalyScanAPI(APIBaseTest):
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
+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:
+ 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
+
+
class TestLogsSeriesBandsAPI(APIBaseTest):
def setUp(self):
super().setUp()
@@ -232,13 +244,22 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
@parameterized.expand(
[
- ("span_over_seven_days", {"date_from": "-14d"}, "at most 7 days"),
- ("start_beyond_retention", {"date_from": "-40d", "date_to": "-34d"}, "at most 35 days ago"),
+ ("span_over_seven_days", {"dateRange": {"date_from": "-14d"}}, "at most 7 days"),
+ (
+ "start_beyond_retention",
+ {"dateRange": {"date_from": "-40d", "date_to": "-34d"}},
+ "at most 35 days ago",
+ ),
+ (
+ "over_bucket_cap",
+ {"dateRange": {"date_from": "-7d"}, "intervalMinutes": 5},
+ "over the cap of 500 buckets per series. Use a 30 minute grain",
+ ),
]
)
- def test_unusable_window_is_rejected_before_querying(self, _name: str, date_range: dict, expected: str):
+ def test_unusable_window_is_rejected_before_querying(self, _name: str, body: dict, expected: str):
with patch("products.logs.backend.presentation.views.anomalies_api.run_series_bands") as run:
- response = self.client.post(self.url, {"serviceName": "svc", "dateRange": date_range}, format="json")
+ response = self.client.post(self.url, {"serviceName": "svc", **body}, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert expected in response.json()["error"]
run.assert_not_called()
diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.py
index 601a2a0019bd..e4ed530cf7ee 100644
--- a/products/logs/backend/test/test_series_bands.py
+++ b/products/logs/backend/test/test_series_bands.py
@@ -40,11 +40,24 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
],
)
- def test_observed_line_and_band_from_prior_weeks(self):
- service = "svc-banded"
+ @parameterized.expand(
+ [
+ # (name, interval_minutes, window_days, banded_upper, quiet_upper)
+ # Hourly: floor of 2 per hour lifts the upper edge; 15 minutes gets a quarter of it.
+ # The finer grain charts 5 days, because 7 days of 15 minute buckets is over the cap.
+ ("hourly", 60, 7, 57.0, 2.0),
+ ("quarter_hour", 15, 5, 55.5, 0.5),
+ ]
+ )
+ def test_observed_line_and_band_from_prior_weeks(
+ self, _name: str, interval_minutes: int, window_days: int, banded_upper: float, quiet_upper: float
+ ):
+ service = f"svc-banded-{interval_minutes}"
+ window_start = WINDOW_END - dt.timedelta(days=window_days)
+ step = dt.timedelta(minutes=interval_minutes)
rows = [
# Anchors the series' lifetime at the full 5-week baseline.
- (self.team.pk, BASELINE_START, service, "ns", "prod", "error", 1),
+ (self.team.pk, window_start - dt.timedelta(weeks=5), 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))
@@ -58,10 +71,13 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
rows.append((self.team.pk + 1, SLOT, service, "ns", "prod", "error", 999))
self._insert(rows)
- result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)
+ result = run_series_bands(
+ self.team, service, window_start=window_start, window_end=WINDOW_END, interval_minutes=interval_minutes
+ )
- assert result.window_start == WINDOW_START
+ assert result.window_start == window_start
assert result.window_end == WINDOW_END
+ assert result.interval_minutes == interval_minutes
assert not result.series_truncated
assert len(result.series) == 1
series = result.series[0]
@@ -69,20 +85,21 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
assert series.baseline_weeks == 5
assert series.band_ready_at is None
assert series.total_count == 25
- assert len(series.buckets) == 7 * 24
+ bucket_count = window_days * 24 * 60 // interval_minutes
+ 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}
# Band folds the five weekly samples 10..50 into a 10% widened envelope,
- # then lifts the upper edge by the 2-per-hour floor.
+ # then lifts the upper edge by the per-hour floor scaled to the grain.
banded = by_time[SLOT]
assert banded.observed == 25
assert banded.lower == pytest.approx(9.0)
- assert banded.upper == pytest.approx(57.0)
+ assert banded.upper == pytest.approx(banded_upper)
- quiet = by_time[SLOT + dt.timedelta(hours=1)]
+ quiet = by_time[SLOT + step]
assert quiet.observed == 0
assert quiet.lower == 0
- assert quiet.upper == 2.0
+ assert quiet.upper == quiet_upper
def test_learning_series_carries_no_band(self):
service = "svc-learning"
@@ -164,8 +181,8 @@ 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) -> SeriesBandsWindow:
- return resolve_window(date_from, date_to, now=NOW_FIXED)
+ def _resolve(self, date_from: str | None, date_to: str | None, interval_minutes: int = 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(
@@ -178,6 +195,13 @@ class TestResolveWindow(SimpleTestCase):
with pytest.raises(SeriesBandsWindowInvalid, match="empty"):
self._resolve("2026-06-17T15:05:00Z", "2026-06-17T15:20:00Z")
+ def test_snaps_to_the_requested_grain(self):
+ # The same bounds that collapse at the hourly grain hold three 5-minute buckets.
+ 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),
+ )
+
def test_thirty_days_back_is_accepted(self):
assert self._resolve("-30d", "-24d").start == (NOW_FIXED - dt.timedelta(days=30)).replace(minute=0)
@@ -197,11 +221,14 @@ class TestResolveWindow(SimpleTestCase):
@parameterized.expand(
[
- ("inverted", "2026-06-10T00:00:00Z", "2026-06-09T00:00:00Z"),
- ("too_long", "-14d", None),
- ("start_beyond_retention", "-40d", "-34d"),
+ ("inverted", "2026-06-10T00:00:00Z", "2026-06-09T00:00:00Z", 60, "after"),
+ ("too_long", "-14d", None, 60, "at most 7 days"),
+ ("start_beyond_retention", "-40d", "-34d", 60, "at most 35 days ago"),
+ ("over_bucket_cap", "-7d", None, 5, "2016 buckets at the 5 minute grain, over the cap of 500"),
]
)
- def test_rejects_invalid_windows(self, _name: str, date_from: str, date_to: str | None) -> None:
- with pytest.raises(SeriesBandsWindowInvalid):
- self._resolve(date_from, date_to)
+ def test_rejects_invalid_windows(
+ self, _name: str, date_from: str, date_to: str | None, interval_minutes: int, message: str
+ ) -> None:
+ with pytest.raises(SeriesBandsWindowInvalid, match=message):
+ self._resolve(date_from, date_to, interval_minutes=interval_minutes)
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 027a019425d5..c4be5713f429 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1256,11 +1256,17 @@ export interface _SeriesBandsDateRangeApi {
}
/**
+ * * `5` - 5
+ * * `15` - 15
+ * * `30` - 30
* * `60` - 60
*/
export type IntervalMinutesEnumApi = (typeof IntervalMinutesEnumApi)[keyof typeof IntervalMinutesEnumApi]
export const IntervalMinutesEnumApi = {
+ Number5: 5,
+ Number15: 15,
+ Number30: 30,
Number60: 60,
} as const
@@ -1269,8 +1275,11 @@ 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. Only hourly is supported today.
+ /** 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.
*
+ * * `5` - 5
+ * * `15` - 15
+ * * `30` - 30
* * `60` - 60 */
intervalMinutes?: IntervalMinutesEnumApi
}
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 97a3bb7e928e..b76cbfbc4cfb 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -531,10 +531,12 @@ 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
- .literal(60)
- .describe('\* `60` - 60')
+ .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)
- .describe('Display grain in minutes for buckets and bands. Only hourly is supported today.\n\n\* `60` - 60'),
+ .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'
+ ),
})
export const LogsCountCreateBody = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d076856a566e..216142e289b3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -47581,12 +47581,18 @@ export namespace Schemas {
}
/**
+ * * `5` - 5
+ * * `15` - 15
+ * * `30` - 30
* * `60` - 60
*/
export type IntervalMinutesEnum = typeof IntervalMinutesEnum[keyof typeof IntervalMinutesEnum];
export const IntervalMinutesEnum = {
+ Number5: 5,
+ Number15: 15,
+ Number30: 30,
Number60: 60,
} as const;
@@ -49833,8 +49839,11 @@ 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. Only hourly is supported today.
+ /** 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.
*
+ * * `5` - 5
+ * * `15` - 15
+ * * `30` - 30
* * `60` - 60 */
intervalMinutes?: IntervalMinutesEnum;
}