:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): tell learning series when their band arrives (#92293)
Jon McCallumc872e1dee544
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.pyindex c601399a6575..73e21b5e9204 100644--- a/products/logs/backend/presentation/views/anomalies_api.py+++ b/products/logs/backend/presentation/views/anomalies_api.py@@ -233,6 +233,15 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):f"Below {MIN_BASELINE_WEEKS_FOR_BAND} the series is still learning and its buckets carry no band."))+ history_start = serializers.DateTimeField(+ help_text="Earliest bucket with data inside the fetched lookback.",+ )+ band_ready_at = serializers.DateTimeField(+ allow_null=True,+ help_text=(+ "When this series gains its band, so a learning series can count down to it. Null once the band is drawn."+ ),+ )buckets = LogsSeriesBandBucketSerializer(many=True,help_text="One entry per display bucket across the whole window, oldest first, zero-filled.",diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.pyindex d880e93fb3a4..5c372e7f4a7f 100644--- a/products/logs/backend/series_bands.py+++ b/products/logs/backend/series_bands.py@@ -59,6 +59,8 @@ class BandSeries:severity: strtotal_count: intbaseline_weeks: int+ history_start: dt.datetime+ band_ready_at: dt.datetime | Nonebuckets: list[BandBucket]@@ -212,6 +214,22 @@ def _baseline_weeks_available(later: dt.datetime, earliest_slot: dt.datetime) ->return min(BASELINE_WEEKS, max(0, weeks))+def _band_gate(+ window_start: dt.datetime, window_end: dt.datetime, earliest_slot: dt.datetime+) -> tuple[int, dt.datetime | None]:+ """Baseline depth at the window start, and when a shallow series gains its band.++ The gate reads history before window_start, so a live window must travel a+ whole window length past the history threshold before a band is drawn. One+ rule returns both, so the countdown cannot drift off the gate it counts to.+ """+ baseline_weeks = _baseline_weeks_available(window_start, earliest_slot)+ if baseline_weeks >= MIN_BASELINE_WEEKS_FOR_BAND:+ return baseline_weeks, None+ threshold = earliest_slot + dt.timedelta(weeks=MIN_BASELINE_WEEKS_FOR_BAND)+ return baseline_weeks, threshold + (window_end - window_start)++def _build_series(key: _SeriesKey,slot_rows: list[_SlotRow],@@ -221,8 +239,8 @@ def _build_series() -> 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+ baseline_weeks, band_ready_at = _band_gate(window_start, window_end, earliest_slot)+ banded = band_ready_at is Nonefloor = BAND_FLOOR_PER_HOUR * interval_minutes / 60buckets: list[BandBucket] = []@@ -255,6 +273,8 @@ def _build_series(severity=key.severity,total_count=total_count,baseline_weeks=baseline_weeks,+ history_start=earliest_slot,+ band_ready_at=band_ready_at,buckets=buckets,)diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.pyindex eddcff86368a..0c34f69d00a4 100644--- a/products/logs/backend/test/test_anomalies_api.py+++ b/products/logs/backend/test/test_anomalies_api.py@@ -198,6 +198,8 @@ class TestLogsSeriesBandsAPI(APIBaseTest):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)],)],@@ -216,6 +218,8 @@ class TestLogsSeriesBandsAPI(APIBaseTest):series = data["series"][0]assert (series["namespace"], series["environment"], series["severity"]) == ("ns", "prod", "error")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 Noneassert series["buckets"][0] == {"time": (T0 - dt.timedelta(hours=1)).isoformat().replace("+00:00", "Z"),"observed": 25,diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.pyindex b8e31c92da7a..a387b055f05b 100644--- a/products/logs/backend/test/test_series_bands.py+++ b/products/logs/backend/test/test_series_bands.py@@ -5,7 +5,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixinfrom posthog.clickhouse.client import sync_execute-from products.logs.backend.series_bands import run_series_bands+from products.logs.backend.series_bands import _band_gate, run_series_bandsUTC = dt.UTC# The scan clock sits ahead of real time so the whole 6-week fixture range stays@@ -57,6 +57,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):series = result.series[0]assert (series.namespace, series.environment, series.severity) == ("ns", "prod", "error")assert series.baseline_weeks == 5+ assert series.band_ready_at is Noneassert series.total_count == 25assert len(series.buckets) == 7 * 24@@ -87,9 +88,20 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):assert len(result.series) == 1series = result.series[0]assert series.baseline_weeks == 1+ assert series.history_start == WINDOW_START - dt.timedelta(weeks=1)+ assert series.band_ready_at == WINDOW_END + dt.timedelta(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_band_ready_at_is_when_the_gate_opens(self):+ earliest = WINDOW_START - dt.timedelta(weeks=1)++ _, ready_at = _band_gate(WINDOW_START, WINDOW_END, earliest)++ assert ready_at is not None+ window = WINDOW_END - WINDOW_START+ assert _band_gate(ready_at - window, ready_at, earliest)[1] is None+def test_missing_baseline_week_drags_floor_to_zero(self):service = "svc-gappy"rows = [(self.team.pk, BASELINE_START, service, "ns", "prod", "warn", 1)]diff --git a/products/logs/frontend/LogsAnomalies.test.ts b/products/logs/frontend/LogsAnomalies.test.tsnew file mode 100644index 000000000000..b6c91d73fcfe--- /dev/null+++ b/products/logs/frontend/LogsAnomalies.test.ts@@ -0,0 +1,24 @@+import { learningBaselineLabel } from './LogsAnomalies'++const WINDOW_END = '2026-08-06T00:00:00Z'++describe('LogsAnomalies', () => {+ describe('learningBaselineLabel', () => {+ // A truncating diff read a 2.9 day wait as "2 more days", which promises the+ // band a day early. A partial day still needs a whole day of data.+ it.each([+ ['2026-08-08T21:36:00Z', 'Learning baseline · 3 more days'],+ ['2026-08-07T04:48:00Z', 'Learning baseline · 2 more days'],+ ['2026-08-07T00:00:00Z', 'Learning baseline · 1 more day'],+ ['2026-08-20T00:00:00Z', 'Learning baseline · 14 more days'],+ ])('rounds a wait ending %s up to whole days', (bandReadyAt, expected) => {+ expect(learningBaselineLabel(bandReadyAt, WINDOW_END)).toBe(expected)+ })++ // The band can land between the fetch and the render. The tag still has to read+ // as a wait, never as "0 more days".+ it.each([WINDOW_END, '2026-08-05T00:00:00Z'])('floors a lapsed wait at one day (%s)', (bandReadyAt) => {+ expect(learningBaselineLabel(bandReadyAt, WINDOW_END)).toBe('Learning baseline · 1 more day')+ })+ })+})diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsxindex 4c312958efee..ccf97729157c 100644--- a/products/logs/frontend/LogsAnomalies.tsx+++ b/products/logs/frontend/LogsAnomalies.tsx@@ -4,7 +4,9 @@ import { memo } from 'react'import { LemonBanner, LemonButton, LemonTag } from '@posthog/lemon-ui'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'@@ -96,7 +98,11 @@ function SeriesBands(): JSX.Element {</div>) : null}{visibleSeries.map((series) => (- <SeriesCard key={`${series.namespace}/${series.environment}/${series.severity}`} series={series} />+ <SeriesCard+ key={`${series.namespace}/${series.environment}/${series.severity}`}+ series={series}+ windowEnd={seriesBands.window_end}+ />))}{hiddenSeriesCount > 0 ? (<LemonButton type="secondary" center onClick={showMoreSeries} data-attr="logs-anomalies-show-more">@@ -107,23 +113,42 @@ function SeriesBands(): JSX.Element {)}+export function learningBaselineLabel(bandReadyAt: string, windowEnd: string): string {+ // Round up: a wait of just over two days still needs a third day of data.+ const days = Math.max(1, Math.ceil(dayjs(bandReadyAt).diff(windowEnd, 'day', true)))+ return `Learning baseline · ${days} more ${days === 1 ? 'day' : 'days'}`+}++function formatDay(timestamp: string): string {+ return dayjs(timestamp).format('MMM D, YYYY')+}+// "Show more" grows the visible slice without touching the cards already on screen, so the charts// they hold should not reconcile again.-const SeriesCard = memo(function SeriesCard({ series }: { series: LogsSeriesBandSeriesApi }): JSX.Element {+const SeriesCard = memo(function SeriesCard({+ series,+ windowEnd,+}: {+ series: LogsSeriesBandSeriesApi+ windowEnd: string+}): JSX.Element {const { openLogsForBucket } = useActions(logsAnomaliesLogic)- // A banded series carries a band on every bucket, so their absence is the backend's own- // "still learning" verdict. Restating its week threshold here would let the two drift.- const learning = series.buckets.length > 0 && series.buckets.every((bucket) => bucket.lower == null)+ // The backend dates the wait, so its history threshold stays out of here and the two cannot drift.+ const bandReadyAt = series.band_ready_atreturn (<div className="rounded border bg-surface-primary p-3" data-attr="logs-anomalies-series"><div className="mb-2 flex items-center gap-2"><LogTag level={series.severity as LogMessage['severity_text']} />{series.namespace ? <LemonTag>{series.namespace}</LemonTag> : null}{series.environment ? <LemonTag>{series.environment}</LemonTag> : null}- {learning ? (- <LemonTag type="caution" title="This series has too little history for an expected range yet.">- Learning baseline- </LemonTag>+ {bandReadyAt ? (+ <Tooltip+ title={`First seen ${formatDay(series.history_start)}. The expected range starts ${formatDay(+ bandReadyAt+ )}.`}+ >+ <LemonTag type="caution">{learningBaselineLabel(bandReadyAt, windowEnd)}</LemonTag>+ </Tooltip>) : null}</div><AnomalyBandChartdiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex bd70df818495..a7408e940df7 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1288,6 +1288,13 @@ export interface LogsSeriesBandSeriesApi {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+ /** Earliest bucket with data inside the fetched lookback. */+ history_start: string+ /**+ * When this series gains its band, so a learning series can count down to it. Null once the band is drawn.+ * @nullable+ */+ band_ready_at: string | null/** One entry per display bucket across the whole window, oldest first, zero-filled. */buckets: LogsSeriesBandBucketApi[]}diff --git a/products/logs/frontend/logsAnomaliesLogic.test.ts b/products/logs/frontend/logsAnomaliesLogic.test.tsindex c7175e109ada..8e6e8112f4fe 100644--- a/products/logs/frontend/logsAnomaliesLogic.test.ts+++ b/products/logs/frontend/logsAnomaliesLogic.test.ts@@ -21,6 +21,8 @@ function seriesBandsResponse(seriesCount: number): LogsSeriesBandsResponseApi {severity: `severity-${index}`,total_count: 100 - index,baseline_weeks: 5,+ history_start: '2026-07-13T10:00:00Z',+ band_ready_at: null,buckets: [],})),}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ae17d0e408c3..1f1fac3931f9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48569,6 +48569,13 @@ export namespace Schemas {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;+ /** Earliest bucket with data inside the fetched lookback. */+ history_start: string;+ /**+ * When this series gains its band, so a learning series can count down to it. Null once the band is drawn.+ * @nullable+ */+ band_ready_at: string | null;/** One entry per display bucket across the whole window, oldest first, zero-filled. */buckets: LogsSeriesBandBucket[];}