: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): draw anomaly bands with the detector's count model (#99421)
Jon McCallumf32f9209ec11
diff --git a/docs/internal/logs-anomaly-bands.md b/docs/internal/logs-anomaly-bands.mdnew file mode 100644index 000000000000..e1e6a3e68276--- /dev/null+++ b/docs/internal/logs-anomaly-bands.md@@ -0,0 +1,52 @@+# 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.diff --git a/products/apm/backend/logic/anomaly_detection/bands.py b/products/apm/backend/logic/anomaly_detection/bands.pyindex 97e3bdec0053..55614e9e16f6 100644--- a/products/apm/backend/logic/anomaly_detection/bands.py+++ b/products/apm/backend/logic/anomaly_detection/bands.py@@ -23,6 +23,8 @@ from typing import Protocolimport numpy as npfrom scipy import stats+from posthog.dataclasses import frozen+from products.apm.backend.logic.anomaly_detection.types import BandTRIM_FRACTION = 0.1@@ -34,6 +36,8 @@ NORMAL_Q1_IN_SIGMA = 0.674TUKEY_FENCE_K = 1.5# Sample variance within this ratio of the mean counts as "not overdispersed".OVERDISPERSION_TOLERANCE = 1.001+ISOLATED_SPIKE_SIGMAS = 10.0+MIN_SPIKE_BASELINE_SAMPLES = 5class BandModel(Protocol):@@ -70,6 +74,13 @@ class PoissonBandModel:return Band(lower=lower, upper=upper, expected=mu)+@frozen+class _CountMoments:+ mean: float+ variance: float+ expected: float++class NegativeBinomialBandModel:"""Poisson band inflated to the measured sample dispersion.@@ -84,18 +95,57 @@ class NegativeBinomialBandModel:self.dispersion_floor = dispersion_floordef compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band:- mu = _robust_rate(samples)- mu_eff = max(mu, self.rate_floor)- var = float(np.var(samples, ddof=1)) if samples.size >= 2 else mu_eff- var = max(var, mu_eff * self.dispersion_floor)- if var <= mu_eff * OVERDISPERSION_TOLERANCE:+ moments = self._moments(samples)+ mu_eff = max(moments.mean, self.rate_floor)+ if moments.variance <= mu_eff * OVERDISPERSION_TOLERANCE:lower, upper = _poisson_interval(mu_eff, alpha)else:- r = mu_eff**2 / (var - mu_eff)+ r = mu_eff**2 / (moments.variance - mu_eff)p = r / (r + mu_eff)lower = float(stats.nbinom.ppf(alpha, r, p))upper = float(stats.nbinom.ppf(1.0 - alpha, r, p))- return Band(lower=lower, upper=upper, expected=mu)+ return Band(lower=lower, upper=upper, expected=moments.expected)++ def _moments(self, samples: np.ndarray) -> _CountMoments:+ if samples.size >= MIN_SPIKE_BASELINE_SAMPLES:+ ordered = np.sort(samples)+ rest = ordered[:-1]+ rest_mean = float(np.mean(rest))+ rest_variance = float(np.var(rest, ddof=1))+ poisson_variance = max(rest_mean, self.rate_floor) * self.dispersion_floor+ if rest_variance <= poisson_variance * OVERDISPERSION_TOLERANCE and ordered[+ -1+ ] > rest_mean + ISOLATED_SPIKE_SIGMAS * np.sqrt(poisson_variance):+ samples = rest+ mu = float(np.mean(samples))+ mu_eff = max(mu, self.rate_floor)+ variance = float(np.var(samples, ddof=1)) if samples.size >= 2 else mu_eff+ return _CountMoments(+ mean=mu, variance=max(variance, mu_eff * self.dispersion_floor), expected=_robust_rate(samples)+ )++ def compute_many(self, samples: list[np.ndarray], alpha: float) -> list[Band]:+ if not samples:+ return []+ moments = [self._moments(sample) for sample in samples]+ means = np.array([moment.mean for moment in moments])+ effective_means = np.maximum(means, self.rate_floor)+ variances = np.array([moment.variance for moment in moments])+ overdispersed = variances > effective_means * OVERDISPERSION_TOLERANCE+ lower = np.empty(len(samples))+ upper = np.empty(len(samples))+ poisson_means = effective_means[~overdispersed]+ lower[~overdispersed] = stats.poisson.ppf(alpha, poisson_means)+ upper[~overdispersed] = stats.poisson.ppf(1.0 - alpha, poisson_means)+ nb_means = effective_means[overdispersed]+ shapes = nb_means**2 / (variances[overdispersed] - nb_means)+ probabilities = shapes / (shapes + nb_means)+ lower[overdispersed] = stats.nbinom.ppf(alpha, shapes, probabilities)+ upper[overdispersed] = stats.nbinom.ppf(1.0 - alpha, shapes, probabilities)+ return [+ Band(lower=float(low), upper=float(high), expected=moment.expected)+ for low, high, moment in zip(lower, upper, moments, strict=True)+ ]class _RegistryBandModel:diff --git a/products/apm/backend/logic/anomaly_detection/validation/REPORT.md b/products/apm/backend/logic/anomaly_detection/validation/REPORT.mdindex ff0d3d76a7fa..dbd77b45ee28 100644--- a/products/apm/backend/logic/anomaly_detection/validation/REPORT.md+++ b/products/apm/backend/logic/anomaly_detection/validation/REPORT.md@@ -1,39 +1,181 @@# Detector validation results-Run: `python -m products.apm.backend.logic.anomaly_detection.validation.run --weeks 10 --eval-weeks 2 --ephemerals 30 --seed 7`-(49 series seeded from the calibration defaults in calibration.py — production-shaped, with absolute volumes rounded — 133 injected anomalies over a 2-week eval window that crosses the 2026-03-08 US DST shift; requires a booted Django env for the registry-backed scorers.)+Recorded on September 16, 2026, with the matched-moment negative-binomial fit and the isolated-spike guard restricted to non-overdispersed baselines.-## Band model recommendation: negative binomial, no severity widening+## Release status-- **negative_binomial**: 6.7 fp/series/day, tier A info precision 0.61 and tier B info 0.78 at window-recall 0.71–1.0. Best on every persistent info/warn group, and the **only model calibrated across the count range**: on clean NB data at lambda 1–10,000 x CV {0.12, 0.5, 2.2} its false-flag rate stays at 0.000–0.006, near the 3.5e-4 target.-- **poisson**: 64 fp/series/day — rejected decisively, and the overdispersion answer is broader than the error-severity headline: high-volume `info` series run several times the dispersion Poisson predicts at their rate, and because absolute overdispersion grows with volume, Poisson's sweep false-flag rate climbs to 0.36–0.78 at lambda >= 1,000 _even at CV 0.12_. The design's illustrative Poisson band does not survive contact with realistic data.-- **mad / zscore / iqr** (registry scorers): 23 / 20 / 13 fp/series/day in the scenario; in the sweep MAD and IQR blow up on overdispersed series (26–33% and 12–13% false-flag at CV 2.2) and all three are structurally symmetric — the lower band goes negative at low rates, making drops undetectable per-bucket.-- **Severity widening is off by default**: NB measures dispersion from the samples, so the per-severity multiplier only costs recall (tier B warn window-recall 0.82 → 0.71 with widening, FP essentially unchanged). The multiplier mechanism remains in config for assumed-dispersion models.+> [!WARNING]+> The short-history chart remains a rollout blocker.+> 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.-## Baseline stages: cold start is usable — mature is where the FPs are+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.+These are scenario results, not production measurements or a guarantee of the configured budget.+The robust expected-rate estimate still controls silence eligibility; changing that estimate to the untrimmed mean introduces false silences on intermittent streams.-Per-stage precision with NB: cold start 0.92, developing 0.66, mature 0.27. The pre-registered fear was cold start dominating false positives; the widened cold bands are in fact the cleanest, and the FP mass sits in mature series (dominated by the error-severity failure below). Cold-start bands are usable from ~3 days of history.+The clean-data sweep uses 40 baseline samples and 500 trials per cell.+The observed negative-binomial false-flag rates range from 0.000 to 0.006 against a nominal two-sided budget of approximately 0.00035.+A sweep with 500 trials per cell cannot establish that small a nominal budget, and several cells exceed it.+The former claim that this establishes calibration across the count range is not supported.-## Error severity is not per-bucket detectable — every model fails+## Short hourly histories-Error-severity series at single-digit per-bucket rates with CV ~2: best precision 0.023 (NB), NB recall 0.25, MAD emits 5,437 FPs. At that dispersion a 5x spike sits inside the noise. Per-bucket band scoring is the wrong instrument for error streams at these rates; the dials follow-up should score error/fatal on coarser windows (30–60 min) or a presence-based instrument. Related: residual persistent-silence FPs (~1,600/2w across 49 series) concentrate in low-rate high-CV series whose seasonal expectation clears `silence_min_expected` while their natural P(0) is large — the silence candidacy gate should become dispersion-aware in the same follow-up.+A separate run of the existing `band_calibration_sweep` uses `rate_floor=12`, `alpha=0.05/24`, `seed=10`, `lambdas=(1000.0,)`, `cvs=(0.12, 0.5, 2.2)`, and the default 500 trials.+The nominal two-sided false-flag rate is approximately 0.00417.+With hourly pooling, two, three, and five complete baseline weeks supply six, nine, and fifteen samples respectively.-## Persistence gate: reproduced+| Samples | CV 0.12 | CV 0.5 | CV 2.2 |+| ------- | ------- | ------ | ------ |+| 6 | 0.048 | 0.062 | 0.076 |+| 9 | 0.026 | 0.012 | 0.040 |+| 15 | 0.016 | 0.012 | 0.024 |-Ephemeral-pod silence FPs over 2 weeks with NB: **0 with the full design vs 134 without the persistence gate**. Two structural notes the original characterization's framing didn't separate: (1) the staged-baseline min-history requirement already suppresses pods younger than ~3 days on its own (birth-side), so the explicit gate's marginal value is bounding the post-death firing window (death-side); (2) multi-day pods' deaths are genuinely indistinguishable from dead workers at death time — that is the irreducible residual, bounded by `persistence_recent_buckets`.+These results isolate the count model; they do not exercise the chart'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.-## Level-shift re-baselining: the ~4-week claim is corrected, in both directions+## Reproduction-- A x2 shift (within `level_factor_clamp`) is absorbed by the slow level component in **~2.6 days** — much faster than 4 weeks.-- A x4 shift **never passively re-baselines** (still firing after 5 weeks): mature baselines sample the same time-of-week only ~5 buckets/week, and verdict-exclusion feedback keeps new-level samples out, so the exclusion cap's readmission cannot catch up.-- The stability test (12 consecutive same-direction verdicts → re-anchor the baseline window at the shift) goes quiet in **1 hour** at the cost of re-learning from scratch. It should ship; passive re-baselining alone is not a viable story for shifts beyond the level clamp.+The full documented runner completed in a booted Django environment, including the registry-backed scorers, severity widening, persistence ablation, and level-shift experiments:-## Bug found by the harness: baseline self-legitimization+```sh+python -m products.apm.backend.logic.anomaly_detection.validation.run --weeks 10 --eval-weeks 2 --ephemerals 30 --seed 7+```-The trailing edge of the developing/mature pools included buckets minutes before the scored one, so an ongoing incident's own (unflagged) buckets entered the baseline, inflated the dispersion estimate, and blinded the detector within ~4 hours of onset. Fixed with `baseline_guard_buckets` (default 1 day): baselines and the level factor only see data at least a guard period old. `test_ongoing_incident_does_not_legitimize_itself` pins it.+The recorded output follows.+The scenario and seed come from the repository's public simulation defaults.-## Caveats+seed=7 weeks=10 eval_weeks=2 series=49 anomalies=133-- Injection density (~9.5 anomalies/day across the population) is set for measurement power, not realism — the issues/day numbers here are not directly comparable to the "median ≤1 new issue/day" launch gate, which shadow evaluates at organic anomaly rates.-- The calibration values are rounded representative defaults modeled on internal measurements of production-shaped log traffic; they are calibrating defaults, not universals. The noise model is swappable (`simulation.NoiseModel`) for design-partner data.-- Persistence-gate dial tuning (window/recency sweeps) is deliberately left to the dial-setting follow-up; this run fixes the mechanism and reproduces its effect.+## Band model bake-off++```text+ model: poisson+ verdicts 17998, fp/series/day 64.023+ issues/day median 110.0 p95 121.0, issue precision 0.033 (50/1524)+ silence: windows 34/38 detected, fp persistent 1428, fp ephemeral 0+ tier A info precision 0.039 window-recall 1.000 tp 264 fp 6436+ tier B info precision 0.134 window-recall 0.971 tp 289 fp 1863+ tier B warn precision 0.052 window-recall 1.000 tp 263 fp 4829+ tier C error precision 0.014 window-recall 0.500 tp 48 fp 3410+ tier C info precision 0.174 window-recall 0.929 tp 104 fp 492+ stage cold_start precision 0.714 tp 40 fp 16+ stage developing precision 0.124 tp 74 fp 521+ stage mature precision 0.049 tp 854 fp 16493+ (84.5s)++ model: negative_binomial+ verdicts 2515, fp/series/day 6.733+ issues/day median 22.5 p95 25.7, issue precision 0.260 (78/300)+ silence: windows 34/38 detected, fp persistent 1578, fp ephemeral 0+ tier A info precision 0.614 window-recall 1.000 tp 264 fp 166+ tier B info precision 0.782 window-recall 0.743 tp 186 fp 52+ tier B warn precision 0.509 window-recall 0.821 tp 175 fp 169+ tier C error precision 0.023 window-recall 0.250 tp 31 fp 1331+ tier C info precision 0.482 window-recall 0.786 tp 68 fp 73+ stage cold_start precision 0.917 tp 33 fp 3+ stage developing precision 0.661 tp 37 fp 19+ stage mature precision 0.270 tp 654 fp 1769+ (40.7s)++ model: mad+ verdicts 6836, fp/series/day 22.929+ issues/day median 28.5 p95 36.4, issue precision 0.217 (80/369)+ silence: windows 30/38 detected, fp persistent 354, fp ephemeral 0+ tier A info precision 0.582 window-recall 1.000 tp 262 fp 188+ tier B info precision 0.652 window-recall 0.714 tp 202 fp 108+ tier B warn precision 0.405 window-recall 0.786 tp 169 fp 248+ tier C error precision 0.005 window-recall 0.393 tp 28 fp 5437+ tier C info precision 0.392 window-recall 0.786 tp 76 fp 118+ stage cold_start precision 0.919 tp 34 fp 3+ stage developing precision 0.562 tp 45 fp 35+ stage mature precision 0.098 tp 658 fp 6061+ (88.4s)++ model: zscore+ verdicts 6169, fp/series/day 20.180+ issues/day median 27.0 p95 37.7, issue precision 0.190 (71/373)+ silence: windows 35/38 detected, fp persistent 4787, fp ephemeral 0+ tier A info precision 0.655 window-recall 1.000 tp 262 fp 138+ tier B info precision 0.712 window-recall 0.714 tp 200 fp 81+ tier B warn precision 0.450 window-recall 0.714 tp 165 fp 202+ tier C error precision 0.020 window-recall 0.607 tp 98 fp 4850+ tier C info precision 0.439 window-recall 0.786 tp 76 fp 97+ stage cold_start precision 0.919 tp 34 fp 3+ stage developing precision 0.616 tp 45 fp 28+ stage mature precision 0.119 tp 722 fp 5337+ (46.9s)++ model: iqr+ verdicts 4184, fp/series/day 12.921+ issues/day median 51.0 p95 59.0, issue precision 0.112 (79/704)+ silence: windows 33/38 detected, fp persistent 1406, fp ephemeral 0+ tier A info precision 0.565 window-recall 1.000 tp 262 fp 202+ tier B info precision 0.663 window-recall 0.714 tp 201 fp 102+ tier B warn precision 0.419 window-recall 0.750 tp 167 fp 232+ tier C error precision 0.013 window-recall 0.464 tp 38 fp 2789+ tier C info precision 0.414 window-recall 0.786 tp 79 fp 112+ stage cold_start precision 0.919 tp 34 fp 3+ stage developing precision 0.570 tp 45 fp 34+ stage mature precision 0.164 tp 668 fp 3400+ (50.4s)++ model: negative_binomial (with severity widening)+ verdicts 2448, fp/series/day 6.586+ issues/day median 21.5 p95 25.7, issue precision 0.251 (74/295)+ silence: windows 34/38 detected, fp persistent 1581, fp ephemeral 0+ tier A info precision 0.614 window-recall 1.000 tp 264 fp 166+ tier B info precision 0.782 window-recall 0.743 tp 186 fp 52+ tier B warn precision 0.479 window-recall 0.714 tp 148 fp 161+ tier C error precision 0.023 window-recall 0.214 tp 30 fp 1300+ tier C info precision 0.482 window-recall 0.786 tp 68 fp 73+ stage cold_start precision 0.917 tp 33 fp 3+ stage developing precision 0.661 tp 37 fp 19+ stage mature precision 0.266 tp 626 fp 1730++```++## Band calibration sweep (clean NB data; calibrated ~= 2\*alpha = 3.5e-04)++```text+ poisson+ cv=0.12 lam= 1: 0.0000 lam= 10: 0.0000 lam= 100: 0.0020 lam= 1000: 0.3560 lam= 10000: 0.7800+ cv=0.5 lam= 1: 0.0000 lam= 10: 0.0220 lam= 100: 0.4760 lam= 1000: 0.8300 lam= 10000: 0.9580+ cv=2.2 lam= 1: 0.0240 lam= 10: 0.1960 lam= 100: 0.5740 lam= 1000: 0.7780 lam= 10000: 0.8780+ negative_binomial+ cv=0.12 lam= 1: 0.0000 lam= 10: 0.0000 lam= 100: 0.0000 lam= 1000: 0.0020 lam= 10000: 0.0000+ cv=0.5 lam= 1: 0.0000 lam= 10: 0.0000 lam= 100: 0.0000 lam= 1000: 0.0060 lam= 10000: 0.0020+ cv=2.2 lam= 1: 0.0020 lam= 10: 0.0020 lam= 100: 0.0040 lam= 1000: 0.0000 lam= 10000: 0.0020+ mad+ cv=0.12 lam= 1: 0.0380 lam= 10: 0.0020 lam= 100: 0.0060 lam= 1000: 0.0060 lam= 10000: 0.0080+ cv=0.5 lam= 1: 0.0340 lam= 10: 0.0140 lam= 100: 0.0040 lam= 1000: 0.0140 lam= 10000: 0.0220+ cv=2.2 lam= 1: 0.3080 lam= 10: 0.3300 lam= 100: 0.2840 lam= 1000: 0.2640 lam= 10000: 0.2860+ zscore+ cv=0.12 lam= 1: 0.0060 lam= 10: 0.0040 lam= 100: 0.0020 lam= 1000: 0.0020 lam= 10000: 0.0020+ cv=0.5 lam= 1: 0.0040 lam= 10: 0.0020 lam= 100: 0.0020 lam= 1000: 0.0080 lam= 10000: 0.0120+ cv=2.2 lam= 1: 0.0160 lam= 10: 0.0300 lam= 100: 0.0240 lam= 1000: 0.0300 lam= 10000: 0.0240+ iqr+ cv=0.12 lam= 1: 0.0100 lam= 10: 0.0060 lam= 100: 0.0080 lam= 1000: 0.0020 lam= 10000: 0.0060+ cv=0.5 lam= 1: 0.0120 lam= 10: 0.0100 lam= 100: 0.0020 lam= 1000: 0.0080 lam= 10000: 0.0220+ cv=2.2 lam= 1: 0.1200 lam= 10: 0.1200 lam= 100: 0.1320 lam= 1000: 0.1160 lam= 10000: 0.1320+```++## Persistence gate ablation (negative_binomial)++```text+ full design silence fp ephemeral 0, persistent 1578, opens/day median 22.5+ no persistence gate silence fp ephemeral 134, persistent 1578, opens/day median 22.5+ naive (no gate, 1h history) silence fp ephemeral 0, persistent 1176, opens/day median 21.0+```++## Level shift re-baselining (permanent shift, 5 weeks runway)++```text+ x2 passive (exclusion cap) 2.6 days (402 verdicts)+ x2 stability test (12 buckets) 0.0 days (12 verdicts)+ x4 passive (exclusion cap) still firing at run end (7810 verdicts)+ x4 stability test (12 buckets) 0.0 days (12 verdicts)+```diff --git a/products/apm/backend/tests/test_anomaly_bands.py b/products/apm/backend/tests/test_anomaly_bands.pyindex 6598e4de8e61..a401422935dc 100644--- a/products/apm/backend/tests/test_anomaly_bands.py+++ b/products/apm/backend/tests/test_anomaly_bands.py@@ -1,5 +1,6 @@import numpy as npfrom parameterized import parameterized+from scipy import statsfrom products.apm.backend.logic.anomaly_detection.bands import (IQRBandModel,@@ -36,13 +37,19 @@ class TestCountBands:band = ZScoreBandModel().compute(samples, 5.0, ALPHA)assert band.lower < 0.0- def test_negative_binomial_inflates_band_for_overdispersed_samples(self) -> None:+ @parameterized.expand([(2.0,), (4.0,)])+ def test_negative_binomial_inflates_band_for_overdispersed_samples(self, shape: float) -> None:mu = 50.0- overdispersed = make_rng().negative_binomial(2, 2 / (2 + mu), size=200).astype(float)+ probability = shape / (shape + mu)+ overdispersed = make_rng().negative_binomial(shape, probability, size=200).astype(float)nb_band = NegativeBinomialBandModel().compute(overdispersed, mu, ALPHA)poisson_band = PoissonBandModel().compute(overdispersed, mu, ALPHA)assert nb_band.upper > poisson_band.upperassert nb_band.lower <= poisson_band.lower+ false_positive_probability = stats.nbinom.cdf(nb_band.lower - 1, shape, probability) + stats.nbinom.sf(+ nb_band.upper, shape, probability+ )+ assert false_positive_probability < 0.005def test_negative_binomial_falls_back_to_poisson_when_not_overdispersed(self) -> None:samples = np.full(40, 100.0)@@ -51,6 +58,44 @@ class TestCountBands:assert nb_band.lower == poisson_band.lowerassert nb_band.upper == poisson_band.upper+ @parameterized.expand([(6,), (9,), (15,)])+ def test_negative_binomial_one_outlier_does_not_collapse_the_band(self, sample_count: int) -> None:+ samples = np.append(np.full(sample_count - 1, 10.0), 10000.0)+ band = NegativeBinomialBandModel().compute(samples, 10.0, ALPHA)+ assert band.lower < 10.0 < band.upper+ assert band.expected == 10.0+ assert band.upper < 30.0++ def test_batched_negative_binomial_bands_match_individual_bands(self) -> None:+ samples = [+ np.zeros(6),+ np.full(9, 100.0),+ np.append(np.full(5, 10.0), 10000.0),+ make_rng().negative_binomial(2, 0.04, size=40).astype(float),+ ]+ model = NegativeBinomialBandModel(rate_floor=12.0)+ assert model.compute_many(samples, ALPHA) == [model.compute(sample, 0.0, ALPHA) for sample in samples]+ assert model.compute_many([], ALPHA) == []++ def test_intermittent_baseline_keeps_robust_silence_expectation(self) -> None:+ samples = np.concatenate((np.zeros(90), np.full(10, 100.0)))+ model = NegativeBinomialBandModel()+ band = model.compute(samples, 0.0, ALPHA)+ assert band.expected == 0.0+ assert band.lower == 0.0+ assert band.upper > 100.0+ assert model.compute_many([samples], ALPHA) == [band]++ def test_overdispersed_baseline_keeps_its_upper_tail(self) -> None:+ samples = np.array([5.0, 10.0, 20.0, 40.0, 80.0, 1000.0])+ mean = float(np.mean(samples))+ variance = float(np.var(samples, ddof=1))+ shape = mean**2 / (variance - mean)+ probability = shape / (shape + mean)+ band = NegativeBinomialBandModel().compute(samples, 100.0, ALPHA)+ assert band.upper == stats.nbinom.ppf(1.0 - ALPHA, shape, probability)+ assert band.expected == mean+def test_flat_baseline_still_produces_nonzero_width_band(self) -> None:samples = np.full(40, 20.0)band = NegativeBinomialBandModel().compute(samples, 20.0, ALPHA)diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.pyindex 58a7ee30e45d..8408176fd260 100644--- a/products/logs/backend/presentation/views/anomalies_api.py+++ b/products/logs/backend/presentation/views/anomalies_api.py@@ -29,7 +29,6 @@ from products.logs.backend.series_bands import (MAX_BUCKETS_PER_SERIES,MAX_WINDOW_DAYS,MAX_WINDOW_START_AGE_DAYS,- MIN_BASELINE_WEEKS_FOR_BAND,MIN_MEAN_PER_ALIVE_BUCKET,SeriesBandsFetchTruncated,SeriesBandsWindowInvalid,@@ -271,11 +270,11 @@ 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 the series has too little history to band.",+ help_text="Lower edge of the expected band. Null while no validated band is available for this series.",)upper = serializers.FloatField(allow_null=True,- help_text="Upper edge of the expected band. Null while the series has too little history to band.",+ help_text="Upper edge of the expected band. Null while no validated band is available for this series.",)verdict = serializers.ChoiceField(choices=LogsSeriesBandVerdict.choices,@@ -301,7 +300,7 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):baseline_weeks = serializers.IntegerField(help_text=(f"Full weeks of history behind the band, 0 to {BASELINE_WEEKS}. "- f"Below {MIN_BASELINE_WEEKS_FOR_BAND} the series is still learning and its buckets carry no band."+ "History depth alone does not enable a band; a validated readiness policy is also required."))history_start = serializers.DateTimeField(@@ -314,7 +313,9 @@ class LogsSeriesBandSeriesSerializer(serializers.Serializer):band_ready_at = serializers.DateTimeField(allow_null=True,help_text=(- "When this series gains its band, so a learning series can count down to it. Null once the band is drawn."+ "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."),)interval_minutes = serializers.IntegerField(diff --git a/products/logs/backend/series_bands.py b/products/logs/backend/series_bands.pyindex c4c542ac1719..39fdded34d4b 100644--- a/products/logs/backend/series_bands.py+++ b/products/logs/backend/series_bands.py@@ -1,12 +1,20 @@"""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 a-time-of-week aligned min/max envelope over the BASELINE_WEEKS weeks before the-window: each display slot's band comes-from the same weekly slot in prior weeks. ClickHouse folds the baseline weeks-onto the display window; Python finishes the envelope (zero-fill, maturity-gating, widening) where the arithmetic is cheap and unit-testable.+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."""import os@@ -18,6 +26,8 @@ from dataclasses import replacefrom typing import Literalfrom zoneinfo import ZoneInfo+import numpy as np+from posthog.schema import HogQLQueryModifiersfrom posthog.hogql import ast@@ -31,6 +41,8 @@ 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+WINDOW_DAYS = 7MAX_WINDOW_DAYS = 7VOLUME_BUCKETS_TTL_DAYS = 42 # TTL on logs_volume_buckets, see posthog/clickhouse/hcl/sql/*/logs.sql@@ -40,8 +52,7 @@ 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-# Below this many full prior weeks the band rests on too little history to draw.-MIN_BASELINE_WEEKS_FOR_BAND = 2+VALIDATED_BASELINE_WEEKS_FOR_BAND: int | None = NoneSECONDS_PER_DAY = 24 * 3600SECONDS_PER_WEEK = 7 * SECONDS_PER_DAY@@ -61,14 +72,11 @@ BUCKET_TARGET = int(os.environ.get("LOGS_SERIES_BANDS_BUCKET_TARGET", "168"))ALIVE_SLOT_FRACTION = float(os.environ.get("LOGS_SERIES_BANDS_ALIVE_SLOT_FRACTION", "0.2"))# A series keeps a grain only where it is dense enough to read there: at least# ALIVE_SLOT_FRACTION of its window buckets are non-empty, and those buckets-# average at least this many records. Below that the band floor, which scales-# with the grain, sits under most observed values and nearly every bucket marks.+# 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"))-# 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.-BAND_WIDEN_FRACTION = 0.1-BAND_FLOOR_PER_HOUR = 2.0+# 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@@ -148,9 +156,8 @@ class _SeriesKey:class _SlotRow:target_time: dt.datetimeobserved: int- baseline_samples: int- baseline_min: int- baseline_max: int+ # (unix seconds, count) per lifetime baseline bucket that folds onto target_time.+ baseline: list[tuple[int, int]]@frozen@@ -178,9 +185,9 @@ def fetch_series_slot_rows(start.Rows are sparse — a (series, slot) with no observed and no baseline data has- no row. Missing baseline weeks are reconstructed in Python from- baseline_samples vs the weeks the series existed. Baseline samples only- count slots at or after the lifetime start. With series_keys the pass reads+ no row. Missing baseline weeks are reconstructed in Python from the baseline+ samples present vs the weeks the series existed. Baseline samples only+ include slots at or after the lifetime start. With series_keys the pass readsonly those series and skips the volume ranking."""tag_queries(product=Product.LOGS, feature=Feature.QUERY, source="logs_series_bands", team_id=str(team.id))@@ -266,9 +273,10 @@ def fetch_series_slot_rows((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,+ groupArrayIf(+ tuple(toUnixTimestamp(slots.slot), slots.slot_count),+ slots.slot < {window_start} AND slots.slot >= lifetimes.lifetime_start+ ) AS baseline,lifetimes.lifetime_start AS lifetime_startFROM slotsINNER JOIN lifetimes@@ -315,14 +323,12 @@ def fetch_series_slot_rows(key = _SeriesKey(namespace=row[0], environment=row[1], severity=row[2])series = rows.get(key)if series is None:- series = rows[key] = _SeriesRows(lifetime_start=ensure_utc(row[8]), slots=[])+ series = rows[key] = _SeriesRows(lifetime_start=ensure_utc(row[6]), 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]),+ baseline=[(int(ts), int(count)) for ts, count in row[5]],))return rows@@ -336,14 +342,22 @@ def _baseline_weeks_available(later: dt.datetime, lifetime_start: dt.datetime) -whose sample slot predates the lifetime says nothing; a week inside thelifetime with no row was a real zero."""- weeks = int((later - lifetime_start).total_seconds()) // SECONDS_PER_WEEK- return min(BASELINE_WEEKS, max(0, weeks))+ return _weeks_between(int(later.timestamp()), int(lifetime_start.timestamp()))+++def _weeks_between(later_ts: int, lifetime_ts: int) -> int:+ return min(BASELINE_WEEKS, max(0, (later_ts - lifetime_ts) // SECONDS_PER_WEEK))+++@frozen+class _BandReadiness:+ baseline_weeks: int+ ready: bool+ ready_at: dt.datetime | None-def _band_gate(- 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.+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.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@@ -351,10 +365,95 @@ def _band_gate(counts to."""baseline_weeks = _baseline_weeks_available(window_start, lifetime_start)- if baseline_weeks >= MIN_BASELINE_WEEKS_FOR_BAND:- return baseline_weeks, None- threshold = lifetime_start + dt.timedelta(weeks=MIN_BASELINE_WEEKS_FOR_BAND)- return baseline_weeks, threshold + (window_end - window_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:+ return _BandReadiness(baseline_weeks=baseline_weeks, ready=True, ready_at=None)+ threshold = lifetime_start + dt.timedelta(weeks=VALIDATED_BASELINE_WEEKS_FOR_BAND)+ 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.+ """++ def __init__(+ self,+ series_rows: _SeriesRows,+ window_start: dt.datetime,+ window_end: dt.datetime,+ interval_minutes: int,+ detection: DetectionConfig,+ ):+ self.detection = detection+ self.step_seconds = interval_minutes * 60+ self.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.observed+ for 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++ 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 _build_series(@@ -363,45 +462,54 @@ def _build_series(window_start: dt.datetime,window_end: dt.datetime,interval_minutes: int,+ detection: DetectionConfig,+ *,+ include_bands: bool = True,) -> BandSeries:- by_time = {row.target_time: row for row in series_rows.slots}+ history = _FoldedHistory(series_rows, window_start, window_end, interval_minutes, detection)lifetime_start = series_rows.lifetime_start- baseline_weeks, band_ready_at = _band_gate(window_start, window_end, lifetime_start)- banded = band_ready_at is None- floor = BAND_FLOOR_PER_HOUR * interval_minutes / 60+ readiness = _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 * grainbuckets: list[BandBucket] = []+ baseline_samples: list[np.ndarray] = []total_count = 0step = dt.timedelta(minutes=interval_minutes)slot = window_startwhile slot < window_end:- row = by_time.get(slot)- observed = row.observed if row else 0+ slot_ts = int(slot.timestamp())+ observed = history.observed(slot_ts)total_count += observed- lower: float | None = None- upper: float | None = Noneif 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, 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.- low = row.baseline_min if row and samples >= expected else 0- high = row.baseline_max if row else 0- lower = low * (1 - BAND_WIDEN_FRACTION)- upper = high * (1 + BAND_WIDEN_FRACTION) + floor- buckets.append(BandBucket(time=slot, observed=observed, lower=lower, upper=upper))+ 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 += step+ if banded:+ 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)+ ]+return BandSeries(namespace=key.namespace,environment=key.environment,severity=key.severity,total_count=total_count,- baseline_weeks=baseline_weeks,+ baseline_weeks=readiness.baseline_weeks,history_start=lifetime_start,- band_ready_at=band_ready_at,+ band_ready_at=readiness.ready_at,interval_minutes=interval_minutes,coarsened_reason=None,buckets=buckets,@@ -435,6 +543,8 @@ 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 ladderto the first rung where it is dense enough, or to the top rung.@@ -480,8 +590,10 @@ def _coarsen_sparse_series(settled.append(fallback)continuecandidate = replace(- _build_series(key, rows[key], rung_start, rung_end, rung), coarsened_reason=fallback.coarsened_reason+ _build_series(key, rows[key], rung_start, rung_end, rung, detection, include_bands=False),+ coarsened_reason=fallback.coarsened_reason,)+ slot_rows[key] = rows[key]if _density_shortfall(candidate) is None:settled.append(candidate)else:@@ -584,18 +696,44 @@ 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)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) for key, rows in slot_rows.items()]+ series = [+ _build_series(key, rows, window_start, window_end, interval_minutes, detection, include_bands=False)+ for key, rows in slot_rows.items()+ ]series.sort(key=lambda s: (-s.total_count, s.namespace, s.environment, s.severity))series_truncated = len(series) > MAX_SERIESseries = _coarsen_sparse_series(- team, service_name, series[:MAX_SERIES], window_start, window_end, interval_minutes, deadline+ team,+ service_name,+ series[:MAX_SERIES],+ window_start,+ window_end,+ interval_minutes,+ deadline,+ detection,+ slot_rows,)+ series = [+ replace(+ _build_series(+ _series_key(candidate),+ slot_rows[_series_key(candidate)],+ 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,+ )+ for candidate in series+ ]series.sort(key=lambda s: (-s.total_count, s.namespace, s.environment, s.severity))return SeriesBandsResult(diff --git a/products/logs/backend/test/test_series_bands.py b/products/logs/backend/test/test_series_bands.pyindex d292ec83ac31..ebf257c8b1e2 100644--- a/products/logs/backend/test/test_series_bands.py+++ b/products/logs/backend/test/test_series_bands.py@@ -1,4 +1,5 @@import datetime as dt+from dataclasses import replaceimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin@@ -36,6 +37,17 @@ 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(@@ -63,11 +75,13 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):@parameterized.expand([- # (name, interval_minutes, window_days, banded_upper, quiet_upper, drop_upper)- # Hourly: floor of 2 per hour lifts the upper edge; 15 minutes gets a quarter of it.- # The finer grain charts 5 days, because 7 days of 15 minute buckets is over the cap.- ("hourly", 60, 7, 57.0, 2.0, 112.0),- ("quarter_hour", 15, 5, 55.5, 0.5, 110.5),+ # (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),])def test_observed_line_and_band_from_prior_weeks(@@ -75,8 +89,10 @@ 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}"@@ -88,18 +104,20 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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):+ for week, value in enumerate([100, 200, 300, 400, 500], start=1):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))- # A slot with no weekly samples bands at [0, floor]; anything above the floor is a spike.- rows.append((self.team.pk, slot + dt.timedelta(hours=2), service, "ns", "prod", "error", 5))- # A slot whose every weekly sample is 100 bands well above zero, so a near-empty bucket is a drop.+ rows.append((self.team.pk, slot, service, "ns", "prod", "error", 50))+ rows.append((self.team.pk, slot, service, "ns", "prod", "error", 50))+ rows.append((self.team.pk, slot + dt.timedelta(minutes=5), service, "ns", "prod", "error", 150))+ # A slot with no weekly samples bands at [0, the rate floor's quantile]; a+ # burst well above that is a spike, and the zero lower edge means a quiet+ # bucket there is never a drop.+ rows.append((self.team.pk, slot + dt.timedelta(hours=2), service, "ns", "prod", "error", 500))+ # A slot whose every weekly sample is 1000 bands well above zero, so a near-empty bucket is a drop.for week in range(1, 6):- rows.append((self.team.pk, slot + dt.timedelta(hours=3, weeks=-week), service, "ns", "prod", "error", 100))- rows.append((self.team.pk, slot + dt.timedelta(hours=3), service, "ns", "prod", "error", 1))+ rows.append((self.team.pk, slot + dt.timedelta(hours=3, weeks=-week), service, "ns", "prod", "error", 1000))+ rows.append((self.team.pk, slot + dt.timedelta(hours=3), service, "ns", "prod", "error", 10))# Steady traffic in every other bucket keeps the series dense at the grain.bucket_count = window_days * 24 * 60 // interval_minutescharted = (slot, slot + step, slot + dt.timedelta(hours=2), slot + dt.timedelta(hours=3))@@ -114,7 +132,12 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):self._insert(rows)result = run_series_bands(- self.team, service, window_start=window_start, window_end=WINDOW_END, interval_minutes=interval_minutes+ self.team,+ service,+ window_start=window_start,+ window_end=WINDOW_END,+ interval_minutes=interval_minutes,+ detection=_detection(pooling=False, level=False),)assert result.window_start == window_start@@ -128,31 +151,32 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):assert series.band_ready_at is Noneassert series.interval_minutes == interval_minutesassert series.coarsened_reason is None- assert series.total_count == 31 + 10 * (bucket_count - 4)+ assert series.total_count == 760 + 10 * (bucket_count - 4)assert [bucket.time for bucket in series.buckets] == [window_start + i * step for i in range(bucket_count)]by_time = {bucket.time: bucket for bucket in series.buckets}- # Band folds the five weekly samples 10..50 into a 10% widened envelope,- # then lifts the upper edge by the per-hour floor scaled to the grain.+ # The band is the negative binomial fitted to the five weekly samples 100..500.banded = by_time[slot]- assert banded.observed == 25- assert banded.lower == pytest.approx(9.0)+ assert banded.observed == 250+ assert banded.lower == pytest.approx(banded_lower)assert banded.upper == pytest.approx(banded_upper)assert banded.verdict is Nonequiet = by_time[slot + step]assert quiet.observed == 0assert quiet.lower == 0- assert quiet.upper == quiet_upper+ assert quiet.upper == pytest.approx(quiet_upper)assert quiet.verdict is Nonespike = by_time[slot + dt.timedelta(hours=2)]- assert (spike.observed, spike.lower, spike.upper) == (5, 0, quiet_upper)+ assert spike.observed == 500+ assert spike.lower == 0+ assert spike.upper == pytest.approx(quiet_upper)assert spike.verdict == "above"drop = by_time[slot + dt.timedelta(hours=3)]- assert drop.observed == 1- assert drop.lower == pytest.approx(90.0)+ assert drop.observed == 10+ assert drop.lower == pytest.approx(drop_lower)assert drop.upper == pytest.approx(drop_upper)assert drop.verdict == "below"@@ -297,7 +321,7 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):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)+ rows += self._slots(service, sustained_from, 4 * 7 * 24, 900)self._insert(rows)result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)@@ -306,14 +330,15 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):assert series.history_start == sustained_fromassert series.baseline_weeks == 3assert 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.+ # 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(8.1)- assert first.upper == pytest.approx(11.9)+ assert first.lower == pytest.approx(815.0)+ assert first.upper == pytest.approx(987.0)assert all(- bucket.observed == 9+ bucket.observed == 900and bucket.lower is not Noneand bucket.upper is not Noneand bucket.lower <= bucket.observed <= bucket.upper@@ -322,36 +347,123 @@ class TestSeriesBands(ClickhouseTestMixin, BaseTest):def test_silent_window_marks_below_the_band(self):service = "svc-silent"- self._insert(self._slots(service, BASELINE_START, 5 * 7 * 24, 9))+ self._insert(self._slots(service, BASELINE_START, 5 * 7 * 24, 900))result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)series = result.series[0]assert series.baseline_weeks == 5assert series.total_count == 0- assert all(bucket.observed == 0 and bucket.lower == pytest.approx(8.1) for bucket in series.buckets)+ # The level component reads the silent days as a lower level, but the+ # 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):+ service = "svc-pooled"+ rows = self._slots(service, BASELINE_START, ALIVE_HOURS, 1)+ for week in range(1, 6):+ rows.append((self.team.pk, SLOT - dt.timedelta(weeks=week), service, "ns", "prod", "error", 100))+ for neighbour in (SLOT - dt.timedelta(hours=1), SLOT + dt.timedelta(hours=1)):+ rows.append((self.team.pk, neighbour - dt.timedelta(weeks=week), service, "ns", "prod", "error", 400))+ rows.append((self.team.pk, SLOT, service, "ns", "prod", "error", 400))+ self._insert(rows)++ result = run_series_bands(+ self.team,+ 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 == 400+ assert 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++ @parameterized.expand([(2,), (3,), (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)+ rows = self._slots(service, history_start, (weeks + 1) * 7 * 24, 100)+ rows.append((self.team.pk, SLOT - dt.timedelta(weeks=1), service, "ns", "prod", "error", 100000))+ self._insert(rows)++ result = run_series_bands(+ self.team,+ service,+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ detection=_detection(pooling=True, level=False),+ )- def test_band_ready_at_is_when_the_gate_opens(self):+ 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.verdict is None++ def test_level_shift_recentres_the_band_within_the_window(self):+ service = "svc-level"+ rows = self._slots(service, BASELINE_START, 5 * 7 * 24, 1000)+ rows += self._slots(service, WINDOW_START, 7 * 24, 600)+ self._insert(rows)++ 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 == 600+ assert 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++ @parameterized.expand([(2,), (4,)])+ def test_band_ready_at_is_when_the_gate_opens(self, validated_weeks: int):earliest = WINDOW_START - dt.timedelta(weeks=1)- _, ready_at = _band_gate(WINDOW_START, WINDOW_END, earliest)+ with patch.object(series_bands, "VALIDATED_BASELINE_WEEKS_FOR_BAND", validated_weeks):+ readiness = _band_gate(WINDOW_START, WINDOW_END, earliest)- assert ready_at is not None- window = WINDOW_END - WINDOW_START- assert _band_gate(ready_at - window, ready_at, earliest)[1] is None+ 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- def test_missing_baseline_week_drags_floor_to_zero(self):+ def test_missing_baseline_week_counts_as_a_zero_sample(self):service = "svc-gappy"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)- result = run_series_bands(self.team, service, window_start=WINDOW_START, window_end=WINDOW_END)+ result = run_series_bands(+ self.team,+ service,+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ 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(134.0)+ assert bucket.upper == pytest.approx(368.0)def test_series_ordered_by_observed_volume(self):service = "svc-ordered"@@ -391,6 +503,32 @@ 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:+ history_start = WINDOW_START - dt.timedelta(weeks=weeks)+ rows = series_bands._SeriesRows(+ lifetime_start=history_start,+ slots=[series_bands._SlotRow(target_time=WINDOW_START, observed=100, baseline=[])],+ )+ 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)++ assert result.baseline_weeks == weeks+ assert result.history_start == history_start+ assert result.band_ready_at is None+ assert result.total_count == 100+ assert 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+ )+ 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++class TestResolveWindow(SimpleTestCase):def _resolve(self, date_from: str | None, date_to: str | None, interval_minutes: int | None = 60diff --git a/products/logs/frontend/LogsAnomalies.test.ts b/products/logs/frontend/LogsAnomalies.test.tsindex b6c91d73fcfe..95c106713585 100644--- a/products/logs/frontend/LogsAnomalies.test.ts+++ b/products/logs/frontend/LogsAnomalies.test.ts@@ -7,11 +7,12 @@ 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'],- ])('rounds a wait ending %s up to whole days', (bandReadyAt, expected) => {+ ])('formats readiness %s as %s', (bandReadyAt, expected) => {expect(learningBaselineLabel(bandReadyAt, WINDOW_END)).toBe(expected)})diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsxindex d37664f743b8..3fe518fb055e 100644--- a/products/logs/frontend/LogsAnomalies.tsx+++ b/products/logs/frontend/LogsAnomalies.tsx@@ -71,7 +71,7 @@ function SeriesBands(): JSX.Element {return (<EmptyMessagetitle="Log volume by series"- description="See a week of log volume for each series a service emits, with the expected range learned from previous weeks. Choose a service to start."+ description="See a week of log volume for each series a service emits. Choose a service to start."/>)}@@ -110,8 +110,13 @@ function SeriesBands(): JSX.Element {<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{' '}- {formatWindowBound(seriesBands.window_end)}, against the range seen at the same time of week in the- previous weeks. Marked points fell outside that range. Click a bucket to read its logs.+ {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.'}{' '}+ Click a bucket to read its logs.</div>{seriesBands.series_truncated ? (<div data-attr="logs-anomalies-truncated">@@ -136,7 +141,10 @@ function SeriesBands(): JSX.Element {)}-export function learningBaselineLabel(bandReadyAt: string, windowEnd: string): string {+export function learningBaselineLabel(bandReadyAt: string | null, windowEnd: string): string {+ if (bandReadyAt === null) {+ return 'Expected range unavailable'+ }// 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'}`@@ -162,17 +170,20 @@ const SeriesCard = memo(function SeriesCard({const { openLogsForBucket } = useActions(logsAnomaliesLogic)// The backend dates the wait, so its history threshold stays out of here and the two cannot drift.const bandReadyAt = series.band_ready_at+ const hasBand = series.buckets.some((bucket) => bucket.lower !== null && bucket.upper !== null)return (<div className="rounded border bg-surface-primary p-3" data-attr="logs-anomalies-series"><div className="mb-2 flex items-center gap-2"><LogTag level={series.severity as LogMessage['severity_text']} />{series.namespace ? <LemonTag>{series.namespace}</LemonTag> : null}{series.environment ? <LemonTag>{series.environment}</LemonTag> : null}- {bandReadyAt ? (+ {bandReadyAt || !hasBand ? (<Tooltip- title={`First seen ${formatDay(series.history_start)}. The expected range starts ${formatDay(+ title={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.'+ }><LemonTag type="caution">{learningBaselineLabel(bandReadyAt, windowEnd)}</LemonTag></Tooltip>diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex c1fe8df18a8f..472546c558eb 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1359,12 +1359,12 @@ export interface LogsSeriesBandBucketApi {/** Log count observed in this bucket. */observed: number/**- * Lower edge of the expected band. Null while the series has too little history to band.+ * Lower edge of the expected band. Null while no validated band is available for this series.* @nullable*/lower: number | null/**- * Upper edge of the expected band. Null while the series has too little history to band.+ * Upper edge of the expected band. Null while no validated band is available for this series.* @nullable*/upper: number | null@@ -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. Below 2 the series is still learning and its buckets carry no band. */+ /** 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. */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, so a learning series can count down to it. Null once the band is drawn.+ * 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.* @nullable*/band_ready_at: string | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6848c7481ece..75402b604faa 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53528,12 +53528,12 @@ export namespace Schemas {/** Log count observed in this bucket. */observed: number;/**- * Lower edge of the expected band. Null while the series has too little history to band.+ * Lower edge of the expected band. Null while no validated band is available for this series.* @nullable*/lower: number | null;/**- * Upper edge of the expected band. Null while the series has too little history to band.+ * Upper edge of the expected band. Null while no validated band is available for this series.* @nullable*/upper: number | null;@@ -53553,12 +53553,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. Below 2 the series is still learning and its buckets carry no band. */+ /** 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. */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, so a learning series can count down to it. Null once the band is drawn.+ * 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.* @nullable*/band_ready_at: string | null;