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): let the anomalies tab chart an earlier week (#92481)

Jon McCallum109705894261
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.py
index 279160fb330e..6ba127682911 100644
--- a/products/logs/backend/presentation/views/anomalies_api.py
+++ b/products/logs/backend/presentation/views/anomalies_api.py
@@ -23,8 +23,12 @@ 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,
+ MAX_WINDOW_DAYS,
+ MAX_WINDOW_START_AGE_DAYS,
MIN_BASELINE_WEEKS_FOR_BAND,
SeriesBandsFetchTruncated,
+ SeriesBandsWindowInvalid,
+ resolve_window,
run_series_bands,
)
@@ -209,10 +213,31 @@ class LogsAnomalyScanErrorSerializer(serializers.Serializer):
error = serializers.CharField(help_text="Human readable description of why the scan could not run.")
+class _SeriesBandsDateRangeSerializer(serializers.Serializer):
+ date_from = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Start of the window. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1wStart, etc.",
+ )
+ date_to = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text='End of the window. Same format as date_from. Omit or null for "now".',
+ )
+
+
class LogsSeriesBandsRequestSerializer(serializers.Serializer):
serviceName = serializers.CharField(
help_text="Service whose per-series volume to chart (the log record's service_name).",
)
+ dateRange = _SeriesBandsDateRangeSerializer(
+ required=False,
+ help_text=(
+ f"Window to chart. Defaults to the last {MAX_WINDOW_DAYS} days. It may span at most "
+ f"{MAX_WINDOW_DAYS} days and start at most {MAX_WINDOW_START_AGE_DAYS} days ago, "
+ f"past which the volume rollup no longer reaches."
+ ),
+ )
intervalMinutes = serializers.ChoiceField(
choices=[60],
default=60,
@@ -350,6 +375,10 @@ class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
response=LogsSeriesBandsResponseSerializer,
description="Observed volume and expected band per series of the service.",
),
+ 400: OpenApiResponse(
+ response=LogsSeriesBandsErrorSerializer,
+ description="The requested window is empty, too wide, or starts before the volume rollup reaches.",
+ ),
422: OpenApiResponse(
response=LogsSeriesBandsErrorSerializer,
description="The service has too many series to chart in one response.",
@@ -357,9 +386,10 @@ class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
},
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."
+ "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 "
+ f"the volume rollup. The window defaults to the last {MAX_WINDOW_DAYS} days and may span at "
+ f"most {MAX_WINDOW_DAYS} days. Synchronous and read only."
),
)
@action(
@@ -373,17 +403,35 @@ class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
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,
+ )
+ except SeriesBandsWindowInvalid as err:
+ return Response({"error": str(err)}, status=status.HTTP_400_BAD_REQUEST)
cache_key = (
"logs_series_bands/"
- + hashlib.sha256(f"{self.team.id}/{service_name}/{interval_minutes}".encode()).hexdigest()
+ + hashlib.sha256(
+ f"{self.team.id}/{service_name}/{interval_minutes}/"
+ f"{window.start.isoformat()}/{window.end.isoformat()}".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)
+ result = run_series_bands(
+ self.team,
+ service_name,
+ window_start=window.start,
+ window_end=window.end,
+ interval_minutes=interval_minutes,
+ )
except SeriesBandsFetchTruncated as err:
return Response({"error": str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.py
index 5c372e7f4a7f..689faa0016c7 100644
--- a/products/logs/backend/series_bands.py
+++ b/products/logs/backend/series_bands.py
@@ -1,8 +1,9 @@
"""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
+The observed line is the caller's window of volume per (namespace, environment,
+severity) series, at most MAX_WINDOW_DAYS wide. 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.
@@ -10,6 +11,7 @@ gating, widening) where the arithmetic is cheap and unit-testable.
import os
import datetime as dt
+from zoneinfo import ZoneInfo
from posthog.schema import HogQLQueryModifiers
@@ -22,9 +24,16 @@ 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
+from posthog.utils import ensure_utc, relative_date_parse
WINDOW_DAYS = 7
+MAX_WINDOW_DAYS = 7
+VOLUME_BUCKETS_TTL_DAYS = 42 # TTL on logs_volume_buckets, see posthog/clickhouse/hcl/sql/*/logs.sql
+# The whole window has to sit inside that retention, or the observed line itself
+# starts vanishing. Baseline depth thins well before this point, but a thin
+# baseline is reported per series through band_ready_at and drawn as still
+# learning, not rejected here.
+MAX_WINDOW_START_AGE_DAYS = VOLUME_BUCKETS_TTL_DAYS - MAX_WINDOW_DAYS
BASELINE_WEEKS = 5
# Below this many full prior weeks the band rests on too little history to draw.
MIN_BASELINE_WEEKS_FOR_BAND = 2
@@ -44,6 +53,10 @@ class SeriesBandsFetchTruncated(Exception):
pass
+class SeriesBandsWindowInvalid(Exception):
+ pass
+
+
@frozen
class BandBucket:
time: dt.datetime
@@ -74,6 +87,12 @@ class SeriesBandsResult:
series: list[BandSeries]
+@frozen
+class SeriesBandsWindow:
+ start: dt.datetime
+ end: dt.datetime
+
+
@frozen
class _SeriesKey:
namespace: str
@@ -279,18 +298,63 @@ def _build_series(
)
-def run_series_bands(
- team: Team,
- service_name: str,
+_UTC_ZONE = ZoneInfo("UTC")
+
+
+def _parse_bound(value: str, *, now: dt.datetime) -> dt.datetime:
+ # No calendar snapping here, so there is no calendar to snap in: a relative
+ # bound is an offset from now and an ISO bound carries its own offset.
+ return ensure_utc(relative_date_parse(value, _UTC_ZONE, now=now))
+
+
+def resolve_window(
+ date_from: str | None,
+ date_to: str | None,
+ *,
interval_minutes: int = 60,
now: dt.datetime | None = None,
-) -> SeriesBandsResult:
+) -> SeriesBandsWindow:
+ """Turn a request date range into the snapped window to chart, defaulting to the last WINDOW_DAYS."""
# 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)
+ now = ensure_utc(now) if now is not None else dt.datetime.now(dt.UTC)
+
+ 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)
+ # 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)
+ window_end = floor_to_interval(window_end, interval_minutes)
+
+ if window_end < window_start:
+ raise SeriesBandsWindowInvalid("date_to must be after date_from.")
+ if window_end == window_start:
+ raise SeriesBandsWindowInvalid(
+ f"The window is empty at the {interval_minutes} minute grain. Pick a range that covers at least one bucket."
+ )
+ if window_end - window_start > dt.timedelta(days=MAX_WINDOW_DAYS):
+ raise SeriesBandsWindowInvalid(f"The window may span at most {MAX_WINDOW_DAYS} days.")
+ if now - window_start > dt.timedelta(days=MAX_WINDOW_START_AGE_DAYS):
+ raise SeriesBandsWindowInvalid(
+ f"Log volume history does not reach that far back. The window may start at most "
+ f"{MAX_WINDOW_START_AGE_DAYS} days ago."
+ )
+
+ return SeriesBandsWindow(start=window_start, end=window_end)
+
+
+def run_series_bands(
+ team: Team,
+ service_name: str,
+ *,
+ window_start: dt.datetime,
+ window_end: dt.datetime,
+ interval_minutes: int = 60,
+) -> SeriesBandsResult:
+ window_start = floor_to_interval(window_start, interval_minutes)
+ window_end = floor_to_interval(window_end, interval_minutes)
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()]
diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.py
index 0c34f69d00a4..98b17d235ca9 100644
--- a/products/logs/backend/test/test_anomalies_api.py
+++ b/products/logs/backend/test/test_anomalies_api.py
@@ -210,7 +210,10 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
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)
+ kwargs = run.call_args.kwargs
+ assert run.call_args.args == (self.team, "svc")
+ assert kwargs["interval_minutes"] == 60
+ assert kwargs["window_end"] - kwargs["window_start"] == dt.timedelta(days=7)
data = response.json()
assert data["service_name"] == "svc"
assert data["interval_minutes"] == 60
@@ -227,6 +230,19 @@ class TestLogsSeriesBandsAPI(APIBaseTest):
"upper": 57.0,
}
+ @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"),
+ ]
+ )
+ def test_unusable_window_is_rejected_before_querying(self, _name: str, date_range: 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")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert expected in response.json()["error"]
+ run.assert_not_called()
+
def test_truncated_fetch_returns_422(self):
with patch(
"products.logs.backend.presentation.views.anomalies_api.run_series_bands",
diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.py
index a387b055f05b..601a2a0019bd 100644
--- a/products/logs/backend/test/test_series_bands.py
+++ b/products/logs/backend/test/test_series_bands.py
@@ -3,9 +3,19 @@ import datetime as dt
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
from posthog.clickhouse.client import sync_execute
-from products.logs.backend.series_bands import _band_gate, run_series_bands
+from products.logs.backend.series_bands import (
+ SeriesBandsWindow,
+ SeriesBandsWindowInvalid,
+ _band_gate,
+ resolve_window,
+ run_series_bands,
+)
UTC = dt.UTC
# The scan clock sits ahead of real time so the whole 6-week fixture range stays
@@ -48,7 +58,7 @@ 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, now=NOW)
+ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)
assert result.window_start == WINDOW_START
assert result.window_end == WINDOW_END
@@ -83,7 +93,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
]
)
- result = run_series_bands(self.team, service, now=NOW)
+ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)
assert len(result.series) == 1
series = result.series[0]
@@ -109,7 +119,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
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)
+ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)
bucket = {b.time: b for b in result.series[0].buckets}[SLOT]
assert bucket.lower == 0
@@ -124,6 +134,74 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):
]
)
- result = run_series_bands(self.team, service, now=NOW)
+ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)
assert [(s.severity, s.total_count) for s in result.series] == [("error", 300), ("info", 5)]
+
+ def test_charts_an_earlier_window(self):
+ service = "svc-earlier"
+ prior_end = WINDOW_START
+ prior_start = prior_end - dt.timedelta(days=7)
+ prior_slot = prior_start + dt.timedelta(days=2, hours=1)
+ self._insert(
+ [
+ (self.team.pk, prior_slot, service, "ns", "prod", "info", 7),
+ (self.team.pk, SLOT, service, "ns", "prod", "info", 900),
+ ]
+ )
+
+ result = run_series_bands(self.team, service, window_start=prior_start, window_end=prior_end)
+
+ assert (result.window_start, result.window_end) == (prior_start, prior_end)
+ series = result.series[0]
+ assert series.total_count == 7
+ by_time = {bucket.time: bucket for bucket in series.buckets}
+ assert by_time[prior_slot].observed == 7
+ assert SLOT not in by_time
+
+
+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 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),
+ )
+
+ 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"):
+ self._resolve("2026-06-17T15:05:00Z", "2026-06-17T15:20:00Z")
+
+ def test_thirty_days_back_is_accepted(self):
+ assert self._resolve("-30d", "-24d").start == (NOW_FIXED - dt.timedelta(days=30)).replace(minute=0)
+
+ def test_defaults_to_the_last_seven_days(self):
+ assert self._resolve(None, None) == SeriesBandsWindow(
+ start=NOW_FIXED.replace(minute=0) - dt.timedelta(days=7),
+ end=NOW_FIXED.replace(minute=0),
+ )
+
+ def test_day_offset_keeps_its_time_of_day(self):
+ window = self._resolve("-7d", None)
+ assert window.start == NOW_FIXED.replace(minute=0) - dt.timedelta(days=7)
+ assert window.end == NOW_FIXED.replace(minute=0)
+
+ def test_future_end_is_clamped_to_now(self):
+ assert self._resolve("-7d", "2026-07-01T00:00:00Z").end == NOW_FIXED.replace(minute=0)
+
+ @parameterized.expand(
+ [
+ ("inverted", "2026-06-10T00:00:00Z", "2026-06-09T00:00:00Z"),
+ ("too_long", "-14d", None),
+ ("start_beyond_retention", "-40d", "-34d"),
+ ]
+ )
+ 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)
diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsx
index ccf97729157c..d37664f743b8 100644
--- a/products/logs/frontend/LogsAnomalies.tsx
+++ b/products/logs/frontend/LogsAnomalies.tsx
@@ -3,12 +3,14 @@ import { memo } from 'react'
import { LemonBanner, LemonButton, LemonTag } from '@posthog/lemon-ui'
+import { DateRangePicker } from 'lib/components/DateFilter/DateRangePicker/DateRangePicker'
import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
import { dayjs } from 'lib/dayjs'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import type { LogMessage } from '~/queries/schema/schema-general'
+import type { DateMappingOption } from '~/types'
import { AnomalyBandChart } from 'products/logs/frontend/components/AnomalyBandChart'
import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'
@@ -16,9 +18,19 @@ import { LogTag } from 'products/logs/frontend/components/LogTag'
import type { LogsSeriesBandSeriesApi } from 'products/logs/frontend/generated/api.schemas'
import { logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'
+// The backend charts at most a week at a time and cannot reach past 35 days, because the
+// source table drops what it would need. Rolling options only: a fixed span needs no calendar,
+// so there is no week boundary to snap and no timezone to snap it in. Pick an arbitrary week
+// through the picker's own start and end fields.
+const DATE_OPTIONS: DateMappingOption[] = [
+ { key: 'Last 24 hours', values: ['-24h'], defaultInterval: 'hour' },
+ { key: 'Last 3 days', values: ['-3d'], defaultInterval: 'hour' },
+ { key: 'Last 7 days', values: ['-7d'], defaultInterval: 'hour' },
+]
+
export function LogsAnomalies(): JSX.Element {
- const { serviceName } = useValues(logsAnomaliesLogic)
- const { setServiceName } = useActions(logsAnomaliesLogic)
+ const { serviceName, dateRange } = useValues(logsAnomaliesLogic)
+ const { setServiceName, setDateRange } = useActions(logsAnomaliesLogic)
return (
<div className="flex flex-col gap-4 flex-1 min-h-0">
@@ -27,13 +39,23 @@ export function LogsAnomalies(): JSX.Element {
<ServiceFilter
value={serviceName ? [serviceName] : []}
onChange={(serviceNames) => setServiceName(serviceNames?.[0] ?? null)}
- // Match the band baseline lookback so a service that recently went
- // silent still shows up as a suggestion.
+ // Suggestions span the whole retention rather than the charted window: a
+ // service that went silent is the one worth charting, and following the
+ // window would drop it from the list exactly when it matters.
dateRange={{ date_from: '-42d' }}
selectionMode="single"
emptyButtonLabel="Choose a service"
/>
</span>
+ <span data-attr="logs-anomalies-date-range">
+ <DateRangePicker
+ dateRange={dateRange}
+ setDateRange={setDateRange}
+ logicKey="logs-anomalies"
+ dateOptions={DATE_OPTIONS}
+ allowedRollingDateOptions={['hours', 'days']}
+ />
+ </span>
</div>
<SeriesBands />
</div>
@@ -87,7 +109,8 @@ function SeriesBands(): JSX.Element {
return (
<div className="flex flex-col gap-2 flex-1 min-h-0 overflow-y-auto" data-attr="logs-anomalies-band-charts">
<div className="text-secondary text-sm">
- Log volume per hour over the last 7 days, against the range seen at the same time of week in the
+ Log volume per hour from {formatWindowBound(seriesBands.window_start)} to{' '}
+ {formatWindowBound(seriesBands.window_end)}, against the range seen at the same time of week in the
previous weeks. Marked points fell outside that range. Click a bucket to read its logs.
</div>
{seriesBands.series_truncated ? (
@@ -119,6 +142,10 @@ export function learningBaselineLabel(bandReadyAt: string, windowEnd: string): s
return `Learning baseline · ${days} more ${days === 1 ? 'day' : 'days'}`
}
+function formatWindowBound(timestamp: string): string {
+ return dayjs(timestamp).format('MMM D, HH:mm')
+}
+
function formatDay(timestamp: string): string {
return dayjs(timestamp).format('MMM D, YYYY')
}
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 04491553f5fa..7e70331e8c22 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1242,6 +1242,19 @@ export interface LogsAnomalyScanErrorApi {
error: string
}
+export interface _SeriesBandsDateRangeApi {
+ /**
+ * Start of the window. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1wStart, etc.
+ * @nullable
+ */
+ date_from?: string | null
+ /**
+ * End of the window. Same format as date_from. Omit or null for "now".
+ * @nullable
+ */
+ date_to?: string | null
+}
+
/**
* * `60` - 60
*/
@@ -1254,6 +1267,8 @@ export const IntervalMinutesEnumApi = {
export interface LogsSeriesBandsRequestApi {
/** Service whose per-series volume to chart (the log record's service_name). */
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.
*
* * `60` - 60 */
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 2a671dfaffdd..d9d79e87434d 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -335,7 +335,7 @@ export const getLogsAnomaliesSeriesBandsCreateUrl = (projectId: string) => {
}
/**
- * 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.
+ * 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 logsAnomaliesSeriesBandsCreate = async (
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 77db6333a258..d22570d40388 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -506,13 +506,30 @@ export const LogsAnomaliesScanCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * 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.
+ * 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
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the window. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1wStart, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('End of the window. Same format as date_from. Omit or null for \"now\".'),
+ })
+ .optional()
+ .describe(
+ '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')
diff --git a/products/logs/frontend/logsAnomaliesLogic.test.ts b/products/logs/frontend/logsAnomaliesLogic.test.ts
index 8e6e8112f4fe..9ceb6e5a4ed3 100644
--- a/products/logs/frontend/logsAnomaliesLogic.test.ts
+++ b/products/logs/frontend/logsAnomaliesLogic.test.ts
@@ -1,6 +1,8 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { ApiError } from 'lib/api-error'
+
import { initKeaTests } from '~/test/init'
import { logsAnomaliesSeriesBandsCreate } from 'products/logs/frontend/generated/api'
@@ -74,6 +76,40 @@ describe('logsAnomaliesLogic', () => {
expect(logsAnomaliesSeriesBandsCreate).toHaveBeenCalledTimes(1)
})
+ it('recharts the picked week', async () => {
+ // The picker only moves this reducer, so a missing reload or a missing body field would
+ // leave the default week on screen under the new label.
+ await expectLogic(logic, () => {
+ logic.actions.setServiceName('checkout')
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDateRange({ date_from: '-2wStart', date_to: '-2wEnd' })
+ }).toFinishAllListeners()
+
+ expect(logsAnomaliesSeriesBandsCreate).toHaveBeenCalledTimes(2)
+ const [, body] = (logsAnomaliesSeriesBandsCreate as jest.Mock).mock.calls[1]
+ expect(body).toMatchObject({
+ serviceName: 'checkout',
+ dateRange: { date_from: '-2wStart', date_to: '-2wEnd' },
+ })
+ })
+
+ it('shows the backend reason a window was rejected', async () => {
+ // Without this the banner reads "Non-OK response (status 400)", which leaves the user
+ // no way to know their range was too wide.
+ const rejection = new ApiError(undefined, 400, undefined, {
+ error: 'The window may span at most 7 days.',
+ })
+ ;(logsAnomaliesSeriesBandsCreate as jest.Mock).mockRejectedValue(rejection)
+
+ await expectLogic(logic, () => {
+ logic.actions.setServiceName('checkout')
+ }).toFinishAllListeners()
+
+ expect(logic.values.seriesBandsError).toBe('The window may span at most 7 days.')
+ })
+
it('drops a slow response for a service the user has already left', async () => {
// The charts carry no service name of their own, so a late response landing under the
// new selection would be read as that service's volume.
diff --git a/products/logs/frontend/logsAnomaliesLogic.tsx b/products/logs/frontend/logsAnomaliesLogic.tsx
index 85a0ec5343b3..93f878e00f05 100644
--- a/products/logs/frontend/logsAnomaliesLogic.tsx
+++ b/products/logs/frontend/logsAnomaliesLogic.tsx
@@ -15,6 +15,7 @@ export const DEFAULT_VISIBLE_SERIES = 12
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicValues {
currentTeamId: number | null // teamLogic
+ dateRange: DateRange
hiddenSeriesCount: number
seriesBands: LogsSeriesBandsResponseApi | null
seriesBandsError: string | null
@@ -48,6 +49,9 @@ export interface logsAnomaliesLogicActions {
dateRange: DateRange
severity: string
}
+ setDateRange: (dateRange: DateRange) => {
+ dateRange: DateRange
+ }
setServiceName: (serviceName: string | null) => {
serviceName: string | null
}
@@ -79,6 +83,7 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({
setServiceName: (serviceName: string | null) => ({ serviceName }),
+ setDateRange: (dateRange: DateRange) => ({ dateRange }),
showMoreSeries: true,
openLogsForBucket: (severity: string, dateRange: DateRange) => ({ severity, dateRange }),
}),
@@ -92,6 +97,7 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
}
const response = await logsAnomaliesSeriesBandsCreate(String(values.currentTeamId), {
serviceName: values.serviceName,
+ dateRange: values.dateRange,
})
// A slow service can resolve after the user has moved to another one. Without
// this the late response would chart itself under the new service's name.
@@ -108,6 +114,12 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
setServiceName: (_, { serviceName }) => serviceName,
},
],
+ dateRange: [
+ { date_from: '-7d' } as DateRange,
+ {
+ setDateRange: (_, { dateRange }) => dateRange,
+ },
+ ],
// Charts from the previous service would misread as the new one, so a
// service switch drops straight to the loading state.
seriesBands: {
@@ -121,7 +133,10 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
setServiceName: () => null,
loadSeriesBands: () => null,
loadSeriesBandsSuccess: () => null,
- loadSeriesBandsFailure: (_, { error }) => error || 'The request did not complete.',
+ // A rejected window is the user's to fix, so the backend's sentence has to reach
+ // the banner ahead of the generic "Non-OK response" message.
+ loadSeriesBandsFailure: (_, { error, errorObject }) =>
+ errorObject?.data?.error || errorObject?.detail || error || 'The request did not complete.',
},
],
visibleSeriesCount: [
@@ -150,6 +165,11 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
actions.loadSeriesBands({})
}
},
+ setDateRange: () => {
+ if (values.serviceName) {
+ actions.loadSeriesBands({})
+ }
+ },
openLogsForBucket: ({ severity, dateRange }) => {
if (!values.serviceName) {
return
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 829888cfa713..e1542836249a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -48933,9 +48933,24 @@ export namespace Schemas {
error: string;
}
+ export interface _SeriesBandsDateRange {
+ /**
+ * Start of the window. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1wStart, etc.
+ * @nullable
+ */
+ date_from?: string | null;
+ /**
+ * End of the window. Same format as date_from. Omit or null for "now".
+ * @nullable
+ */
+ date_to?: string | null;
+ }
+
export interface LogsSeriesBandsRequest {
/** Service whose per-series volume to chart (the log record's service_name). */
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.
*
* * `60` - 60 */