: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): restore calibrated anomaly chart ranges (#103104)
Jon McCallum89d902b414aa
diff --git a/docs/internal/logs-anomaly-bands.md b/docs/internal/logs-anomaly-bands.mdindex e1e6a3e68276..c440e9759543 100644--- a/docs/internal/logs-anomaly-bands.md+++ b/docs/internal/logs-anomaly-bands.md@@ -1,52 +1,113 @@# Logs anomaly bands-The Logs **Anomalies** tab shows observed counts.-Expected ranges and anomaly markers are disabled until a validated history policy is defined.-The chart labels the expected range as unavailable and does not promise a readiness date.-Once a validated policy exists, the chart can compare counts against a modeled expected range.-The range is not the minimum and maximum seen in previous weeks.-The response keeps the existing `lower`, `upper`, and `verdict` fields.--## Baseline and count model--The chart pools the same time of week and nearby buckets from up to five previous weeks.-There is no validated maturity threshold for enabling these bands.-The readiness gate therefore remains closed for every history depth, including the full five-week lookback.-Missing buckets inside a series' lifetime contribute zero; times before that lifetime do not.-A guarded trailing-day level adjustment lets the range follow a sustained change without immediately absorbing a spike.-Quiet series have a lower bound of zero, so quiet hours are not marked as drops.--The chart and anomaly scan use the same negative-binomial band model.-They do not promise identical verdicts: display grain, history depth, pooling, and the scan's persistence and exclusion gates differ.--The negative-binomial distribution's mean and sample variance use the same observations.-The model does not trim a fixed fraction from each tail, which would underestimate genuine count variability.-For at least five samples, it screens the largest observation against the remaining samples.-It removes that observation only when the remaining samples are not overdispersed and the observation exceeds their mean by ten Poisson-floor standard deviations.-It does not remove an upper-tail observation from an already overdispersed baseline.-This isolated-spike heuristic is not a calibrated outlier probability or a general treatment of contaminated history.-The model retains the other observations and uses a Poisson band when they are not overdispersed.-The returned `expected` value keeps the detector's trimmed-mean estimate of typical traffic.-The silence gate uses that estimate so occasional bursts do not make an otherwise quiet stream appear continuously active.-The interval fit uses the untrimmed moments of the retained observations, not that silence-gate estimate.--## Cost--The chart chooses each series' final display grain before fitting its bands.-Discarded coarsening candidates and series beyond the response cap do not need fitted bands.-Quantiles run in NumPy/SciPy batches per returned series instead of separate SciPy calls for every bucket.-The scalar scan and batched chart paths share the moment estimator and have an equality regression test.--## Validation and rollout--The [detector validation report](../../products/apm/backend/logic/anomaly_detection/validation/REPORT.md) records the full calibration command and its limitations.-The simulation is evidence about the modeled scenarios, not a guarantee that real traffic meets the configured false-flag budget.-Six or nine pooled hourly samples do not support the configured false-flag budget.-The two-week gate is no longer used as evidence of readiness.-Bands cannot be enabled merely by passing `include_bands=True`; the validated-history gate must also pass.-Correlated neighboring buckets and sustained shifts also need review with representative services.--Before broad rollout, compare normal seasonal traffic, isolated spikes, sustained drops, and quiet services at both hourly and finer grains.-Check that ordinary variability stays inside the band while clear spikes and drops remain visible.-Monitor the series-bands endpoint's latency and errors, and review scan output because the estimator is shared.-The API response shape and observed counts do not change.+The Logs **Anomalies** tab shows observed counts and calibrated expected ranges.+The ranges target 99% marginal coverage of individual buckets when historical and future traffic follow comparable patterns.+An out-of-range point is a reason to investigate, not a confirmed incident or an alert.+This is not a 99% guarantee that every point in a chart stays inside its range.+The API keeps the existing `lower`, `upper`, and `verdict` fields.++## History and readiness++The chart uses complete UTC weeks before the displayed window, up to the five-week lookback.+It needs at least four complete weeks: two to fit the weekly pattern and count variability, followed by two separate weeks to calibrate the prediction errors.+With five available weeks, three train the model and two calibrate it.+Neither stage reads observations from the displayed window.+Missing buckets inside the series' sustained lifetime count as zero.+Buckets before that lifetime do not enter the model.++At hourly grain, the two calibration weeks provide 336 errors.+Finer grains provide more errors, not necessarily more independent information.+The implementation rejects calibration sets too short for the finite-sample quantile instead of interpolating an unsupported percentile.+The four-week minimum is a requirement of this train/calibration split, not a claim that age alone makes any traffic pattern predictable.++Younger series still show observed counts and the amount of earlier history they need.+`band_ready_at` gives the earliest end of a rolling window of the same length with enough preceding history.+Waiting does not add earlier history to a fixed historical window; select a more recent window instead.+Retention can also limit the history available to an older window.++## Count model and calibration++The model is local to Logs charts.+It does not change the anomaly scan's detector, persistence rules, or alert budget.++The fitting stage estimates each time-of-week slot's mean from the training weeks.+It pools the within-slot sample variances to estimate a series-wide negative-binomial dispersion:++```text+dispersion = max(0, sum(slot_variance - slot_mean)) / max(1, sum(slot_mean ** 2))+expected = max(1, (sum(slot_training_counts) + mean(all_training_counts) * dispersion)+ / (training_weeks + dispersion))+```++The second expression shrinks noisy, short-history slot means toward the series mean.+Without shrinkage, a few zero training observations can produce unreasonable predictions for a variable stream.+The model starts with the 5th and 95th percentiles of the fitted count distribution.+It falls back to Poisson when fitted dispersion is negligible.+These initial bounds are not advertised as calibrated probabilities.++The calibration stage applies conformalized quantile regression to `log1p(count)`:++```text+score = max(log1p(initial_lower) - log1p(observed),+ log1p(observed) - log1p(initial_upper))+rank = ceil((number_of_calibration_buckets + 1) * 0.99)+expansion = sorted_scores[rank - 1]+lower = expm1(log1p(initial_lower) - expansion)+upper = expm1(log1p(initial_upper) + expansion)+```++Using an order statistic rather than an interpolated percentile accounts for finite calibration sample size.+The logarithmic score adjusts the asymmetric count interval multiplicatively.+Calibration can widen an overconfident interval or shrink an unnecessarily broad one.+For a slot whose interval would become empty, the expansion stops at the midpoint in log space.+This only enlarges the conformal prediction set.+Bounds are clipped at zero and rounded outward to integers.+An isolated extreme calibration observation does not determine the 99% order statistic across two complete weeks.++The finite-sample coverage result requires exchangeable calibration and future scores conditional on the fitted model.+Time-series residuals are not automatically exchangeable.+Weekly seasonality, serial dependence, changing variance, deployments, and daylight-saving shifts can violate the assumptions.+The target is therefore checked empirically, not presented as an unconditional production guarantee.+See [Conformalized Quantile Regression](https://arxiv.org/abs/1905.03222) for the split-conformal construction.++## Validation++Run the deterministic, synthetic chronological holdout suite:++```sh+uv run python -m products.logs.backend.series_prediction_validation --trials 1000 --seed 20260919+```++Each trial generates training weeks, subsequent calibration weeks, and a separate future test week.+The test week does not fit or calibrate the model.+Cases cover four and five weeks of history, sparse and high-volume counts, Poisson and overdispersed noise, daily and weekly seasonality, cron peaks, correlated noise, occasional bursts, and 5-, 15-, and 60-minute grains.+Spike and drop checks replace test observations with five times or one tenth of the known simulated expectation.++The runner reports the missed-bucket fraction and its standard error across independent simulated histories.+It also reports spike/drop recall, interval width, and fit time.+Its calibration regression threshold requires the approximate 95% upper confidence limit on misses to be at most 1.5%, against the 1% target.+This tolerance detects material miscalibration without pretending a finite simulation proves exactly 99% coverage.+For high-volume, low-variability scenarios, both injected-change recall checks must reach 95%.+Highly variable sparse counts can legitimately have a zero lower bound and a broad upper bound; small changes cannot reliably be distinguished from their normal noise.++Integration tests cover observed-count accuracy, missing-history zeros, short windows using complete calibration weeks, grain coarsening, readiness boundaries, and sustained drops that cannot redefine their own baseline.+The existing scan validation report describes a different model and must not be used as evidence for these chart ranges.++The command above passed all 25 scenarios with 1,000 independently generated histories per scenario.+Observed missed-bucket fractions ranged from 0.11% to 0.97%; correlated traffic had the highest rate (0.97%, standard error 0.037 percentage points).+All required high-volume, low-variability spike and drop checks exceeded 99.99% recall.+Occasional bursts reduced spike recall to 97.17%.+Sparse or highly variable traffic had much lower power, sometimes no detectable injected drops and very broad intervals.+These are synthetic results, not measured production accuracy or proof of useful ranges for every service.++## Cost and rollout++The chart fits only the selected series at their final display grains.+Each fit batches one week's count quantiles, reusing them for calibration and display.+No extra database query or external model service is needed.+The existing `logs-anomalies` feature flag remains the rollout control; this change does not broaden its audience.++Synthetic validation is not a substitute for reviewing real services.+Before a broader rollout, backtest representative services on held-out periods, label normal traffic and known incidents, and inspect coverage and usefulness separately.+Track series-bands latency and errors through the existing query tagging and error reporting.+Long-correlated regime changes, UTC/DST misalignment, heavy contamination, and changes in traffic shape remain limitations to review.diff --git a/products/apm/backend/logic/anomaly_detection/validation/REPORT.md b/products/apm/backend/logic/anomaly_detection/validation/REPORT.mdindex dbd77b45ee28..16430a9c431c 100644--- a/products/apm/backend/logic/anomaly_detection/validation/REPORT.md+++ b/products/apm/backend/logic/anomaly_detection/validation/REPORT.md@@ -5,11 +5,10 @@ Recorded on September 16, 2026, with the matched-moment negative-binomial fit an## Release status> [!WARNING]-> The short-history chart remains a rollout blocker.+> Short baselines remain a rollout blocker for the scan detector.> Passing the regression tests does not mean that six or nine pooled hourly samples support the configured false-flag budget.-> Chart bands and markers are disabled while no validated history policy exists.-> Observed counts remain available, with no promised readiness date.-> Re-enabling bands requires a validated policy or a separately validated short-history model.+> Logs charts use a separate calibrated prediction model; this report does not validate their ranges.+> See [Logs anomaly bands](../../../../../../docs/internal/logs-anomaly-bands.md) for the chart model, readiness rule, and holdout validation command.The negative-binomial model produces 6.733 false-positive buckets per series per day in the seeded scenario, compared with 64.023 for Poisson.Its tier A and B info precision is 0.614 and 0.782; their window recall is 1.000 and 0.743.@@ -33,7 +32,7 @@ With hourly pooling, two, three, and five complete baseline weeks supply six, ni| 9 | 0.026 | 0.012 | 0.040 || 15 | 0.016 | 0.012 | 0.024 |-These results isolate the count model; they do not exercise the chart's level adjustment, neighboring-bucket correlations, or history gate.+These results isolate the count model; they do not exercise the detector's level adjustment, neighboring-bucket correlations, or history gate.Removing the fixed-fraction variance trim fixes a real bias, but it does not account for parameter uncertainty with small samples.A generic ten-standard-deviation rejection rule also removes legitimate upper-tail samples from variable baselines, so the guard applies only when the remaining samples are not overdispersed.diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.pyindex 8408176fd260..86486ad749d7 100644--- a/products/logs/backend/presentation/views/anomalies_api.py+++ b/products/logs/backend/presentation/views/anomalies_api.py@@ -270,18 +270,19 @@ class LogsSeriesBandBucketSerializer(serializers.Serializer):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 no validated band is available for this series.",+ help_text="Lower edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.",)upper = serializers.FloatField(allow_null=True,- help_text="Upper edge of the expected band. Null while no validated band is available for this series.",+ help_text="Upper edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.",)verdict = serializers.ChoiceField(choices=LogsSeriesBandVerdict.choices,allow_null=True,help_text=("Where the observed count sits against the band: above when it exceeds upper, below when it falls "- "under lower. Null while it sits inside the band, or while the band is not ready."+ "under lower. Null while it sits inside the band, or while the band is not ready. "+ "An out-of-range bucket is not a confirmed incident or an alert."),)@@ -300,7 +301,7 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):baseline_weeks = serializers.IntegerField(help_text=(f"Full weeks of history behind the band, 0 to {BASELINE_WEEKS}. "- "History depth alone does not enable a band; a validated readiness policy is also required."+ "Four complete weeks are required: at least two for fitting and two separate weeks for calibration."))history_start = serializers.DateTimeField(@@ -313,8 +314,8 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):band_ready_at = serializers.DateTimeField(allow_null=True,help_text=(- "When this series gains its band under a validated readiness policy. "- "Null when the band is ready or no validated readiness date is available. "+ "Earliest end of a rolling window of this length with four complete preceding weeks. "+ "Null when the band is ready. A fixed historical window does not gain history by waiting. ""Check the buckets' lower and upper values to determine whether a band is present."),)diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.pyindex 39fdded34d4b..f1d0574b4474 100644--- a/products/logs/backend/series_bands.py+++ b/products/logs/backend/series_bands.py@@ -1,20 +1,13 @@"""Per-series log volume band charts for one service, read from logs_volume_buckets.-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 the APM-detector's negative binomial count band over time-of-week aligned samples from-the BASELINE_WEEKS weeks before the window: each display slot pools the same-weekly slot, and its neighbours within the detector's developing-stage pool-width, from prior weeks, scaled by the detector's level component. ClickHouse-folds the baseline weeks onto the display window; Python finishes the band-(zero-fill, maturity gating, pooling, level adjustment, the band model) where-the arithmetic is cheap and unit-testable.--The band model and its dials are the detector's, but the chart is not a-detector run. It folds on a UTC week with no DST widening, applies no traffic-tiers or exclusion feedback, and stays at the developing pool width however old-the series is. A bucket outside its band here is evidence to read, not a-verdict.+The chart fits a weekly count model on earlier weeks and calibrates its ranges+on two subsequent complete weeks. Both sets precede the displayed window.+ClickHouse folds up to BASELINE_WEEKS weeks onto a UTC week; Python fills missing+counts with zeros and fits only each returned series' final display grain.++The 99% target describes marginal bucket coverage under stable patterns, not+incident probability or simultaneous coverage across a chart. The independent+anomaly scan's detector, persistence rules, and alert budget are unchanged."""import os@@ -41,7 +34,7 @@ from posthog.dataclasses import frozenfrom posthog.models import Teamfrom posthog.utils import ensure_utc, relative_date_parse-from products.apm.backend.facade.api import BUCKET_MINUTES, DetectionConfig, NegativeBinomialBandModel+from products.logs.backend.series_prediction import MIN_HISTORY_WEEKS, WeeklyPredictionBandWINDOW_DAYS = 7MAX_WINDOW_DAYS = 7@@ -52,7 +45,6 @@ VOLUME_BUCKETS_TTL_DAYS = 42 # TTL on logs_volume_buckets, see posthog/clickhou# learning, not rejected here.MAX_WINDOW_START_AGE_DAYS = VOLUME_BUCKETS_TTL_DAYS - MAX_WINDOW_DAYSBASELINE_WEEKS = 5-VALIDATED_BASELINE_WEEKS_FOR_BAND: int | None = NoneSECONDS_PER_DAY = 24 * 3600SECONDS_PER_WEEK = 7 * SECONDS_PER_DAY@@ -75,8 +67,6 @@ ALIVE_SLOT_FRACTION = float(os.environ.get("LOGS_SERIES_BANDS_ALIVE_SLOT_FRACTIO# average at least this many records. Below that the line is a scatter of single# records under a band held open by the detector's rate floor, and reads as nothing.MIN_MEAN_PER_ALIVE_BUCKET = float(os.environ.get("LOGS_SERIES_BANDS_MIN_MEAN_PER_ALIVE_BUCKET", "5"))-# Its rates and bucket counts are per 5 minute detector bucket; scale them to the display grain where used.-DETECTION = DetectionConfig.from_env()# ClickHouse time one request may spend, shared across its passes. The# coarsening walk costs one pass per rung, so a per-pass cap would let a@@ -357,7 +347,7 @@ class _BandReadiness:def _band_gate(window_start: dt.datetime, window_end: dt.datetime, lifetime_start: dt.datetime) -> _BandReadiness:- """Baseline depth, readiness, and the next readiness date under a validated policy.+ """Baseline depth and readiness for separate training and calibration weeks.The gate reads sustained history before window_start, so a live window musttravel a whole window length past the lifetime threshold before a band is@@ -365,24 +355,17 @@ def _band_gate(window_start: dt.datetime, window_end: dt.datetime, lifetime_starcounts to."""baseline_weeks = _baseline_weeks_available(window_start, lifetime_start)- if VALIDATED_BASELINE_WEEKS_FOR_BAND is None:- return _BandReadiness(baseline_weeks=baseline_weeks, ready=False, ready_at=None)- if baseline_weeks >= VALIDATED_BASELINE_WEEKS_FOR_BAND:+ if baseline_weeks >= MIN_HISTORY_WEEKS:return _BandReadiness(baseline_weeks=baseline_weeks, ready=True, ready_at=None)- threshold = lifetime_start + dt.timedelta(weeks=VALIDATED_BASELINE_WEEKS_FOR_BAND)+ threshold = lifetime_start + dt.timedelta(weeks=MIN_HISTORY_WEEKS)return _BandReadiness(baseline_weeks=baseline_weeks, ready=False, ready_at=threshold + (window_end - window_start))class _FoldedHistory:- """One series' counts on a dense grid at the display grain, from the baseline- start to the window end, zero where the rollup has no row, plus each folded- slot's weekly samples padded to the weeks the slot has existed.-- Baseline buckets come from the folded rows' sample lists and observed- buckets from the rows' observed counts, so the grid is contiguous across the- window start and the level component can read a trailing day from either- side. Times are unix seconds; the display grain divides an hour, so every- bucket edge is a whole multiple of the step from the grid start.+ """Dense display-grain counts, with complete historical weeks before the window.++ Missing lifetime buckets are real zeros. The prediction slices only complete+ weeks preceding window_start, never observations inside the displayed window."""def __init__(@@ -391,26 +374,18 @@ class _FoldedHistory:window_start: dt.datetime,window_end: dt.datetime,interval_minutes: int,- detection: DetectionConfig,):- self.detection = detectionself.step_seconds = interval_minutes * 60self.window_start_ts = int(window_start.timestamp())self.grid_start_ts = self.window_start_ts - BASELINE_WEEKS * SECONDS_PER_WEEK- self.lifetime_ts = int(series_rows.lifetime_start.timestamp())window_end_ts = int(window_end.timestamp())self.counts = np.zeros(self._index(window_end_ts), dtype=np.float64)- self.samples: dict[int, np.ndarray] = {}for row in series_rows.slots:target_ts = int(row.target_time.timestamp())if self.window_start_ts <= target_ts < window_end_ts:self.counts[self._index(target_ts)] = row.observedfor bucket_ts, count in row.baseline:self.counts[self._index(bucket_ts)] = count- values = [float(count) for _, count in row.baseline]- values.extend([0.0] * max(0, _weeks_between(target_ts, self.lifetime_ts) - len(values)))- self.samples[target_ts] = np.array(values, dtype=np.float64)- self.cumulative = np.concatenate(([0.0], np.cumsum(self.counts)))def _index(self, at_ts: int) -> int:return (at_ts - self.grid_start_ts) // self.step_seconds@@ -418,42 +393,10 @@ class _FoldedHistory:def observed(self, slot_ts: int) -> int:return int(self.counts[self._index(slot_ts)])- def mean(self, start_ts: int, end_ts: int) -> float | None:- first = max(self._index(start_ts), 0)- last = min(self._index(end_ts), self.counts.size)- if last <= first:- return None- return float(self.cumulative[last] - self.cumulative[first]) / (last - first)-- def pooled_samples(self, slot_ts: int, half_width: int) -> np.ndarray:- """Weekly samples for slot and its neighbours within half_width slots.-- A neighbour outside the display window still folds onto a row of the- same week, so the fold rather than the window bounds the lookup.- """- parts = []- for offset in range(-half_width, half_width + 1):- folded = (- self.window_start_ts + (slot_ts + offset * self.step_seconds - self.window_start_ts) % SECONDS_PER_WEEK- )- part = self.samples.get(folded)- parts.append(part if part is not None else np.zeros(_weeks_between(folded, self.lifetime_ts)))- return np.concatenate(parts)-- def level_factor(self, slot_ts: int) -> float:- """The detector's slow level component: the mean of a trailing day,- lagged by the baseline guard so an ongoing anomaly cannot re-level- itself, over the mean of the whole history before that guard."""- detection = self.detection- if not detection.level_adjustment_enabled:- return 1.0- reference_end = slot_ts - detection.baseline_guard_buckets * BUCKET_MINUTES * 60- recent_start = reference_end - detection.level_window_buckets * BUCKET_MINUTES * 60- recent = self.mean(max(recent_start, self.lifetime_ts), reference_end)- reference = self.mean(self.lifetime_ts, reference_end)- if recent is None or reference is None or reference <= 0.0:- return 1.0- return min(max(recent / reference, 1.0 / detection.level_factor_clamp), detection.level_factor_clamp)+ def prediction(self, baseline_weeks: int) -> WeeklyPredictionBand:+ end = self._index(self.window_start_ts)+ start = end - baseline_weeks * SECONDS_PER_WEEK // self.step_seconds+ return WeeklyPredictionBand.fit(self.counts[start:end].reshape(baseline_weeks, -1))def _build_series(@@ -462,28 +405,15 @@ def _build_series(window_start: dt.datetime,window_end: dt.datetime,interval_minutes: int,- detection: DetectionConfig,*,include_bands: bool = True,) -> BandSeries:- history = _FoldedHistory(series_rows, window_start, window_end, interval_minutes, detection)+ history = _FoldedHistory(series_rows, window_start, window_end, interval_minutes)lifetime_start = series_rows.lifetime_startreadiness = _band_gate(window_start, window_end, lifetime_start)banded = readiness.ready and include_bands- grain = interval_minutes / BUCKET_MINUTES- band_model = NegativeBinomialBandModel(- rate_floor=detection.band_rate_floor * grain, dispersion_floor=detection.dispersion_floor- )- alpha = detection.alpha_per_bucket * grain- pool_half_width = detection.developing_pool_buckets * BUCKET_MINUTES // interval_minutes- # The detector only calls a zero bucket silence above this expected count. The- # chart draws the lower edge at zero for the whole slot below it, so a quiet- # series never marks a drop where the detector would still flag a low count.- silence_min_expected = detection.silence_min_expected * grain-buckets: list[BandBucket] = []- baseline_samples: list[np.ndarray] = []total_count = 0step = dt.timedelta(minutes=interval_minutes)slot = window_start@@ -491,15 +421,14 @@ def _build_series(slot_ts = int(slot.timestamp())observed = history.observed(slot_ts)total_count += observed- if banded:- baseline_samples.append(history.pooled_samples(slot_ts, pool_half_width) * history.level_factor(slot_ts))buckets.append(BandBucket(time=slot, observed=observed, lower=None, upper=None))slot += stepif banded:+ prediction = history.prediction(readiness.baseline_weeks)buckets = [- replace(bucket, lower=band.lower if band.expected >= silence_min_expected else 0.0, upper=band.upper)- for bucket, band in zip(buckets, band_model.compute_many(baseline_samples, alpha), strict=True)+ replace(bucket, lower=float(prediction.lower[index]), upper=float(prediction.upper[index]))+ for index, bucket in enumerate(buckets)]return BandSeries(@@ -543,7 +472,6 @@ def _coarsen_sparse_series(window_end: dt.datetime,interval_minutes: int,deadline: float,- detection: DetectionConfig,slot_rows: dict[_SeriesKey, _SeriesRows],) -> list[BandSeries]:"""Move each series that is too sparse at the requested grain up the ladder@@ -590,7 +518,7 @@ def _coarsen_sparse_series(settled.append(fallback)continuecandidate = replace(- _build_series(key, rows[key], rung_start, rung_end, rung, detection, include_bands=False),+ _build_series(key, rows[key], rung_start, rung_end, rung, include_bands=False),coarsened_reason=fallback.coarsened_reason,)slot_rows[key] = rows[key]@@ -696,7 +624,6 @@ def run_series_bands(window_start: dt.datetime,window_end: dt.datetime,interval_minutes: int = 60,- detection: DetectionConfig = DETECTION,) -> SeriesBandsResult:window_start = floor_to_interval(window_start, interval_minutes)window_end = floor_to_interval(window_end, interval_minutes)@@ -704,7 +631,7 @@ def run_series_bands(deadline = time.monotonic() + MAX_EXECUTION_SECONDSslot_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, detection, include_bands=False)+ _build_series(key, rows, window_start, window_end, interval_minutes, include_bands=False)for key, rows in slot_rows.items()]series.sort(key=lambda s: (-s.total_count, s.namespace, s.environment, s.severity))@@ -717,7 +644,6 @@ def run_series_bands(window_end,interval_minutes,deadline,- detection,slot_rows,)series = [@@ -728,7 +654,6 @@ def run_series_bands(floor_to_interval(window_start, candidate.interval_minutes),floor_to_interval(window_end, candidate.interval_minutes),candidate.interval_minutes,- detection,),coarsened_reason=candidate.coarsened_reason,)diff --git a/products/logs/backend/series_prediction.py b/products/logs/backend/series_prediction.pynew file mode 100644index 000000000000..98281d27e38f--- /dev/null+++ b/products/logs/backend/series_prediction.py@@ -0,0 +1,51 @@+import math++import numpy as np+from scipy import stats++from posthog.dataclasses import frozen++COVERAGE = 0.99+CALIBRATION_WEEKS = 2+MIN_HISTORY_WEEKS = CALIBRATION_WEEKS + 2+++@frozen+class WeeklyPredictionBand:+ lower: np.ndarray+ upper: np.ndarray++ @classmethod+ def fit(cls, history: np.ndarray) -> "WeeklyPredictionBand":+ if history.ndim != 2 or history.shape[0] < MIN_HISTORY_WEEKS:+ raise ValueError("At least four complete weeks of history are required")+ if not np.all(np.isfinite(history)) or np.any(history < 0):+ raise ValueError("History must contain finite, nonnegative counts")++ training = history[:-CALIBRATION_WEEKS]+ calibration = history[-CALIBRATION_WEEKS:]+ means = np.mean(training, axis=0)+ variances = np.var(training, axis=0, ddof=1)+ dispersion = max(0.0, float(np.sum(variances - means))) / max(1.0, float(np.sum(means**2)))+ expected = np.maximum(+ (np.sum(training, axis=0) + np.mean(training) * dispersion) / (len(training) + dispersion), 1.0+ )+ if dispersion <= 1e-8:+ lower = stats.poisson.ppf(0.05, expected)+ upper = stats.poisson.ppf(0.95, expected)+ else:+ shape = 1.0 / dispersion+ probability = shape / (shape + expected)+ lower = stats.nbinom.ppf(0.05, shape, probability)+ upper = stats.nbinom.ppf(0.95, shape, probability)+ scores = np.maximum(np.log1p(lower) - np.log1p(calibration), np.log1p(calibration) - np.log1p(upper)).ravel()+ rank = math.ceil((scores.size + 1) * COVERAGE)+ if rank > scores.size:+ raise ValueError("Not enough calibration buckets for the requested coverage")+ expansion = np.maximum(+ float(np.partition(scores, rank - 1)[rank - 1]), -0.5 * (np.log1p(upper) - np.log1p(lower))+ )+ return cls(+ lower=np.floor(np.maximum(0.0, np.expm1(np.log1p(lower) - expansion))),+ upper=np.ceil(np.expm1(np.log1p(upper) + expansion)),+ )diff --git a/products/logs/backend/series_prediction_validation.py b/products/logs/backend/series_prediction_validation.pynew file mode 100644index 000000000000..25dec287f6ec--- /dev/null+++ b/products/logs/backend/series_prediction_validation.py@@ -0,0 +1,120 @@+"""Reproduce synthetic holdout checks: python -m products.logs.backend.series_prediction_validation."""++import sys+import time+import argparse++import numpy as np++from posthog.dataclasses import frozen++from products.logs.backend.series_prediction import WeeklyPredictionBand+++@frozen+class SyntheticSeries:+ counts: np.ndarray+ expected: np.ndarray+++def generate_series(+ rng: np.random.Generator, *, weeks: int, interval_minutes: int, mean: float, cv: float, pattern: str+) -> SyntheticSeries:+ slots = 7 * 24 * 60 // interval_minutes+ hours = np.arange(slots) * interval_minutes / 60+ profile = np.ones(slots)+ if pattern in ("daily", "correlated", "bursty"):+ profile = 1 + 0.7 * np.sin(hours * np.pi / 12)+ elif pattern == "weekend":+ profile[hours >= 120] = 0.2+ elif pattern == "cron":+ profile[hours % 24 < 1] = 8+ expected = mean * interval_minutes / 60 * profile+ shape = (weeks + 1, slots)+ if pattern == "correlated":+ noise = np.zeros((weeks + 1) * slots)+ innovations = rng.normal(0, 0.25 * np.sqrt(1 - 0.7**2), noise.size)+ for index in range(1, noise.size):+ noise[index] = 0.7 * noise[index - 1] + innovations[index]+ counts = rng.poisson(np.tile(expected, weeks + 1) * np.exp(noise - 0.25**2 / 2)).reshape(shape)+ elif cv == 0:+ counts = rng.poisson(expected, size=shape)+ else:+ counts = rng.negative_binomial(1 / cv**2, 1 / (1 + expected * cv**2), size=shape)+ if pattern == "bursty":+ counts *= rng.choice([1, 3], size=shape, p=[0.98, 0.02])+ return SyntheticSeries(counts=counts, expected=expected)+++@frozen+class ValidationCase:+ weeks: int+ interval_minutes: int+ mean: float+ cv: float+ pattern: str+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--trials", type=int, default=1000)+ parser.add_argument("--seed", type=int, default=20260918)+ args = parser.parse_args()+ if args.trials < 2:+ parser.error("--trials must be at least 2")+ cases = (+ [+ ValidationCase(weeks=weeks, interval_minutes=60, mean=mean, cv=cv, pattern="daily")+ for weeks in (4, 5)+ for mean in (5.0, 1000.0)+ for cv in (0.0, 0.12, 0.5, 2.2)+ ]+ + [+ ValidationCase(weeks=5, interval_minutes=60, mean=1000, cv=0.12, pattern=pattern)+ for pattern in ("flat", "weekend", "cron", "correlated", "bursty")+ ]+ + [+ ValidationCase(weeks=weeks, interval_minutes=grain, mean=1000, cv=0.12, pattern="daily")+ for weeks in (4, 5)+ for grain in (5, 15)+ ]+ )+ sys.stdout.write(+ "weeks,minutes,mean,cv,pattern,miss_rate,miss_se,spike_recall,drop_recall,mean_width_ratio,fit_ms\n"+ )+ passed = True+ for case in cases:+ rng = np.random.default_rng(args.seed)+ misses, spikes, drops, widths, durations = [], [], [], [], []+ for _trial in range(args.trials):+ sample = generate_series(+ rng,+ weeks=case.weeks,+ interval_minutes=case.interval_minutes,+ mean=case.mean,+ cv=case.cv,+ pattern=case.pattern,+ )+ started = time.perf_counter()+ band = WeeklyPredictionBand.fit(sample.counts[:-1])+ durations.append(time.perf_counter() - started)+ misses.append(float(np.mean((sample.counts[-1] < band.lower) | (sample.counts[-1] > band.upper))))+ spikes.append(float(np.mean(np.round(5 * sample.expected) > band.upper)))+ drops.append(float(np.mean(np.round(0.1 * sample.expected) < band.lower)))+ widths.append(float(np.mean((band.upper - band.lower) / sample.expected)))+ miss_rate = float(np.mean(misses))+ miss_se = float(np.std(misses, ddof=1) / np.sqrt(args.trials))+ passed &= miss_rate + 1.96 * miss_se <= 0.015+ if case.mean == 1000 and case.cv <= 0.12 and case.pattern != "bursty":+ passed &= bool(np.mean(spikes) >= 0.95 and np.mean(drops) >= 0.95)+ sys.stdout.write(+ f"{case.weeks},{case.interval_minutes},{case.mean},{case.cv},{case.pattern},"+ f"{miss_rate:.6f},{miss_se:.6f},{np.mean(spikes):.6f},{np.mean(drops):.6f},"+ f"{np.mean(widths):.3f},{1000 * np.mean(durations):.3f}\n"+ )+ sys.stdout.flush()+ return 0 if passed else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.pyindex ebf257c8b1e2..a0ed968fa4af 100644--- a/products/logs/backend/test/test_series_bands.py+++ b/products/logs/backend/test/test_series_bands.py@@ -1,5 +1,4 @@import datetime as dt-from dataclasses import replaceimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin@@ -37,17 +36,6 @@ NEARBY_STRAY = WINDOW_START - dt.timedelta(weeks=1, days=5)ALIVE_HOURS = 48-def _detection(*, pooling: bool, level: bool) -> series_bands.DetectionConfig:- # Pooling and level adjustment each need their own fixture shape; with both- # off a slot's band is a function of that slot's weekly samples alone.- return replace(- series_bands.DETECTION,- developing_pool_buckets=series_bands.DETECTION.developing_pool_buckets if pooling else 0,- level_adjustment_enabled=level,- )--[email protected](series_bands, "VALIDATED_BASELINE_WEEKS_FOR_BAND", 2)class TestSeriesBands(ClickhouseTestMixin, BaseTest):def _insert(self, rows: list[tuple]) -> None:sync_execute(@@ -75,13 +63,8 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):@parameterized.expand([- # (name, interval_minutes, window_days, banded_lower, banded_upper, quiet_upper, drop_lower, drop_upper)- # The band is the detector's negative binomial at its per-day false-flag- # budget, so the finer grain spends a smaller alpha per bucket and its- # rate floor is a quarter of the hourly one. The finer grain charts 5- # days, because 7 days of 15 minute buckets is over the cap.- ("hourly", 60, 7, 33.0, 951.0, 23.0, 911.0, 1092.0),- ("quarter_hour", 15, 5, 21.0, 1094.0, 10.0, 898.0, 1105.0),+ ("hourly", 60, 7),+ ("quarter_hour", 15, 5),])def test_observed_line_and_band_from_prior_weeks(@@ -89,11 +72,6 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):_name: str,interval_minutes: int,window_days: int,- banded_lower: float,- banded_upper: float,- quiet_upper: float,- drop_lower: float,- drop_upper: float,):service = f"svc-banded-{interval_minutes}"window_start = WINDOW_END - dt.timedelta(days=window_days)@@ -137,7 +115,6 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):window_start=window_start,window_end=WINDOW_END,interval_minutes=interval_minutes,- detection=_detection(pooling=False, level=False),)assert result.window_start == window_start@@ -155,29 +132,27 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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}- # The band is the negative binomial fitted to the five weekly samples 100..500.banded = by_time[slot]assert banded.observed == 250- assert banded.lower == pytest.approx(banded_lower)- assert banded.upper == pytest.approx(banded_upper)- assert banded.verdict is None+ assert banded.lower is not None and banded.upper is not None+ assert 0 <= banded.lower <= banded.upperquiet = by_time[slot + step]assert quiet.observed == 0assert quiet.lower == 0- assert quiet.upper == pytest.approx(quiet_upper)+ assert quiet.upper is not None and 0 < quiet.upper < 500assert quiet.verdict is Nonespike = by_time[slot + dt.timedelta(hours=2)]assert spike.observed == 500assert spike.lower == 0- assert spike.upper == pytest.approx(quiet_upper)+ assert spike.upper == quiet.upperassert spike.verdict == "above"drop = by_time[slot + dt.timedelta(hours=3)]assert drop.observed == 10- assert drop.lower == pytest.approx(drop_lower)- assert drop.upper == pytest.approx(drop_upper)+ assert drop.lower is not None and drop.lower > 10+ assert drop.upper is not None and drop.upper >= 1000assert drop.verdict == "below"@parameterized.expand(@@ -311,7 +286,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):history_start = sustained_from if sustained_from is not None else WINDOW_STARTassert series.history_start == history_startassert series.baseline_weeks == baseline_weeks- assert series.band_ready_at == history_start + dt.timedelta(weeks=2, days=7)+ assert series.band_ready_at == history_start + dt.timedelta(weeks=series_bands.MIN_HISTORY_WEEKS, days=7)assert all(bucket.lower is None and bucket.upper is None and bucket.verdict is None for bucket in series.buckets)@@ -319,24 +294,21 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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, 900)+ sustained_from = WINDOW_START - dt.timedelta(weeks=4)+ rows = [(self.team.pk, sustained_from - dt.timedelta(weeks=1), service, "ns", "prod", "error", 1)]+ rows += self._slots(service, sustained_from, 5 * 7 * 24, 900)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.baseline_weeks == 4assert series.band_ready_at is None- # The stray row folds onto the window's first slot; the band there is- # still the Poisson band of the three sustained weeks of 900, and the- # stray 1 is neither a sample nor a hole.first = series.buckets[0]assert first.time == WINDOW_START- assert first.lower == pytest.approx(815.0)- assert first.upper == pytest.approx(987.0)+ assert first.lower is not None and 800 < first.lower < 900+ assert first.upper is not None and 900 <= first.upper < 1000assert all(bucket.observed == 900and bucket.lower is not None@@ -358,7 +330,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):# clamp keeps the band well above zero, so every bucket stays a drop.assert all(bucket.observed == 0 and bucket.verdict == "below" for bucket in series.buckets)- def test_pooled_neighbours_share_a_slots_band(self):+ def test_neighbouring_seasonal_peaks_do_not_hide_a_spike(self):service = "svc-pooled"rows = self._slots(service, BASELINE_START, ALIVE_HOURS, 1)for week in range(1, 6):@@ -373,19 +345,15 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):service,window_start=WINDOW_START,window_end=WINDOW_END,- detection=_detection(pooling=True, level=False),)bucket = {b.time: b for b in result.series[0].buckets}[SLOT]- # The slot's own five samples of 100 would band at [73, 130] and read- # 400 as a spike; the neighbours' ten samples of 400 an hour either side- # pool in and the band fits the level the series runs at around that hour.assert bucket.observed == 400assert bucket.lower is not None and 0 < bucket.lower < 100- assert bucket.upper is not None and 400 < bucket.upper < 1000- assert bucket.verdict is None+ assert bucket.upper is not None and 100 < bucket.upper < 400+ assert bucket.verdict == "above"- @parameterized.expand([(2,), (3,), (5,)])+ @parameterized.expand([(4,), (5,)])def test_isolated_baseline_spike_keeps_short_history_bands_useful(self, weeks: int):service = f"svc-baseline-spike-{weeks}"history_start = WINDOW_START - dt.timedelta(weeks=weeks)@@ -398,16 +366,15 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):service,window_start=WINDOW_START,window_end=WINDOW_END,- detection=_detection(pooling=True, level=False),)bucket = {bucket.time: bucket for bucket in result.series[0].buckets}[SLOT]assert bucket.observed == 100- assert bucket.lower is not None and 0 < bucket.lower < 100- assert bucket.upper is not None and 100 < bucket.upper < 200+ assert bucket.lower is not None and 0 < bucket.lower <= 100+ assert bucket.upper is not None and 100 <= bucket.upper < 200assert bucket.verdict is None- def test_level_shift_recentres_the_band_within_the_window(self):+ def test_sustained_drop_does_not_redefine_its_own_expected_range(self):service = "svc-level"rows = self._slots(service, BASELINE_START, 5 * 7 * 24, 1000)rows += self._slots(service, WINDOW_START, 7 * 24, 600)@@ -416,33 +383,27 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)by_time = {b.time: b for b in result.series[0].buckets}- # A day in, the level still reads from the baseline weeks: 600 against a- # band around 1000 is a drop. Three days in, the trailing day behind the- # baseline guard already runs at 600, so the band re-centres on it.early = by_time[WINDOW_START + dt.timedelta(days=1)]assert early.observed == 600assert early.verdict == "below"settled = by_time[WINDOW_START + dt.timedelta(days=3)]assert settled.observed == 600- assert settled.verdict is None- assert settled.lower is not None and settled.upper is not None- assert settled.lower < 600 < settled.upper < 1000+ assert settled.verdict == "below"+ assert (settled.lower, settled.upper) == (early.lower, early.upper)- @parameterized.expand([(2,), (4,)])- def test_band_ready_at_is_when_the_gate_opens(self, validated_weeks: int):+ def test_band_ready_at_is_when_the_gate_opens(self):earliest = WINDOW_START - dt.timedelta(weeks=1)- with patch.object(series_bands, "VALIDATED_BASELINE_WEEKS_FOR_BAND", validated_weeks):- readiness = _band_gate(WINDOW_START, WINDOW_END, earliest)+ readiness = _band_gate(WINDOW_START, WINDOW_END, earliest)- assert readiness.ready is False- ready_at = earliest + dt.timedelta(weeks=validated_weeks) + (WINDOW_END - WINDOW_START)- assert readiness.ready_at == ready_at- window = WINDOW_END - WINDOW_START- assert _band_gate(ready_at - window - dt.timedelta(hours=1), ready_at, earliest).ready is False- mature = _band_gate(ready_at - window, ready_at, earliest)- assert mature.ready is True- assert mature.ready_at is None+ assert readiness.ready is False+ ready_at = earliest + dt.timedelta(weeks=series_bands.MIN_HISTORY_WEEKS) + (WINDOW_END - WINDOW_START)+ assert readiness.ready_at == ready_at+ window = WINDOW_END - WINDOW_START+ assert _band_gate(ready_at - window - dt.timedelta(hours=1), ready_at, earliest).ready is False+ mature = _band_gate(ready_at - window, ready_at, earliest)+ assert mature.ready is True+ assert mature.ready_at is Nonedef test_missing_baseline_week_counts_as_a_zero_sample(self):service = "svc-gappy"@@ -456,14 +417,11 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):service,window_start=WINDOW_START,window_end=WINDOW_END,- detection=_detection(pooling=False, level=False),)bucket = {b.time: b for b in result.series[0].buckets}[SLOT]- # Two lifetime weeks with no row at this slot are two samples of zero, so- # the band spreads to cover both the zeros and the hundreds.assert bucket.lower == 0- assert bucket.upper == pytest.approx(368.0)+ assert bucket.upper is not None and bucket.upper > 0def test_series_ordered_by_observed_volume(self):service = "svc-ordered"@@ -503,9 +461,43 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):NOW_FIXED = dt.datetime(2026, 6, 17, 15, 30, tzinfo=UTC)-class TestBandReadinessWithoutValidatedPolicy(SimpleTestCase):- @parameterized.expand([(weeks, grain) for weeks in (0, 1, 2, 3, 5) for grain in (15, 60)])- def test_observed_volume_has_no_band_or_readiness_promise(self, weeks: int, grain: int) -> None:+class TestBandReadiness(SimpleTestCase):+ @parameterized.expand([(5,), (15,), (60,)])+ def test_short_windows_use_full_calibration_weeks_without_observed_data(self, grain: int) -> None:+ step = dt.timedelta(minutes=grain)+ slots = [+ series_bands._SlotRow(+ target_time=WINDOW_START + index * step,+ observed=100,+ baseline=[+ (int((WINDOW_START + index * step - dt.timedelta(weeks=week)).timestamp()), 100)+ for week in range(1, 5)+ ],+ )+ for index in range(7 * 24 * 60 // grain)+ ]+ rows = series_bands._SeriesRows(lifetime_start=WINDOW_START - dt.timedelta(weeks=4), slots=slots)+ key = series_bands._SeriesKey(namespace="ns", environment="prod", severity="info")+ end = WINDOW_START + dt.timedelta(hours=6)+ normal = series_bands._build_series(key, rows, WINDOW_START, end, grain)+ changed = series_bands._SeriesRows(+ lifetime_start=rows.lifetime_start,+ slots=[+ series_bands._SlotRow(target_time=slot.target_time, observed=100000, baseline=slot.baseline)+ for slot in slots+ ],+ )+ spike = series_bands._build_series(key, changed, WINDOW_START, end, grain)++ assert len(normal.buckets) == 6 * 60 // grain+ assert all(bucket.verdict is None and bucket.lower is not None for bucket in normal.buckets)+ assert all(bucket.verdict == "above" for bucket in spike.buckets)+ assert [(bucket.lower, bucket.upper) for bucket in normal.buckets] == [+ (bucket.lower, bucket.upper) for bucket in spike.buckets+ ]++ @parameterized.expand([(weeks, grain) for weeks in (0, 1, 2, 3, 4, 5) for grain in (15, 60)])+ def test_bands_require_separate_training_and_calibration_history(self, weeks: int, grain: int) -> None:history_start = WINDOW_START - dt.timedelta(weeks=weeks)rows = series_bands._SeriesRows(lifetime_start=history_start,@@ -513,20 +505,20 @@ class TestBandReadinessWithoutValidatedPolicy(SimpleTestCase):)key = series_bands._SeriesKey(namespace="ns", environment="prod", severity="info")- result = series_bands._build_series(key, rows, WINDOW_START, WINDOW_END, grain, series_bands.DETECTION)+ result = series_bands._build_series(key, rows, WINDOW_START, WINDOW_END, grain)+ ready = weeks >= series_bands.MIN_HISTORY_WEEKS+ ready_at = None if ready else history_start + dt.timedelta(weeks=series_bands.MIN_HISTORY_WEEKS + 1)assert result.baseline_weeks == weeksassert result.history_start == history_start- assert result.band_ready_at is None+ assert result.band_ready_at == ready_atassert result.total_count == 100assert result.buckets[0].observed == 100- assert all(- bucket.lower is None and bucket.upper is None and bucket.verdict is None for bucket in result.buckets- )+ assert all((bucket.lower is not None and bucket.upper is not None) == ready for bucket in result.buckets)readiness = _band_gate(WINDOW_START, WINDOW_END, history_start)assert readiness.baseline_weeks == weeks- assert readiness.ready is False- assert readiness.ready_at is None+ assert readiness.ready is ready+ assert readiness.ready_at == ready_atclass TestResolveWindow(SimpleTestCase):diff --git a/products/logs/backend/test/test_series_prediction.py b/products/logs/backend/test/test_series_prediction.pynew file mode 100644index 000000000000..e1f5162ead5b--- /dev/null+++ b/products/logs/backend/test/test_series_prediction.py@@ -0,0 +1,89 @@+import pytest++import numpy as np+from parameterized import parameterized++from products.logs.backend.series_prediction import WeeklyPredictionBand+++class TestWeeklyPredictionBand:+ @parameterized.expand([(4,), (5,)])+ def test_constant_seasonality_and_spike_drop_detection(self, weeks: int) -> None:+ expected = np.tile(np.concatenate((np.full(12, 100.0), np.full(12, 1000.0))), 7)+ history = np.tile(expected, (weeks, 1))+ band = WeeklyPredictionBand.fit(history)++ assert np.all(band.lower <= expected)+ assert np.all(band.upper >= expected)+ assert np.all(band.upper < expected * 1.5)+ assert np.all(band.lower > expected * 0.5)+ assert 500 > band.upper[0]+ assert 0 < band.lower[12]++ def test_calibration_observations_do_not_fit_the_forecast(self) -> None:+ history = np.full((5, 168), 100.0)+ history[-2:, :10] = 130.0+ band = WeeklyPredictionBand.fit(history)++ assert np.all((band.lower >= 74) & (band.lower <= 76))+ assert np.all((band.upper >= 130) & (band.upper <= 131))++ def test_uses_finite_sample_rank_without_interpolation(self) -> None:+ history = np.zeros((4, 168))+ history[-2:] = np.arange(336).reshape(2, 168)+ band = WeeklyPredictionBand.fit(history)++ np.testing.assert_array_equal(band.lower, np.zeros(168))+ assert np.all((band.upper >= 333) & (band.upper <= 334))++ def test_one_calibration_spike_does_not_widen_every_bucket(self) -> None:+ history = np.full((5, 168), 100.0)+ clean = WeeklyPredictionBand.fit(history)+ history[-1, 0] = 100000.0+ band = WeeklyPredictionBand.fit(history)++ np.testing.assert_array_equal(band.lower, clean.lower)+ np.testing.assert_array_equal(band.upper, clean.upper)++ def test_training_outlier_does_not_make_all_other_slots_uninformative(self) -> None:+ history = np.full((5, 168), 100.0)+ history[0, 0] = 100000.0+ band = WeeklyPredictionBand.fit(history)++ assert np.all(band.upper[1:] < 200)+ assert np.all(band.lower[1:] > 0)+ assert np.all(band.lower <= band.upper)++ @parameterized.expand(+ [+ ("short", np.ones((3, 168))),+ ("too_few_buckets", np.ones((4, 24))),+ ("negative", np.full((4, 168), -1.0)),+ ("missing", np.full((4, 168), np.nan)),+ ("infinite", np.full((4, 168), np.inf)),+ ]+ )+ def test_rejects_unsupported_history(self, _name: str, history: np.ndarray) -> None:+ with pytest.raises(ValueError):+ WeeklyPredictionBand.fit(history)++ @parameterized.expand(+ [(weeks, mean, cv) for weeks in (4, 5) for mean in (5.0, 1000.0) for cv in (0.0, 0.12, 0.5, 2.2)]+ )+ def test_held_out_week_coverage(self, weeks: int, mean: float, cv: float) -> None:+ rng = np.random.default_rng(8143)+ profile = np.tile(1.0 + 0.7 * np.sin(np.arange(24) * np.pi / 12), 7)+ means = mean * profile+ outside = []+ for _trial in range(128):+ counts = (+ rng.poisson(means, size=(weeks + 1, 168))+ if cv == 0+ else rng.negative_binomial(1 / cv**2, 1 / (1 + means * cv**2), size=(weeks + 1, 168))+ )+ band = WeeklyPredictionBand.fit(counts[:-1])+ outside.append(float(np.mean((counts[-1] < band.lower) | (counts[-1] > band.upper))))+ if mean == 1000 and cv <= 0.12:+ assert np.mean(5 * means > band.upper) > 0.95+ assert np.mean(0.1 * means < band.lower) > 0.95+ assert float(np.mean(outside)) < 0.015, (weeks, mean, cv, np.mean(outside))diff --git a/products/logs/frontend/LogsAnomalies.test.ts b/products/logs/frontend/LogsAnomalies.test.tsindex 95c106713585..93ce1751c08a 100644--- a/products/logs/frontend/LogsAnomalies.test.ts+++ b/products/logs/frontend/LogsAnomalies.test.ts@@ -7,11 +7,11 @@ describe('LogsAnomalies', () => {// 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([- [null, 'Expected range unavailable'],- ['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'],+ [null, 'No expected range for this window'],+ ['2026-08-08T21:36:00Z', 'Learning baseline · 3 more days of history'],+ ['2026-08-07T04:48:00Z', 'Learning baseline · 2 more days of history'],+ ['2026-08-07T00:00:00Z', 'Learning baseline · 1 more day of history'],+ ['2026-08-20T00:00:00Z', 'Learning baseline · 14 more days of history'],])('formats readiness %s as %s', (bandReadyAt, expected) => {expect(learningBaselineLabel(bandReadyAt, WINDOW_END)).toBe(expected)})@@ -19,7 +19,7 @@ describe('LogsAnomalies', () => {// 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')+ expect(learningBaselineLabel(bandReadyAt, WINDOW_END)).toBe('Learning baseline · 1 more day of history')})})})diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsxindex 3fe518fb055e..c4ef24da3454 100644--- a/products/logs/frontend/LogsAnomalies.tsx+++ b/products/logs/frontend/LogsAnomalies.tsx@@ -109,13 +109,13 @@ 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 from {formatWindowBound(seriesBands.window_start)} to{' '}+ Log volume from {formatWindowBound(seriesBands.window_start)} to{' '}{formatWindowBound(seriesBands.window_end)}.{' '}{seriesBands.series.some((series) =>series.buckets.some((bucket) => bucket.lower !== null && bucket.upper !== null))- ? 'Expected ranges use the same time of week in previous weeks. Marked points fell outside that range.'- : 'Expected ranges are not available yet.'}{' '}+ ? 'Expected ranges target 99% coverage for individual buckets when traffic patterns stay stable. Marked points fall outside the range and need investigation.'+ : 'Expected ranges need at least four weeks of sustained traffic before this window. Try a more recent window, or check back as history builds.'}{' '}Click a bucket to read its logs.</div>{seriesBands.series_truncated ? (@@ -143,11 +143,11 @@ function SeriesBands(): JSX.Element {export function learningBaselineLabel(bandReadyAt: string | null, windowEnd: string): string {if (bandReadyAt === null) {- return 'Expected range unavailable'+ return 'No expected range for this window'}// 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'}`+ return `Learning baseline · ${days} more ${days === 1 ? 'day' : 'days'} of history`}function formatWindowBound(timestamp: string): string {@@ -181,8 +181,8 @@ const SeriesCard = memo(function SeriesCard({<Tooltiptitle={bandReadyAt- ? `First seen ${formatDay(series.history_start)}. The expected range starts ${formatDay(bandReadyAt)}.`- : 'Expected ranges are not available yet. You can still select a bucket to read its logs.'+ ? `Sustained traffic starts ${formatDay(series.history_start)}. A rolling window of this length has enough earlier history from ${formatDay(bandReadyAt)}. For a fixed historical window, choose a more recent date range.`+ : 'There is no expected range for this window. Choose a more recent window, or select a bucket to read its logs.'}><LemonTag type="caution">{learningBaselineLabel(bandReadyAt, windowEnd)}</LemonTag>diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 472546c558eb..281cc524ad7e 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1359,16 +1359,16 @@ export interface LogsSeriesBandBucketApi {/** Log count observed in this bucket. */observed: number/**- * Lower edge of the expected band. Null while no validated band is available for this series.+ * Lower edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.* @nullable*/lower: number | null/**- * Upper edge of the expected band. Null while no validated band is available for this series.+ * Upper edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.* @nullable*/upper: number | null- /** Where the observed count sits against the band: above when it exceeds upper, below when it falls under lower. Null while it sits inside the band, or while the band is not ready.+ /** Where the observed count sits against the band: above when it exceeds upper, below when it falls under lower. Null while it sits inside the band, or while the band is not ready. An out-of-range bucket is not a confirmed incident or an alert.** * `above` - Above the band* * `below` - Below the band */@@ -1384,12 +1384,12 @@ export interface LogsSeriesBandSeriesApi {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. History depth alone does not enable a band; a validated readiness policy is also required. */+ /** Full weeks of history behind the band, 0 to 5. Four complete weeks are required: at least two for fitting and two separate weeks for calibration. */baseline_weeks: number/** 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 under a validated readiness policy. Null when the band is ready or no validated readiness date is available. Check the buckets' lower and upper values to determine whether a band is present.+ * Earliest end of a rolling window of this length with four complete preceding weeks. Null when the band is ready. A fixed historical window does not gain history by waiting. Check the buckets' lower and upper values to determine whether a band is present.* @nullable*/band_ready_at: string | nulldiff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 76ca1424fafb..666026f9093a 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -312,12 +312,15 @@ tools:Return log volume for every (namespace, environment, severity) series of one service, each with an expectedband learned from the same time of week over the previous weeks of the volume rollup. This is the databehind the Anomalies tab in the logs UI. A bucket whose observed count sits above upper or below lower fell- outside the expected range. lower and upper are null while a series is still learning; band_ready_at says- when its band arrives. Omit intervalMinutes and the grain is picked from the window (7 days gives 60- minutes, 1 day gives 15); pass 5, 15, 30 or 60 to choose. A series too sparse or too quiet for the requested- grain comes back coarser, with its own interval_minutes and a coarsened_reason. Requires a serviceName (use- logs-services-create or the resource attribute values tool to discover services). The window defaults to the- last 7 days, may span at most 7 days, and may start at most 35 days ago. Synchronous and read only.+ outside the expected range. Ranges target 99% coverage of individual buckets, so an out-of-range bucket is a+ reason to investigate, not a confirmed incident. lower and upper are null while a series is still learning.+ band_ready_at gives the earliest end of a rolling window of the same length with enough earlier history.+ Waiting does not add earlier history to a fixed historical window; select a more recent window instead. Omit+ intervalMinutes and the grain is picked from the window (7 days gives 60 minutes, 1 day gives 15); pass 5,+ 15, 30 or 60 to choose. A series too sparse or too quiet for the requested grain comes back coarser, with+ its own interval_minutes and a coarsened_reason. Requires a serviceName (use logs-services-create or the+ resource attribute values tool to discover services). The window defaults to the last 7 days, may span at+ most 7 days, and may start at most 35 days ago. Synchronous and read only.feature_flag: logs-anomalieslogs-attribute-values-list:operation: logs_values_retrievediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 561e0e1c5986..16902db540fa 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7659,7 +7659,7 @@"feature_flag": "logs-anomalies"},"logs-anomalies-series-bands": {- "description": "Return log volume for every (namespace, environment, severity) series of one service, each with an expected band learned from the same time of week over the previous weeks of the volume rollup. This is the data behind the Anomalies tab in the logs UI. A bucket whose observed count sits above upper or below lower fell outside the expected range. lower and upper are null while a series is still learning; band_ready_at says when its band arrives. Omit intervalMinutes and the grain is picked from the window (7 days gives 60 minutes, 1 day gives 15); pass 5, 15, 30 or 60 to choose. A series too sparse or too quiet for the requested grain comes back coarser, with its own interval_minutes and a coarsened_reason. Requires a serviceName (use logs-services-create or the resource attribute values tool to discover services). The window defaults to the last 7 days, may span at most 7 days, and may start at most 35 days ago. Synchronous and read only.",+ "description": "Return log volume for every (namespace, environment, severity) series of one service, each with an expected band learned from the same time of week over the previous weeks of the volume rollup. This is the data behind the Anomalies tab in the logs UI. A bucket whose observed count sits above upper or below lower fell outside the expected range. Ranges target 99% coverage of individual buckets, so an out-of-range bucket is a reason to investigate, not a confirmed incident. lower and upper are null while a series is still learning. band_ready_at gives the earliest end of a rolling window of the same length with enough earlier history. Waiting does not add earlier history to a fixed historical window; select a more recent window instead. Omit intervalMinutes and the grain is picked from the window (7 days gives 60 minutes, 1 day gives 15); pass 5, 15, 30 or 60 to choose. A series too sparse or too quiet for the requested grain comes back coarser, with its own interval_minutes and a coarsened_reason. Requires a serviceName (use logs-services-create or the resource attribute values tool to discover services). The window defaults to the last 7 days, may span at most 7 days, and may start at most 35 days ago. Synchronous and read only.","category": "Logs","feature": "logs","summary": "Per-series log volume with expected bands",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 1194be4a328d..cc2e79181792 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8038,7 +8038,7 @@"feature_flag": "logs-anomalies"},"logs-anomalies-series-bands": {- "description": "Return log volume for every (namespace, environment, severity) series of one service, each with an expected band learned from the same time of week over the previous weeks of the volume rollup. This is the data behind the Anomalies tab in the logs UI. A bucket whose observed count sits above upper or below lower fell outside the expected range. lower and upper are null while a series is still learning; band_ready_at says when its band arrives. Omit intervalMinutes and the grain is picked from the window (7 days gives 60 minutes, 1 day gives 15); pass 5, 15, 30 or 60 to choose. A series too sparse or too quiet for the requested grain comes back coarser, with its own interval_minutes and a coarsened_reason. Requires a serviceName (use logs-services-create or the resource attribute values tool to discover services). The window defaults to the last 7 days, may span at most 7 days, and may start at most 35 days ago. Synchronous and read only.",+ "description": "Return log volume for every (namespace, environment, severity) series of one service, each with an expected band learned from the same time of week over the previous weeks of the volume rollup. This is the data behind the Anomalies tab in the logs UI. A bucket whose observed count sits above upper or below lower fell outside the expected range. Ranges target 99% coverage of individual buckets, so an out-of-range bucket is a reason to investigate, not a confirmed incident. lower and upper are null while a series is still learning. band_ready_at gives the earliest end of a rolling window of the same length with enough earlier history. Waiting does not add earlier history to a fixed historical window; select a more recent window instead. Omit intervalMinutes and the grain is picked from the window (7 days gives 60 minutes, 1 day gives 15); pass 5, 15, 30 or 60 to choose. A series too sparse or too quiet for the requested grain comes back coarser, with its own interval_minutes and a coarsened_reason. Requires a serviceName (use logs-services-create or the resource attribute values tool to discover services). The window defaults to the last 7 days, may span at most 7 days, and may start at most 35 days ago. Synchronous and read only.","category": "Logs","feature": "logs","summary": "Per-series log volume with expected bands",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0afab01d4681..21cb978c5612 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53655,16 +53655,16 @@ export namespace Schemas {/** Log count observed in this bucket. */observed: number;/**- * Lower edge of the expected band. Null while no validated band is available for this series.+ * Lower edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.* @nullable*/lower: number | null;/**- * Upper edge of the expected band. Null while no validated band is available for this series.+ * Upper edge of the calibrated count range targeting 99% marginal bucket coverage under stable traffic. Null without four complete preceding weeks.* @nullable*/upper: number | null;- /** Where the observed count sits against the band: above when it exceeds upper, below when it falls under lower. Null while it sits inside the band, or while the band is not ready.+ /** Where the observed count sits against the band: above when it exceeds upper, below when it falls under lower. Null while it sits inside the band, or while the band is not ready. An out-of-range bucket is not a confirmed incident or an alert.** * `above` - Above the band* * `below` - Below the band */@@ -53680,12 +53680,12 @@ export namespace Schemas {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. History depth alone does not enable a band; a validated readiness policy is also required. */+ /** Full weeks of history behind the band, 0 to 5. Four complete weeks are required: at least two for fitting and two separate weeks for calibration. */baseline_weeks: number;/** 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 under a validated readiness policy. Null when the band is ready or no validated readiness date is available. Check the buckets' lower and upper values to determine whether a band is present.+ * Earliest end of a rolling window of this length with four complete preceding weeks. Null when the band is ready. A fixed historical window does not gain history by waiting. Check the buckets' lower and upper values to determine whether a band is present.* @nullable*/band_ready_at: string | null;