: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
fix(logs): start a series-bands baseline at sustained traffic, not the first row (#95919)
Jon McCallum97103b5ee570
diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.pyindex cdacc20f76e5..f38205ccfaa0 100644--- a/products/logs/backend/presentation/views/anomalies_api.py+++ b/products/logs/backend/presentation/views/anomalies_api.py@@ -282,7 +282,11 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):))history_start = serializers.DateTimeField(- help_text="Earliest bucket with data inside the fetched lookback.",+ help_text=(+ "Start of sustained traffic inside the fetched lookback: the first bucket followed by a week with "+ "enough non-empty buckets. A stray earlier row does not move it. The window start when no traffic "+ "is sustained yet."+ ),)band_ready_at = serializers.DateTimeField(allow_null=True,diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.pyindex b395e0891192..2316d37a96d6 100644--- a/products/logs/backend/series_bands.py+++ b/products/logs/backend/series_bands.py@@ -10,6 +10,7 @@ gating, widening) where the arithmetic is cheap and unit-testable."""import os+import mathimport datetime as dtfrom zoneinfo import ZoneInfo@@ -37,13 +38,19 @@ MAX_WINDOW_START_AGE_DAYS = VOLUME_BUCKETS_TTL_DAYS - MAX_WINDOW_DAYSBASELINE_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+SECONDS_PER_DAY = 24 * 3600+SECONDS_PER_WEEK = 7 * SECONDS_PER_DAYMAX_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"))+# A series' lifetime starts at the first slot followed by sustained traffic: at+# least this fraction of the slots after it are non-empty, over the day and over+# the week. A stray row before the real start would otherwise date the lifetime+# and turn every empty week between them into a baseline of zeros.+ALIVE_SLOT_FRACTION = float(os.environ.get("LOGS_SERIES_BANDS_ALIVE_SLOT_FRACTION", "0.2"))# 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.@@ -111,7 +118,12 @@ class _SlotRow:baseline_samples: intbaseline_min: intbaseline_max: int- earliest_slot: dt.datetime+++@frozen+class _SeriesRows:+ lifetime_start: dt.datetime+ slots: list[_SlotRow]def floor_to_interval(value: dt.datetime, interval_minutes: int) -> dt.datetime:@@ -125,16 +137,27 @@ def fetch_series_slot_rows(window_start: dt.datetime,window_end: dt.datetime,interval_minutes: int,-) -> dict[_SeriesKey, list[_SlotRow]]:+) -> dict[_SeriesKey, _SeriesRows]:"""One ClickHouse pass: interval rollup over the window plus baseline, folded- by time-of-week onto the display window's slots.+ by time-of-week onto the display window's slots, plus each series' lifetime+ start.Rows are sparse — a (series, slot) with no observed and no baseline data hasno row. Missing baseline weeks are reconstructed in Python from- baseline_samples vs the weeks the series existed."""+ baseline_samples vs the weeks the series existed. Baseline samples only+ count slots at or after the lifetime start."""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)+ # arrayFirst yields index 0 when no run of alive_slots slots fits inside a+ # week, so a series without sustained traffic is dated from the window start+ # and reports as learning with band_ready_at ahead of the window.+ alive_slots = max(1, math.ceil(ALIVE_SLOT_FRACTION * SECONDS_PER_WEEK / (interval_minutes * 60)))+ # The week's count alone reads a few stray rows a few days ahead of a dense+ # stretch as its start, because the stretch supplies the count. Holding the+ # same fraction over the day after the slot leaves only slots that carry+ # traffic of their own.+ alive_day_slots = max(1, math.ceil(ALIVE_SLOT_FRACTION * SECONDS_PER_DAY / (interval_minutes * 60)))# The series cap ranks over the whole 42d, not the display window: a series# that went silent this week has zero window volume, and ranking on the# window alone would drop exactly the series a silence should surface. The@@ -142,19 +165,7 @@ def fetch_series_slot_rows(# 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 (+ WITH slots AS (SELECTnamespace,environment,@@ -176,8 +187,41 @@ def fetch_series_slot_rows(LIMIT {max_series_plus_probe})GROUP BY namespace, environment, severity_text, slot+ ),+ lifetimes AS (+ SELECT+ namespace,+ environment,+ severity_text,+ arraySort(groupArray(toUnixTimestamp(slot))) AS slot_times,+ arrayFirst(+ i -> i + {alive_slots} - 1 <= length(slot_times)+ AND slot_times[i + {alive_slots} - 1] - slot_times[i] < {week_seconds}+ AND slot_times[i + {alive_day_slots} - 1] - slot_times[i] < {day_seconds},+ arrayEnumerate(slot_times)+ ) AS alive_index,+ if(alive_index = 0, {window_start}, toDateTime(slot_times[alive_index])) AS lifetime_start+ FROM slots+ GROUP BY namespace, environment, severity_text)- GROUP BY namespace, environment, severity_text, target_time+ SELECT+ slots.namespace AS namespace,+ slots.environment AS environment,+ slots.severity_text AS severity_text,+ {window_start} + toIntervalSecond(+ (toUnixTimestamp(slots.slot) - toUnixTimestamp({window_start}) + {baseline_seconds}) % {week_seconds}+ ) AS target_time,+ sumIf(slots.slot_count, slots.slot >= {window_start}) AS observed,+ countIf(slots.slot < {window_start} AND slots.slot >= lifetimes.lifetime_start) AS baseline_samples,+ minIf(slots.slot_count, slots.slot < {window_start} AND slots.slot >= lifetimes.lifetime_start) AS baseline_min,+ maxIf(slots.slot_count, slots.slot < {window_start} AND slots.slot >= lifetimes.lifetime_start) AS baseline_max,+ lifetimes.lifetime_start AS lifetime_start+ FROM slots+ INNER JOIN lifetimes+ ON slots.namespace = lifetimes.namespace+ AND slots.environment = lifetimes.environment+ AND slots.severity_text = lifetimes.severity_text+ GROUP BY namespace, environment, severity_text, target_time, lifetime_startLIMIT {row_limit}""",placeholders={@@ -188,6 +232,9 @@ def fetch_series_slot_rows("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),+ "alive_slots": ast.Constant(value=alive_slots),+ "alive_day_slots": ast.Constant(value=alive_day_slots),+ "day_seconds": ast.Constant(value=SECONDS_PER_DAY),"max_series_plus_probe": ast.Constant(value=MAX_SERIES + 1),"row_limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),},@@ -209,60 +256,63 @@ def fetch_series_slot_rows(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]] = {}+ rows: dict[_SeriesKey, _SeriesRows] = {}for row in response.results:key = _SeriesKey(namespace=row[0], environment=row[1], severity=row[2])- rows.setdefault(key, []).append(+ series = rows.get(key)+ if series is None:+ series = rows[key] = _SeriesRows(lifetime_start=ensure_utc(row[8]), slots=[])+ series.slots.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:+def _baseline_weeks_available(later: dt.datetime, lifetime_start: 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 displayslot 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+ whose sample slot predates the lifetime says nothing; a week inside thelifetime with no row was a real zero."""- weeks = int((later - earliest_slot).total_seconds()) // SECONDS_PER_WEEK+ weeks = int((later - lifetime_start).total_seconds()) // SECONDS_PER_WEEKreturn min(BASELINE_WEEKS, max(0, weeks))def _band_gate(- window_start: dt.datetime, window_end: dt.datetime, earliest_slot: dt.datetime+ window_start: dt.datetime, window_end: dt.datetime, lifetime_start: 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.+ The gate reads sustained history before window_start, so a live window must+ travel a whole window length past the lifetime 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)+ baseline_weeks = _baseline_weeks_available(window_start, lifetime_start)if baseline_weeks >= MIN_BASELINE_WEEKS_FOR_BAND:return baseline_weeks, None- threshold = earliest_slot + dt.timedelta(weeks=MIN_BASELINE_WEEKS_FOR_BAND)+ threshold = lifetime_start + 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],+ series_rows: _SeriesRows,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, band_ready_at = _band_gate(window_start, window_end, earliest_slot)+ by_time = {row.target_time: row for row in series_rows.slots}+ lifetime_start = series_rows.lifetime_start+ baseline_weeks, band_ready_at = _band_gate(window_start, window_end, lifetime_start)banded = band_ready_at is Nonefloor = BAND_FLOOR_PER_HOUR * interval_minutes / 60@@ -279,7 +329,7 @@ def _build_series(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)+ expected = _baseline_weeks_available(slot, lifetime_start)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.@@ -296,7 +346,7 @@ def _build_series(severity=key.severity,total_count=total_count,baseline_weeks=baseline_weeks,- history_start=earliest_slot,+ history_start=lifetime_start,band_ready_at=band_ready_at,buckets=buckets,)diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.pyindex e4ed530cf7ee..ab7d92040899 100644--- a/products/logs/backend/test/test_series_bands.py+++ b/products/logs/backend/test/test_series_bands.py@@ -27,6 +27,11 @@ 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)+# Close enough to a sustained start five days later to share one week-long run.+NEARBY_STRAY = WINDOW_START - dt.timedelta(weeks=1, days=5)+# Two days of rows clear the sustained-traffic threshold at every grain on the+# ladder, so a series' lifetime starts at the first of them.+ALIVE_HOURS = 48class TestSeriesBands(ClickhouseTestMixin, BaseTest):@@ -40,6 +45,20 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):],)+ def _slots(+ self,+ service: str,+ start: dt.datetime,+ hours: int,+ count: int,+ key: tuple[str, str, str] = ("ns", "prod", "error"),+ interval_minutes: int = 60,+ ) -> list[tuple]:+ step = dt.timedelta(minutes=interval_minutes)+ return [+ (self.team.pk, start + slot * step, service, *key, count) for slot in range(hours * 60 // interval_minutes)+ ]+@parameterized.expand([# (name, interval_minutes, window_days, banded_upper, quiet_upper)@@ -55,20 +74,22 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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, window_start - dt.timedelta(weeks=5), service, "ns", "prod", "error", 1),- ]+ # This window's own display slot, far enough in that the run below folds clear of it.+ slot = window_start + dt.timedelta(days=3, hours=4)+ # Starts the series' lifetime at the full 5-week baseline.+ rows = self._slots(+ service, window_start - dt.timedelta(weeks=5), ALIVE_HOURS, 1, interval_minutes=interval_minutes+ )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))+ 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))+ 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))+ 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(@@ -91,35 +112,99 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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 per-hour floor scaled to the grain.- banded = by_time[SLOT]+ banded = by_time[slot]assert banded.observed == 25assert banded.lower == pytest.approx(9.0)assert banded.upper == pytest.approx(banded_upper)- quiet = by_time[SLOT + step]+ quiet = by_time[slot + step]assert quiet.observed == 0assert quiet.lower == 0assert quiet.upper == quiet_upper- def test_learning_series_carries_no_band(self):+ @parameterized.expand(+ [+ # A stray row two weeks before the sustained start does not date the lifetime.+ ("stray_then_sustained", (WINDOW_START - dt.timedelta(weeks=3),), WINDOW_START - dt.timedelta(weeks=1), 1),+ # A stray row that shares a week-long run with the sustained start does not either.+ ("nearby_stray", (NEARBY_STRAY,), WINDOW_START - dt.timedelta(weeks=1), 1),+ # Nor does a pair of stray rows an hour apart, which carries no day of traffic.+ (+ "stray_pair",+ (NEARBY_STRAY, NEARBY_STRAY + dt.timedelta(hours=1)),+ WINDOW_START - dt.timedelta(weeks=1),+ 1,+ ),+ # Traffic that starts mid-week dates the lifetime at that slot, not a week boundary.+ ("mid_week_start", (), WINDOW_START - dt.timedelta(days=10, hours=19), 1),+ # No sustained traffic at all dates the lifetime at the window start.+ ("never_sustained", (WINDOW_START - dt.timedelta(weeks=1),), None, 0),+ ]+ )+ def test_learning_series_dates_history_from_sustained_traffic(+ self,+ _name: str,+ strays: tuple[dt.datetime, ...],+ sustained_from: dt.datetime | None,+ baseline_weeks: int,+ ) -> None:service = "svc-learning"- self._insert(- [- (self.team.pk, WINDOW_START - dt.timedelta(weeks=1), service, "", "", "info", 10),- (self.team.pk, SLOT, service, "", "", "info", 12),- ]- )+ key = ("", "", "info")+ rows = [(self.team.pk, SLOT, service, *key, 12)]+ rows += [(self.team.pk, stray, service, *key, 10) for stray in strays]+ if sustained_from is not None:+ rows += self._slots(service, sustained_from, ALIVE_HOURS, 1, key)+ self._insert(rows)result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)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)+ history_start = sustained_from if sustained_from is not None else WINDOW_START+ assert series.history_start == history_start+ assert series.baseline_weeks == baseline_weeks+ assert series.band_ready_at == history_start + dt.timedelta(weeks=2, days=7)assert all(bucket.lower is None and bucket.upper is None for bucket in series.buckets)assert series.total_count == 12+ def test_band_after_stray_row_comes_from_sustained_traffic(self):+ service = "svc-stray"+ sustained_from = WINDOW_START - dt.timedelta(weeks=3)+ rows = [(self.team.pk, sustained_from - dt.timedelta(weeks=2), service, "ns", "prod", "error", 1)]+ rows += self._slots(service, sustained_from, 4 * 7 * 24, 9)+ self._insert(rows)++ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)++ series = result.series[0]+ assert series.history_start == sustained_from+ assert series.baseline_weeks == 3+ assert series.band_ready_at is None+ # The stray row folds onto the window's first slot; the band there still+ # comes from the three sustained weeks of 9, not the stray 1.+ first = series.buckets[0]+ assert first.time == WINDOW_START+ assert first.lower == pytest.approx(8.1)+ assert first.upper == pytest.approx(11.9)+ assert all(+ bucket.observed == 9+ and bucket.lower is not None+ and bucket.upper is not None+ and bucket.lower <= bucket.observed <= bucket.upper+ for bucket in series.buckets+ )++ def test_silent_window_marks_below_the_band(self):+ service = "svc-silent"+ self._insert(self._slots(service, BASELINE_START, 5 * 7 * 24, 9))++ result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)++ series = result.series[0]+ assert series.baseline_weeks == 5+ assert series.total_count == 0+ assert all(bucket.observed == 0 and bucket.lower == pytest.approx(8.1) for bucket in series.buckets)+def test_band_ready_at_is_when_the_gate_opens(self):earliest = WINDOW_START - dt.timedelta(weeks=1)@@ -131,7 +216,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):def test_missing_baseline_week_drags_floor_to_zero(self):service = "svc-gappy"- rows = [(self.team.pk, BASELINE_START, service, "ns", "prod", "warn", 1)]+ rows = self._slots(service, BASELINE_START, ALIVE_HOURS, 1, ("ns", "prod", "warn"))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)diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex c4be5713f429..cb10628ceaf4 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1312,7 +1312,7 @@ 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. */+ /** Start of sustained traffic inside the fetched lookback: the first bucket followed by a week with enough non-empty buckets. A stray earlier row does not move it. The window start when no traffic is sustained yet. */history_start: string/*** When this series gains its band, so a learning series can count down to it. Null once the band is drawn.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex acb29971daab..6d90774ba62b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49818,7 +49818,7 @@ 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. */+ /** Start of sustained traffic inside the fetched lookback: the first bucket followed by a week with enough non-empty buckets. A stray earlier row does not move it. The window start when no traffic is sustained yet. */history_start: string;/*** When this series gains its band, so a learning series can count down to it. Null once the band is drawn.