:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(apm): add log anomaly detector core and validation harness (#77275)
Jon McCallum5812ca6de6ec
diff --git a/products/apm/backend/logic/anomaly_detection/__init__.py b/products/apm/backend/logic/anomaly_detection/__init__.pynew file mode 100644index 000000000000..23914868f6a4--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/__init__.py@@ -0,0 +1,24 @@+"""Zero-config log volume anomaly detection — pure detector core.++Everything in this package is a pure function over counts: no ClickHouse,+Temporal, or Django imports. The aggregation layer feeds it rollup counts;+the filing layer persists its verdicts. This separation is what lets the+validation harness (validation/) exercise the risky band math in-process.+"""++from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.detector import evaluate_series_bucket, evaluate_tick+from products.apm.backend.logic.anomaly_detection.issues import IssueSnapshot, evaluate_issue_transition+from products.apm.backend.logic.anomaly_detection.types import BucketVerdict, SeriesHistory, SeriesKey, VerdictType++__all__ = [+ "BucketVerdict",+ "DetectionConfig",+ "IssueSnapshot",+ "SeriesHistory",+ "SeriesKey",+ "VerdictType",+ "evaluate_issue_transition",+ "evaluate_series_bucket",+ "evaluate_tick",+]diff --git a/products/apm/backend/logic/anomaly_detection/bands.py b/products/apm/backend/logic/anomaly_detection/bands.pynew file mode 100644index 000000000000..97e3bdec0053--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/bands.py@@ -0,0 +1,168 @@+"""Candidate band models for the bake-off.++All models share one decision semantics: given baseline samples and a per-side+alpha, produce a ``Band``; the detector flags observed counts outside the+(possibly widened) band. That keeps the comparison apples-to-apples — same+alpha budget, same widening — while the models differ in how they estimate+dispersion and shape:++* ``poisson`` / ``negative_binomial`` are new count-aware asymmetric bands.+ They are not in the alerts detector registry; the recorded reason for fresh+ code is that count-aware asymmetric bands are locked architecturally and no+ registry scorer models counts (symmetric bands go negative at low rates,+ making drops undetectable).+* ``mad`` / ``zscore`` / ``iqr`` reuse the alerts detector registry scorers:+ the registry detector is fitted on the baseline samples and the band is read+ off its fitted statistics at the equivalent normal quantile.+"""++from __future__ import annotations++from typing import Protocol++import numpy as np+from scipy import stats++from products.apm.backend.logic.anomaly_detection.types import Band++TRIM_FRACTION = 0.1+# Modified z-score scale: MAD of a normal distribution is 0.6745 sigma.+MAD_TO_SIGMA = 0.6745+# Under normality, IQR = 1.349 sigma and Q1 sits at -0.674 sigma.+NORMAL_IQR_IN_SIGMA = 1.349+NORMAL_Q1_IN_SIGMA = 0.674+TUKEY_FENCE_K = 1.5+# Sample variance within this ratio of the mean counts as "not overdispersed".+OVERDISPERSION_TOLERANCE = 1.001+++class BandModel(Protocol):+ name: str++ def compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band: ...+++def widen(band: Band, factor: float) -> Band:+ if factor == 1.0:+ return band+ lower = band.expected - (band.expected - band.lower) * factor+ upper = band.expected + (band.upper - band.expected) * factor+ return Band(lower=max(lower, 0.0), upper=upper, expected=band.expected)+++def _robust_rate(samples: np.ndarray) -> float:+ return float(stats.trim_mean(samples, TRIM_FRACTION)) if samples.size >= 3 else float(np.mean(samples))+++def _poisson_interval(mu: float, alpha: float) -> tuple[float, float]:+ return float(stats.poisson.ppf(alpha, mu)), float(stats.poisson.ppf(1.0 - alpha, mu))+++class PoissonBandModel:+ name = "poisson"++ def __init__(self, rate_floor: float = 1.0) -> None:+ self.rate_floor = rate_floor++ def compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band:+ mu = _robust_rate(samples)+ lower, upper = _poisson_interval(max(mu, self.rate_floor), alpha)+ return Band(lower=lower, upper=upper, expected=mu)+++class NegativeBinomialBandModel:+ """Poisson band inflated to the measured sample dispersion.++ Falls back to the Poisson band when the samples are not overdispersed —+ Poisson is the tightest band a count series is allowed.+ """++ name = "negative_binomial"++ def __init__(self, rate_floor: float = 1.0, dispersion_floor: float = 1.0) -> None:+ self.rate_floor = rate_floor+ self.dispersion_floor = dispersion_floor++ def 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:+ lower, upper = _poisson_interval(mu_eff, alpha)+ else:+ r = mu_eff**2 / (var - 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)+++class _RegistryBandModel:+ """Base for models that reuse an alerts detector registry scorer."""++ name: str+ detector_type: str # a posthog.schema.DetectorType value++ def _fit_metadata(self, samples: np.ndarray, observed: float) -> dict[str, float]:+ # noqa comment applies to the import chain, not laziness for its own+ # sake: posthog.tasks.__init__ imports Django models, so a module-level+ # import would make this whole package require django.setup() — the+ # detector must stay importable with no infra.+ from posthog.tasks.alerts.detectors.registry import get_detector # noqa: PLC0415++ detector = get_detector({"type": self.detector_type, "window": int(samples.size)})+ result = detector.detect(np.append(samples.astype(float), observed))+ return result.metadata+++class MADBandModel(_RegistryBandModel):+ name = "mad"+ detector_type = "mad"++ def compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band:+ meta = self._fit_metadata(samples, observed)+ median = meta["median"]+ mad = meta["median_abs_deviation"]+ k = float(stats.norm.ppf(1.0 - alpha))+ half_width = k * mad / MAD_TO_SIGMA+ return Band(lower=median - half_width, upper=median + half_width, expected=median)+++class ZScoreBandModel(_RegistryBandModel):+ name = "zscore"+ detector_type = "zscore"++ def compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band:+ meta = self._fit_metadata(samples, observed)+ mean = meta["mean"]+ std = meta["std"]+ k = float(stats.norm.ppf(1.0 - alpha))+ return Band(lower=mean - k * std, upper=mean + k * std, expected=mean)+++class IQRBandModel(_RegistryBandModel):+ name = "iqr"+ detector_type = "iqr"++ def compute(self, samples: np.ndarray, observed: float, alpha: float) -> Band:+ meta = self._fit_metadata(samples, observed)+ q1, q3, iqr = meta["q1"], meta["q3"], meta["iqr"]+ # Fence multiplier equivalent to the per-side alpha under normality,+ # floored at Tukey's conventional fence.+ k = max(+ (float(stats.norm.ppf(1.0 - alpha)) - NORMAL_Q1_IN_SIGMA) / NORMAL_IQR_IN_SIGMA,+ TUKEY_FENCE_K,+ )+ expected = (q1 + q3) / 2.0+ return Band(lower=q1 - k * iqr, upper=q3 + k * iqr, expected=expected)+++def default_band_models(rate_floor: float = 1.0, dispersion_floor: float = 1.0) -> list[BandModel]:+ return [+ PoissonBandModel(rate_floor=rate_floor),+ NegativeBinomialBandModel(rate_floor=rate_floor, dispersion_floor=dispersion_floor),+ MADBandModel(),+ ZScoreBandModel(),+ IQRBandModel(),+ ]diff --git a/products/apm/backend/logic/anomaly_detection/baseline.py b/products/apm/backend/logic/anomaly_detection/baseline.pynew file mode 100644index 000000000000..187e262eecd9--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/baseline.py@@ -0,0 +1,211 @@+"""Staged baseline selection: which past buckets are comparable to the scored one.++An exact time-of-week slot has only 3 observations after 3 weeks, so weekly+seasonality cannot be the starting model — the stage ladder widens the match+criteria for young series and narrows them as history accumulates:++* cold start: same day-type (weekday/weekend), same time of day ± pool+* developing: same weekday, same time of day ± pool+* mature: same time of week ± a small pool, across up to 12 weeks++Buckets are on a fixed UTC grid; time-of-week matching maps through the+project timezone so cron- and business-hour-shaped seasonality lines up with+local clocks. DST shift weeks are flagged so the detector can widen bands+(explicit reduced-confidence policy rather than silent misalignment).+"""++from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime, timedelta+from zoneinfo import ZoneInfo++import numpy as np++from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKET_MINUTES, BUCKETS_PER_DAY, BUCKETS_PER_WEEK+from products.apm.backend.logic.anomaly_detection.types import BaselineStage, SeriesHistory++MINUTES_PER_DAY = 24 * 60+MINUTES_PER_WEEK = 7 * MINUTES_PER_DAY+++@dataclass(frozen=True, slots=True)+class TimeGrid:+ """Per-bucket local-time attributes, computed once per (grid_start, length, tz)+ and shared across every series on the same grid."""++ start: datetime+ minute_of_day: np.ndarray+ weekday: np.ndarray+ minute_of_week: np.ndarray+ utc_offset_minutes: np.ndarray++ @classmethod+ def build(cls, grid_start: datetime, length: int, tz: ZoneInfo) -> TimeGrid:+ minute_of_day = np.empty(length, dtype=np.int32)+ weekday = np.empty(length, dtype=np.int8)+ utc_offset = np.empty(length, dtype=np.int32)+ for i in range(length):+ local = (grid_start + timedelta(minutes=BUCKET_MINUTES * i)).astimezone(tz)+ minute_of_day[i] = local.hour * 60 + local.minute+ weekday[i] = local.weekday()+ offset = local.utcoffset()+ utc_offset[i] = int(offset.total_seconds() // 60) if offset is not None else 0+ minute_of_week = weekday.astype(np.int32) * MINUTES_PER_DAY + minute_of_day+ return cls(+ start=grid_start,+ minute_of_day=minute_of_day,+ weekday=weekday,+ minute_of_week=minute_of_week,+ utc_offset_minutes=utc_offset,+ )++ def is_dst_shift_week(self, index: int) -> bool:+ week_ago = index - BUCKETS_PER_WEEK+ if week_ago < 0:+ return False+ return bool(self.utc_offset_minutes[index] != self.utc_offset_minutes[week_ago])+++@dataclass(frozen=True, slots=True)+class BaselineResult:+ samples: np.ndarray+ stage: BaselineStage+ level_factor: float+ is_dst_shift_week: bool++ @property+ def scorable(self) -> bool:+ return self.stage is not BaselineStage.INSUFFICIENT+++def _circular_diff(values: np.ndarray, target: int, period: int) -> np.ndarray:+ diff = np.abs(values - target)+ return np.minimum(diff, period - diff)+++def _stage_for_age(age_buckets: int, config: DetectionConfig) -> BaselineStage:+ if age_buckets < config.min_history_buckets:+ return BaselineStage.INSUFFICIENT+ if age_buckets < config.cold_start_until_buckets:+ return BaselineStage.COLD_START+ if age_buckets < config.developing_until_buckets:+ return BaselineStage.DEVELOPING+ return BaselineStage.MATURE+++# DST shifts local time-of-week by up to an hour relative to UTC grid stepping,+# so candidate supersets are padded by this many buckets before exact filtering.+_DST_SLACK_BUCKETS = 60 // BUCKET_MINUTES+++def _stepped_positions(index: int, window_start: int, window_end: int, period: int, half_width: int) -> np.ndarray:+ """Superset of candidates at ``index - k*period ± half_width``, cheap to+ build (O(occurrences x pool) instead of O(window)) and filtered down to the+ exact time-of-week condition afterwards."""+ max_steps = (index - window_start) // period + 1+ steps = np.arange(0, max_steps + 1) * period+ offsets = np.arange(-half_width, half_width + 1)+ positions = np.unique(index - steps[:, None] + offsets[None, :])+ return positions[(positions >= window_start) & (positions < window_end)]+++def _candidate_positions(+ grid: TimeGrid, index: int, window_start: int, window_end: int, stage: BaselineStage, config: DetectionConfig+) -> np.ndarray:+ if stage is BaselineStage.COLD_START:+ half_width = config.developing_pool_buckets + _DST_SLACK_BUCKETS+ positions = _stepped_positions(index, window_start, window_end, BUCKETS_PER_DAY, half_width)+ is_weekend = grid.weekday[positions] >= 5+ target_weekend = bool(grid.weekday[index] >= 5)+ time_match = (+ _circular_diff(grid.minute_of_day[positions], int(grid.minute_of_day[index]), MINUTES_PER_DAY)+ <= config.developing_pool_buckets * BUCKET_MINUTES+ )+ return positions[(is_weekend == target_weekend) & time_match]+ if stage is BaselineStage.DEVELOPING:+ half_width = config.developing_pool_buckets + _DST_SLACK_BUCKETS+ positions = _stepped_positions(index, window_start, window_end, BUCKETS_PER_WEEK, half_width)+ day_match = grid.weekday[positions] == grid.weekday[index]+ time_match = (+ _circular_diff(grid.minute_of_day[positions], int(grid.minute_of_day[index]), MINUTES_PER_DAY)+ <= config.developing_pool_buckets * BUCKET_MINUTES+ )+ return positions[day_match & time_match]+ half_width = config.mature_pool_buckets + _DST_SLACK_BUCKETS+ positions = _stepped_positions(index, window_start, window_end, BUCKETS_PER_WEEK, half_width)+ time_match = (+ _circular_diff(grid.minute_of_week[positions], int(grid.minute_of_week[index]), MINUTES_PER_WEEK)+ <= config.mature_pool_buckets * BUCKET_MINUTES+ )+ return positions[time_match]+++def _apply_exclusions(candidates: np.ndarray, excluded: set[int], config: DetectionConfig) -> np.ndarray:+ if not excluded:+ return candidates+ excluded_sel = np.array(sorted(i for i in excluded if i in set(candidates.tolist())), dtype=candidates.dtype)+ if excluded_sel.size == 0:+ return candidates+ max_excludable = int(config.exclusion_cap_fraction * candidates.size)+ if excluded_sel.size > max_excludable:+ # Over the cap a permanent level shift is re-baselining itself: re-admit+ # the newest flagged buckets (the new level) and keep excluding the rest.+ readmit_count = excluded_sel.size - max_excludable+ readmitted = set(excluded_sel[-readmit_count:].tolist())+ excluded_sel = excluded_sel[:-readmit_count]+ drop = set(excluded_sel.tolist()) - readmitted+ else:+ drop = set(excluded_sel.tolist())+ return candidates[~np.isin(candidates, np.array(sorted(drop), dtype=candidates.dtype))]+++def _level_factor(+ history: SeriesHistory, index: int, window_start: int, window_end: int, config: DetectionConfig+) -> float:+ if not config.level_adjustment_enabled:+ return 1.0+ recent_start = max(window_start, window_end - config.level_window_buckets)+ recent = history.counts[recent_start:window_end]+ reference = history.counts[window_start:window_end]+ if recent.size == 0 or reference.size == 0:+ return 1.0+ recent_mean = float(np.mean(recent))+ reference_mean = float(np.mean(reference))+ if reference_mean <= 0.0:+ return 1.0+ factor = recent_mean / reference_mean+ return float(np.clip(factor, 1.0 / config.level_factor_clamp, config.level_factor_clamp))+++def select_baseline(+ history: SeriesHistory,+ index: int,+ grid: TimeGrid,+ config: DetectionConfig,+) -> BaselineResult:+ empty = np.array([], dtype=history.counts.dtype)+ first_active = history.first_active_index+ if first_active is None or first_active >= index:+ return BaselineResult(empty, BaselineStage.INSUFFICIENT, 1.0, False)++ age = index - first_active+ stage = _stage_for_age(age, config)+ if stage is BaselineStage.INSUFFICIENT:+ return BaselineResult(empty, stage, 1.0, False)++ window_start = max(first_active, index - config.max_lookback_buckets, history.baseline_floor_index)+ window_end = index - config.baseline_guard_buckets+ if window_end <= window_start:+ return BaselineResult(empty, BaselineStage.INSUFFICIENT, 1.0, False)+ candidates = _candidate_positions(grid, index, window_start, window_end, stage, config)+ candidates = _apply_exclusions(candidates, history.excluded, config)+ if candidates.size < config.min_baseline_samples:+ return BaselineResult(empty, BaselineStage.INSUFFICIENT, 1.0, False)++ level = _level_factor(history, index, window_start, window_end, config)+ samples = history.counts[candidates].astype(float)+ if level != 1.0:+ samples = samples * level+ return BaselineResult(samples, stage, level, grid.is_dst_shift_week(index))diff --git a/products/apm/backend/logic/anomaly_detection/config.py b/products/apm/backend/logic/anomaly_detection/config.pynew file mode 100644index 000000000000..7fbd349dd518--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/config.py@@ -0,0 +1,117 @@+"""Detection dials. Every value here is an alpha parameter expected to move.++Defaults are calibrated against an internal characterization of production+log workloads — a calibrating floor, not a universal. That is why each dial is env-tunable (``APM_ANOMALY_*``)+rather than a constant: argocd can retune without a deploy.+"""++from __future__ import annotations++import os+from dataclasses import dataclass, field, fields++from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY, BUCKETS_PER_HOUR, BUCKETS_PER_WEEK+from products.apm.backend.logic.anomaly_detection.types import TrafficTier++_ENV_PREFIX = "APM_ANOMALY_"+++@dataclass(frozen=True, slots=True)+class DetectionConfig:+ # --- band significance ---+ # Per-side false-flag budget per series per day; alpha per bucket is this / 288.+ false_flag_budget_per_day: float = 0.05+ # Widening for band models that assume their dispersion (e.g. Poisson).+ # Empty by default: the recommended negative-binomial model measures+ # dispersion from the samples, so widening would double-count it — see+ # validation/REPORT.md.+ severity_variance_multipliers: dict[str, float] = field(default_factory=dict)+ # Minimum variance-to-mean ratio used when estimating dispersion, so a+ # MAD-zero / flat baseline can't produce a zero-width band.+ dispersion_floor: float = 1.0+ # Rate floor for count bands: a near-zero learned rate still gets a small+ # nonzero band, so the first log after a quiet hour is not a spike.+ band_rate_floor: float = 1.0+ # Bands widen by this factor during DST shift weeks (reduced confidence).+ dst_band_multiplier: float = 1.5+ # Bands widen by this factor while a series is in cold start.+ cold_start_band_multiplier: float = 2.0++ # --- baseline stages (thresholds in buckets of series age) ---+ min_history_buckets: int = 3 * BUCKETS_PER_DAY+ cold_start_until_buckets: int = 14 * BUCKETS_PER_DAY+ developing_until_buckets: int = 6 * BUCKETS_PER_WEEK+ # Pooling half-width around the scored time-of-week slot, in buckets.+ developing_pool_buckets: int = 12 # ±60 min+ mature_pool_buckets: int = 2 # ±10 min+ max_lookback_buckets: int = 12 * BUCKETS_PER_WEEK+ # Baselines only use buckets at least this old. Without a guard, the+ # trailing edge of the pool overlaps an ongoing anomaly, which inflates the+ # dispersion estimate until the detector legitimizes the incident it should+ # be flagging.+ baseline_guard_buckets: int = BUCKETS_PER_DAY+ min_baseline_samples: int = 12+ # Anomalous buckets are excluded from baselines, but only up to this share+ # of the candidate window — beyond it a level shift re-baselines itself.+ exclusion_cap_fraction: float = 0.5++ # --- level component ---+ level_adjustment_enabled: bool = True+ level_window_buckets: int = BUCKETS_PER_DAY+ level_factor_clamp: float = 2.0++ # --- gates ---+ # Sustained traffic floor: >=1 log/min over the floor window (per-bucket mean).+ traffic_floor_per_bucket: float = 5.0+ traffic_floor_window_buckets: int = BUCKETS_PER_DAY+ # Persistence: the series must have been alive on both sides of the window+ # (the characterization's decisive gate: silence FP 44% -> 11.75%).+ persistence_window_buckets: int = BUCKETS_PER_DAY+ persistence_recent_buckets: int = 2 * BUCKETS_PER_HOUR+ # A series absent longer than this expires out of silence coverage.+ expiry_buckets: int = 1 * BUCKETS_PER_DAY++ # --- tiers (per-bucket rate edges: 0.5/s, 0.1/s, 1/min) ---+ tier_a_min_per_bucket: float = 150.0+ tier_b_min_per_bucket: float = 30.0+ tier_c_min_per_bucket: float = 5.0++ # --- silence ---+ # Seasonal gate: expected count in the bucket must reach this for silence+ # to be a candidate (a near-zero overnight rate cannot fire overnight).+ silence_min_expected: float = 5.0+ # Consecutive empty buckets required before a silence issue opens, per tier.+ silence_confirm_buckets: dict[TrafficTier, int] = field(+ default_factory=lambda: {TrafficTier.A: 1, TrafficTier.B: 2, TrafficTier.C: 3}+ )++ # --- issue lifecycle ---+ # Consecutive anomalous buckets before a spike/drop issue opens.+ open_after_buckets: int = 2+ # Consecutive normal buckets before an active issue resolves.+ resolve_after_buckets: int = 12+ # A recurrence within this window reopens the resolved issue; later ones are new.+ reopen_window_buckets: int = 7 * BUCKETS_PER_DAY++ @property+ def alpha_per_bucket(self) -> float:+ return self.false_flag_budget_per_day / BUCKETS_PER_DAY++ @classmethod+ def from_env(cls, environ: dict[str, str] | None = None) -> DetectionConfig:+ """Scalar dials only — the dict-valued dials (severity multipliers,+ silence confirmation) need code changes, which is deliberate: their+ shape is part of the detection contract, not a tuning knob."""+ env = os.environ if environ is None else environ+ overrides: dict[str, object] = {}+ for f in fields(cls):+ raw = env.get(f"{_ENV_PREFIX}{f.name.upper()}")+ if raw is None:+ continue+ if f.type in ("int",):+ overrides[f.name] = int(raw)+ elif f.type in ("float",):+ overrides[f.name] = float(raw)+ elif f.type in ("bool",):+ overrides[f.name] = raw.strip().lower() in ("1", "true", "yes")+ return cls(**overrides) # type: ignore[arg-type]diff --git a/products/apm/backend/logic/anomaly_detection/constants.py b/products/apm/backend/logic/anomaly_detection/constants.pynew file mode 100644index 000000000000..622da446a435--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/constants.py@@ -0,0 +1,9 @@+"""Fixed grid constants. The 5-minute UTC bucket grid is architectural+(bucket identities must stay stable across ticks, backfills, and recomputes),+so unlike the dials in config.py these are not env-tunable.+"""++BUCKET_MINUTES = 5+BUCKETS_PER_HOUR = 60 // BUCKET_MINUTES+BUCKETS_PER_DAY = 24 * BUCKETS_PER_HOUR+BUCKETS_PER_WEEK = 7 * BUCKETS_PER_DAYdiff --git a/products/apm/backend/logic/anomaly_detection/detector.py b/products/apm/backend/logic/anomaly_detection/detector.pynew file mode 100644index 000000000000..7c2e84ba1be3--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/detector.py@@ -0,0 +1,127 @@+"""The detector: (series history, grid, config, band model) -> verdicts.++Pure and stateless per bucket — the only cross-bucket state is the exclusion+set the caller threads through on ``SeriesHistory.excluded`` (buckets already+flagged anomalous, kept out of future baselines) and the issue layer's+snapshots. Consecutive-bucket confirmation lives in the issue layer, which has+the memory; this module answers "is this bucket outside its learned band".++Silence needs no separate expected-set machinery here: the dense grid makes a+missing rollup row a zero count, and the expiry gate stops zero-count verdicts+once a series has been quiet past the inactivity horizon.+"""++from __future__ import annotations++from collections.abc import Mapping++import numpy as np++from products.apm.backend.logic.anomaly_detection.bands import BandModel, widen+from products.apm.backend.logic.anomaly_detection.baseline import BaselineResult, TimeGrid, select_baseline+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.types import (+ BaselineStage,+ BucketVerdict,+ SeriesHistory,+ SeriesKey,+ TrafficTier,+ VerdictType,+)+++def _trailing_rate(history: SeriesHistory, index: int, config: DetectionConfig) -> float:+ window_start = max(0, index - config.traffic_floor_window_buckets)+ window = history.counts[window_start:index]+ return float(np.mean(window)) if window.size else 0.0+++def traffic_tier(history: SeriesHistory, index: int, config: DetectionConfig) -> TrafficTier:+ rate = _trailing_rate(history, index, config)+ if rate >= config.tier_a_min_per_bucket:+ return TrafficTier.A+ if rate >= config.tier_b_min_per_bucket:+ return TrafficTier.B+ if rate >= config.tier_c_min_per_bucket:+ return TrafficTier.C+ return TrafficTier.D+++def _passes_gates(history: SeriesHistory, index: int, observed: float, config: DetectionConfig) -> bool:+ first_active = history.first_active_index+ if first_active is None:+ return False+ # Persistence, side one: alive since before the evaluation window.+ if index - first_active < config.persistence_window_buckets:+ return False+ if observed == 0:+ last_active = history.last_active_index(index)+ if last_active is None:+ return False+ # Expiry: a series quiet past the horizon has left silence coverage.+ if index - last_active > config.expiry_buckets:+ return False+ # Persistence, side two: recently alive (an ephemeral pod that died is+ # not a silent service — the characterization's decisive finding).+ if index - last_active > config.persistence_recent_buckets:+ return False+ # Sustained traffic floor over the trailing window.+ return _trailing_rate(history, index, config) >= config.traffic_floor_per_bucket+++def _band_multiplier(key: SeriesKey, baseline: BaselineResult, config: DetectionConfig) -> float:+ factor = config.severity_variance_multipliers.get(key.severity, 1.0)+ if baseline.stage is BaselineStage.COLD_START:+ factor *= config.cold_start_band_multiplier+ if baseline.is_dst_shift_week:+ factor *= config.dst_band_multiplier+ return factor+++def evaluate_series_bucket(+ history: SeriesHistory,+ index: int,+ key: SeriesKey,+ grid: TimeGrid,+ config: DetectionConfig,+ band_model: BandModel,+) -> BucketVerdict | None:+ observed = float(history.counts[index])+ if not _passes_gates(history, index, observed, config):+ return None++ baseline = select_baseline(history, index, grid, config)+ if not baseline.scorable:+ return None++ band = band_model.compute(baseline.samples, observed, config.alpha_per_bucket)+ band = widen(band, _band_multiplier(key, baseline, config))+ tier = traffic_tier(history, index, config)++ if observed == 0:+ # Zero observations are only ever silence — and only when the learned+ # seasonal expectation says logs were due (a near-zero overnight rate+ # cannot fire overnight silence).+ if band.expected >= config.silence_min_expected and tier is not TrafficTier.D:+ return BucketVerdict(key, index, VerdictType.SILENCE, observed, band, baseline.stage, tier)+ return None+ if observed > band.upper:+ return BucketVerdict(key, index, VerdictType.SPIKE, observed, band, baseline.stage, tier)+ if observed < band.lower:+ return BucketVerdict(key, index, VerdictType.DROP, observed, band, baseline.stage, tier)+ return None+++def evaluate_tick(+ series: Mapping[SeriesKey, SeriesHistory],+ index: int,+ grid: TimeGrid,+ config: DetectionConfig,+ band_model: BandModel,+) -> list[BucketVerdict]:+ verdicts = []+ for key, history in series.items():+ verdict = evaluate_series_bucket(history, index, key, grid, config, band_model)+ if verdict is not None:+ verdicts.append(verdict)+ return verdictsdiff --git a/products/apm/backend/logic/anomaly_detection/issues.py b/products/apm/backend/logic/anomaly_detection/issues.pynew file mode 100644index 000000000000..35f3e26c6130--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/issues.py@@ -0,0 +1,168 @@+"""Issue lifecycle as a pure state machine, one snapshot in, one outcome out —+the same shape as products/logs/backend/alert_state_machine.py. The filing+layer (not built yet) owns model mutation; nothing here touches a database.++Identity: spikes (UP) are per severity series; drops and silence (DOWN) share+a severity-less fingerprint per service, which is what lets a drop deepen into+silence within the same issue and full-service silence file one issue, not one+per severity.+"""++from __future__ import annotations++from dataclasses import dataclass, replace+from enum import StrEnum++from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.types import (+ VERDICT_DIRECTION,+ Direction,+ SeriesKey,+ TrafficTier,+ VerdictType,+)+++class IssueState(StrEnum):+ PENDING = "pending" # counting toward open; no issue row exists yet+ ACTIVE = "active"+ RESOLVED = "resolved"+++class IssueAction(StrEnum):+ NONE = "none"+ OPEN = "open"+ RECORD = "record"+ ESCALATE = "escalate" # drop deepened into silence within the same issue+ RESOLVE = "resolve"+ REOPEN = "reopen"+++@dataclass(frozen=True, slots=True)+class IssueFingerprint:+ namespace: str+ service: str+ environment: str+ severity: str | None+ direction: Direction+++def fingerprint_for(key: SeriesKey, verdict_type: VerdictType) -> IssueFingerprint:+ direction = VERDICT_DIRECTION[verdict_type]+ return IssueFingerprint(+ namespace=key.namespace,+ service=key.service,+ environment=key.environment,+ severity=key.severity if direction is Direction.UP else None,+ direction=direction,+ )+++@dataclass(frozen=True, slots=True)+class IssueSnapshot:+ state: IssueState+ kind: VerdictType+ consecutive_anomalous: int+ consecutive_normal: int+ last_anomalous_index: int+ opened_at_index: int | None+++@dataclass(frozen=True, slots=True)+class IssueOutcome:+ action: IssueAction+ snapshot: IssueSnapshot | None+++def required_consecutive(verdict_type: VerdictType, tier: TrafficTier, config: DetectionConfig) -> int:+ if verdict_type is VerdictType.SILENCE:+ return config.silence_confirm_buckets.get(tier, config.open_after_buckets)+ return config.open_after_buckets+++def _escalated_kind(current: VerdictType, incoming: VerdictType) -> VerdictType:+ # One-way: silence dominates drop; partial recovery does not de-escalate.+ if VerdictType.SILENCE in (current, incoming):+ return VerdictType.SILENCE+ return incoming+++def evaluate_issue_transition(+ snapshot: IssueSnapshot | None,+ verdict_type: VerdictType | None,+ index: int,+ required: int,+ config: DetectionConfig,+) -> IssueOutcome:+ """Advance one fingerprint's lifecycle by one bucket.++ ``verdict_type`` is None for a normal (in-band) bucket. ``required`` is the+ consecutive-candidate count that opens (or reopens) an issue, resolved by+ the caller via ``required_consecutive`` — silence is tier-dependent.+ """+ if snapshot is None:+ if verdict_type is None:+ return IssueOutcome(IssueAction.NONE, None)+ pending = IssueSnapshot(+ state=IssueState.PENDING,+ kind=verdict_type,+ consecutive_anomalous=1,+ consecutive_normal=0,+ last_anomalous_index=index,+ opened_at_index=None,+ )+ if pending.consecutive_anomalous >= required:+ return IssueOutcome(IssueAction.OPEN, replace(pending, state=IssueState.ACTIVE, opened_at_index=index))+ return IssueOutcome(IssueAction.NONE, pending)++ if snapshot.state is IssueState.PENDING:+ if verdict_type is None:+ return IssueOutcome(IssueAction.NONE, None)+ pending = replace(+ snapshot,+ kind=_escalated_kind(snapshot.kind, verdict_type),+ consecutive_anomalous=snapshot.consecutive_anomalous + 1,+ last_anomalous_index=index,+ )+ if pending.consecutive_anomalous >= required:+ return IssueOutcome(IssueAction.OPEN, replace(pending, state=IssueState.ACTIVE, opened_at_index=index))+ return IssueOutcome(IssueAction.NONE, pending)++ if snapshot.state is IssueState.ACTIVE:+ if verdict_type is None:+ normals = snapshot.consecutive_normal + 1+ if normals >= config.resolve_after_buckets:+ return IssueOutcome(+ IssueAction.RESOLVE,+ replace(snapshot, state=IssueState.RESOLVED, consecutive_normal=normals, consecutive_anomalous=0),+ )+ return IssueOutcome(IssueAction.NONE, replace(snapshot, consecutive_normal=normals))+ kind = _escalated_kind(snapshot.kind, verdict_type)+ action = IssueAction.ESCALATE if kind is not snapshot.kind else IssueAction.RECORD+ return IssueOutcome(+ action,+ replace(+ snapshot,+ kind=kind,+ consecutive_anomalous=snapshot.consecutive_anomalous + 1,+ consecutive_normal=0,+ last_anomalous_index=index,+ ),+ )++ # RESOLVED+ if verdict_type is None:+ return IssueOutcome(IssueAction.NONE, snapshot)+ if index - snapshot.last_anomalous_index > config.reopen_window_buckets:+ # Recurrence past the window is a new problem: restart as fresh pending.+ return evaluate_issue_transition(None, verdict_type, index, required, config)+ reopened = replace(+ snapshot,+ kind=_escalated_kind(snapshot.kind, verdict_type),+ consecutive_anomalous=snapshot.consecutive_anomalous + 1 if snapshot.consecutive_normal == 0 else 1,+ consecutive_normal=0,+ last_anomalous_index=index,+ )+ if reopened.consecutive_anomalous >= required:+ return IssueOutcome(IssueAction.REOPEN, replace(reopened, state=IssueState.ACTIVE))+ return IssueOutcome(IssueAction.NONE, reopened)diff --git a/products/apm/backend/logic/anomaly_detection/types.py b/products/apm/backend/logic/anomaly_detection/types.pynew file mode 100644index 000000000000..5d3603a8a8d4--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/types.py@@ -0,0 +1,108 @@+"""Core types for the anomaly detection pure functions."""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import UTC, datetime, timedelta+from enum import StrEnum++import numpy as np++from products.apm.backend.logic.anomaly_detection.constants import BUCKET_MINUTES+++class VerdictType(StrEnum):+ SPIKE = "spike"+ DROP = "drop"+ SILENCE = "silence"+++class Direction(StrEnum):+ UP = "up"+ DOWN = "down"+++class BaselineStage(StrEnum):+ INSUFFICIENT = "insufficient"+ COLD_START = "cold_start"+ DEVELOPING = "developing"+ MATURE = "mature"+++class TrafficTier(StrEnum):+ """Rate bands over trailing per-bucket rate (thresholds in config)."""++ A = "a" # >=0.5/s+ B = "b" # 0.1-0.5/s+ C = "c" # 1/min-0.1/s+ D = "d" # <1/min — below the detection floor+++VERDICT_DIRECTION: dict[VerdictType, Direction] = {+ VerdictType.SPIKE: Direction.UP,+ VerdictType.DROP: Direction.DOWN,+ VerdictType.SILENCE: Direction.DOWN,+}+++@dataclass(frozen=True, slots=True)+class SeriesKey:+ namespace: str+ service: str+ environment: str+ severity: str+++@dataclass(frozen=True, slots=True)+class Band:+ lower: float+ upper: float+ expected: float+++@dataclass(frozen=True, slots=True)+class BucketVerdict:+ key: SeriesKey+ bucket_index: int+ verdict_type: VerdictType+ observed: float+ band: Band+ stage: BaselineStage+ tier: TrafficTier+++@dataclass(slots=True)+class SeriesHistory:+ """Dense per-series counts on the 5-minute grid.++ ``counts[i]`` is the count for the bucket starting at+ ``grid_start + i * 5min``. A missing rollup row is a zero count — for log+ volume the two are the same observation.++ ``baseline_floor_index`` re-anchors the baseline window: buckets before it+ never enter baselines. A re-baselining policy (e.g. a stability test that+ accepts a level shift as the new normal) sets it to the shift point.+ """++ grid_start: datetime+ counts: np.ndarray+ excluded: set[int] = field(default_factory=set)+ baseline_floor_index: int = 0++ def __post_init__(self) -> None:+ if self.grid_start.tzinfo is None:+ raise ValueError("grid_start must be timezone-aware")+ if self.grid_start.astimezone(UTC).minute % BUCKET_MINUTES != 0 or self.grid_start.second != 0:+ raise ValueError("grid_start must be aligned to the 5-minute UTC grid")++ def bucket_time(self, index: int) -> datetime:+ return self.grid_start + timedelta(minutes=BUCKET_MINUTES * index)++ @property+ def first_active_index(self) -> int | None:+ nonzero = np.flatnonzero(self.counts)+ return int(nonzero[0]) if nonzero.size else None++ def last_active_index(self, before: int) -> int | None:+ nonzero = np.flatnonzero(self.counts[:before])+ return int(nonzero[-1]) if nonzero.size else Nonediff --git a/products/apm/backend/logic/anomaly_detection/validation/REPORT.md b/products/apm/backend/logic/anomaly_detection/validation/REPORT.mdnew file mode 100644index 000000000000..ff0d3d76a7fa--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/REPORT.md@@ -0,0 +1,39 @@+# 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.)++## Band model recommendation: negative binomial, no severity widening++- **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.++## Baseline stages: cold start is usable — mature is where the FPs are++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.++## Error severity is not per-bucket detectable — every model fails++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.++## Persistence gate: reproduced++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`.++## Level-shift re-baselining: the ~4-week claim is corrected, in both directions++- 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.++## Bug found by the harness: baseline self-legitimization++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.++## Caveats++- 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.diff --git a/products/apm/backend/logic/anomaly_detection/validation/__init__.py b/products/apm/backend/logic/anomaly_detection/validation/__init__.pynew file mode 100644index 000000000000..1979cffdd854--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/__init__.py@@ -0,0 +1,5 @@+"""Validation harness: seeded simulation + bake-off metrics for the detector.++Ships with the detector so the validation of the risky band math is repeatable+as parameters move — not a throwaway prototype.+"""diff --git a/products/apm/backend/logic/anomaly_detection/validation/calibration.py b/products/apm/backend/logic/anomaly_detection/validation/calibration.pynew file mode 100644index 000000000000..180a587ce270--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/calibration.py@@ -0,0 +1,65 @@+"""Noise-model calibration: representative defaults for production-shaped log traffic.++Values are modeled on an internal characterization of real log workloads and+deliberately rounded — absolute volumes here are representative, not+measurements. The raw characterization stays internal.++Representativeness caveat: the underlying workload is infrastructure logging.+Customer workloads may be smaller, spikier, less cron-shaped, and differently+ephemeral. The noise model is swappable (see simulation.NoiseModel) so a+design partner's measurements can replace this module wholesale.+"""++from __future__ import annotations++from dataclasses import dataclass++from products.apm.backend.logic.anomaly_detection.types import TrafficTier+++@dataclass(frozen=True, slots=True)+class TierCalibration:+ median_per_bucket: float+ cv: float+ # Fraction of buckets naturally empty for persistent pairs at this tier.+ empty_bucket_rate: float+++# 5-min bucket statistics per tier, persistent pairs (post-persistence-gate).+# Band C's natural empty rate collapses to ~0 once the persistence gate holds;+# band D stays too gappy for 5-min detection and sits below the floor.+TIER_CALIBRATION: dict[TrafficTier, TierCalibration] = {+ TrafficTier.A: TierCalibration(median_per_bucket=1_500.0, cv=0.12, empty_bucket_rate=0.0005),+ TrafficTier.B: TierCalibration(median_per_bucket=60.0, cv=0.35, empty_bucket_rate=0.002),+ TrafficTier.C: TierCalibration(median_per_bucket=20.0, cv=0.50, empty_bucket_rate=0.01),+ TrafficTier.D: TierCalibration(median_per_bucket=2.0, cv=0.80, empty_bucket_rate=0.29),+}++# Population share per tier: a small head of high-volume series and a long+# tail below the detection floor.+TIER_POPULATION_SHARE: dict[TrafficTier, float] = {+ TrafficTier.A: 0.15,+ TrafficTier.B: 0.05,+ TrafficTier.C: 0.12,+ TrafficTier.D: 0.68,+}++# Severity taxonomy is clean at ingest (canonical lowercase OTel values); info+# dominates, error is a sub-percent sliver.+SEVERITY_MIX: dict[str, float] = {"info": 0.85, "warn": 0.08, "debug": 0.065, "error": 0.005}++# Error streams run far more overdispersed (CV ~2) than info/debug at the same+# rate — the overdispersion headline the band bake-off exists to settle.+ERROR_CV = 2.2++# Seasonal peak/trough ratios: near-flat infra, diurnal user-facing traffic,+# cron step-functions firing at fixed local hours, and a weekend-peaking shape.+FLAT_PEAK_TROUGH = 1.07+DIURNAL_PEAK_TROUGH = 2.3+CRON_STEP_FACTOR = 14.0+CRON_STEP_HOURS = (3, 15) # fixed local hours the step fires+WEEKEND_PEAK_FACTOR = 2.0++# Ephemeral pods dominate bands C and D: lifetimes of a couple of hours,+# mostly contiguous while alive — born, emit steadily, die.+EPHEMERAL_MEDIAN_LIFETIME_BUCKETS: dict[TrafficTier, int] = {TrafficTier.C: 24, TrafficTier.D: 12}diff --git a/products/apm/backend/logic/anomaly_detection/validation/harness.py b/products/apm/backend/logic/anomaly_detection/validation/harness.pynew file mode 100644index 000000000000..4dd6aa578f02--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/harness.py@@ -0,0 +1,350 @@+"""Runs the detector over a scenario and scores it against injected truth.++Everything here is deterministic given a seed. Bucket-level metrics are+grouped by the spec's tier and severity so the report can answer the ticket's+question directly: which band model holds the false-positive budget per tier+and per severity, and does error-severity overdispersion break Poisson.+"""++from __future__ import annotations++from collections import defaultdict+from dataclasses import dataclass, field, replace++import numpy as np++from products.apm.backend.logic.anomaly_detection.bands import BandModel+from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY+from products.apm.backend.logic.anomaly_detection.detector import evaluate_series_bucket+from products.apm.backend.logic.anomaly_detection.issues import (+ IssueAction,+ IssueFingerprint,+ IssueSnapshot,+ evaluate_issue_transition,+ fingerprint_for,+ required_consecutive,+)+from products.apm.backend.logic.anomaly_detection.types import (+ VERDICT_DIRECTION,+ BaselineStage,+ BucketVerdict,+ SeriesHistory,+ TrafficTier,+ VerdictType,+)+from products.apm.backend.logic.anomaly_detection.validation.simulation import (+ AnomalyKind,+ NegativeBinomialNoise,+ Scenario,+ SeriesSpec,+)+++@dataclass(slots=True)+class GroupMetrics:+ true_positive_buckets: int = 0+ false_positive_buckets: int = 0+ windows_total: int = 0+ windows_detected: int = 0+ series_count: int = 0++ @property+ def precision(self) -> float | None:+ flagged = self.true_positive_buckets + self.false_positive_buckets+ return self.true_positive_buckets / flagged if flagged else None++ @property+ def window_recall(self) -> float | None:+ return self.windows_detected / self.windows_total if self.windows_total else None+++@dataclass(slots=True)+class IssueStats:+ opens_per_day: list[int] = field(default_factory=list)+ opens_in_truth: int = 0+ opens_total: int = 0++ @property+ def precision(self) -> float | None:+ return self.opens_in_truth / self.opens_total if self.opens_total else None++ @property+ def median_per_day(self) -> float:+ return float(np.median(self.opens_per_day)) if self.opens_per_day else 0.0++ @property+ def p95_per_day(self) -> float:+ return float(np.percentile(self.opens_per_day, 95)) if self.opens_per_day else 0.0+++@dataclass(slots=True)+class ModelReport:+ model_name: str+ groups: dict[tuple[TrafficTier, str], GroupMetrics]+ stage_groups: dict[BaselineStage, GroupMetrics]+ issues: IssueStats+ silence_fp_ephemeral: int+ silence_fp_persistent: int+ silence_windows_detected: int+ silence_windows_total: int+ verdict_count: int+ eval_days: float+ scored_series: int++ @property+ def false_positives_per_series_day(self) -> float:+ fp = sum(g.false_positive_buckets for g in self.groups.values())+ denominator = self.scored_series * self.eval_days+ return fp / denominator if denominator else 0.0+++def _verdict_matches_truth(scenario: Scenario, verdict: BucketVerdict) -> bool:+ truth = scenario.truth_at(verdict.key, verdict.bucket_index)+ return truth is not None and truth.direction is VERDICT_DIRECTION[verdict.verdict_type]+++def run_model(+ scenario: Scenario,+ grid: TimeGrid,+ config: DetectionConfig,+ model: BandModel,+ eval_start: int,+ eval_end: int,+) -> ModelReport:+ specs_by_key = {spec.key: spec for spec in scenario.specs}+ shifted_keys = {a.key for a in scenario.anomalies if a.kind is AnomalyKind.LEVEL_SHIFT}+ histories = {+ spec.key: SeriesHistory(grid_start=grid.start, counts=scenario.counts[spec.key].copy())+ for spec in scenario.specs+ }++ groups: dict[tuple[TrafficTier, str], GroupMetrics] = defaultdict(GroupMetrics)+ stage_groups: dict[BaselineStage, GroupMetrics] = defaultdict(GroupMetrics)+ issues = IssueStats()+ snapshots: dict[IssueFingerprint, IssueSnapshot] = {}+ opens_by_day: dict[int, int] = defaultdict(int)+ silence_fp_ephemeral = 0+ silence_fp_persistent = 0+ verdict_count = 0+ detected_windows: set[int] = set()++ for index in range(eval_start, eval_end):+ tick_verdicts: dict[IssueFingerprint, BucketVerdict] = {}+ for spec in scenario.specs:+ history = histories[spec.key]+ verdict = evaluate_series_bucket(history, index, spec.key, grid, config, model)+ if verdict is None:+ continue+ history.excluded.add(index)+ verdict_count += 1++ if spec.key not in shifted_keys:+ matched = _verdict_matches_truth(scenario, verdict)+ group = groups[(spec.tier, spec.key.severity)]+ stage_group = stage_groups[verdict.stage]+ if matched:+ group.true_positive_buckets += 1+ stage_group.true_positive_buckets += 1+ else:+ group.false_positive_buckets += 1+ stage_group.false_positive_buckets += 1+ if verdict.verdict_type is VerdictType.SILENCE:+ if spec.is_ephemeral:+ silence_fp_ephemeral += 1+ else:+ silence_fp_persistent += 1+ if matched:+ for position, anomaly in enumerate(scenario.anomalies):+ if anomaly.key == verdict.key and anomaly.contains(index):+ detected_windows.add(position)++ fingerprint = fingerprint_for(verdict.key, verdict.verdict_type)+ existing = tick_verdicts.get(fingerprint)+ if existing is None or verdict.verdict_type is VerdictType.SILENCE:+ tick_verdicts[fingerprint] = verdict++ for fingerprint in set(snapshots) | set(tick_verdicts):+ verdict = tick_verdicts.get(fingerprint)+ if verdict is not None:+ required = required_consecutive(verdict.verdict_type, verdict.tier, config)+ outcome = evaluate_issue_transition(+ snapshots.get(fingerprint), verdict.verdict_type, index, required, config+ )+ else:+ outcome = evaluate_issue_transition(+ snapshots.get(fingerprint), None, index, config.open_after_buckets, config+ )+ if outcome.snapshot is None:+ snapshots.pop(fingerprint, None)+ else:+ snapshots[fingerprint] = outcome.snapshot+ if outcome.action in (IssueAction.OPEN, IssueAction.REOPEN):+ opens_by_day[(index - eval_start) // BUCKETS_PER_DAY] += 1+ issues.opens_total += 1+ if verdict is not None and _verdict_matches_truth(scenario, verdict):+ issues.opens_in_truth += 1++ eval_days = (eval_end - eval_start) / BUCKETS_PER_DAY+ issues.opens_per_day = [opens_by_day.get(day, 0) for day in range(int(np.ceil(eval_days)))]++ silence_positions = [+ position+ for position, anomaly in enumerate(scenario.anomalies)+ if anomaly.kind is AnomalyKind.SILENCE and anomaly.key not in shifted_keys+ ]+ for position, anomaly in enumerate(scenario.anomalies):+ if anomaly.key in shifted_keys or anomaly.kind is AnomalyKind.LEVEL_SHIFT:+ continue+ spec = specs_by_key[anomaly.key]+ group = groups[(spec.tier, anomaly.key.severity)]+ group.windows_total += 1+ if position in detected_windows:+ group.windows_detected += 1++ scored_series = sum(1 for spec in scenario.specs if not spec.is_ephemeral and spec.key not in shifted_keys)+ return ModelReport(+ model_name=model.name,+ groups=dict(groups),+ stage_groups=dict(stage_groups),+ issues=issues,+ silence_fp_ephemeral=silence_fp_ephemeral,+ silence_fp_persistent=silence_fp_persistent,+ silence_windows_detected=sum(1 for p in silence_positions if p in detected_windows),+ silence_windows_total=len(silence_positions),+ verdict_count=verdict_count,+ eval_days=eval_days,+ scored_series=scored_series,+ )+++def silence_gate_ablation(+ scenario: Scenario,+ grid: TimeGrid,+ config: DetectionConfig,+ model: BandModel,+ eval_start: int,+ eval_end: int,+) -> dict[str, ModelReport]:+ """The persistence-gate experiment on an identical scenario.++ Three rungs: the full design; the design minus the explicit persistence+ gate (its marginal effect over staged-baseline min-history, which already+ suppresses pods younger than the history requirement); and a naive config+ with neither, approximating the characterization's ungated 44% baseline.+ """+ gate_off = replace(+ config,+ persistence_window_buckets=0,+ persistence_recent_buckets=config.expiry_buckets,+ )+ naive = replace(+ gate_off,+ min_history_buckets=BUCKETS_PER_DAY // 24, # an hour of life is enough to be scored+ min_baseline_samples=6,+ # Rate over the last hour, not the trailing day — a trailing-day floor+ # quietly does the persistence gate's work for short-lived pods.+ traffic_floor_window_buckets=BUCKETS_PER_DAY // 24,+ )+ return {+ "full design": run_model(scenario, grid, config, model, eval_start, eval_end),+ "no persistence gate": run_model(scenario, grid, gate_off, model, eval_start, eval_end),+ "naive (no gate, 1h history)": run_model(scenario, grid, naive, model, eval_start, eval_end),+ }+++@dataclass(slots=True)+class RebaselineResult:+ buckets_to_quiet: int | None # None: still firing at the end of the run+ verdicts_emitted: int++ @property+ def days_to_quiet(self) -> float | None:+ return self.buckets_to_quiet / BUCKETS_PER_DAY if self.buckets_to_quiet is not None else None+++def rebaseline_experiment(+ spec: SeriesSpec,+ counts: np.ndarray,+ grid: TimeGrid,+ config: DetectionConfig,+ model: BandModel,+ shift_index: int,+ eval_end: int,+ stability_buckets: int | None = None,+) -> RebaselineResult:+ """How long a permanent level shift keeps firing.++ Passive mode (stability_buckets=None) relies on the exclusion cap+ readmitting new-level buckets. Stability mode models a caller-side policy:+ after N consecutive same-direction verdicts, treat the shift as the new+ level by re-anchoring the baseline window at the shift point — the series+ goes quiet immediately, at the cost of re-learning from scratch.+ """+ history = SeriesHistory(grid_start=grid.start, counts=counts.copy())+ quiet_run = 0+ consecutive_up = 0+ last_verdict_index: int | None = None+ verdicts_emitted = 0+ for index in range(shift_index, eval_end):+ verdict = evaluate_series_bucket(history, index, spec.key, grid, config, model)+ if verdict is not None:+ history.excluded.add(index)+ verdicts_emitted += 1+ last_verdict_index = index+ quiet_run = 0+ consecutive_up = consecutive_up + 1 if verdict.verdict_type is VerdictType.SPIKE else 0+ if stability_buckets is not None and consecutive_up >= stability_buckets:+ history.baseline_floor_index = index - stability_buckets+ history.excluded.clear()+ consecutive_up = 0+ else:+ quiet_run += 1+ consecutive_up = 0+ if quiet_run >= BUCKETS_PER_DAY:+ break+ if last_verdict_index is None:+ return RebaselineResult(buckets_to_quiet=0, verdicts_emitted=0)+ if quiet_run < BUCKETS_PER_DAY:+ return RebaselineResult(buckets_to_quiet=None, verdicts_emitted=verdicts_emitted)+ return RebaselineResult(buckets_to_quiet=last_verdict_index + 1 - shift_index, verdicts_emitted=verdicts_emitted)+++@dataclass(slots=True)+class SweepCell:+ model_name: str+ lam: float+ cv: float+ false_positive_rate: float+++def band_calibration_sweep(+ models: list[BandModel],+ alpha: float,+ seed: int,+ lambdas: tuple[float, ...] = (1.0, 10.0, 100.0, 1_000.0, 10_000.0),+ cvs: tuple[float, ...] = (0.12, 0.5, 2.2),+ n_samples: int = 40,+ trials: int = 500,+) -> list[SweepCell]:+ """Pure calibration check across the count range, no baseline machinery:+ baseline samples and the observed value are drawn from the same NB+ distribution, so a calibrated band flags ~2*alpha of clean observations.+ Covers the spec's lambda 1..10,000 range beyond what the population+ (tier medians up to ~1,590) exercises."""+ noise = NegativeBinomialNoise()+ cells = []+ for model in models:+ rng = np.random.default_rng(seed)+ for lam in lambdas:+ for cv in cvs:+ false_positives = 0+ for _ in range(trials):+ draws = noise.sample(rng, np.full(n_samples + 1, lam), cv).astype(float)+ samples, observed = draws[:-1], float(draws[-1])+ band = model.compute(samples, observed, alpha)+ if observed > band.upper or (observed < band.lower and observed > 0):+ false_positives += 1+ cells.append(SweepCell(model.name, lam, cv, false_positives / trials))+ return cellsdiff --git a/products/apm/backend/logic/anomaly_detection/validation/run.py b/products/apm/backend/logic/anomaly_detection/validation/run.pynew file mode 100644index 000000000000..9911e2daf497--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/run.py@@ -0,0 +1,226 @@+"""Bake-off report CLI.++ python -m products.apm.backend.logic.anomaly_detection.validation.run \+ --weeks 10 --eval-weeks 2 --seed 7 --out report.md++Runs every candidate band model over the same seeded scenario and prints the+precision/recall, issue-volume, persistence-ablation, and re-baseline numbers+the launch gates are tuned from.+"""++from __future__ import annotations++import os+import sys+import time+import argparse+from dataclasses import replace as dc_replace+from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import django++import numpy as np++from products.apm.backend.logic.anomaly_detection.bands import default_band_models+from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY, BUCKETS_PER_WEEK+from products.apm.backend.logic.anomaly_detection.types import SeriesKey, TrafficTier+from products.apm.backend.logic.anomaly_detection.validation.harness import (+ ModelReport,+ band_calibration_sweep,+ rebaseline_experiment,+ run_model,+ silence_gate_ablation,+)+from products.apm.backend.logic.anomaly_detection.validation.simulation import (+ AnomalyKind,+ InjectedAnomaly,+ SeasonalProfile,+ SeriesSpec,+ apply_anomaly,+ build_scenario,+ generate_counts,+ inject_anomalies,+)++GRID_START = datetime(2026, 1, 5, tzinfo=UTC) # a Monday+# US spring DST (2026-03-08) lands inside the eval window of the default+# 10-week run, so the shift-week widening is exercised, not just unit-tested.+PROJECT_TZ = ZoneInfo("America/Los_Angeles")+++def _format_group_lines(report: ModelReport) -> list[str]:+ lines = []+ for (tier, severity), metrics in sorted(report.groups.items(), key=lambda kv: (kv[0][0].value, kv[0][1])):+ precision = f"{metrics.precision:.3f}" if metrics.precision is not None else " n/a"+ recall = f"{metrics.window_recall:.3f}" if metrics.window_recall is not None else " n/a"+ lines.append(+ f" tier {tier.value.upper()} {severity:<6} precision {precision} window-recall {recall} "+ f"tp {metrics.true_positive_buckets:>5} fp {metrics.false_positive_buckets:>5}"+ )+ return lines+++def _report_section(report: ModelReport) -> str:+ lines = [+ f" model: {report.model_name}",+ f" verdicts {report.verdict_count}, fp/series/day {report.false_positives_per_series_day:.3f}",+ f" issues/day median {report.issues.median_per_day:.1f} p95 {report.issues.p95_per_day:.1f}, "+ f"issue precision {report.issues.precision if report.issues.precision is not None else float('nan'):.3f} "+ f"({report.issues.opens_in_truth}/{report.issues.opens_total})",+ f" silence: windows {report.silence_windows_detected}/{report.silence_windows_total} detected, "+ f"fp persistent {report.silence_fp_persistent}, fp ephemeral {report.silence_fp_ephemeral}",+ *_format_group_lines(report),+ ]+ for stage, metrics in sorted(report.stage_groups.items(), key=lambda kv: kv[0].value):+ precision = f"{metrics.precision:.3f}" if metrics.precision is not None else " n/a"+ lines.append(+ f" stage {stage.value:<11} precision {precision} "+ f"tp {metrics.true_positive_buckets:>5} fp {metrics.false_positive_buckets:>5}"+ )+ return "\n".join(lines)+++def main(argv: list[str] | None = None) -> int:+ # The detector itself is infra-free; only the registry-backed band models+ # (mad/zscore/iqr) sit behind posthog.tasks, which needs Django app setup.+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+ django.setup()++ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--weeks", type=int, default=10)+ parser.add_argument("--eval-weeks", type=int, default=2)+ parser.add_argument("--seed", type=int, default=7)+ parser.add_argument("--ephemerals", type=int, default=30)+ parser.add_argument("--models", nargs="*", default=None, help="subset of model names to run")+ parser.add_argument("--out", type=str, default=None)+ args = parser.parse_args(argv)+ if args.weeks < 2 or not 1 <= args.eval_weeks < args.weeks:+ parser.error("--eval-weeks must be >= 1 and smaller than --weeks (>= 2)")++ config = DetectionConfig.from_env()+ grid_length = args.weeks * BUCKETS_PER_WEEK+ eval_start = grid_length - args.eval_weeks * BUCKETS_PER_WEEK+ grid = TimeGrid.build(GRID_START, grid_length, PROJECT_TZ)++ # Young services put cold-start and developing stages inside the eval+ # window; everything born at t=0 is mature by then.+ young_births = (max(0, eval_start - 5 * BUCKETS_PER_DAY), max(0, eval_start - 3 * BUCKETS_PER_WEEK))+ scenario = build_scenario(+ grid, grid_length, seed=args.seed, ephemeral_count=args.ephemerals, young_births=young_births+ )+ rng = np.random.default_rng(args.seed + 1)+ inject_anomalies(scenario, rng, eval_start, grid_length)++ models = default_band_models(rate_floor=config.band_rate_floor, dispersion_floor=config.dispersion_floor)+ if args.models:+ known = {m.name for m in models}+ unknown = sorted(set(args.models) - known)+ if unknown:+ parser.error(f"unknown model(s): {', '.join(unknown)}; choose from: {', '.join(sorted(known))}")+ models = [m for m in models if m.name in args.models]++ out = [+ "# Anomaly detector bake-off",+ f"seed={args.seed} weeks={args.weeks} eval_weeks={args.eval_weeks} "+ f"series={len(scenario.specs)} anomalies={len(scenario.anomalies)}",+ "",+ "## Band model bake-off",+ "```",+ ]+ reports = {}+ for model in models:+ started = time.monotonic()+ report = run_model(scenario, grid, config, model, eval_start, grid_length)+ reports[model.name] = report+ out.append(_report_section(report))+ out.append(f" ({time.monotonic() - started:.1f}s)")+ out.append("")+ print(out[-3], file=sys.stderr) # noqa: T201++ # Defaults ship without severity widening (NB measures dispersion itself);+ # quantify what the multiplier mechanism would do to NB for the record.+ nb = next((m for m in models if m.name == "negative_binomial"), None)+ if nb is not None:+ widened = dc_replace(config, severity_variance_multipliers={"error": 4.0, "fatal": 4.0, "warn": 1.5})+ report = run_model(scenario, grid, widened, nb, eval_start, grid_length)+ report.model_name = "negative_binomial (with severity widening)"+ out.append(_report_section(report))+ out.append("")+ out.append("```")++ sweep = band_calibration_sweep(models, config.alpha_per_bucket, seed=args.seed + 3)+ out += [+ "",+ f"## Band calibration sweep (clean NB data; calibrated ~= 2*alpha = {2 * config.alpha_per_bucket:.1e})",+ "```",+ ]+ for model in models:+ out.append(f" {model.name}")+ for cv in sorted({c.cv for c in sweep}):+ cells = sorted((c for c in sweep if c.model_name == model.name and c.cv == cv), key=lambda c: c.lam)+ rates = " ".join(f"lam={c.lam:>6.0f}: {c.false_positive_rate:.4f}" for c in cells)+ out.append(f" cv={cv:<5} {rates}")+ out.append("```")++ # Gate and re-baseline experiments measure baseline/gate behavior, so they+ # need a calibrated band model under them — a miscalibrated one (Poisson on+ # overdispersed data) fires constantly and swamps the effect being measured.+ ablation_model = next((m for m in models if m.name == "negative_binomial"), models[0])+ ablation = silence_gate_ablation(scenario, grid, config, ablation_model, eval_start, grid_length)+ out += ["", f"## Persistence gate ablation ({ablation_model.name})", "```"]+ for label, report in ablation.items():+ out.append(+ f" {label:<28} silence fp ephemeral {report.silence_fp_ephemeral:>4}, "+ f"persistent {report.silence_fp_persistent:>4}, opens/day median {report.issues.median_per_day:.1f}"+ )+ out.append("```")++ # Dedicated longer timeline: the passive re-baseline claim is ~4 weeks, so+ # the shift needs >4 weeks of runway regardless of the bake-off's --weeks.+ shift_weeks = 12+ shift_grid_length = shift_weeks * BUCKETS_PER_WEEK+ shift_grid = TimeGrid.build(GRID_START, shift_grid_length, ZoneInfo("UTC"))+ shift_spec = SeriesSpec(+ key=SeriesKey(namespace="default", service="svc-shift", environment="production", severity="info"),+ tier=TrafficTier.A,+ profile=SeasonalProfile.DIURNAL,+ mean_per_bucket=1_500.0,+ cv=0.12,+ )+ shift_index = 7 * BUCKETS_PER_WEEK+ out += ["", "## Level shift re-baselining (permanent shift, 5 weeks runway)", "```"]+ # x2 sits inside the level-factor clamp (absorbed by the level component);+ # x4 exceeds it and exercises the exclusion-cap path the claim is about.+ for factor in (2.0, 4.0):+ shift_rng = np.random.default_rng(args.seed + 2)+ shift_counts = generate_counts(shift_spec, shift_grid, shift_rng)+ shift = InjectedAnomaly(shift_spec.key, AnomalyKind.LEVEL_SHIFT, shift_index, shift_grid_length, factor)+ apply_anomaly(shift_counts, shift)+ for label, stability in (("passive (exclusion cap)", None), ("stability test (12 buckets)", 12)):+ result = rebaseline_experiment(+ shift_spec,+ shift_counts,+ shift_grid,+ config,+ ablation_model,+ shift_index,+ shift_grid_length,+ stability_buckets=stability,+ )+ days = f"{result.days_to_quiet:.1f} days" if result.days_to_quiet is not None else "still firing at run end"+ out.append(f" x{factor:.0f} {label:<28} {days} ({result.verdicts_emitted} verdicts)")+ out.append("```")++ text = "\n".join(out)+ print(text) # noqa: T201+ if args.out:+ with open(args.out, "w") as f:+ f.write(text + "\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/apm/backend/logic/anomaly_detection/validation/simulation.py b/products/apm/backend/logic/anomaly_detection/validation/simulation.pynew file mode 100644index 000000000000..c0b2be9cc06e--- /dev/null+++ b/products/apm/backend/logic/anomaly_detection/validation/simulation.py@@ -0,0 +1,314 @@+"""Seeded series generator: production-shaped noise, synthetic anomalies.++A simulation fed synthetic Poisson noise would validate our assumptions+against themselves (and confidently report that a Poisson detector works).+Instead the generator is seeded with tier medians, per-severity CVs,+empty-bucket rates, and seasonal profiles calibrated to an internal+characterization of production log workloads — real noise, known answers. Injected anomalies provide the ground truth.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import StrEnum+from typing import Protocol++import numpy as np++from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid+from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY+from products.apm.backend.logic.anomaly_detection.types import Direction, SeriesKey, TrafficTier+from products.apm.backend.logic.anomaly_detection.validation import calibration++MINUTES_PER_DAY = 24 * 60+++class SeasonalProfile(StrEnum):+ FLAT = "flat"+ DIURNAL = "diurnal"+ CRON = "cron"+ WEEKEND_PEAK = "weekend_peak"+++class AnomalyKind(StrEnum):+ SPIKE = "spike"+ DROP = "drop"+ SILENCE = "silence"+ LEVEL_SHIFT = "level_shift"+++ANOMALY_DIRECTION: dict[AnomalyKind, Direction] = {+ AnomalyKind.SPIKE: Direction.UP,+ AnomalyKind.DROP: Direction.DOWN,+ AnomalyKind.SILENCE: Direction.DOWN,+ AnomalyKind.LEVEL_SHIFT: Direction.UP,+}+++@dataclass(frozen=True, slots=True)+class SeriesSpec:+ key: SeriesKey+ tier: TrafficTier+ profile: SeasonalProfile+ mean_per_bucket: float+ cv: float+ empty_bucket_rate: float = 0.0+ birth_index: int = 0+ death_index: int | None = None++ @property+ def is_ephemeral(self) -> bool:+ return self.death_index is not None+++@dataclass(frozen=True, slots=True)+class InjectedAnomaly:+ key: SeriesKey+ kind: AnomalyKind+ start: int+ end: int # exclusive+ factor: float++ @property+ def direction(self) -> Direction:+ return ANOMALY_DIRECTION[self.kind]++ def contains(self, index: int) -> bool:+ return self.start <= index < self.end+++@dataclass(slots=True)+class Scenario:+ specs: list[SeriesSpec]+ counts: dict[SeriesKey, np.ndarray]+ anomalies: list[InjectedAnomaly] = field(default_factory=list)++ def truth_at(self, key: SeriesKey, index: int) -> InjectedAnomaly | None:+ for anomaly in self.anomalies:+ if anomaly.key == key and anomaly.contains(index):+ return anomaly+ return None+++class NoiseModel(Protocol):+ def sample(self, rng: np.random.Generator, means: np.ndarray, cv: float) -> np.ndarray: ...+++class NegativeBinomialNoise:+ """Counts with a target CV: negative binomial when overdispersed relative+ to Poisson, Poisson otherwise. The default NoiseModel — swappable so a+ design partner's measured distributions can replace it."""++ def sample(self, rng: np.random.Generator, means: np.ndarray, cv: float) -> np.ndarray:+ counts = np.zeros(means.shape, dtype=np.int64)+ positive = means > 0+ mu = means[positive]+ var = (cv * mu) ** 2+ overdispersed = var > mu * 1.001+ out = np.empty(mu.shape, dtype=np.int64)+ if np.any(overdispersed):+ mu_od = mu[overdispersed]+ var_od = var[overdispersed]+ r = mu_od**2 / (var_od - mu_od)+ p = r / (r + mu_od)+ out[overdispersed] = rng.negative_binomial(r, p)+ if np.any(~overdispersed):+ out[~overdispersed] = rng.poisson(mu[~overdispersed])+ counts[positive] = out+ return counts+++def seasonal_multipliers(profile: SeasonalProfile, grid: TimeGrid) -> np.ndarray:+ hours = grid.minute_of_day / 60.0+ if profile is SeasonalProfile.FLAT:+ ratio = calibration.FLAT_PEAK_TROUGH+ shape = 1.0 + (ratio - 1.0) / 2.0 * np.sin(2 * np.pi * (hours - 9.0) / 24.0)+ elif profile is SeasonalProfile.DIURNAL:+ ratio = calibration.DIURNAL_PEAK_TROUGH+ trough = 2.0 / (1.0 + ratio)+ peak = trough * ratio+ shape = trough + (peak - trough) * (0.5 + 0.5 * np.sin(2 * np.pi * (hours - 9.0) / 24.0))+ elif profile is SeasonalProfile.CRON:+ shape = np.ones(grid.minute_of_day.shape)+ in_step = np.isin(grid.minute_of_day // 60, calibration.CRON_STEP_HOURS)+ shape[in_step] = calibration.CRON_STEP_FACTOR+ else: # WEEKEND_PEAK — the measured Saturday-peaking service+ shape = np.where(grid.weekday == 5, calibration.WEEKEND_PEAK_FACTOR, 1.0)+ return shape / float(np.mean(shape))+++def generate_counts(+ spec: SeriesSpec,+ grid: TimeGrid,+ rng: np.random.Generator,+ noise: NoiseModel | None = None,+) -> np.ndarray:+ noise = noise or NegativeBinomialNoise()+ means = spec.mean_per_bucket * seasonal_multipliers(spec.profile, grid)+ counts = noise.sample(rng, means, spec.cv)+ if spec.empty_bucket_rate > 0:+ counts[rng.random(counts.shape) < spec.empty_bucket_rate] = 0+ counts[: spec.birth_index] = 0+ if spec.death_index is not None:+ counts[spec.death_index :] = 0+ return counts+++def apply_anomaly(counts: np.ndarray, anomaly: InjectedAnomaly) -> None:+ window = slice(anomaly.start, anomaly.end)+ if anomaly.kind is AnomalyKind.SILENCE:+ counts[window] = 0+ elif anomaly.kind is AnomalyKind.LEVEL_SHIFT:+ counts[anomaly.start :] = np.round(counts[anomaly.start :] * anomaly.factor)+ else:+ counts[window] = np.round(counts[window] * anomaly.factor)+++def _series_key(service: str, severity: str) -> SeriesKey:+ return SeriesKey(namespace="default", service=service, environment="production", severity=severity)+++def build_population(+ grid_length: int,+ rng: np.random.Generator,+ ephemeral_count: int = 30,+ young_births: tuple[int, ...] = (),+) -> list[SeriesSpec]:+ """Persistent services across tiers/profiles/severities, plus the ephemeral+ pod population that makes the persistence-gate ablation meaningful.++ young_births adds persistent services born mid-timeline so the eval+ window contains cold-start and developing-stage series — per-stage metrics+ are meaningless if every series is mature by eval time."""+ tiers = calibration.TIER_CALIBRATION+ specs: list[SeriesSpec] = []++ for profile in (SeasonalProfile.FLAT, SeasonalProfile.DIURNAL, SeasonalProfile.CRON, SeasonalProfile.WEEKEND_PEAK):+ service = f"svc-a-{profile.value}"+ a = tiers[TrafficTier.A]+ specs.append(+ SeriesSpec(+ _series_key(service, "info"), TrafficTier.A, profile, a.median_per_bucket, a.cv, a.empty_bucket_rate+ )+ )+ # Severity mix puts warn at ~10% and error at ~0.5% of info volume;+ # error carries the measured overdispersion (CV 2.2).+ specs.append(+ SeriesSpec(_series_key(service, "warn"), TrafficTier.B, profile, a.median_per_bucket * 0.10, 0.35, 0.01)+ )+ specs.append(+ SeriesSpec(+ _series_key(service, "error"),+ TrafficTier.C,+ profile,+ a.median_per_bucket * 0.005,+ calibration.ERROR_CV,+ 0.05,+ )+ )++ for profile in (SeasonalProfile.FLAT, SeasonalProfile.DIURNAL, SeasonalProfile.CRON):+ service = f"svc-b-{profile.value}"+ b = tiers[TrafficTier.B]+ specs.append(+ SeriesSpec(+ _series_key(service, "info"), TrafficTier.B, profile, b.median_per_bucket, b.cv, b.empty_bucket_rate+ )+ )++ for profile in (SeasonalProfile.FLAT, SeasonalProfile.DIURNAL):+ service = f"svc-c-{profile.value}"+ c = tiers[TrafficTier.C]+ specs.append(+ SeriesSpec(+ _series_key(service, "info"), TrafficTier.C, profile, c.median_per_bucket, c.cv, c.empty_bucket_rate+ )+ )++ for i, birth in enumerate(young_births):+ b = tiers[TrafficTier.B]+ profile = SeasonalProfile.FLAT if i % 2 == 0 else SeasonalProfile.DIURNAL+ specs.append(+ SeriesSpec(+ _series_key(f"svc-young-{i}", "info"),+ TrafficTier.B,+ profile,+ b.median_per_bucket,+ b.cv,+ b.empty_bucket_rate,+ birth_index=birth,+ )+ )++ for i in range(ephemeral_count):+ tier = TrafficTier.C if i % 2 == 0 else TrafficTier.D+ cal = tiers[tier]+ median_lifetime = calibration.EPHEMERAL_MEDIAN_LIFETIME_BUCKETS[tier]+ birth = int(rng.integers(0, max(1, grid_length - median_lifetime)))+ # Mostly hours-lived (the measured median), with a multi-day tail —+ # short pods are suppressed by the baseline min-history gate either+ # way; only the tail isolates the persistence gate's death-side effect.+ if rng.random() < 0.2:+ lifetime = int(rng.uniform(2, 6) * BUCKETS_PER_DAY)+ else:+ lifetime = max(2, int(rng.exponential(median_lifetime)))+ death = min(grid_length, birth + lifetime)+ specs.append(+ SeriesSpec(+ _series_key(f"pod-{i}", "info"),+ tier,+ SeasonalProfile.FLAT,+ cal.median_per_bucket,+ cal.cv,+ 0.0,+ birth_index=birth,+ death_index=death,+ )+ )+ return specs+++def inject_anomalies(+ scenario: Scenario,+ rng: np.random.Generator,+ eval_start: int,+ eval_end: int,+ spikes_per_series: int = 3,+ drops_per_series: int = 2,+ silences_per_series: int = 2,+) -> None:+ """Schedules non-overlapping anomalies on every persistent series inside+ the eval window and applies them to the counts."""+ plan = [+ (AnomalyKind.SPIKE, spikes_per_series, 6, 5.0),+ (AnomalyKind.DROP, drops_per_series, 12, 0.2),+ (AnomalyKind.SILENCE, silences_per_series, 12, 0.0),+ ]+ for spec in scenario.specs:+ if spec.is_ephemeral:+ continue+ occupied: list[tuple[int, int]] = []+ for kind, count, duration, factor in plan:+ for _ in range(count):+ for _attempt in range(50):+ start = int(rng.integers(eval_start, eval_end - duration))+ padded = (start - 2 * duration, start + 3 * duration)+ if all(padded[1] <= s or padded[0] >= e for s, e in occupied):+ occupied.append(padded)+ anomaly = InjectedAnomaly(spec.key, kind, start, start + duration, factor)+ scenario.anomalies.append(anomaly)+ apply_anomaly(scenario.counts[spec.key], anomaly)+ break+++def build_scenario(+ grid: TimeGrid,+ grid_length: int,+ seed: int,+ ephemeral_count: int = 30,+ young_births: tuple[int, ...] = (),+) -> Scenario:+ rng = np.random.default_rng(seed)+ specs = build_population(grid_length, rng, ephemeral_count=ephemeral_count, young_births=young_births)+ counts = {spec.key: generate_counts(spec, grid, rng) for spec in specs}+ return Scenario(specs=specs, counts=counts)diff --git a/products/apm/backend/tests/test_anomaly_bands.py b/products/apm/backend/tests/test_anomaly_bands.pynew file mode 100644index 000000000000..6598e4de8e61--- /dev/null+++ b/products/apm/backend/tests/test_anomaly_bands.py@@ -0,0 +1,86 @@+import numpy as np+from parameterized import parameterized++from products.apm.backend.logic.anomaly_detection.bands import (+ IQRBandModel,+ MADBandModel,+ NegativeBinomialBandModel,+ PoissonBandModel,+ ZScoreBandModel,+ widen,+)+from products.apm.backend.logic.anomaly_detection.types import Band++ALPHA = 0.05 / 288+++def make_rng() -> np.random.Generator:+ return np.random.default_rng(42)+++class TestCountBands:+ def test_poisson_band_matches_theoretical_quantiles(self) -> None:+ samples = np.full(40, 100.0)+ band = PoissonBandModel().compute(samples, 100.0, 0.025)+ assert band.lower == 81.0+ assert band.upper == 120.0++ def test_poisson_lower_band_never_negative_at_low_rate(self) -> None:+ samples = np.full(40, 5.0)+ band = PoissonBandModel().compute(samples, 5.0, ALPHA)+ assert band.lower >= 0.0+ assert band.upper > 5.0++ def test_zscore_lower_band_goes_negative_at_low_rate(self) -> None:+ samples = make_rng().poisson(5.0, size=40).astype(float)+ band = ZScoreBandModel().compute(samples, 5.0, ALPHA)+ assert band.lower < 0.0++ def test_negative_binomial_inflates_band_for_overdispersed_samples(self) -> None:+ mu = 50.0+ overdispersed = make_rng().negative_binomial(2, 2 / (2 + mu), size=200).astype(float)+ nb_band = NegativeBinomialBandModel().compute(overdispersed, mu, ALPHA)+ poisson_band = PoissonBandModel().compute(overdispersed, mu, ALPHA)+ assert nb_band.upper > poisson_band.upper+ assert nb_band.lower <= poisson_band.lower++ def test_negative_binomial_falls_back_to_poisson_when_not_overdispersed(self) -> None:+ samples = np.full(40, 100.0)+ nb_band = NegativeBinomialBandModel().compute(samples, 100.0, ALPHA)+ poisson_band = PoissonBandModel().compute(samples, 100.0, ALPHA)+ assert nb_band.lower == poisson_band.lower+ assert nb_band.upper == poisson_band.upper++ def test_flat_baseline_still_produces_nonzero_width_band(self) -> None:+ samples = np.full(40, 20.0)+ band = NegativeBinomialBandModel().compute(samples, 20.0, ALPHA)+ assert band.upper > band.lower++ def test_rate_floor_prevents_spike_on_first_log_after_quiet(self) -> None:+ samples = np.zeros(40)+ band = PoissonBandModel(rate_floor=1.0).compute(samples, 1.0, ALPHA)+ assert band.upper >= 1.0+++class TestRegistryBands:+ @parameterized.expand([(MADBandModel,), (ZScoreBandModel,), (IQRBandModel,)])+ def test_outlier_lands_above_band(self, model_cls: type) -> None:+ samples = make_rng().normal(100.0, 10.0, size=60).round()+ band = model_cls().compute(samples, 500.0, ALPHA)+ assert 500.0 > band.upper+ assert band.lower < 100.0 < band.upper+++class TestWiden:+ def test_widen_scales_half_widths_around_expected(self) -> None:+ band = widen(Band(lower=80.0, upper=120.0, expected=100.0), 2.0)+ assert band.lower == 60.0+ assert band.upper == 140.0++ def test_widen_clamps_lower_at_zero(self) -> None:+ band = widen(Band(lower=2.0, upper=20.0, expected=10.0), 3.0)+ assert band.lower == 0.0++ def test_widen_factor_one_is_identity(self) -> None:+ band = Band(lower=80.0, upper=120.0, expected=100.0)+ assert widen(band, 1.0) is banddiff --git a/products/apm/backend/tests/test_anomaly_baseline.py b/products/apm/backend/tests/test_anomaly_baseline.pynew file mode 100644index 000000000000..96cf32acf1c7--- /dev/null+++ b/products/apm/backend/tests/test_anomaly_baseline.py@@ -0,0 +1,133 @@+from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import numpy as np+from parameterized import parameterized++from products.apm.backend.logic.anomaly_detection.baseline import MINUTES_PER_WEEK, TimeGrid, select_baseline+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKET_MINUTES, BUCKETS_PER_DAY, BUCKETS_PER_WEEK+from products.apm.backend.logic.anomaly_detection.types import BaselineStage, SeriesHistory++GRID_START = datetime(2026, 1, 5, tzinfo=UTC) # a Monday+GRID_LENGTH = 7 * BUCKETS_PER_WEEK+UTC_GRID = TimeGrid.build(GRID_START, GRID_LENGTH, ZoneInfo("UTC"))++NO_LEVEL_CONFIG = DetectionConfig(level_adjustment_enabled=False)+++def make_history(counts: np.ndarray) -> SeriesHistory:+ return SeriesHistory(grid_start=GRID_START, counts=counts)+++class TestStageLadder:+ @parameterized.expand(+ [+ ("too_young", 2 * BUCKETS_PER_DAY, BaselineStage.INSUFFICIENT),+ ("cold", 5 * BUCKETS_PER_DAY, BaselineStage.COLD_START),+ ("developing", 3 * BUCKETS_PER_WEEK, BaselineStage.DEVELOPING),+ ("mature", 6 * BUCKETS_PER_WEEK + 1, BaselineStage.MATURE),+ ]+ )+ def test_stage_follows_series_age(self, _name: str, age: int, expected: BaselineStage) -> None:+ counts = np.zeros(GRID_LENGTH)+ start = GRID_LENGTH - age - 1+ counts[start : GRID_LENGTH - 1] = 10.0+ result = select_baseline(make_history(counts), GRID_LENGTH - 1, UTC_GRID, NO_LEVEL_CONFIG)+ assert result.stage is expected+++class TestSampleSelection:+ def test_developing_samples_come_from_the_same_weekday_and_time(self) -> None:+ counts = UTC_GRID.weekday.astype(float) + 10.0+ index = 4 * BUCKETS_PER_WEEK # a Monday, age 4 weeks -> developing+ result = select_baseline(make_history(counts), index, UTC_GRID, NO_LEVEL_CONFIG)+ assert result.stage is BaselineStage.DEVELOPING+ assert set(np.unique(result.samples)) == {10.0 + UTC_GRID.weekday[index]}++ def test_mature_samples_come_from_the_same_time_of_week(self) -> None:+ counts = UTC_GRID.minute_of_week.astype(float)+ index = GRID_LENGTH - 1+ config = DetectionConfig(level_adjustment_enabled=False, developing_until_buckets=5 * BUCKETS_PER_DAY)+ result = select_baseline(make_history(counts), index, UTC_GRID, config)+ assert result.stage is BaselineStage.MATURE+ target = UTC_GRID.minute_of_week[index]+ linear = np.abs(result.samples - target)+ circular = np.minimum(linear, MINUTES_PER_WEEK - linear)+ assert np.all(circular <= config.mature_pool_buckets * BUCKET_MINUTES)++ def test_cold_start_pools_by_day_type(self) -> None:+ counts = np.where(UTC_GRID.weekday >= 5, 200.0, 50.0)+ counts[: GRID_LENGTH - 6 * BUCKETS_PER_DAY] = 0.0+ index = GRID_LENGTH - 1 # a Sunday+ result = select_baseline(make_history(counts), index, UTC_GRID, NO_LEVEL_CONFIG)+ assert result.stage is BaselineStage.COLD_START+ assert set(np.unique(result.samples)) == {200.0}++ def test_insufficient_when_fewer_than_min_samples(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ config = DetectionConfig(level_adjustment_enabled=False, min_baseline_samples=10_000)+ result = select_baseline(make_history(counts), GRID_LENGTH - 1, UTC_GRID, config)+ assert result.stage is BaselineStage.INSUFFICIENT+++class TestExclusions:+ def test_excluded_buckets_leave_the_baseline(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ index = GRID_LENGTH - 1+ clean = select_baseline(make_history(counts), index, UTC_GRID, NO_LEVEL_CONFIG)+ history = make_history(counts.copy())+ poisoned = index - BUCKETS_PER_WEEK+ history.counts[poisoned] = 9_999.0+ history.excluded = {poisoned}+ result = select_baseline(history, index, UTC_GRID, NO_LEVEL_CONFIG)+ assert result.samples.size == clean.samples.size - 1+ assert 9_999.0 not in result.samples++ def test_exclusion_cap_readmits_newest_buckets_so_level_shifts_rebaseline(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ index = GRID_LENGTH - 1+ history = make_history(counts)+ all_candidates = select_baseline(history, index, UTC_GRID, NO_LEVEL_CONFIG).samples.size+ history.excluded = set(range(index))+ result = select_baseline(history, index, UTC_GRID, NO_LEVEL_CONFIG)+ assert result.stage is not BaselineStage.INSUFFICIENT+ assert result.samples.size >= int(all_candidates * NO_LEVEL_CONFIG.exclusion_cap_fraction)+++class TestLevelFactor:+ def test_sustained_recent_level_scales_the_samples(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ index = GRID_LENGTH - 1+ counts[index - 2 * BUCKETS_PER_DAY : index] = 20.0+ config = DetectionConfig()+ result = select_baseline(make_history(counts), index, UTC_GRID, config)+ assert result.level_factor > 1.5+ assert float(np.median(result.samples)) > 10.0++ def test_level_factor_is_clamped(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ index = GRID_LENGTH - 1+ counts[index - 2 * BUCKETS_PER_DAY : index] = 10_000.0+ result = select_baseline(make_history(counts), index, UTC_GRID, DetectionConfig())+ assert result.level_factor == DetectionConfig().level_factor_clamp++ def test_level_ignores_change_inside_the_guard_window(self) -> None:+ counts = np.full(GRID_LENGTH, 10.0)+ index = GRID_LENGTH - 1+ config = DetectionConfig()+ counts[index - config.baseline_guard_buckets : index] = 10_000.0+ result = select_baseline(make_history(counts), index, UTC_GRID, config)+ assert result.level_factor == 1.0+++class TestDst:+ def test_shift_week_is_flagged_in_project_timezone(self) -> None:+ tz = ZoneInfo("America/Los_Angeles")+ start = datetime(2026, 10, 12, tzinfo=UTC) # DST ends 2026-11-01 in the US+ length = 4 * BUCKETS_PER_WEEK+ grid = TimeGrid.build(start, length, tz)+ before_shift = 1 * BUCKETS_PER_WEEK + 3 * BUCKETS_PER_DAY+ after_shift = 3 * BUCKETS_PER_WEEK+ assert not grid.is_dst_shift_week(before_shift)+ assert grid.is_dst_shift_week(after_shift)diff --git a/products/apm/backend/tests/test_anomaly_detector.py b/products/apm/backend/tests/test_anomaly_detector.pynew file mode 100644index 000000000000..28ed9856b102--- /dev/null+++ b/products/apm/backend/tests/test_anomaly_detector.py@@ -0,0 +1,132 @@+from dataclasses import replace+from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import numpy as np+from parameterized import parameterized++from products.apm.backend.logic.anomaly_detection.bands import PoissonBandModel+from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY+from products.apm.backend.logic.anomaly_detection.detector import evaluate_series_bucket, evaluate_tick, traffic_tier+from products.apm.backend.logic.anomaly_detection.types import SeriesHistory, SeriesKey, TrafficTier, VerdictType++GRID_START = datetime(2026, 1, 5, tzinfo=UTC)+GRID_LENGTH = 15 * BUCKETS_PER_DAY+GRID = TimeGrid.build(GRID_START, GRID_LENGTH, ZoneInfo("UTC"))+INDEX = GRID_LENGTH - 1++# Pins every full-history series at DEVELOPING: same-weekday matching works+# inside a 15-day grid, where MATURE would need same time-of-week from prior+# weeks and COLD_START would widen the bands under test.+CONFIG = DetectionConfig(+ min_history_buckets=BUCKETS_PER_DAY,+ cold_start_until_buckets=2 * BUCKETS_PER_DAY,+ developing_until_buckets=30 * BUCKETS_PER_DAY,+ persistence_window_buckets=BUCKETS_PER_DAY,+ persistence_recent_buckets=24,+ expiry_buckets=BUCKETS_PER_DAY,+ level_adjustment_enabled=False,+)++KEY = SeriesKey(namespace="prod", service="checkout", environment="us", severity="info")+MODEL = PoissonBandModel(rate_floor=CONFIG.band_rate_floor)+++def steady_history(rate: float = 100.0) -> SeriesHistory:+ return SeriesHistory(grid_start=GRID_START, counts=np.full(GRID_LENGTH, rate))+++def evaluate(history: SeriesHistory, index: int = INDEX) -> VerdictType | None:+ verdict = evaluate_series_bucket(history, index, KEY, GRID, CONFIG, MODEL)+ return verdict.verdict_type if verdict else None+++class TestVerdicts:+ @parameterized.expand(+ [+ ("normal_bucket", 100.0, None),+ ("spike", 1_000.0, VerdictType.SPIKE),+ ("drop", 20.0, VerdictType.DROP),+ ("silence", 0.0, VerdictType.SILENCE),+ ]+ )+ def test_observed_vs_steady_baseline(self, _name: str, observed: float, expected: VerdictType | None) -> None:+ history = steady_history()+ history.counts[INDEX] = observed+ assert evaluate(history) is expected++ def test_ongoing_incident_does_not_legitimize_itself(self) -> None:+ history = steady_history()+ history.counts[INDEX - 100 :] = 1_000.0+ assert evaluate(history) is VerdictType.SPIKE++ def test_severity_multiplier_widens_the_band(self) -> None:+ history = steady_history()+ history.counts[INDEX] = 145.0+ assert evaluate(history) is VerdictType.SPIKE+ widened_config = replace(CONFIG, severity_variance_multipliers={"error": 4.0})+ error_key = SeriesKey(namespace="prod", service="checkout", environment="us", severity="error")+ verdict = evaluate_series_bucket(history, INDEX, error_key, GRID, widened_config, MODEL)+ assert verdict is None+++class TestGates:+ def test_young_series_gets_no_verdict_even_on_a_huge_spike(self) -> None:+ history = steady_history()+ history.counts[: INDEX - CONFIG.persistence_window_buckets + 10] = 0.0+ history.counts[INDEX] = 10_000.0+ assert evaluate(history) is None++ def test_dead_ephemeral_pod_is_not_a_silent_service(self) -> None:+ history = steady_history()+ death = INDEX - CONFIG.persistence_recent_buckets - 10+ history.counts[death:] = 0.0+ assert evaluate(history) is None++ def test_recently_quiet_persistent_series_is_silence(self) -> None:+ history = steady_history()+ history.counts[INDEX - 3 :] = 0.0+ assert evaluate(history) is VerdictType.SILENCE++ def test_expired_series_leaves_coverage(self) -> None:+ history = steady_history()+ history.counts[INDEX - CONFIG.expiry_buckets - 5 :] = 0.0+ assert evaluate(history) is None++ def test_sub_floor_series_is_not_scored(self) -> None:+ history = steady_history(rate=2.0)+ history.counts[INDEX] = 50.0+ assert evaluate(history) is None++ def test_overnight_quiet_hours_cannot_fire_silence(self) -> None:+ hour_of_day = (GRID.minute_of_day // 60).astype(float)+ counts = np.where((hour_of_day >= 8) & (hour_of_day < 20), 100.0, 0.0)+ history = SeriesHistory(grid_start=GRID_START, counts=counts)+ night_index = INDEX - 2 # 23:45 UTC — learned rate ~0+ assert history.counts[night_index] == 0.0+ assert evaluate(history, night_index) is None+++class TestTiers:+ @parameterized.expand(+ [+ (200.0, TrafficTier.A),+ (50.0, TrafficTier.B),+ (10.0, TrafficTier.C),+ (1.0, TrafficTier.D),+ ]+ )+ def test_tier_from_trailing_rate(self, rate: float, expected: TrafficTier) -> None:+ assert traffic_tier(steady_history(rate), INDEX, CONFIG) is expected+++class TestEvaluateTick:+ def test_returns_verdicts_for_anomalous_series_only(self) -> None:+ quiet = steady_history()+ spiking = steady_history()+ spiking.counts[INDEX] = 10_000.0+ other_key = SeriesKey(namespace="prod", service="worker", environment="us", severity="info")+ verdicts = evaluate_tick({KEY: quiet, other_key: spiking}, INDEX, GRID, CONFIG, MODEL)+ assert [(v.key, v.verdict_type) for v in verdicts] == [(other_key, VerdictType.SPIKE)]diff --git a/products/apm/backend/tests/test_anomaly_issues.py b/products/apm/backend/tests/test_anomaly_issues.pynew file mode 100644index 000000000000..a68f6e91c73e--- /dev/null+++ b/products/apm/backend/tests/test_anomaly_issues.py@@ -0,0 +1,128 @@+from parameterized import parameterized++from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.issues import (+ IssueAction,+ IssueSnapshot,+ IssueState,+ evaluate_issue_transition,+ fingerprint_for,+ required_consecutive,+)+from products.apm.backend.logic.anomaly_detection.types import Direction, SeriesKey, TrafficTier, VerdictType++CONFIG = DetectionConfig(open_after_buckets=2, resolve_after_buckets=3, reopen_window_buckets=100)++KEY = SeriesKey(namespace="prod", service="checkout", environment="us", severity="error")+++def run_sequence(events: list[VerdictType | None], required: int = 2) -> list[IssueAction]:+ snapshot: IssueSnapshot | None = None+ actions = []+ for index, verdict_type in enumerate(events):+ outcome = evaluate_issue_transition(snapshot, verdict_type, index, required, CONFIG)+ snapshot = outcome.snapshot+ actions.append(outcome.action)+ return actions+++SPIKE = VerdictType.SPIKE+DROP = VerdictType.DROP+SILENCE = VerdictType.SILENCE+N = None+NONE = IssueAction.NONE+++class TestIssueTransitions:+ @parameterized.expand(+ [+ ("opens_after_required_consecutive", [SPIKE, SPIKE], 2, [NONE, IssueAction.OPEN]),+ ("single_blip_never_opens", [SPIKE, N, SPIKE, N], 2, [NONE, NONE, NONE, NONE]),+ ("opens_immediately_when_required_is_one", [SILENCE], 1, [IssueAction.OPEN]),+ (+ "active_records_then_resolves_after_sustained_recovery",+ [SPIKE, SPIKE, SPIKE, N, N, N],+ 2,+ [NONE, IssueAction.OPEN, IssueAction.RECORD, NONE, NONE, IssueAction.RESOLVE],+ ),+ (+ "recovery_counter_resets_on_recurrence",+ [SPIKE, SPIKE, N, N, SPIKE, N, N, N],+ 2,+ [NONE, IssueAction.OPEN, NONE, NONE, IssueAction.RECORD, NONE, NONE, IssueAction.RESOLVE],+ ),+ (+ "drop_deepening_into_silence_escalates_within_issue",+ [DROP, DROP, SILENCE],+ 2,+ [NONE, IssueAction.OPEN, IssueAction.ESCALATE],+ ),+ (+ "silence_does_not_deescalate_to_drop",+ [SILENCE, SILENCE, DROP],+ 2,+ [NONE, IssueAction.OPEN, IssueAction.RECORD],+ ),+ (+ "resolved_issue_reopens_on_recurrence",+ [SPIKE, SPIKE, N, N, N, SPIKE, SPIKE],+ 2,+ [NONE, IssueAction.OPEN, NONE, NONE, IssueAction.RESOLVE, NONE, IssueAction.REOPEN],+ ),+ ]+ )+ def test_transition_sequences(+ self, _name: str, events: list[VerdictType | None], required: int, expected: list[IssueAction]+ ) -> None:+ assert run_sequence(events, required) == expected++ def test_recurrence_past_reopen_window_starts_a_fresh_issue(self) -> None:+ snapshot = IssueSnapshot(+ state=IssueState.RESOLVED,+ kind=SPIKE,+ consecutive_anomalous=0,+ consecutive_normal=5,+ last_anomalous_index=10,+ opened_at_index=1,+ )+ outcome = evaluate_issue_transition(snapshot, SPIKE, 10 + CONFIG.reopen_window_buckets + 1, 1, CONFIG)+ assert outcome.action is IssueAction.OPEN+ assert outcome.snapshot is not None+ assert outcome.snapshot.opened_at_index == 10 + CONFIG.reopen_window_buckets + 1++ def test_pending_kind_escalates_before_open(self) -> None:+ actions = run_sequence([DROP, SILENCE], required=2)+ assert actions == [NONE, IssueAction.OPEN]+++class TestFingerprints:+ def test_spike_fingerprints_are_per_severity(self) -> None:+ error_key = KEY+ info_key = SeriesKey(namespace="prod", service="checkout", environment="us", severity="info")+ assert fingerprint_for(error_key, SPIKE) != fingerprint_for(info_key, SPIKE)++ @parameterized.expand([(DROP,), (SILENCE,)])+ def test_down_fingerprints_omit_severity(self, verdict_type: VerdictType) -> None:+ error_key = KEY+ info_key = SeriesKey(namespace="prod", service="checkout", environment="us", severity="info")+ fp = fingerprint_for(error_key, verdict_type)+ assert fp == fingerprint_for(info_key, verdict_type)+ assert fp.severity is None+ assert fp.direction is Direction.DOWN++ def test_drop_and_silence_share_a_fingerprint(self) -> None:+ assert fingerprint_for(KEY, DROP) == fingerprint_for(KEY, SILENCE)+++class TestRequiredConsecutive:+ @parameterized.expand(+ [+ (SILENCE, TrafficTier.A, 1),+ (SILENCE, TrafficTier.B, 2),+ (SILENCE, TrafficTier.C, 3),+ (SPIKE, TrafficTier.A, 2),+ (DROP, TrafficTier.C, 2),+ ]+ )+ def test_tier_and_kind_mapping(self, verdict_type: VerdictType, tier: TrafficTier, expected: int) -> None:+ assert required_consecutive(verdict_type, tier, CONFIG) == expecteddiff --git a/products/apm/backend/tests/test_anomaly_validation.py b/products/apm/backend/tests/test_anomaly_validation.pynew file mode 100644index 000000000000..84263c268c3a--- /dev/null+++ b/products/apm/backend/tests/test_anomaly_validation.py@@ -0,0 +1,157 @@+from datetime import UTC, datetime+from zoneinfo import ZoneInfo++import numpy as np+from parameterized import parameterized++from products.apm.backend.logic.anomaly_detection.bands import PoissonBandModel+from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid+from products.apm.backend.logic.anomaly_detection.config import DetectionConfig+from products.apm.backend.logic.anomaly_detection.constants import BUCKETS_PER_DAY, BUCKETS_PER_WEEK+from products.apm.backend.logic.anomaly_detection.types import SeriesKey, TrafficTier+from products.apm.backend.logic.anomaly_detection.validation.harness import run_model, silence_gate_ablation+from products.apm.backend.logic.anomaly_detection.validation.simulation import (+ AnomalyKind,+ InjectedAnomaly,+ NegativeBinomialNoise,+ Scenario,+ SeasonalProfile,+ SeriesSpec,+ apply_anomaly,+ generate_counts,+ inject_anomalies,+ seasonal_multipliers,+)++GRID_START = datetime(2026, 1, 5, tzinfo=UTC)+GRID_LENGTH = 4 * BUCKETS_PER_WEEK+GRID = TimeGrid.build(GRID_START, GRID_LENGTH, ZoneInfo("UTC"))++CONFIG = DetectionConfig(+ min_history_buckets=BUCKETS_PER_DAY,+ cold_start_until_buckets=7 * BUCKETS_PER_DAY,+ developing_until_buckets=52 * BUCKETS_PER_WEEK,+ persistence_window_buckets=BUCKETS_PER_DAY,+ persistence_recent_buckets=24,+ level_adjustment_enabled=False,+)+++def make_spec(**overrides: object) -> SeriesSpec:+ defaults: dict = {+ "key": SeriesKey(namespace="default", service="svc", environment="production", severity="info"),+ "tier": TrafficTier.A,+ "profile": SeasonalProfile.FLAT,+ "mean_per_bucket": 200.0,+ "cv": 0.12,+ }+ defaults.update(overrides)+ return SeriesSpec(**defaults)+++class TestGenerator:+ @parameterized.expand(+ [+ ("tier_a_info", 1_500.0, 0.12),+ ("tier_b_info", 60.0, 0.35),+ ("error_overdispersed", 6.0, 2.2),+ ]+ )+ def test_counts_match_target_mean_and_cv(self, _name: str, mean: float, cv: float) -> None:+ spec = make_spec(mean_per_bucket=mean, cv=cv)+ counts = generate_counts(spec, GRID, np.random.default_rng(3))+ observed_mean = float(np.mean(counts))+ observed_cv = float(np.std(counts) / observed_mean)+ assert abs(observed_mean - mean) / mean < 0.15+ assert abs(observed_cv - cv) / cv < 0.35++ def test_ephemeral_series_is_zero_outside_lifetime(self) -> None:+ spec = make_spec(birth_index=100, death_index=200, mean_per_bucket=50.0)+ counts = generate_counts(spec, GRID, np.random.default_rng(3))+ assert np.all(counts[:100] == 0)+ assert np.all(counts[200:] == 0)+ assert np.any(counts[100:200] > 0)++ @parameterized.expand([(SeasonalProfile.DIURNAL, 1.8), (SeasonalProfile.CRON, 5.0)])+ def test_seasonal_profiles_have_the_measured_shape(self, profile: SeasonalProfile, min_ratio: float) -> None:+ multipliers = seasonal_multipliers(profile, GRID)+ assert float(np.max(multipliers) / np.min(multipliers)) >= min_ratio+ assert abs(float(np.mean(multipliers)) - 1.0) < 0.01++ def test_weekend_peak_profile_peaks_on_saturday(self) -> None:+ multipliers = seasonal_multipliers(SeasonalProfile.WEEKEND_PEAK, GRID)+ saturday = multipliers[GRID.weekday == 5]+ weekday = multipliers[GRID.weekday < 5]+ assert float(np.min(saturday)) > float(np.max(weekday))++ def test_overdispersed_noise_actually_exceeds_poisson_variance(self) -> None:+ rng = np.random.default_rng(3)+ means = np.full(5_000, 20.0)+ counts = NegativeBinomialNoise().sample(rng, means, cv=2.0)+ assert float(np.var(counts)) > 3 * float(np.mean(counts))+++class TestInjection:+ def test_injection_modifies_counts_and_registers_truth(self) -> None:+ spec = make_spec()+ rng = np.random.default_rng(5)+ scenario = Scenario(specs=[spec], counts={spec.key: generate_counts(spec, GRID, rng)})+ eval_start = GRID_LENGTH - BUCKETS_PER_WEEK+ inject_anomalies(scenario, rng, eval_start, GRID_LENGTH, 1, 1, 1)+ assert len(scenario.anomalies) == 3+ silence = next(a for a in scenario.anomalies if a.kind is AnomalyKind.SILENCE)+ assert np.all(scenario.counts[spec.key][silence.start : silence.end] == 0)+ assert scenario.truth_at(spec.key, silence.start) is silence+ assert scenario.truth_at(spec.key, eval_start - 1) is None+++class TestHarness:+ def test_detector_finds_injected_anomalies_on_a_clean_series(self) -> None:+ spec = make_spec()+ rng = np.random.default_rng(11)+ scenario = Scenario(specs=[spec], counts={spec.key: generate_counts(spec, GRID, rng)})+ eval_start = GRID_LENGTH - BUCKETS_PER_WEEK+ inject_anomalies(scenario, rng, eval_start, GRID_LENGTH, 2, 1, 1)+ report = run_model(scenario, GRID, CONFIG, PoissonBandModel(), eval_start, GRID_LENGTH)+ group = report.groups[(TrafficTier.A, "info")]+ assert group.window_recall == 1.0+ assert report.issues.opens_total >= 1++ def test_persistence_gate_suppresses_dead_pod_silence(self) -> None:+ eval_start_index = GRID_LENGTH - BUCKETS_PER_WEEK+ # Alive long enough to pass the baseline min-history and floor gates —+ # for shorter-lived pods those suppress silence with or without the+ # persistence gate, so the gate's marginal effect is on the death side.+ pod = make_spec(+ key=SeriesKey(namespace="default", service="pod-1", environment="production", severity="info"),+ tier=TrafficTier.C,+ mean_per_bucket=20.0,+ cv=0.5,+ birth_index=eval_start_index - 2 * BUCKETS_PER_DAY,+ death_index=eval_start_index + BUCKETS_PER_DAY // 2,+ )+ steady = make_spec()+ rng = np.random.default_rng(13)+ scenario = Scenario(+ specs=[steady, pod],+ counts={s.key: generate_counts(s, GRID, rng) for s in (steady, pod)},+ )+ eval_start = GRID_LENGTH - BUCKETS_PER_WEEK+ ablation = silence_gate_ablation(scenario, GRID, CONFIG, PoissonBandModel(), eval_start, GRID_LENGTH)+ with_gate = ablation["full design"]+ without_gate = ablation["no persistence gate"]+ # A multi-day pod's death is indistinguishable from a dead worker at+ # death time (the characterization's residual FP), so the gate's+ # contract is bounding the firing window, not eliminating it.+ assert with_gate.silence_fp_ephemeral <= CONFIG.persistence_recent_buckets+ assert without_gate.silence_fp_ephemeral >= 5 * max(with_gate.silence_fp_ephemeral, 1)++ def test_level_shifted_series_is_excluded_from_precision_metrics(self) -> None:+ spec = make_spec()+ rng = np.random.default_rng(17)+ counts = generate_counts(spec, GRID, rng)+ shift = InjectedAnomaly(spec.key, AnomalyKind.LEVEL_SHIFT, GRID_LENGTH - BUCKETS_PER_WEEK, GRID_LENGTH, 2.0)+ apply_anomaly(counts, shift)+ scenario = Scenario(specs=[spec], counts={spec.key: counts}, anomalies=[shift])+ report = run_model(scenario, GRID, CONFIG, PoissonBandModel(), GRID_LENGTH - BUCKETS_PER_WEEK, GRID_LENGTH)+ assert report.groups == {}