Skip to content

: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.

feat(apm): expose per-bucket anomaly evaluation detail (#78719)

Jon McCallum4873f51a10a5
diff --git a/products/apm/backend/facade/api.py b/products/apm/backend/facade/api.py
index 22f368d8b4bc..51bbd1210bfe 100644
--- a/products/apm/backend/facade/api.py
+++ b/products/apm/backend/facade/api.py
@@ -5,10 +5,70 @@ The ONLY module other products are allowed to import.
Accept frozen dataclasses, call logic/, return frozen
dataclasses. Never return ORM instances or import DRF.
-So far the only thing consuming products need from APM is whether it is switched
-on for a given team, so that is all this exposes for now.
+Exposes the flag check plus the pure anomaly-detection core (detector,
+issue state machine, config, and types) for consumers that bring their own
+counts — currently the logs product's JIT anomaly scan. The detector is
+infra-free by contract: everything re-exported here is a pure function or a
+frozen dataclass over counts.
"""
from products.apm.backend.feature_flags import is_apm_enabled
+from products.apm.backend.logic.anomaly_detection.bands import NegativeBinomialBandModel
+from products.apm.backend.logic.anomaly_detection.baseline import TimeGrid, candidate_slice_pad_buckets
+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.detector import (
+ evaluate_series_bucket,
+ evaluate_series_bucket_detail,
+ traffic_tier,
+)
+from products.apm.backend.logic.anomaly_detection.issues import (
+ IssueAction,
+ IssueFingerprint,
+ IssueSnapshot,
+ IssueState,
+ evaluate_issue_transition,
+ fingerprint_for,
+ required_consecutive,
+)
+from products.apm.backend.logic.anomaly_detection.types import (
+ Band,
+ BaselineStage,
+ BucketEvaluation,
+ BucketVerdict,
+ Direction,
+ SeriesHistory,
+ SeriesKey,
+ TrafficTier,
+ VerdictType,
+)
-__all__ = ["is_apm_enabled"]
+__all__ = [
+ "BUCKET_MINUTES",
+ "BUCKETS_PER_DAY",
+ "BUCKETS_PER_WEEK",
+ "Band",
+ "BaselineStage",
+ "BucketEvaluation",
+ "BucketVerdict",
+ "DetectionConfig",
+ "Direction",
+ "IssueAction",
+ "IssueFingerprint",
+ "IssueSnapshot",
+ "IssueState",
+ "NegativeBinomialBandModel",
+ "SeriesHistory",
+ "SeriesKey",
+ "TimeGrid",
+ "TrafficTier",
+ "VerdictType",
+ "candidate_slice_pad_buckets",
+ "evaluate_issue_transition",
+ "evaluate_series_bucket",
+ "evaluate_series_bucket_detail",
+ "fingerprint_for",
+ "is_apm_enabled",
+ "required_consecutive",
+ "traffic_tier",
+]
diff --git a/products/apm/backend/logic/anomaly_detection/baseline.py b/products/apm/backend/logic/anomaly_detection/baseline.py
index 187e262eecd9..470725145300 100644
--- a/products/apm/backend/logic/anomaly_detection/baseline.py
+++ b/products/apm/backend/logic/anomaly_detection/baseline.py
@@ -179,6 +179,18 @@ def _level_factor(
return float(np.clip(factor, 1.0 / config.level_factor_clamp, config.level_factor_clamp))
+def candidate_slice_pad_buckets(config: DetectionConfig) -> int:
+ """Half-width, in buckets, of the widest candidate pool any stage draws
+ around a daily or weekly step from the evaluated bucket.
+
+ A caller fetching sparse history (e.g. a just-in-time scan reading only the
+ time slices baselines can sample) must pad each daily/weekly slice by this
+ much per side to guarantee every position `_candidate_positions` can emit
+ is backed by fetched data.
+ """
+ return max(config.developing_pool_buckets, config.mature_pool_buckets) + _DST_SLACK_BUCKETS
+
+
def select_baseline(
history: SeriesHistory,
index: int,
diff --git a/products/apm/backend/logic/anomaly_detection/detector.py b/products/apm/backend/logic/anomaly_detection/detector.py
index 7c2e84ba1be3..dcbd4b3f3d7a 100644
--- a/products/apm/backend/logic/anomaly_detection/detector.py
+++ b/products/apm/backend/logic/anomaly_detection/detector.py
@@ -22,6 +22,7 @@ from products.apm.backend.logic.anomaly_detection.baseline import BaselineResult
from products.apm.backend.logic.anomaly_detection.config import DetectionConfig
from products.apm.backend.logic.anomaly_detection.types import (
BaselineStage,
+ BucketEvaluation,
BucketVerdict,
SeriesHistory,
SeriesKey,
@@ -78,38 +79,49 @@ def _band_multiplier(key: SeriesKey, baseline: BaselineResult, config: Detection
return factor
-def evaluate_series_bucket(
+def evaluate_series_bucket_detail(
history: SeriesHistory,
index: int,
key: SeriesKey,
grid: TimeGrid,
config: DetectionConfig,
band_model: BandModel,
-) -> BucketVerdict | None:
+) -> BucketEvaluation:
observed = float(history.counts[index])
if not _passes_gates(history, index, observed, config):
- return None
+ return BucketEvaluation(observed=observed, band=None, stage=None, tier=None, verdict=None)
baseline = select_baseline(history, index, grid, config)
if not baseline.scorable:
- return None
+ return BucketEvaluation(observed=observed, band=None, stage=baseline.stage, tier=None, verdict=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)
+ verdict: BucketVerdict | None = None
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
+ verdict = BucketVerdict(key, index, VerdictType.SILENCE, observed, band, baseline.stage, tier)
+ elif observed > band.upper:
+ verdict = BucketVerdict(key, index, VerdictType.SPIKE, observed, band, baseline.stage, tier)
+ elif observed < band.lower:
+ verdict = BucketVerdict(key, index, VerdictType.DROP, observed, band, baseline.stage, tier)
+ return BucketEvaluation(observed=observed, band=band, stage=baseline.stage, tier=tier, verdict=verdict)
+
+
+def evaluate_series_bucket(
+ history: SeriesHistory,
+ index: int,
+ key: SeriesKey,
+ grid: TimeGrid,
+ config: DetectionConfig,
+ band_model: BandModel,
+) -> BucketVerdict | None:
+ return evaluate_series_bucket_detail(history, index, key, grid, config, band_model).verdict
def evaluate_tick(
diff --git a/products/apm/backend/logic/anomaly_detection/types.py b/products/apm/backend/logic/anomaly_detection/types.py
index 5d3603a8a8d4..0bec1ffc006b 100644
--- a/products/apm/backend/logic/anomaly_detection/types.py
+++ b/products/apm/backend/logic/anomaly_detection/types.py
@@ -71,6 +71,22 @@ class BucketVerdict:
tier: TrafficTier
+@dataclass(frozen=True, slots=True)
+class BucketEvaluation:
+ """Full evaluation of one bucket, verdict or not.
+
+ ``band`` and ``tier`` are None when the bucket was gated out or the
+ baseline was unscorable — consumers that chart observed-vs-band use the
+ band wherever it exists, independent of whether a verdict fired.
+ """
+
+ observed: float
+ band: Band | None
+ stage: BaselineStage | None
+ tier: TrafficTier | None
+ verdict: BucketVerdict | None
+
+
@dataclass(slots=True)
class SeriesHistory:
"""Dense per-series counts on the 5-minute grid.
diff --git a/products/apm/backend/tests/test_anomaly_baseline.py b/products/apm/backend/tests/test_anomaly_baseline.py
index 96cf32acf1c7..72cb90945b0a 100644
--- a/products/apm/backend/tests/test_anomaly_baseline.py
+++ b/products/apm/backend/tests/test_anomaly_baseline.py
@@ -4,7 +4,12 @@ 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.baseline import (
+ MINUTES_PER_WEEK,
+ TimeGrid,
+ candidate_slice_pad_buckets,
+ 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
@@ -131,3 +136,43 @@ class TestDst:
after_shift = 3 * BUCKETS_PER_WEEK
assert not grid.is_dst_shift_week(before_shift)
assert grid.is_dst_shift_week(after_shift)
+
+
+DST_GRID_START = datetime(2026, 10, 5, tzinfo=UTC) # a Monday; US DST ends 2026-11-01
+DST_GRID_LENGTH = 5 * BUCKETS_PER_WEEK
+DST_GRID = TimeGrid.build(DST_GRID_START, DST_GRID_LENGTH, ZoneInfo("America/Los_Angeles"))
+
+
+class TestCandidateSlicePadding:
+ # Evaluated after the DST shift, so local-time matching selects candidates
+ # through the slack region beyond the pool — the padding guarantee's edge.
+ @parameterized.expand(
+ [
+ (
+ "cold_start",
+ DetectionConfig(level_adjustment_enabled=False, cold_start_until_buckets=100 * BUCKETS_PER_WEEK),
+ BaselineStage.COLD_START,
+ BUCKETS_PER_DAY,
+ ),
+ ("developing", NO_LEVEL_CONFIG, BaselineStage.DEVELOPING, BUCKETS_PER_WEEK),
+ (
+ "mature",
+ DetectionConfig(level_adjustment_enabled=False, developing_until_buckets=4 * BUCKETS_PER_WEEK),
+ BaselineStage.MATURE,
+ BUCKETS_PER_WEEK,
+ ),
+ ]
+ )
+ def test_samples_stay_within_padded_slices(
+ self, _name: str, config: DetectionConfig, expected_stage: BaselineStage, step_buckets: int
+ ) -> None:
+ index = DST_GRID_LENGTH - 1
+ counts = np.arange(DST_GRID_LENGTH, dtype=float) + 1.0 # value i+1 marks position i
+ history = SeriesHistory(grid_start=DST_GRID_START, counts=counts)
+ result = select_baseline(history, index, DST_GRID, config)
+ assert result.stage is expected_stage
+ assert result.samples.size > 0
+ positions = result.samples - 1.0
+ step_offset = (index - positions) % step_buckets
+ distance = np.minimum(step_offset, step_buckets - step_offset)
+ assert float(distance.max()) <= candidate_slice_pad_buckets(config)
diff --git a/products/apm/backend/tests/test_anomaly_detector.py b/products/apm/backend/tests/test_anomaly_detector.py
index 28ed9856b102..c3cecc4641c0 100644
--- a/products/apm/backend/tests/test_anomaly_detector.py
+++ b/products/apm/backend/tests/test_anomaly_detector.py
@@ -9,8 +9,19 @@ 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
+from products.apm.backend.logic.anomaly_detection.detector import (
+ evaluate_series_bucket,
+ evaluate_series_bucket_detail,
+ evaluate_tick,
+ traffic_tier,
+)
+from products.apm.backend.logic.anomaly_detection.types import (
+ BaselineStage,
+ SeriesHistory,
+ SeriesKey,
+ TrafficTier,
+ VerdictType,
+)
GRID_START = datetime(2026, 1, 5, tzinfo=UTC)
GRID_LENGTH = 15 * BUCKETS_PER_DAY
@@ -122,6 +133,26 @@ class TestTiers:
assert traffic_tier(steady_history(rate), INDEX, CONFIG) is expected
+class TestEvaluateDetail:
+ def test_in_band_bucket_still_reports_band_stage_and_tier(self) -> None:
+ detail = evaluate_series_bucket_detail(steady_history(), INDEX, KEY, GRID, CONFIG, MODEL)
+ assert detail.verdict is None
+ assert detail.band is not None
+ assert detail.band.lower <= detail.observed <= detail.band.upper
+ assert detail.stage is BaselineStage.DEVELOPING
+ assert detail.tier is TrafficTier.B
+
+ def test_gated_bucket_reports_observed_only(self) -> None:
+ history = steady_history(rate=2.0) # below the traffic floor
+ history.counts[INDEX] = 50.0
+ detail = evaluate_series_bucket_detail(history, INDEX, KEY, GRID, CONFIG, MODEL)
+ assert detail.observed == 50.0
+ assert detail.band is None
+ assert detail.stage is None
+ assert detail.tier is None
+ assert detail.verdict is None
+
+
class TestEvaluateTick:
def test_returns_verdicts_for_anomalous_series_only(self) -> None:
quiet = steady_history()