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(signals): add anomaly-search and anomaly-insight-get endpoints (#122849)

posthog[bot]fdc068fa91ce
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index 8a532f1bf37a..52c6885ba946 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -46,6 +46,7 @@ products/mcp_analytics/backend/tests/test_tool_tables.py
products/product_analytics/backend/hogql_queries
products/product_analytics/backend/tests/test_insight_data_checks.py
products/replay_vision/backend/tests/test_session_identity.py
+products/signals/backend/test/test_anomaly_search.py
products/signals/backend/test/test_anomaly_scoring_tick.py
products/web_analytics/backend/hogql_queries
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index 865b404a465a..d99384f71ec0 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -28,6 +28,7 @@ from products.product_analytics.backend.facade.contracts import (
InsightSeries,
InsightVariableDefinition,
SavedInsightDefinition,
+ ViewableInsight,
WatchedTrendsInsight,
)
from products.product_analytics.backend.models.insight import Insight
@@ -227,6 +228,20 @@ def user_can_view_insight(*, team: Team, user: User, insight_id: int) -> bool:
return access_control.check_access_level_for_object(insight, "viewer")
+def viewable_insights(*, team: Team, user: User, insight_ids: Collection[int]) -> list[ViewableInsight]:
+ """The live insights of this team among ``insight_ids`` that the user may view, in one query."""
+ if not insight_ids:
+ return []
+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
+ insights = access_control.filter_queryset_by_access_level(
+ Insight.objects.filter(team_id=team.id, id__in=insight_ids, deleted=False), resource="insight"
+ )
+ return [
+ ViewableInsight(id=insight_id, short_id=short_id, name=name or derived_name)
+ for insight_id, short_id, name, derived_name in insights.values_list("id", "short_id", "name", "derived_name")
+ ]
+
+
def save_saved_insight_query(
*, team: Team, user: User, insight_id: int, expected_query: dict[str, Any], query: dict[str, Any]
) -> str | None:
diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.py
index fb5f29db504e..d81dff904855 100644
--- a/products/product_analytics/backend/facade/contracts.py
+++ b/products/product_analytics/backend/facade/contracts.py
@@ -146,6 +146,14 @@ class WatchedTrendsInsight:
interval: str
+@dataclass(frozen=True)
+class ViewableInsight:
+ id: int
+ short_id: str
+ # The saved name, else the generated one. None when the insight has neither.
+ name: str | None
+
+
@dataclass(frozen=True)
class TeamEmailAccess:
# A match reveals that an email belongs to the team, so each source needs the caller to be allowed to read it.
diff --git a/products/signals/backend/anomaly_scores/config.py b/products/signals/backend/anomaly_scores/config.py
index 0f8938b4c115..dbecc1450d98 100644
--- a/products/signals/backend/anomaly_scores/config.py
+++ b/products/signals/backend/anomaly_scores/config.py
@@ -242,6 +242,16 @@ def parse_config(payload: Any) -> AnomalyScoringConfig:
)
+def covers_team(config: AnomalyScoringConfig, team: "Team") -> bool:
+ """Whether the tick scores this team's insights. The event quota check of `queue.eligible_teams` is left out."""
+ return (
+ config.enabled
+ and str(team.organization_id) in config.organization_ids
+ and team.id not in config.skip_team_ids
+ and (not config.allow_team_ids or team.id in config.allow_team_ids)
+ )
+
+
def read_payload() -> dict | None:
return read_flag_payload(ANOMALY_SCORING_FLAG, ANOMALY_SCORING_FLAG_DISTINCT_ID)
diff --git a/products/signals/backend/anomaly_scores/read.py b/products/signals/backend/anomaly_scores/read.py
new file mode 100644
index 000000000000..108add2041ce
--- /dev/null
+++ b/products/signals/backend/anomaly_scores/read.py
@@ -0,0 +1,470 @@
+"""Read the `$anomaly_score` events of a project back, as anomaly rates per series and as scored buckets.
+
+A bucket can be scored more than once, so every read keeps the newest result of each series and bucket.
+Warm-up rows have a null score and count nowhere. A bucket that was not scored is unknown, never 0.
+A raw score ranks buckets within one series only, so a ranking across series uses rates, never scores.
+"""
+
+import json
+import math
+import datetime
+from collections.abc import Collection, Mapping, Sequence
+from typing import Any, cast
+from zoneinfo import ZoneInfo
+
+from posthog.schema import IntervalType
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.interval_specs import interval_spec
+from posthog.models import Team
+
+from products.signals.backend.anomaly_scores.config import DEFAULT_PROFILE
+from products.signals.backend.anomaly_scores.queue import SCORE_EVENT, SOURCE_INSIGHT
+from products.signals.backend.anomaly_scores.scoring import bucket_end
+
+# The window before the requested range that `baseline_rate` covers.
+BASELINE_WINDOW = datetime.timedelta(days=30)
+# One row is one series. Far more than the series of every watched insight of one project.
+MAX_SERIES = 10_000
+MAX_BUCKETS = 2_000
+# Each rate shrinks toward its baseline by this many buckets, so 1 flagged of 1 scored does not top a ranking.
+PRIOR_BUCKETS = 10
+# The prior when no series of the project has a scored baseline: about what a 0.95 threshold flags on noise.
+DEFAULT_PRIOR_RATE = 0.05
+# The intervals the scorer writes. Any member can capture a row with another interval, such as `second`,
+# and stepping through its buckets over a long range would take hours.
+SCORED_INTERVALS = frozenset(DEFAULT_PROFILE.intervals)
+
+_LATEST_BUCKETS = """
+SELECT
+ toInt(properties.$anomaly_insight_id) AS insight_id,
+ properties.$anomaly_series_key AS series_key,
+ timestamp AS bucket_start,
+ toFloat(properties.$anomaly_score) AS score,
+ toInt(properties.$anomaly_flag) AS flag,
+ toFloat(properties.$anomaly_value) AS value,
+ properties.$anomaly_interval AS bucket_interval,
+ properties.$anomaly_series_label AS series_label,
+ properties.$anomaly_breakdown_value AS breakdown_value,
+ properties.$anomaly_detector AS detector,
+ properties.$anomaly_detector_version AS detector_version,
+ properties.$anomaly_profile AS profile,
+ JSONExtractString(properties, '$anomaly_details') AS details,
+ toDateTime(properties.$anomaly_scored_at) AS scored_at
+FROM events
+WHERE event = {event}
+ AND properties.$anomaly_source = {source}
+ AND timestamp >= {since}
+ AND timestamp <= {until}
+ AND {scope}
+ORDER BY scored_at DESC
+LIMIT 1 BY series_key, bucket_start
+"""
+
+_SERIES_QUERY = f"""
+SELECT
+ insight_id,
+ series_key,
+ argMax(series_label, bucket_start),
+ argMax(breakdown_value, bucket_start),
+ argMax(bucket_interval, bucket_start),
+ argMax(detector, bucket_start),
+ argMax(detector_version, bucket_start),
+ argMax(profile, bucket_start),
+ max(bucket_start),
+ countIf(score IS NOT NULL AND bucket_start >= {{date_from}}),
+ countIf(score IS NOT NULL AND bucket_start >= {{date_from}} AND flag = 1),
+ countIf(score IS NOT NULL AND bucket_start < {{date_from}}),
+ countIf(score IS NOT NULL AND bucket_start < {{date_from}} AND flag = 1),
+ maxIf(bucket_start, score IS NOT NULL AND bucket_start >= {{date_from}}),
+ groupArrayIf(tuple(bucket_start, value, score), score IS NOT NULL AND bucket_start >= {{date_from}} AND flag = 1)
+FROM ({_LATEST_BUCKETS})
+GROUP BY insight_id, series_key
+LIMIT {{limit}}
+"""
+
+_BUCKETS_QUERY = f"""
+SELECT series_key, bucket_start, score, flag, value, details, scored_at
+FROM ({_LATEST_BUCKETS})
+WHERE bucket_start >= {{date_from}} AND {{keep}}
+ORDER BY bucket_start DESC, series_key
+LIMIT {{limit}}
+"""
+
+
+@frozen
+class FlaggedPoint:
+ bucket_start: datetime.datetime
+ value: float | None
+ score: float | None
+
+
+@frozen
+class SeriesSummary:
+ """One series over the requested range and the baseline window before it. Counts cover scored buckets only."""
+
+ insight_id: int
+ series_key: str
+ series_label: str | None
+ breakdown_value: str | None
+ interval: IntervalType
+ detector: str | None
+ detector_version: str | None
+ profile: str | None
+ # Any bucket of the series, scored or warm-up, so expected buckets can line up with its bucket starts.
+ newest_bucket: datetime.datetime
+ scored_buckets: int
+ flagged_buckets: int
+ baseline_scored_buckets: int
+ baseline_flagged_buckets: int
+ # The newest scored bucket in the range. None when no bucket of the range was scored.
+ scored_through: datetime.datetime | None
+ # Every flagged bucket of the range, newest first.
+ flagged_points: tuple[FlaggedPoint, ...]
+
+ @property
+ def anomaly_rate(self) -> float | None:
+ return self.flagged_buckets / self.scored_buckets if self.scored_buckets else None
+
+ @property
+ def baseline_rate(self) -> float | None:
+ return self.baseline_flagged_buckets / self.baseline_scored_buckets if self.baseline_scored_buckets else None
+
+ @property
+ def first_flagged_bucket(self) -> datetime.datetime | None:
+ return self.flagged_points[-1].bucket_start if self.flagged_points else None
+
+ @property
+ def last_flagged_bucket(self) -> datetime.datetime | None:
+ return self.flagged_points[0].bucket_start if self.flagged_points else None
+
+
+@frozen
+class SeriesSummaries:
+ series: list[SeriesSummary]
+ truncated: bool
+
+
+@frozen
+class ScoredBucket:
+ series_key: str
+ bucket_start: datetime.datetime
+ # False for a completed bucket of the range that has no score row. Its value, score and flag are unknown.
+ scored: bool
+ value: float | None = None
+ # Null on a warm-up row.
+ score: float | None = None
+ flag: bool | None = None
+ scored_at: datetime.datetime | None = None
+ details: dict[str, Any] | None = None
+
+
+@frozen
+class ScoredBuckets:
+ buckets: list[ScoredBucket]
+ truncated: bool
+
+
+@frozen
+class SeriesImportance:
+ on_dashboard: bool
+ viewers: int
+
+
+@frozen(order=True)
+class _RankKey:
+ """Sorts smallest first, field by field, so each measure is negated to put the largest first."""
+
+ negative_lift: float
+ negative_flagged_buckets: int
+ negative_last_flagged: float
+ off_dashboard: bool
+ negative_viewers: int
+ insight_id: int
+ series_key: str
+
+
+@frozen
+class InsightRollup:
+ """Buckets summed over the series of one insight. Rates of series are never averaged."""
+
+ series_count: int
+ flagged_series: int
+ scored_buckets: int
+ flagged_buckets: int
+ last_flagged_bucket: datetime.datetime | None
+
+ @property
+ def anomaly_rate(self) -> float | None:
+ return self.flagged_buckets / self.scored_buckets if self.scored_buckets else None
+
+
+def _local(value: datetime.datetime, timezone: ZoneInfo) -> datetime.datetime:
+ aware = value.replace(tzinfo=datetime.UTC) if value.tzinfo is None else value
+ return aware.astimezone(timezone)
+
+
+def _float(value: Any) -> float | None:
+ return float(value) if isinstance(value, int | float) and math.isfinite(value) else None
+
+
+def _text(value: Any) -> str | None:
+ return None if value is None or value == "" else str(value)
+
+
+def _details(value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, str):
+ return None
+ try:
+ details = json.loads(value)
+ except ValueError:
+ return None
+ return details if isinstance(details, dict) else None
+
+
+def _scope(insight_ids: Collection[int] | None, series_key: str | None) -> ast.Expr:
+ exprs: list[ast.Expr] = []
+ if insight_ids is not None:
+ exprs.append(
+ parse_expr(
+ "toInt(properties.$anomaly_insight_id) IN {insight_ids}",
+ placeholders={
+ "insight_ids": ast.Tuple(
+ exprs=[ast.Constant(value=insight_id) for insight_id in sorted(insight_ids)]
+ )
+ },
+ )
+ )
+ if series_key is not None:
+ exprs.append(
+ parse_expr("properties.$anomaly_series_key = {series_key}", {"series_key": ast.Constant(value=series_key)})
+ )
+ if not exprs:
+ return ast.Constant(value=True)
+ return ast.And(exprs=exprs)
+
+
+def _placeholders(
+ *,
+ since: datetime.datetime,
+ until: datetime.datetime,
+ insight_ids: Collection[int] | None,
+ series_key: str | None,
+) -> dict[str, ast.Expr]:
+ return {
+ "event": ast.Constant(value=SCORE_EVENT),
+ "source": ast.Constant(value=SOURCE_INSIGHT),
+ "since": ast.Constant(value=since),
+ "until": ast.Constant(value=until),
+ "scope": _scope(insight_ids, series_key),
+ }
+
+
+def series_summaries(
+ team: Team,
+ *,
+ date_from: datetime.datetime,
+ date_to: datetime.datetime,
+ insight_ids: Collection[int] | None = None,
+ series_key: str | None = None,
+) -> SeriesSummaries:
+ """Each series with a score row from ``date_from - BASELINE_WINDOW`` to ``date_to``, in one scan."""
+ if insight_ids is not None and not insight_ids:
+ return SeriesSummaries(series=[], truncated=False)
+ tag_queries(product=Product.SIGNALS, feature=Feature.ALERTING)
+ response = execute_hogql_query(
+ _SERIES_QUERY,
+ team,
+ query_type="AnomalyScoresSeriesSummaries",
+ placeholders={
+ **_placeholders(
+ since=date_from - BASELINE_WINDOW, until=date_to, insight_ids=insight_ids, series_key=series_key
+ ),
+ "date_from": ast.Constant(value=date_from),
+ "limit": ast.Constant(value=MAX_SERIES + 1),
+ },
+ ch_user=ClickHouseUser.DEFAULT,
+ )
+ rows = cast(list[tuple[Any, ...]], response.results or [])
+ timezone = team.timezone_info
+ series: list[SeriesSummary] = []
+ for (
+ insight_id,
+ key,
+ label,
+ breakdown_value,
+ interval,
+ detector,
+ detector_version,
+ profile,
+ newest_bucket,
+ scored,
+ flagged,
+ baseline_scored,
+ baseline_flagged,
+ scored_through,
+ points,
+ ) in rows[:MAX_SERIES]:
+ # Any member can capture an event with any properties, so a row may not name a real series.
+ if insight_id is None or not key or interval not in SCORED_INTERVALS:
+ continue
+ flagged_points = sorted(
+ (
+ FlaggedPoint(bucket_start=_local(start, timezone), value=_float(value), score=_float(score))
+ for start, value, score in points
+ ),
+ key=lambda point: point.bucket_start,
+ reverse=True,
+ )
+ series.append(
+ SeriesSummary(
+ insight_id=int(insight_id),
+ series_key=str(key),
+ series_label=_text(label),
+ breakdown_value=_text(breakdown_value),
+ interval=IntervalType(interval),
+ detector=_text(detector),
+ detector_version=_text(detector_version),
+ profile=_text(profile),
+ newest_bucket=_local(newest_bucket, timezone),
+ scored_buckets=int(scored),
+ flagged_buckets=int(flagged),
+ baseline_scored_buckets=int(baseline_scored),
+ baseline_flagged_buckets=int(baseline_flagged),
+ scored_through=_local(scored_through, timezone) if scored else None,
+ flagged_points=tuple(flagged_points),
+ )
+ )
+ return SeriesSummaries(series=series, truncated=len(rows) > MAX_SERIES)
+
+
+def latest_buckets(
+ team: Team,
+ *,
+ insight_id: int,
+ date_from: datetime.datetime,
+ date_to: datetime.datetime,
+ series_key: str | None = None,
+ include_warmup: bool = False,
+ limit: int = MAX_BUCKETS,
+) -> ScoredBuckets:
+ """The newest result of each scored bucket of one insight in the range, newest first, up to ``limit``."""
+ tag_queries(product=Product.SIGNALS, feature=Feature.ALERTING)
+ response = execute_hogql_query(
+ _BUCKETS_QUERY,
+ team,
+ query_type="AnomalyScoresLatestBuckets",
+ placeholders={
+ **_placeholders(since=date_from, until=date_to, insight_ids=[insight_id], series_key=series_key),
+ "date_from": ast.Constant(value=date_from),
+ "keep": ast.Constant(value=True) if include_warmup else parse_expr("score IS NOT NULL"),
+ "limit": ast.Constant(value=limit + 1),
+ },
+ ch_user=ClickHouseUser.DEFAULT,
+ )
+ rows = cast(list[tuple[Any, ...]], response.results or [])
+ timezone = team.timezone_info
+ buckets = [
+ ScoredBucket(
+ series_key=str(key),
+ bucket_start=_local(start, timezone),
+ scored=True,
+ value=_float(value),
+ score=_float(score),
+ flag=None if flag is None else bool(flag),
+ scored_at=None if scored_at is None else _local(scored_at, timezone),
+ details=_details(details),
+ )
+ for key, start, score, flag, value, details, scored_at in rows[:limit]
+ if key
+ ]
+ return ScoredBuckets(buckets=buckets, truncated=len(rows) > limit)
+
+
+def _previous_start(start: datetime.datetime, interval: IntervalType) -> datetime.datetime:
+ if interval == IntervalType.HOUR:
+ return (start.astimezone(datetime.UTC) - datetime.timedelta(hours=1)).astimezone(start.tzinfo)
+ return start - interval_spec(interval).period
+
+
+def bucket_starts(
+ anchor: datetime.datetime,
+ interval: IntervalType,
+ *,
+ date_from: datetime.datetime,
+ date_to: datetime.datetime,
+ now: datetime.datetime,
+) -> list[datetime.datetime]:
+ """The completed bucket starts from ``date_from`` to ``date_to``, oldest first, aligned to ``anchor``.
+
+ ``anchor`` is any bucket start of the series, so the buckets line up with the insight's own buckets.
+ """
+ start = anchor
+ while start > date_from:
+ start = _previous_start(start, interval)
+ while start < date_from:
+ start = bucket_end(start, interval)
+ starts: list[datetime.datetime] = []
+ while start <= date_to and bucket_end(start, interval) <= now:
+ starts.append(start)
+ start = bucket_end(start, interval)
+ return starts
+
+
+def prior_rate(series: Sequence[SeriesSummary]) -> float:
+ """The project's baseline rate, summed over every series, for series that have no baseline of their own."""
+ scored = sum(summary.baseline_scored_buckets for summary in series)
+ flagged = sum(summary.baseline_flagged_buckets for summary in series)
+ return flagged / scored if scored else DEFAULT_PRIOR_RATE
+
+
+def rate_lift(summary: SeriesSummary, prior: float) -> float:
+ """The smoothed rate in the range less the smoothed baseline rate. Only a ranking uses it."""
+ baseline = summary.baseline_rate if summary.baseline_rate is not None else prior
+ rate = (summary.flagged_buckets + PRIOR_BUCKETS * baseline) / (summary.scored_buckets + PRIOR_BUCKETS)
+ smoothed_baseline = (summary.baseline_flagged_buckets + PRIOR_BUCKETS * prior) / (
+ summary.baseline_scored_buckets + PRIOR_BUCKETS
+ )
+ return rate - smoothed_baseline
+
+
+def rank_series(
+ series: Sequence[SeriesSummary], *, prior: float, importance: Mapping[int, SeriesImportance]
+) -> list[SeriesSummary]:
+ """Most anomalous first, using only measures that compare across series and intervals.
+
+ Rate lift first, then flagged buckets, then the newest flag, then the insight's importance.
+ """
+ unknown = SeriesImportance(on_dashboard=False, viewers=0)
+
+ def key(summary: SeriesSummary) -> _RankKey:
+ last_flagged = summary.last_flagged_bucket
+ insight_importance = importance.get(summary.insight_id, unknown)
+ return _RankKey(
+ negative_lift=-rate_lift(summary, prior),
+ negative_flagged_buckets=-summary.flagged_buckets,
+ negative_last_flagged=-last_flagged.timestamp() if last_flagged else math.inf,
+ off_dashboard=not insight_importance.on_dashboard,
+ negative_viewers=-insight_importance.viewers,
+ insight_id=summary.insight_id,
+ series_key=summary.series_key,
+ )
+
+ return sorted(series, key=key)
+
+
+def rollup(series: Sequence[SeriesSummary]) -> InsightRollup:
+ last_flagged = [summary.last_flagged_bucket for summary in series if summary.last_flagged_bucket is not None]
+ return InsightRollup(
+ series_count=len(series),
+ flagged_series=sum(1 for summary in series if summary.flagged_buckets),
+ scored_buckets=sum(summary.scored_buckets for summary in series),
+ flagged_buckets=sum(summary.flagged_buckets for summary in series),
+ last_flagged_bucket=max(last_flagged) if last_flagged else None,
+ )
diff --git a/products/signals/backend/anomaly_scores/search.py b/products/signals/backend/anomaly_scores/search.py
new file mode 100644
index 000000000000..44c68fc66d85
--- /dev/null
+++ b/products/signals/backend/anomaly_scores/search.py
@@ -0,0 +1,387 @@
+"""Anomaly search and insight history: the read layer joined with insight access and usage.
+
+Rows of insights that are deleted, or that the user cannot read, are dropped. A series that was not
+scored in the range does not appear, so each answer also says how many insights were checked.
+"""
+
+import json
+import datetime
+from collections.abc import Collection, Sequence
+from urllib.parse import urlencode
+
+from django.db import models
+
+from posthog.schema import IntervalType
+
+from posthog.dataclasses import frozen
+from posthog.interval_specs import interval_spec
+from posthog.models import Team, User
+from posthog.utils import absolute_uri
+
+from products.dashboards.backend.facade.api import dashboards_by_insight, live_tile_insight_ids, viewable_dashboard_ref
+from products.product_analytics.backend.facade.api import viewable_insights
+from products.product_analytics.backend.facade.contracts import ViewableInsight
+from products.signals.backend.anomaly_scores.config import MAX_LIMITS, covers_team, parse_config, read_payload
+from products.signals.backend.anomaly_scores.queue import watched_insights
+from products.signals.backend.anomaly_scores.read import (
+ MAX_BUCKETS,
+ FlaggedPoint,
+ InsightRollup,
+ ScoredBucket,
+ SeriesImportance,
+ SeriesSummary,
+ bucket_starts,
+ latest_buckets,
+ prior_rate,
+ rank_series,
+ rollup,
+ series_summaries,
+)
+from products.signals.backend.anomaly_scores.scoring import bucket_end
+from products.signals.backend.anomaly_scores.selection import insight_usage
+
+TOP_SERIES = 3
+FLAGGED_POINTS = 5
+# The insight link shows this many buckets before the first flag and after the last one.
+URL_PADDING_BUCKETS = 7
+# The scorer writes at most this many series per insight. More come from events any member can capture.
+MAX_INSIGHT_SERIES = MAX_LIMITS.max_series
+SCORING_DISABLED_MESSAGE = "Anomaly scoring is not enabled for this project, so no insight is scored."
+
+
+class AnomalyInterval(models.TextChoices):
+ HOUR = "hour", "Hour"
+ DAY = "day", "Day"
+ WEEK = "week", "Week"
+ MONTH = "month", "Month"
+
+
+class AnomalyGroupBy(models.TextChoices):
+ SERIES = "series", "Series"
+ INSIGHT = "insight", "Insight"
+
+
+class AnomalyDashboardNotFound(Exception):
+ pass
+
+
+@frozen
+class AnomalySearchFilters:
+ date_from: datetime.datetime
+ date_to: datetime.datetime
+ insight_id: int | None = None
+ dashboard_id: int | None = None
+ interval: IntervalType | None = None
+ only_flagged: bool = True
+ group_by: AnomalyGroupBy = AnomalyGroupBy.SERIES
+ limit: int = 25
+
+
+@frozen
+class SeriesRow:
+ summary: SeriesSummary
+ insight: ViewableInsight
+ insight_url: str
+ expected_buckets: int
+ # Newest first.
+ flagged_points: tuple[FlaggedPoint, ...]
+
+ @property
+ def coverage(self) -> float | None:
+ return min(1.0, self.summary.scored_buckets / self.expected_buckets) if self.expected_buckets else None
+
+
+@frozen
+class InsightRow:
+ insight: ViewableInsight
+ insight_url: str
+ rollup: InsightRollup
+ top_series: list[SeriesSummary]
+
+
+@frozen
+class AnomalySearchResult:
+ scoring_enabled: bool
+ watched_insights: int
+ insights_scored_in_range: int
+ series: list[SeriesRow]
+ insights: list[InsightRow]
+ truncated: bool
+ # Says why the result is empty. None when it is not.
+ message: str | None
+
+
+@frozen
+class AnomalyHistoryFilters:
+ insight_id: int
+ date_from: datetime.datetime
+ date_to: datetime.datetime
+ series_key: str | None = None
+ include_buckets: bool = True
+ include_warmup: bool = False
+
+
+@frozen
+class SeriesHistory:
+ summary: SeriesSummary
+ expected_buckets: int
+ # Oldest first. Empty when the request leaves buckets out.
+ buckets: list[ScoredBucket]
+
+ @property
+ def coverage(self) -> float | None:
+ return min(1.0, self.summary.scored_buckets / self.expected_buckets) if self.expected_buckets else None
+
+
+@frozen
+class AnomalyInsightHistory:
+ scoring_enabled: bool
+ insight: ViewableInsight
+ insight_url: str
+ # From the newest scored bucket of the insight. None when no bucket was scored in the range.
+ interval: IntervalType | None
+ profile: str | None
+ detector: str | None
+ detector_version: str | None
+ rollup: InsightRollup
+ series: list[SeriesHistory]
+ truncated: bool
+ message: str | None
+
+
+def insight_url(
+ team: Team, insight: ViewableInsight, flagged: Sequence[datetime.datetime], interval: IntervalType | None
+) -> str:
+ """A link to the insight. With flagged buckets, its date range covers them with a few buckets around."""
+ url = absolute_uri(f"/project/{team.project_id}/insights/{insight.short_id}")
+ if not flagged or interval is None:
+ return url
+ padding = interval_spec(interval).period * URL_PADDING_BUCKETS
+ date_range = {
+ "date_from": (min(flagged) - padding).isoformat(),
+ "date_to": (bucket_end(max(flagged), interval) + padding).isoformat(),
+ }
+ return f"{url}?{urlencode({'filters_override': json.dumps(date_range, separators=(',', ':'))})}"
+
+
+def _flagged_starts(series: Sequence[SeriesSummary]) -> list[datetime.datetime]:
+ return [point.bucket_start for summary in series for point in summary.flagged_points]
+
+
+def _expected_buckets(
+ summary: SeriesSummary, date_from: datetime.datetime, date_to: datetime.datetime, now: datetime.datetime
+) -> int:
+ return len(bucket_starts(summary.newest_bucket, summary.interval, date_from=date_from, date_to=date_to, now=now))
+
+
+def _importance(team: Team, insight_ids: Collection[int], now: datetime.datetime) -> dict[int, SeriesImportance]:
+ if not insight_ids:
+ return {}
+ usage = insight_usage(team_id=team.id, insight_ids=insight_ids, now=now)
+ on_dashboard = dashboards_by_insight(insight_ids, team_id=team.id)
+ return {
+ insight_id: SeriesImportance(on_dashboard=insight_id in on_dashboard, viewers=usage[insight_id].viewers)
+ for insight_id in insight_ids
+ }
+
+
+def _requested_insight_ids(team: Team, user: User, filters: AnomalySearchFilters) -> set[int] | None:
+ """The insights the filters allow, or None for every insight."""
+ insight_ids: set[int] | None = None
+ if filters.dashboard_id is not None:
+ if viewable_dashboard_ref(filters.dashboard_id, team=team, user=user) is None:
+ raise AnomalyDashboardNotFound()
+ insight_ids = set(live_tile_insight_ids(filters.dashboard_id))
+ if filters.insight_id is not None:
+ insight_ids = {filters.insight_id} if insight_ids is None else insight_ids & {filters.insight_id}
+ return insight_ids
+
+
+def _empty_message(*, scoring_enabled: bool, watched: int, scored_in_range: int) -> str:
+ if not scoring_enabled:
+ return SCORING_DISABLED_MESSAGE
+ if not scored_in_range:
+ return f"No insight was scored in this range. Scoring checks {watched} watched insights, a few at a time."
+ return (
+ f"Nothing was flagged in this range among the {scored_in_range} insights scored. "
+ "Insights that were not scored in the range were not checked."
+ )
+
+
+def search(team: Team, user: User, filters: AnomalySearchFilters, now: datetime.datetime) -> AnomalySearchResult:
+ """The anomaly rate of each series in the range, most anomalous first, by series or by insight."""
+ config = parse_config(read_payload())
+ scoring_enabled = covers_team(config, team)
+ requested = _requested_insight_ids(team, user, filters)
+ intervals = (filters.interval,) if filters.interval is not None else config.intervals
+ watched = {insight.insight_id for insight in watched_insights([team.id], intervals, now)}
+ if requested is not None:
+ watched &= requested
+
+ summaries = series_summaries(team, date_from=filters.date_from, date_to=filters.date_to, insight_ids=requested)
+ insights = {
+ insight.id: insight
+ for insight in viewable_insights(
+ team=team, user=user, insight_ids=watched | {summary.insight_id for summary in summaries.series}
+ )
+ }
+ readable = [summary for summary in summaries.series if summary.insight_id in insights]
+ in_range = [
+ summary
+ for summary in readable
+ if summary.scored_buckets and (filters.interval is None or summary.interval == filters.interval)
+ ]
+ ranked = rank_series(
+ in_range,
+ prior=prior_rate(readable),
+ importance=_importance(team, {summary.insight_id for summary in in_range}, now),
+ )
+ scored_in_range = len({summary.insight_id for summary in in_range})
+
+ series_rows: list[SeriesRow] = []
+ insight_rows: list[InsightRow] = []
+ if filters.group_by == AnomalyGroupBy.SERIES:
+ matching = [summary for summary in ranked if summary.flagged_buckets or not filters.only_flagged]
+ truncated = len(matching) > filters.limit
+ series_rows = [
+ SeriesRow(
+ summary=summary,
+ insight=insights[summary.insight_id],
+ insight_url=insight_url(
+ team, insights[summary.insight_id], _flagged_starts([summary]), summary.interval
+ ),
+ expected_buckets=_expected_buckets(summary, filters.date_from, filters.date_to, now),
+ flagged_points=summary.flagged_points[:FLAGGED_POINTS],
+ )
+ for summary in matching[: filters.limit]
+ ]
+ else:
+ by_insight: dict[int, list[SeriesSummary]] = {}
+ for summary in ranked:
+ by_insight.setdefault(summary.insight_id, []).append(summary)
+ matching_insights = [
+ (insight_id, series)
+ for insight_id, series in by_insight.items()
+ if any(summary.flagged_buckets for summary in series) or not filters.only_flagged
+ ]
+ truncated = len(matching_insights) > filters.limit
+ insight_rows = [
+ InsightRow(
+ insight=insights[insight_id],
+ insight_url=insight_url(team, insights[insight_id], _flagged_starts(series), series[0].interval),
+ rollup=rollup(series),
+ top_series=[summary for summary in series if summary.flagged_buckets][:TOP_SERIES],
+ )
+ for insight_id, series in matching_insights[: filters.limit]
+ ]
+
+ watched_count = len(watched & insights.keys())
+ return AnomalySearchResult(
+ scoring_enabled=scoring_enabled,
+ watched_insights=watched_count,
+ insights_scored_in_range=scored_in_range,
+ series=series_rows,
+ insights=insight_rows,
+ truncated=truncated or summaries.truncated,
+ message=None
+ if series_rows or insight_rows
+ else _empty_message(scoring_enabled=scoring_enabled, watched=watched_count, scored_in_range=scored_in_range),
+ )
+
+
+def _series_buckets(
+ series_key: str,
+ starts: list[datetime.datetime],
+ scored: list[ScoredBucket],
+ *,
+ scored_since: datetime.datetime | None,
+) -> list[ScoredBucket]:
+ """Scored rows and a `scored: false` row for each completed bucket without one, oldest first.
+
+ ``scored_since`` is the oldest scored row a capped query returned, so no gap is made up before it.
+ """
+ by_start = {
+ start: ScoredBucket(series_key=series_key, bucket_start=start, scored=False)
+ for start in starts
+ if scored_since is None or start >= scored_since
+ }
+ for bucket in scored:
+ by_start[bucket.bucket_start] = bucket
+ return [by_start[start] for start in sorted(by_start)]
+
+
+def insight_history(
+ team: Team, user: User, filters: AnomalyHistoryFilters, now: datetime.datetime
+) -> AnomalyInsightHistory | None:
+ """Every series of one insight with its scored buckets, or None when the user cannot read the insight."""
+ readable = viewable_insights(team=team, user=user, insight_ids=[filters.insight_id])
+ if not readable:
+ return None
+ insight = readable[0]
+ scoring_enabled = covers_team(parse_config(read_payload()), team)
+ summaries = series_summaries(
+ team,
+ date_from=filters.date_from,
+ date_to=filters.date_to,
+ insight_ids=[insight.id],
+ series_key=filters.series_key,
+ )
+ # A series with only baseline rows was not scored in the range at all.
+ in_range = [summary for summary in summaries.series if summary.newest_bucket >= filters.date_from]
+ ranked = rank_series(in_range, prior=prior_rate(summaries.series), importance={})
+ truncated = summaries.truncated or len(ranked) > MAX_INSIGHT_SERIES
+ ranked = ranked[:MAX_INSIGHT_SERIES]
+
+ scored_by_series: dict[str, list[ScoredBucket]] = {}
+ scored_since: datetime.datetime | None = None
+ if filters.include_buckets and ranked:
+ latest = latest_buckets(
+ team,
+ insight_id=insight.id,
+ date_from=filters.date_from,
+ date_to=filters.date_to,
+ series_key=filters.series_key,
+ include_warmup=filters.include_warmup,
+ )
+ for bucket in latest.buckets:
+ scored_by_series.setdefault(bucket.series_key, []).append(bucket)
+ if latest.truncated and latest.buckets:
+ truncated = True
+ scored_since = min(bucket.bucket_start for bucket in latest.buckets)
+
+ # Each series keeps at most an equal share of the cap, its newest buckets, so the total stays within it.
+ per_series = MAX_BUCKETS // max(1, len(ranked))
+ series: list[SeriesHistory] = []
+ for summary in ranked:
+ starts = bucket_starts(
+ summary.newest_bucket, summary.interval, date_from=filters.date_from, date_to=filters.date_to, now=now
+ )
+ buckets = (
+ _series_buckets(
+ summary.series_key, starts, scored_by_series.get(summary.series_key, []), scored_since=scored_since
+ )
+ if filters.include_buckets
+ else []
+ )
+ if len(buckets) > per_series:
+ truncated = True
+ buckets = buckets[-per_series:]
+ series.append(SeriesHistory(summary=summary, expected_buckets=len(starts), buckets=buckets))
+
+ newest = max(in_range, key=lambda summary: summary.newest_bucket, default=None)
+ message = None
+ if newest is None:
+ message = "No bucket of this insight was scored in this range." if scoring_enabled else SCORING_DISABLED_MESSAGE
+ return AnomalyInsightHistory(
+ scoring_enabled=scoring_enabled,
+ insight=insight,
+ insight_url=insight_url(team, insight, _flagged_starts(ranked), newest.interval if newest else None),
+ interval=newest.interval if newest else None,
+ profile=newest.profile if newest else None,
+ detector=newest.detector if newest else None,
+ detector_version=newest.detector_version if newest else None,
+ rollup=rollup(in_range),
+ series=series,
+ truncated=truncated,
+ message=message,
+ )
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 16f02d4c1ee2..7eb64ac3f5df 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -35,6 +35,16 @@ from products.signals.backend.activity_summary.read import (
ActivitySummaryVersionView as ActivitySummaryVersionView,
ActivitySummaryView as ActivitySummaryView,
)
+from products.signals.backend.anomaly_scores import search as anomaly_search
+from products.signals.backend.anomaly_scores.search import (
+ AnomalyDashboardNotFound as AnomalyDashboardNotFound,
+ AnomalyGroupBy as AnomalyGroupBy,
+ AnomalyHistoryFilters as AnomalyHistoryFilters,
+ AnomalyInsightHistory as AnomalyInsightHistory,
+ AnomalyInterval as AnomalyInterval,
+ AnomalySearchFilters as AnomalySearchFilters,
+ AnomalySearchResult as AnomalySearchResult,
+)
from products.signals.backend.artefact_schemas import (
# Re-exported so the Slack mention handler can label the task it starts from a report's
# notification thread without naming the relationship vocabulary itself.
@@ -221,6 +231,18 @@ def list_activity_summary_versions(
return activity_summary_read.list_versions(team, user_id, limit=limit, version=version)
+def search_anomalies(*, team: Team, user: User, filters: AnomalySearchFilters, now: datetime) -> AnomalySearchResult:
+ """The anomaly rate of each scored insight series the user can read, most anomalous first."""
+ return anomaly_search.search(team, user, filters, now)
+
+
+def get_anomaly_insight_history(
+ *, team: Team, user: User, filters: AnomalyHistoryFilters, now: datetime
+) -> AnomalyInsightHistory | None:
+ """Every scored series of one insight with its buckets, or None when the user cannot read the insight."""
+ return anomaly_search.insight_history(team, user, filters, now)
+
+
@frozen
class ScoutTrialSkill:
name: str
diff --git a/products/signals/backend/presentation/anomalies.py b/products/signals/backend/presentation/anomalies.py
new file mode 100644
index 000000000000..12516122e700
--- /dev/null
+++ b/products/signals/backend/presentation/anomalies.py
@@ -0,0 +1,483 @@
+import datetime
+from typing import Any
+
+from django.utils import timezone
+
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.schema import IntervalType
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import (
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ is_mcp_request,
+)
+from posthog.dataclasses import frozen
+from posthog.event_usage import report_user_action
+from posthog.models import User
+from posthog.permissions import APIScopePermission, is_service_auth
+from posthog.ph_client import feature_enabled_or_false
+from posthog.utils import relative_date_parse
+
+from products.signals.backend.facade import api as signals_facade
+from products.signals.backend.facade.api import (
+ AnomalyDashboardNotFound,
+ AnomalyGroupBy,
+ AnomalyHistoryFilters,
+ AnomalyInterval,
+ AnomalySearchFilters,
+)
+
+ANOMALIES_SEARCH_FLAG = "anomalies-search"
+READ_EVENT = "anomaly search read"
+# Bounds the work of filling unscored buckets: an hourly series has 24 buckets a day.
+MAX_RANGE = datetime.timedelta(days=366)
+
+
+@frozen
+class _DateRange:
+ date_from: datetime.datetime
+ date_to: datetime.datetime
+
+
+class ProjectDateTimeField(serializers.DateTimeField):
+ """Keeps the offset of the project timezone. The default field converts every value to UTC."""
+
+ def to_representation(self, value: datetime.datetime) -> str:
+ return value.isoformat()
+
+
+class AnomalySearchQuerySerializer(serializers.Serializer):
+ date_from = serializers.CharField(
+ default="-7d",
+ help_text="Earliest bucket start in the range. A relative date such as `-7d` or `-24h`, or an ISO 8601 date.",
+ )
+ date_to = serializers.CharField(
+ required=False,
+ help_text="Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.",
+ )
+ insight_id = serializers.IntegerField(required=False, help_text="Only the series of this insight, by numeric id.")
+ dashboard_id = serializers.IntegerField(
+ required=False, help_text="Only the series of the insights on this dashboard, by numeric id."
+ )
+ interval = serializers.ChoiceField(
+ choices=AnomalyInterval.choices, required=False, help_text="Only series with this interval."
+ )
+ only_flagged = serializers.BooleanField(
+ default=True,
+ help_text="Only series, or insights, with at least one flagged bucket in the range. Set false to also list quiet ones.",
+ )
+ group_by = serializers.ChoiceField(
+ choices=AnomalyGroupBy.choices,
+ default=AnomalyGroupBy.SERIES,
+ help_text="`series` returns one row per series in `series`. `insight` returns one row per insight in `insights`.",
+ )
+ limit = serializers.IntegerField(min_value=1, max_value=100, default=25, help_text="The most rows to return.")
+
+
+class AnomalyInsightQuerySerializer(serializers.Serializer):
+ insight_id = serializers.IntegerField(help_text="The insight, by numeric id.")
+ series_key = serializers.CharField(
+ required=False, help_text="Only this series, by the `series_key` of an anomaly search row."
+ )
+ date_from = serializers.CharField(
+ default="-30d",
+ help_text="Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.",
+ )
+ date_to = serializers.CharField(
+ required=False,
+ help_text="Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.",
+ )
+ include_buckets = serializers.BooleanField(
+ default=True, help_text="Return the buckets of each series. Set false for the per-series summary only."
+ )
+ include_warmup = serializers.BooleanField(
+ default=False,
+ help_text="Include warm-up buckets: scored rows with a null score and flag, written while the detector "
+ "still lacks history. When false, a warm-up bucket shows as `scored: false`.",
+ )
+
+
+class AnomalyFlaggedPointSerializer(serializers.Serializer):
+ bucket_start = ProjectDateTimeField(help_text="The start of the flagged bucket, in the project timezone.")
+ value = serializers.FloatField(allow_null=True, help_text="The series value of the bucket at scoring time.")
+ score = serializers.FloatField(
+ allow_null=True, help_text="The detector score of the bucket. Compare it only with buckets of the same series."
+ )
+
+
+class AnomalySeriesSerializer(serializers.Serializer):
+ insight_id = serializers.IntegerField(source="summary.insight_id", help_text="The numeric id of the insight.")
+ insight_name = serializers.CharField(
+ source="insight.name", allow_null=True, help_text="The name of the insight. Null when it has none."
+ )
+ insight_url = serializers.CharField(
+ help_text="Opens the insight with a date range around the flagged buckets of this series."
+ )
+ series_key = serializers.CharField(
+ source="summary.series_key", help_text="Identifies the series. Pass it to anomaly insight history."
+ )
+ series_label = serializers.CharField(
+ source="summary.series_label", allow_null=True, help_text="The series name as the insight shows it."
+ )
+ breakdown_value = serializers.CharField(
+ source="summary.breakdown_value", allow_null=True, help_text="The breakdown value of the series, if any."
+ )
+ interval = serializers.ChoiceField(
+ source="summary.interval", choices=AnomalyInterval.choices, help_text="The bucket interval of the series."
+ )
+ scored_buckets = serializers.IntegerField(
+ source="summary.scored_buckets", help_text="Buckets in the range with a score. Warm-up buckets do not count."
+ )
+ flagged_buckets = serializers.IntegerField(
+ source="summary.flagged_buckets", help_text="Scored buckets in the range that the detector flagged."
+ )
+ anomaly_rate = serializers.FloatField(
+ source="summary.anomaly_rate", allow_null=True, help_text="`flagged_buckets / scored_buckets`."
+ )
+ expected_buckets = serializers.IntegerField(
+ help_text="Completed buckets of the series interval in the range, scored or not."
+ )
+ coverage = serializers.FloatField(
+ allow_null=True,
+ help_text="`scored_buckets / expected_buckets`: how much of the range was scored. Unscored buckets are unknown, not quiet.",
+ )
+ scored_through = ProjectDateTimeField(
+ source="summary.scored_through",
+ allow_null=True,
+ help_text="The newest scored bucket in the range. Buckets after it were not checked yet.",
+ )
+ baseline_rate = serializers.FloatField(
+ source="summary.baseline_rate",
+ allow_null=True,
+ help_text="The anomaly rate over the 30 days before the range. Null when no bucket was scored then.",
+ )
+ first_flagged_bucket = ProjectDateTimeField(
+ source="summary.first_flagged_bucket",
+ allow_null=True,
+ help_text="The oldest flagged bucket in the range, in the project timezone.",
+ )
+ last_flagged_bucket = ProjectDateTimeField(
+ source="summary.last_flagged_bucket",
+ allow_null=True,
+ help_text="The newest flagged bucket in the range, in the project timezone.",
+ )
+ flagged_points = AnomalyFlaggedPointSerializer(
+ many=True, help_text="Up to 5 flagged buckets in the range, newest first."
+ )
+
+
+class AnomalyTopSeriesSerializer(serializers.Serializer):
+ series_key = serializers.CharField(help_text="Identifies the series.")
+ series_label = serializers.CharField(allow_null=True, help_text="The series name as the insight shows it.")
+ breakdown_value = serializers.CharField(allow_null=True, help_text="The breakdown value of the series, if any.")
+ scored_buckets = serializers.IntegerField(help_text="Scored buckets of the series in the range.")
+ flagged_buckets = serializers.IntegerField(help_text="Flagged buckets of the series in the range.")
+ anomaly_rate = serializers.FloatField(allow_null=True, help_text="`flagged_buckets / scored_buckets`.")
+ baseline_rate = serializers.FloatField(
+ allow_null=True, help_text="The anomaly rate over the 30 days before the range."
+ )
+
+
+class AnomalyInsightRowSerializer(serializers.Serializer):
+ insight_id = serializers.IntegerField(source="insight.id", help_text="The numeric id of the insight.")
+ insight_name = serializers.CharField(
+ source="insight.name", allow_null=True, help_text="The name of the insight. Null when it has none."
+ )
+ insight_url = serializers.CharField(help_text="Opens the insight with a date range around its flagged buckets.")
+ series_count = serializers.IntegerField(
+ source="rollup.series_count", help_text="Series of the insight scored in the range."
+ )
+ flagged_series = serializers.IntegerField(
+ source="rollup.flagged_series", help_text="Series with at least one flagged bucket in the range."
+ )
+ scored_buckets = serializers.IntegerField(
+ source="rollup.scored_buckets", help_text="Scored buckets, summed over the series."
+ )
+ flagged_buckets = serializers.IntegerField(
+ source="rollup.flagged_buckets", help_text="Flagged buckets, summed over the series."
+ )
+ anomaly_rate = serializers.FloatField(
+ source="rollup.anomaly_rate",
+ allow_null=True,
+ help_text="Summed `flagged_buckets / scored_buckets`. Never an average of series rates.",
+ )
+ last_flagged_bucket = ProjectDateTimeField(
+ source="rollup.last_flagged_bucket", allow_null=True, help_text="The newest flagged bucket of any series."
+ )
+ top_series = AnomalyTopSeriesSerializer(many=True, help_text="Up to 3 flagged series, most anomalous first.")
+
+
+class AnomalySearchResponseSerializer(serializers.Serializer):
+ scoring_enabled = serializers.BooleanField(help_text="Whether anomaly scoring covers this project.")
+ watched_insights = serializers.IntegerField(
+ help_text="Insights that scoring watches: saved trends insights on a dashboard or viewed in the last 30 days."
+ )
+ insights_scored_in_range = serializers.IntegerField(
+ help_text="Insights with at least one scored bucket in the range. Results cover only these insights."
+ )
+ date_from = ProjectDateTimeField(help_text="The applied start of the range, in the project timezone.")
+ date_to = ProjectDateTimeField(help_text="The applied end of the range, in the project timezone.")
+ group_by = serializers.ChoiceField(choices=AnomalyGroupBy.choices, help_text="The applied grouping.")
+ series = AnomalySeriesSerializer(
+ many=True, help_text="One row per series, most anomalous first. Empty unless `group_by` is `series`."
+ )
+ insights = AnomalyInsightRowSerializer(
+ many=True, help_text="One row per insight, most anomalous first. Empty unless `group_by` is `insight`."
+ )
+ truncated = serializers.BooleanField(help_text="True when `limit` or a read cap left rows out.")
+ message = serializers.CharField(allow_null=True, help_text="Says why the result is empty. Null when it is not.")
+
+
+class AnomalyBucketSerializer(serializers.Serializer):
+ bucket_start = ProjectDateTimeField(help_text="The start of the bucket, in the project timezone.")
+ scored = serializers.BooleanField(
+ help_text="False for a completed bucket that has no score. Its value, score and flag are unknown, not 0."
+ )
+ value = serializers.FloatField(allow_null=True, help_text="The series value of the bucket at scoring time.")
+ score = serializers.FloatField(
+ allow_null=True, help_text="The detector score. Null on an unscored or warm-up bucket."
+ )
+ flag = serializers.BooleanField(
+ allow_null=True, help_text="Whether the detector flagged the bucket. Null on an unscored or warm-up bucket."
+ )
+ scored_at = ProjectDateTimeField(allow_null=True, help_text="When the bucket was scored.")
+ details = serializers.DictField(
+ child=serializers.JSONField(),
+ allow_null=True,
+ help_text="Detector-specific values for the bucket. The keys depend on the detector.",
+ )
+
+
+class AnomalyInsightSeriesSerializer(serializers.Serializer):
+ series_key = serializers.CharField(source="summary.series_key", help_text="Identifies the series.")
+ series_label = serializers.CharField(
+ source="summary.series_label", allow_null=True, help_text="The series name as the insight shows it."
+ )
+ breakdown_value = serializers.CharField(
+ source="summary.breakdown_value", allow_null=True, help_text="The breakdown value of the series, if any."
+ )
+ scored_buckets = serializers.IntegerField(
+ source="summary.scored_buckets", help_text="Buckets in the range with a score."
+ )
+ flagged_buckets = serializers.IntegerField(
+ source="summary.flagged_buckets", help_text="Scored buckets in the range that the detector flagged."
+ )
+ anomaly_rate = serializers.FloatField(
+ source="summary.anomaly_rate", allow_null=True, help_text="`flagged_buckets / scored_buckets`."
+ )
+ baseline_rate = serializers.FloatField(
+ source="summary.baseline_rate",
+ allow_null=True,
+ help_text="The anomaly rate over the 30 days before the range. Null when no bucket was scored then.",
+ )
+ expected_buckets = serializers.IntegerField(help_text="Completed buckets in the range, scored or not.")
+ coverage = serializers.FloatField(allow_null=True, help_text="`scored_buckets / expected_buckets`.")
+ last_flagged_bucket = ProjectDateTimeField(
+ source="summary.last_flagged_bucket", allow_null=True, help_text="The newest flagged bucket in the range."
+ )
+ buckets = AnomalyBucketSerializer(
+ many=True, help_text="Oldest first, the newest result of each bucket. Empty when `include_buckets` is false."
+ )
+
+
+class AnomalyInsightResponseSerializer(serializers.Serializer):
+ scoring_enabled = serializers.BooleanField(help_text="Whether anomaly scoring covers this project.")
+ insight_id = serializers.IntegerField(source="insight.id", help_text="The numeric id of the insight.")
+ insight_name = serializers.CharField(
+ source="insight.name", allow_null=True, help_text="The name of the insight. Null when it has none."
+ )
+ insight_url = serializers.CharField(help_text="Opens the insight with a date range around its flagged buckets.")
+ interval = serializers.ChoiceField(
+ choices=AnomalyInterval.choices, allow_null=True, help_text="The bucket interval the scorer used."
+ )
+ profile = serializers.CharField(allow_null=True, help_text="The scoring profile.")
+ detector = serializers.CharField(allow_null=True, help_text="The detector type, for example `zscore`.")
+ detector_version = serializers.CharField(
+ allow_null=True, help_text="A hash of the detector settings. It changes when the settings change."
+ )
+ series_count = serializers.IntegerField(source="rollup.series_count", help_text="Series scored in the range.")
+ flagged_series = serializers.IntegerField(
+ source="rollup.flagged_series", help_text="Series with at least one flagged bucket in the range."
+ )
+ scored_buckets = serializers.IntegerField(
+ source="rollup.scored_buckets", help_text="Scored buckets, summed over the series."
+ )
+ flagged_buckets = serializers.IntegerField(
+ source="rollup.flagged_buckets", help_text="Flagged buckets, summed over the series."
+ )
+ anomaly_rate = serializers.FloatField(
+ source="rollup.anomaly_rate",
+ allow_null=True,
+ help_text="Summed `flagged_buckets / scored_buckets`. Never an average of series rates.",
+ )
+ date_from = ProjectDateTimeField(help_text="The applied start of the range, in the project timezone.")
+ date_to = ProjectDateTimeField(help_text="The applied end of the range, in the project timezone.")
+ series = AnomalyInsightSeriesSerializer(many=True, help_text="Every scored series, most anomalous first.")
+ truncated = serializers.BooleanField(help_text="True when the cap of 2,000 buckets cut the history.")
+ message = serializers.CharField(allow_null=True, help_text="Says why the result is empty. Null when it is not.")
+
+
+class AnomalyViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Read-only anomaly rates of the saved trends insights that anomaly scoring checks."""
+
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "insight"
+ pagination_class = None
+
+ def _user(self, request: Request) -> User:
+ # The flag and insight access are both per user, so a request without a real user sees nothing.
+ if is_service_auth(request) or not isinstance(request.user, User) or not self._enabled(request.user):
+ raise NotFound()
+ return request.user
+
+ def _enabled(self, user: User) -> bool:
+ organization_id = str(self.team.organization_id)
+ return feature_enabled_or_false(
+ ANOMALIES_SEARCH_FLAG,
+ str(user.distinct_id),
+ groups={"organization": organization_id, "project": str(self.team.uuid)},
+ group_properties={
+ "organization": {"id": organization_id},
+ "project": {"id": self.team.id, "uuid": str(self.team.uuid)},
+ },
+ )
+
+ def _date_range(self, query: dict[str, Any], now: datetime.datetime) -> _DateRange:
+ timezone_info = self.team.timezone_info
+ try:
+ date_from = relative_date_parse(query["date_from"], timezone_info, now=now)
+ date_to = relative_date_parse(query["date_to"], timezone_info, now=now) if query.get("date_to") else now
+ except (ValueError, OverflowError):
+ raise ValidationError({"date_from": "Use a relative date such as -7d, or an ISO 8601 date."})
+ date_from, date_to = date_from.astimezone(timezone_info), date_to.astimezone(timezone_info)
+ if date_from >= date_to:
+ raise ValidationError({"date_from": "date_from must be before date_to."})
+ if date_to - date_from > MAX_RANGE:
+ raise ValidationError({"date_from": "The range can be at most 366 days."})
+ return _DateRange(date_from=date_from, date_to=date_to)
+
+ def _capture_read(self, request: Request, endpoint: str, **properties: Any) -> None:
+ report_user_action(
+ request.user,
+ READ_EVENT,
+ properties={"endpoint": endpoint, "via_mcp": is_mcp_request(request), **properties},
+ team=self.team,
+ request=request,
+ )
+
+ @validated_request(
+ query_serializer=AnomalySearchQuerySerializer,
+ responses={200: OpenApiResponse(response=AnomalySearchResponseSerializer)},
+ summary="Search anomalous insight series",
+ )
+ @action(detail=False, methods=["GET"], required_scopes=["insight:read"])
+ def search(self, request: ValidatedRequest, **kwargs: object) -> Response:
+ user = self._user(request)
+ query = request.validated_query_data
+ now = timezone.now()
+ date_range = self._date_range(query, now)
+ filters = AnomalySearchFilters(
+ date_from=date_range.date_from,
+ date_to=date_range.date_to,
+ insight_id=query.get("insight_id"),
+ dashboard_id=query.get("dashboard_id"),
+ interval=IntervalType(query["interval"]) if query.get("interval") else None,
+ only_flagged=query["only_flagged"],
+ group_by=AnomalyGroupBy(query["group_by"]),
+ limit=query["limit"],
+ )
+ try:
+ result = signals_facade.search_anomalies(team=self.team, user=user, filters=filters, now=now)
+ except AnomalyDashboardNotFound:
+ raise NotFound("Dashboard not found.")
+ self._capture_read(
+ request,
+ "search",
+ group_by=filters.group_by.value,
+ scoring_enabled=result.scoring_enabled,
+ rows=len(result.series) + len(result.insights),
+ insights_scored_in_range=result.insights_scored_in_range,
+ )
+ return Response(
+ AnomalySearchResponseSerializer(
+ {
+ "scoring_enabled": result.scoring_enabled,
+ "watched_insights": result.watched_insights,
+ "insights_scored_in_range": result.insights_scored_in_range,
+ "date_from": date_range.date_from,
+ "date_to": date_range.date_to,
+ "group_by": filters.group_by,
+ "series": result.series,
+ "insights": result.insights,
+ "truncated": result.truncated,
+ "message": result.message,
+ }
+ ).data
+ )
+
+ @validated_request(
+ query_serializer=AnomalyInsightQuerySerializer,
+ responses={
+ 200: OpenApiResponse(response=AnomalyInsightResponseSerializer),
+ 404: OpenApiResponse(description="The insight does not exist or the user cannot read it."),
+ },
+ summary="Get the scored anomaly history of an insight",
+ )
+ @action(detail=False, methods=["GET"], required_scopes=["insight:read"])
+ def insight(self, request: ValidatedRequest, **kwargs: object) -> Response:
+ user = self._user(request)
+ query = request.validated_query_data
+ now = timezone.now()
+ date_range = self._date_range(query, now)
+ history = signals_facade.get_anomaly_insight_history(
+ team=self.team,
+ user=user,
+ filters=AnomalyHistoryFilters(
+ insight_id=query["insight_id"],
+ date_from=date_range.date_from,
+ date_to=date_range.date_to,
+ series_key=query.get("series_key"),
+ include_buckets=query["include_buckets"],
+ include_warmup=query["include_warmup"],
+ ),
+ now=now,
+ )
+ if history is None:
+ raise NotFound("Insight not found.")
+ self._capture_read(
+ request,
+ "insight",
+ scoring_enabled=history.scoring_enabled,
+ series=len(history.series),
+ flagged_series=history.rollup.flagged_series,
+ )
+ return Response(
+ AnomalyInsightResponseSerializer(
+ {
+ "scoring_enabled": history.scoring_enabled,
+ "insight": history.insight,
+ "insight_url": history.insight_url,
+ "interval": history.interval,
+ "profile": history.profile,
+ "detector": history.detector,
+ "detector_version": history.detector_version,
+ "rollup": history.rollup,
+ "date_from": date_range.date_from,
+ "date_to": date_range.date_to,
+ "series": history.series,
+ "truncated": history.truncated,
+ "message": history.message,
+ }
+ ).data
+ )
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 368fe33cb9af..9f5bde2a552b 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
import products.signals.backend.views as signals
from products.signals.backend.presentation.activity_summary import ActivitySummaryViewSet
+from products.signals.backend.presentation.anomalies import AnomalyViewSet
from products.signals.backend.presentation.inbox_summary import InboxSummaryViewSet
from products.signals.backend.presentation.onboarding import InboxOnboardingViewSet
from products.signals.backend.presentation.scout_rubrics import SignalScoutRubricViewSet
@@ -28,6 +29,7 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"signals/activity_summary", ActivitySummaryViewSet, "project_signals_activity_summary", ["team_id"]
)
+ routers.projects.register(r"signals/anomalies", AnomalyViewSet, "project_signals_anomalies", ["team_id"])
routers.projects.register(
r"signals/scout/rubrics", SignalScoutRubricViewSet, "project_signals_scout_rubrics", ["team_id"]
)
diff --git a/products/signals/backend/test/test_anomaly_search.py b/products/signals/backend/test/test_anomaly_search.py
new file mode 100644
index 000000000000..42e688442ccf
--- /dev/null
+++ b/products/signals/backend/test/test_anomaly_search.py
@@ -0,0 +1,243 @@
+import datetime
+from typing import Any
+
+import time_machine
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import IntervalType
+
+from posthog.models import Team
+
+from products.product_analytics.backend.facade.models import Insight
+from products.signals.backend.anomaly_scores.emission import SCORER_DISTINCT_ID
+from products.signals.backend.anomaly_scores.read import SeriesSummary, prior_rate, rank_series, rollup
+from products.signals.backend.anomaly_scores.search import MAX_INSIGHT_SERIES
+
+NOW = datetime.datetime(2026, 10, 23, 12, tzinfo=datetime.UTC)
+
+
+def _day(day: int) -> datetime.datetime:
+ return datetime.datetime(2026, 10, day, tzinfo=datetime.UTC)
+
+
+def _summary(
+ key: str, *, scored: int, flagged: int, baseline_scored: int = 0, baseline_flagged: int = 0
+) -> SeriesSummary:
+ return SeriesSummary(
+ insight_id=1,
+ series_key=key,
+ series_label=key,
+ breakdown_value=None,
+ interval=IntervalType.DAY,
+ detector="zscore",
+ detector_version="v1",
+ profile="default-v1",
+ newest_bucket=_day(22),
+ scored_buckets=scored,
+ flagged_buckets=flagged,
+ baseline_scored_buckets=baseline_scored,
+ baseline_flagged_buckets=baseline_flagged,
+ scored_through=_day(22),
+ flagged_points=(),
+ )
+
+
+class TestAnomalyRanking(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "more_evidence_beats_one_lucky_bucket",
+ _summary("three_of_ten", scored=10, flagged=3),
+ _summary("one_of_one", scored=1, flagged=1),
+ ),
+ (
+ "quiet_baseline_beats_always_noisy",
+ _summary("quiet_before", scored=10, flagged=3, baseline_scored=30, baseline_flagged=0),
+ _summary("noisy_before", scored=10, flagged=3, baseline_scored=30, baseline_flagged=10),
+ ),
+ ]
+ )
+ def test_ranks_series_by_comparable_rates(
+ self, _name: str, expected_first: SeriesSummary, other: SeriesSummary
+ ) -> None:
+ series = [other, expected_first]
+ ranked = rank_series(series, prior=prior_rate(series), importance={})
+
+ assert [summary.series_key for summary in ranked] == [expected_first.series_key, other.series_key]
+
+ def test_rollup_sums_buckets_instead_of_averaging_rates(self) -> None:
+ insight = rollup(
+ [_summary("a", scored=1, flagged=1), _summary("b", scored=9, flagged=1), _summary("c", scored=5, flagged=0)]
+ )
+
+ assert (insight.series_count, insight.flagged_series, insight.scored_buckets, insight.flagged_buckets) == (
+ 3,
+ 2,
+ 15,
+ 2,
+ )
+ assert insight.anomaly_rate == 2 / 15
+
+
+@time_machine.travel(NOW, tick=False)
+class TestAnomalySearchAPI(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="Signups", saved=True)
+ flag = patch("products.signals.backend.presentation.anomalies.feature_enabled_or_false", return_value=True)
+ self.flag = flag.start()
+ self.addCleanup(flag.stop)
+ payload = patch(
+ "products.signals.backend.anomaly_scores.search.read_payload",
+ return_value={"enabled": True, "organization_ids": [str(self.organization.id)]},
+ )
+ self.payload = payload.start()
+ self.addCleanup(payload.stop)
+
+ def _score(
+ self,
+ bucket: datetime.datetime,
+ *,
+ score: float | None,
+ flag: int | None,
+ scored_at: datetime.datetime = NOW,
+ series_key: str = "signups",
+ interval: str = "day",
+ insight: Insight | None = None,
+ team: Team | None = None,
+ ) -> None:
+ _create_event(
+ team=team or self.team,
+ event="$anomaly_score",
+ distinct_id=SCORER_DISTINCT_ID,
+ timestamp=bucket,
+ properties={
+ "$anomaly_score": score,
+ "$anomaly_flag": flag,
+ "$anomaly_value": 10.0,
+ "$anomaly_bucket_start": bucket.isoformat(),
+ "$anomaly_interval": interval,
+ "$anomaly_series_key": series_key,
+ "$anomaly_source": "insight",
+ "$anomaly_insight_id": (insight or self.insight).id,
+ "$anomaly_series_label": series_key.title(),
+ "$anomaly_breakdown_value": None,
+ "$anomaly_detector": "zscore",
+ "$anomaly_detector_version": "v1",
+ "$anomaly_profile": "default-v1",
+ "$anomaly_scored_at": scored_at.isoformat(),
+ "$anomaly_details": '{"z": 3.1}',
+ },
+ )
+
+ def _score_history(self) -> None:
+ # Oct 19 was scored twice: the rescore unflagged it. Oct 20 is warm-up, Oct 21 was never scored.
+ self._score(_day(19), score=0.99, flag=1, scored_at=_day(20))
+ self._score(_day(19), score=0.40, flag=0, scored_at=_day(21))
+ self._score(_day(20), score=None, flag=None)
+ self._score(_day(22), score=0.98, flag=1)
+ self._score(_day(22), score=0.10, flag=0, series_key="logins")
+ # Any member can capture a row like this. The scorer never writes a `second` interval.
+ self._score(_day(22), score=0.99, flag=1, series_key="forged", interval="second")
+
+ def _get(self, endpoint: str, **params: Any) -> Any:
+ return self.client.get(f"/api/projects/{self.team.id}/signals/anomalies/{endpoint}/", params)
+
+ def test_search_counts_the_latest_result_of_each_scored_bucket(self) -> None:
+ self._score_history()
+
+ response = self._get("search", date_from="2026-10-19")
+
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert (body["scoring_enabled"], body["insights_scored_in_range"], body["message"]) == (True, 1, None)
+ assert len(body["series"]) == 1
+ row = body["series"][0]
+ assert {key: row[key] for key in ("series_key", "scored_buckets", "flagged_buckets", "expected_buckets")} == {
+ "series_key": "signups",
+ "scored_buckets": 2,
+ "flagged_buckets": 1,
+ "expected_buckets": 4,
+ }
+ assert (row["anomaly_rate"], row["coverage"], row["baseline_rate"]) == (0.5, 0.5, None)
+ assert row["last_flagged_bucket"] == row["first_flagged_bucket"] == "2026-10-22T00:00:00+00:00"
+ assert row["flagged_points"] == [{"bucket_start": "2026-10-22T00:00:00+00:00", "value": 10.0, "score": 0.98}]
+
+ def test_search_explains_an_empty_result_for_a_team_outside_the_scoring_payload(self) -> None:
+ self.payload.return_value = {"enabled": True, "organization_ids": []}
+
+ body = self._get("search").json()
+
+ assert (body["scoring_enabled"], body["series"]) == (False, [])
+ assert body["message"] == "Anomaly scoring is not enabled for this project, so no insight is scored."
+
+ def test_insight_returns_every_bucket_of_each_series_oldest_first(self) -> None:
+ self._score_history()
+
+ body = self._get("insight", insight_id=self.insight.id, date_from="2026-10-19").json()
+
+ assert (body["series_count"], body["flagged_series"], body["scored_buckets"], body["flagged_buckets"]) == (
+ 2,
+ 1,
+ 3,
+ 1,
+ )
+ series = {row["series_key"]: row for row in body["series"]}
+ assert [row["series_key"] for row in body["series"]] == ["signups", "logins"]
+ assert [
+ (bucket["bucket_start"][:10], bucket["scored"], bucket["score"], bucket["flag"])
+ for bucket in series["signups"]["buckets"]
+ ] == [
+ ("2026-10-19", True, 0.40, False),
+ ("2026-10-20", False, None, None),
+ ("2026-10-21", False, None, None),
+ ("2026-10-22", True, 0.98, True),
+ ]
+ assert series["signups"]["buckets"][-1]["details"] == {"z": 3.1}
+
+ def test_insight_narrows_to_one_series_and_shows_warmup_on_request(self) -> None:
+ self._score_history()
+
+ body = self._get(
+ "insight", insight_id=self.insight.id, date_from="2026-10-19", series_key="signups", include_warmup=True
+ ).json()
+
+ assert [row["series_key"] for row in body["series"]] == ["signups"]
+ warmup = body["series"][0]["buckets"][1]
+ assert (warmup["bucket_start"][:10], warmup["scored"], warmup["score"], warmup["value"]) == (
+ "2026-10-20",
+ True,
+ None,
+ 10.0,
+ )
+
+ def test_insight_caps_series_at_the_scorer_maximum(self) -> None:
+ for index in range(MAX_INSIGHT_SERIES + 1):
+ self._score(_day(22), score=0.5, flag=0, series_key=f"series_{index}")
+
+ body = self._get("insight", insight_id=self.insight.id, date_from="2026-10-19").json()
+
+ assert (len(body["series"]), body["series_count"], body["truncated"]) == (
+ MAX_INSIGHT_SERIES,
+ MAX_INSIGHT_SERIES + 1,
+ True,
+ )
+
+ def test_insight_returns_404_for_an_insight_the_user_cannot_read(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_insight = Insight.objects.create(team=other_team, name="Other", saved=True)
+ self._score(_day(22), score=0.98, flag=1, insight=other_insight)
+
+ assert self._get("insight", insight_id=other_insight.id).status_code == 404
+ assert self._get("search", date_from="2026-10-19").json()["series"] == []
+
+ @parameterized.expand([("search",), ("insight",)])
+ def test_returns_404_when_the_flag_is_off(self, endpoint: str) -> None:
+ self.flag.return_value = False
+
+ assert self._get(endpoint, insight_id=self.insight.id).status_code == 404
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index fa77dfddfcfd..a4dd4b434cc9 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -297,6 +297,349 @@ export interface ActivitySummaryVersionApi {
computed: ActivitySummaryComputedApi | null
}
+/**
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month
+ */
+export type AnomalyIntervalEnumApi = (typeof AnomalyIntervalEnumApi)[keyof typeof AnomalyIntervalEnumApi]
+
+export const AnomalyIntervalEnumApi = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+} as const
+
+/**
+ * Detector-specific values for the bucket. The keys depend on the detector.
+ * @nullable
+ */
+export type AnomalyBucketApiDetails = { [key: string]: unknown } | null
+
+export interface AnomalyBucketApi {
+ /** The start of the bucket, in the project timezone. */
+ bucket_start: string
+ /** False for a completed bucket that has no score. Its value, score and flag are unknown, not 0. */
+ scored: boolean
+ /**
+ * The series value of the bucket at scoring time.
+ * @nullable
+ */
+ value: number | null
+ /**
+ * The detector score. Null on an unscored or warm-up bucket.
+ * @nullable
+ */
+ score: number | null
+ /**
+ * Whether the detector flagged the bucket. Null on an unscored or warm-up bucket.
+ * @nullable
+ */
+ flag: boolean | null
+ /**
+ * When the bucket was scored.
+ * @nullable
+ */
+ scored_at: string | null
+ /**
+ * Detector-specific values for the bucket. The keys depend on the detector.
+ * @nullable
+ */
+ details: AnomalyBucketApiDetails
+}
+
+export interface AnomalyInsightSeriesApi {
+ /** Identifies the series. */
+ series_key: string
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null
+ /** Buckets in the range with a score. */
+ scored_buckets: number
+ /** Scored buckets in the range that the detector flagged. */
+ flagged_buckets: number
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null
+ /**
+ * The anomaly rate over the 30 days before the range. Null when no bucket was scored then.
+ * @nullable
+ */
+ baseline_rate: number | null
+ /** Completed buckets in the range, scored or not. */
+ expected_buckets: number
+ /**
+ * `scored_buckets / expected_buckets`.
+ * @nullable
+ */
+ coverage: number | null
+ /**
+ * The newest flagged bucket in the range.
+ * @nullable
+ */
+ last_flagged_bucket: string | null
+ /** Oldest first, the newest result of each bucket. Empty when `include_buckets` is false. */
+ buckets: AnomalyBucketApi[]
+}
+
+export interface AnomalyInsightResponseApi {
+ /** Whether anomaly scoring covers this project. */
+ scoring_enabled: boolean
+ /** The numeric id of the insight. */
+ insight_id: number
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null
+ /** Opens the insight with a date range around its flagged buckets. */
+ insight_url: string
+ /** The bucket interval the scorer used.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: AnomalyIntervalEnumApi | null
+ /**
+ * The scoring profile.
+ * @nullable
+ */
+ profile: string | null
+ /**
+ * The detector type, for example `zscore`.
+ * @nullable
+ */
+ detector: string | null
+ /**
+ * A hash of the detector settings. It changes when the settings change.
+ * @nullable
+ */
+ detector_version: string | null
+ /** Series scored in the range. */
+ series_count: number
+ /** Series with at least one flagged bucket in the range. */
+ flagged_series: number
+ /** Scored buckets, summed over the series. */
+ scored_buckets: number
+ /** Flagged buckets, summed over the series. */
+ flagged_buckets: number
+ /**
+ * Summed `flagged_buckets / scored_buckets`. Never an average of series rates.
+ * @nullable
+ */
+ anomaly_rate: number | null
+ /** The applied start of the range, in the project timezone. */
+ date_from: string
+ /** The applied end of the range, in the project timezone. */
+ date_to: string
+ /** Every scored series, most anomalous first. */
+ series: AnomalyInsightSeriesApi[]
+ /** True when the cap of 2,000 buckets cut the history. */
+ truncated: boolean
+ /**
+ * Says why the result is empty. Null when it is not.
+ * @nullable
+ */
+ message: string | null
+}
+
+/**
+ * * `series` - Series
+ * * `insight` - Insight
+ */
+export type AnomalyGroupByEnumApi = (typeof AnomalyGroupByEnumApi)[keyof typeof AnomalyGroupByEnumApi]
+
+export const AnomalyGroupByEnumApi = {
+ Series: 'series',
+ Insight: 'insight',
+} as const
+
+export interface AnomalyFlaggedPointApi {
+ /** The start of the flagged bucket, in the project timezone. */
+ bucket_start: string
+ /**
+ * The series value of the bucket at scoring time.
+ * @nullable
+ */
+ value: number | null
+ /**
+ * The detector score of the bucket. Compare it only with buckets of the same series.
+ * @nullable
+ */
+ score: number | null
+}
+
+export interface AnomalySeriesApi {
+ /** The numeric id of the insight. */
+ insight_id: number
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null
+ /** Opens the insight with a date range around the flagged buckets of this series. */
+ insight_url: string
+ /** Identifies the series. Pass it to anomaly insight history. */
+ series_key: string
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null
+ /** The bucket interval of the series.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: AnomalyIntervalEnumApi
+ /** Buckets in the range with a score. Warm-up buckets do not count. */
+ scored_buckets: number
+ /** Scored buckets in the range that the detector flagged. */
+ flagged_buckets: number
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null
+ /** Completed buckets of the series interval in the range, scored or not. */
+ expected_buckets: number
+ /**
+ * `scored_buckets / expected_buckets`: how much of the range was scored. Unscored buckets are unknown, not quiet.
+ * @nullable
+ */
+ coverage: number | null
+ /**
+ * The newest scored bucket in the range. Buckets after it were not checked yet.
+ * @nullable
+ */
+ scored_through: string | null
+ /**
+ * The anomaly rate over the 30 days before the range. Null when no bucket was scored then.
+ * @nullable
+ */
+ baseline_rate: number | null
+ /**
+ * The oldest flagged bucket in the range, in the project timezone.
+ * @nullable
+ */
+ first_flagged_bucket: string | null
+ /**
+ * The newest flagged bucket in the range, in the project timezone.
+ * @nullable
+ */
+ last_flagged_bucket: string | null
+ /** Up to 5 flagged buckets in the range, newest first. */
+ flagged_points: AnomalyFlaggedPointApi[]
+}
+
+export interface AnomalyTopSeriesApi {
+ /** Identifies the series. */
+ series_key: string
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null
+ /** Scored buckets of the series in the range. */
+ scored_buckets: number
+ /** Flagged buckets of the series in the range. */
+ flagged_buckets: number
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null
+ /**
+ * The anomaly rate over the 30 days before the range.
+ * @nullable
+ */
+ baseline_rate: number | null
+}
+
+export interface AnomalyInsightRowApi {
+ /** The numeric id of the insight. */
+ insight_id: number
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null
+ /** Opens the insight with a date range around its flagged buckets. */
+ insight_url: string
+ /** Series of the insight scored in the range. */
+ series_count: number
+ /** Series with at least one flagged bucket in the range. */
+ flagged_series: number
+ /** Scored buckets, summed over the series. */
+ scored_buckets: number
+ /** Flagged buckets, summed over the series. */
+ flagged_buckets: number
+ /**
+ * Summed `flagged_buckets / scored_buckets`. Never an average of series rates.
+ * @nullable
+ */
+ anomaly_rate: number | null
+ /**
+ * The newest flagged bucket of any series.
+ * @nullable
+ */
+ last_flagged_bucket: string | null
+ /** Up to 3 flagged series, most anomalous first. */
+ top_series: AnomalyTopSeriesApi[]
+}
+
+export interface AnomalySearchResponseApi {
+ /** Whether anomaly scoring covers this project. */
+ scoring_enabled: boolean
+ /** Insights that scoring watches: saved trends insights on a dashboard or viewed in the last 30 days. */
+ watched_insights: number
+ /** Insights with at least one scored bucket in the range. Results cover only these insights. */
+ insights_scored_in_range: number
+ /** The applied start of the range, in the project timezone. */
+ date_from: string
+ /** The applied end of the range, in the project timezone. */
+ date_to: string
+ /** The applied grouping.
+ *
+ * * `series` - Series
+ * * `insight` - Insight */
+ group_by: AnomalyGroupByEnumApi
+ /** One row per series, most anomalous first. Empty unless `group_by` is `series`. */
+ series: AnomalySeriesApi[]
+ /** One row per insight, most anomalous first. Empty unless `group_by` is `insight`. */
+ insights: AnomalyInsightRowApi[]
+ /** True when `limit` or a read cap left rows out. */
+ truncated: boolean
+ /**
+ * Says why the result is empty. Null when it is not.
+ * @nullable
+ */
+ message: string | null
+}
+
/**
* Per-repository base branch overrides for auto-started inbox PRs, keyed by 'organization/repository'. The branch is what the auto-PR targets; omit a repo (or send {}) to keep targeting the repo default branch.
*/
@@ -9691,6 +10034,103 @@ export type SignalsActivitySummaryVersionsRetrieveParams = {
version?: number
}
+export type SignalsAnomaliesInsightRetrieveParams = {
+ /**
+ * Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.
+ * @minLength 1
+ */
+ date_from?: string
+ /**
+ * Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.
+ * @minLength 1
+ */
+ date_to?: string
+ /**
+ * Return the buckets of each series. Set false for the per-series summary only.
+ */
+ include_buckets?: boolean
+ /**
+ * Include warm-up buckets: scored rows with a null score and flag, written while the detector still lacks history. When false, a warm-up bucket shows as `scored: false`.
+ */
+ include_warmup?: boolean
+ /**
+ * The insight, by numeric id.
+ */
+ insight_id: number
+ /**
+ * Only this series, by the `series_key` of an anomaly search row.
+ * @minLength 1
+ */
+ series_key?: string
+}
+
+export type SignalsAnomaliesSearchRetrieveParams = {
+ /**
+ * Only the series of the insights on this dashboard, by numeric id.
+ */
+ dashboard_id?: number
+ /**
+ * Earliest bucket start in the range. A relative date such as `-7d` or `-24h`, or an ISO 8601 date.
+ * @minLength 1
+ */
+ date_from?: string
+ /**
+ * Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.
+ * @minLength 1
+ */
+ date_to?: string
+ /**
+ * `series` returns one row per series in `series`. `insight` returns one row per insight in `insights`.
+ *
+ * * `series` - Series
+ * * `insight` - Insight
+ * @minLength 1
+ */
+ group_by?: SignalsAnomaliesSearchRetrieveGroupBy
+ /**
+ * Only the series of this insight, by numeric id.
+ */
+ insight_id?: number
+ /**
+ * Only series with this interval.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month
+ * @minLength 1
+ */
+ interval?: SignalsAnomaliesSearchRetrieveInterval
+ /**
+ * The most rows to return.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Only series, or insights, with at least one flagged bucket in the range. Set false to also list quiet ones.
+ */
+ only_flagged?: boolean
+}
+
+export type SignalsAnomaliesSearchRetrieveGroupBy =
+ (typeof SignalsAnomaliesSearchRetrieveGroupBy)[keyof typeof SignalsAnomaliesSearchRetrieveGroupBy]
+
+export const SignalsAnomaliesSearchRetrieveGroupBy = {
+ Series: 'series',
+ Insight: 'insight',
+} as const
+
+export type SignalsAnomaliesSearchRetrieveInterval =
+ (typeof SignalsAnomaliesSearchRetrieveInterval)[keyof typeof SignalsAnomaliesSearchRetrieveInterval]
+
+export const SignalsAnomaliesSearchRetrieveInterval = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+} as const
+
export type SignalsProcessingListParams = {
/**
* Number of results to return per page.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index e1dd8c8a2443..bb779f93498c 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -11,6 +11,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
ActivitySummaryApi,
ActivitySummaryVersionApi,
+ AnomalyInsightResponseApi,
+ AnomalySearchResponseApi,
CancelReportCheckRequestApi,
CommitDiffResponseApi,
CreateReportCheckRequestApi,
@@ -135,6 +137,8 @@ import type {
SignalUserAutonomyConfigApi,
SignalUserAutonomyConfigCreateApi,
SignalsActivitySummaryVersionsRetrieveParams,
+ SignalsAnomaliesInsightRetrieveParams,
+ SignalsAnomaliesSearchRetrieveParams,
SignalsProcessingListParams,
SignalsReportArtefactsListParams,
SignalsReportChecksListParams,
@@ -238,6 +242,74 @@ export const signalsActivitySummaryVersionsRetrieve = async (
})
}
+export const getSignalsAnomaliesInsightRetrieveUrl = (
+ projectId: string,
+ params: SignalsAnomaliesInsightRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/anomalies/insight/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/anomalies/insight/`
+}
+
+/**
+ * Read-only anomaly rates of the saved trends insights that anomaly scoring checks.
+ * @summary Get the scored anomaly history of an insight
+ */
+export const signalsAnomaliesInsightRetrieve = async (
+ projectId: string,
+ params: SignalsAnomaliesInsightRetrieveParams,
+ options?: RequestInit
+): Promise<AnomalyInsightResponseApi> => {
+ return apiMutator<AnomalyInsightResponseApi>(getSignalsAnomaliesInsightRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsAnomaliesSearchRetrieveUrl = (
+ projectId: string,
+ params?: SignalsAnomaliesSearchRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/anomalies/search/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/anomalies/search/`
+}
+
+/**
+ * Read-only anomaly rates of the saved trends insights that anomaly scoring checks.
+ * @summary Search anomalous insight series
+ */
+export const signalsAnomaliesSearchRetrieve = async (
+ projectId: string,
+ params?: SignalsAnomaliesSearchRetrieveParams,
+ options?: RequestInit
+): Promise<AnomalySearchResponseApi> => {
+ return apiMutator<AnomalySearchResponseApi>(getSignalsAnomaliesSearchRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsConfigListUrl = (projectId: string) => {
return `/api/projects/${projectId}/signals/config/`
}
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 3e6f7da482aa..cabfd981d0b5 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -35,6 +35,49 @@ tools:
point at. A 404 means activity summaries are not available for this project, or that the requested version
does not exist.
feature_flag: activity-summary
+ anomaly-insight-get:
+ operation: signals_anomalies_insight_retrieve
+ enabled: true
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get the scored anomaly history of an insight
+ description: >
+ Get the full anomaly scoring history of one saved trends insight: every scored series with its anomaly rate,
+ baseline rate and coverage, and each bucket of the range oldest first with its value, score, flag and
+ detector `details`. A completed bucket that was not scored has `scored: false` and null value, score and
+ flag; it is unknown, not zero. Seeing every series together tells a global cause (every breakdown value
+ flags on the same day) from a segment cause (one series flags alone). Pass `series_key` from an
+ anomaly-search row to narrow to one series, and `include_buckets: false` for the per-series summary only.
+ Values are as they were at scoring time, so they can differ from the live chart after late data arrives. The
+ keys of `details` depend on the detector. A 404 means the insight does not exist, you cannot read it, or
+ anomaly search is not available for this project.
+ feature_flag: anomalies-search
+ anomaly-search:
+ operation: signals_anomalies_search_retrieve
+ enabled: true
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Search anomalous insight series
+ description: >
+ Find which series of the project's saved product analytics insights (trends) were anomalous in a date range,
+ from the scheduled anomaly scoring of those insights. For anomalies in the Metrics product, use
+ characterize-metric-anomaly instead. Each row is one series with `anomaly_rate` (flagged buckets divided by
+ scored buckets in the range). Read it against `baseline_rate`, the same rate over the 30 days before the
+ range: a series that is usually quiet and now flags matters more than one that always flags. Read it
+ together with `coverage` (the share of the range that was scored) and `scored_through` (the newest scored
+ bucket, so later buckets were not checked yet). Scores compare only within one series, so never rank series
+ by score. Scoring is sampled, so a range can be partly scored, and results cover only the insights checked
+ in the range: `insights_scored_in_range` of `watched_insights`. To check a result, `flagged_points` gives
+ the value at each flagged bucket, anomaly-insight-get with the row's `insight_id` gives the full scored
+ history of every series of that insight, and the insight's own query (for example query-trends on the
+ insight) shows the live chart. An empty result means nothing was flagged among the insights scored in the
+ range, or that scoring is not enabled for the project (`scoring_enabled: false`); `message` says which. Use
+ `group_by: insight` for one row per insight. A 404 means anomaly search is not available for this project.
+ feature_flag: anomalies-search
inbox-ranking-outcomes-list:
operation: signals_reports_ranking_outcomes_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e5c259548bbc..7ad125385513 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1129,6 +1129,38 @@
},
"feature_flag": "customer-analytics-csp"
},
+ "anomaly-insight-get": {
+ "description": "Get the full anomaly scoring history of one saved trends insight: every scored series with its anomaly rate, baseline rate and coverage, and each bucket of the range oldest first with its value, score, flag and detector `details`. A completed bucket that was not scored has `scored: false` and null value, score and flag; it is unknown, not zero. Seeing every series together tells a global cause (every breakdown value flags on the same day) from a segment cause (one series flags alone). Pass `series_key` from an anomaly-search row to narrow to one series, and `include_buckets: false` for the per-series summary only. Values are as they were at scoring time, so they can differ from the live chart after late data arrives. The keys of `details` depend on the detector. A 404 means the insight does not exist, you cannot read it, or anomaly search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get the scored anomaly history of an insight",
+ "title": "Get the scored anomaly history of an insight",
+ "required_scopes": ["insight:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/anomalies/insight/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "anomalies-search"
+ },
+ "anomaly-search": {
+ "description": "Find which series of the project's saved product analytics insights (trends) were anomalous in a date range, from the scheduled anomaly scoring of those insights. For anomalies in the Metrics product, use characterize-metric-anomaly instead. Each row is one series with `anomaly_rate` (flagged buckets divided by scored buckets in the range). Read it against `baseline_rate`, the same rate over the 30 days before the range: a series that is usually quiet and now flags matters more than one that always flags. Read it together with `coverage` (the share of the range that was scored) and `scored_through` (the newest scored bucket, so later buckets were not checked yet). Scores compare only within one series, so never rank series by score. Scoring is sampled, so a range can be partly scored, and results cover only the insights checked in the range: `insights_scored_in_range` of `watched_insights`. To check a result, `flagged_points` gives the value at each flagged bucket, anomaly-insight-get with the row's `insight_id` gives the full scored history of every series of that insight, and the insight's own query (for example query-trends on the insight) shows the live chart. An empty result means nothing was flagged among the insights scored in the range, or that scoring is not enabled for the project (`scoring_enabled: false`); `message` says which. Use `group_by: insight` for one row per insight. A 404 means anomaly search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Search anomalous insight series",
+ "title": "Search anomalous insight series",
+ "required_scopes": ["insight:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/anomalies/search/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "anomalies-search"
+ },
"apm-attribute-breakdown": {
"description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"breakdownKey\": \"server.address\", \"breakdownType\": \"span_attribute\" } }\n```\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values in results are in nanoseconds (1s = 1,000,000,000). A `duration` filter value is in milliseconds.\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",
"category": "Tracing",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 0024e72616e5..5da1e88b78d1 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1144,6 +1144,38 @@
},
"feature_flag": "customer-analytics-csp"
},
+ "anomaly-insight-get": {
+ "description": "Get the full anomaly scoring history of one saved trends insight: every scored series with its anomaly rate, baseline rate and coverage, and each bucket of the range oldest first with its value, score, flag and detector `details`. A completed bucket that was not scored has `scored: false` and null value, score and flag; it is unknown, not zero. Seeing every series together tells a global cause (every breakdown value flags on the same day) from a segment cause (one series flags alone). Pass `series_key` from an anomaly-search row to narrow to one series, and `include_buckets: false` for the per-series summary only. Values are as they were at scoring time, so they can differ from the live chart after late data arrives. The keys of `details` depend on the detector. A 404 means the insight does not exist, you cannot read it, or anomaly search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Get the scored anomaly history of an insight",
+ "title": "Get the scored anomaly history of an insight",
+ "required_scopes": ["insight:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/anomalies/insight/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "anomalies-search"
+ },
+ "anomaly-search": {
+ "description": "Find which series of the project's saved product analytics insights (trends) were anomalous in a date range, from the scheduled anomaly scoring of those insights. For anomalies in the Metrics product, use characterize-metric-anomaly instead. Each row is one series with `anomaly_rate` (flagged buckets divided by scored buckets in the range). Read it against `baseline_rate`, the same rate over the 30 days before the range: a series that is usually quiet and now flags matters more than one that always flags. Read it together with `coverage` (the share of the range that was scored) and `scored_through` (the newest scored bucket, so later buckets were not checked yet). Scores compare only within one series, so never rank series by score. Scoring is sampled, so a range can be partly scored, and results cover only the insights checked in the range: `insights_scored_in_range` of `watched_insights`. To check a result, `flagged_points` gives the value at each flagged bucket, anomaly-insight-get with the row's `insight_id` gives the full scored history of every series of that insight, and the insight's own query (for example query-trends on the insight) shows the live chart. An empty result means nothing was flagged among the insights scored in the range, or that scoring is not enabled for the project (`scoring_enabled: false`); `message` says which. Use `group_by: insight` for one row per insight. A 404 means anomaly search is not available for this project.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Search anomalous insight series",
+ "title": "Search anomalous insight series",
+ "required_scopes": ["insight:read"],
+ "api_operations": ["GET /api/projects/{project_id}/signals/anomalies/search/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "anomalies-search"
+ },
"apm-attribute-breakdown": {
"description": "Group spans by one attribute's value — the \"what is different about the bad spans?\" tool.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"breakdownKey\": \"server.address\", \"breakdownType\": \"span_attribute\" } }\n```\n\nReturns one row per distinct value of the chosen attribute, across the spans matching the filters:\n\n- `value` — the attribute's value (`''` for spans that don't carry the attribute)\n- `count` — spans with that value\n- `error_count` — of those, spans with OTel status `Error` (status_code = 2)\n- `p50_duration_nano`, `p95_duration_nano` — duration quantiles in nanoseconds\n\nRows are ordered by `count` DESC (or `error_count` DESC via `orderBy`) and capped at 5000.\n\nUse to answer:\n\n- \"Which attribute values are over-represented among the errored/slow spans?\"\n- \"Which downstream destination (`server.address`) is failing?\"\n- \"What `http.response.status_code` values are we getting back, and how often?\"\n- \"Which pod / version / region is the bad traffic concentrated on?\" (resource attributes)\n\nFor aggregates grouped by operation, use `apm-spans-aggregate`. For trends over time, use `apm-spans-sparkline`.\n\n# \"What's different\" workflow\n\n1. Scope to the bad spans with `filterGroup` (e.g. `status_code = Error`) or `serviceNames`.\n2. Discover candidate keys with `apm-attributes-list` (don't guess — keys vary per project).\n3. Run `apm-attribute-breakdown` per candidate key. A value owning most of the `count` is your signature.\n4. To confirm over-representation, re-run without the bad-spans filter (or check `error_count / count` per row): a value at 95% of errors but 10% of all traffic is the smoking gun.\n\n# Parameters\n\n## query.breakdownKey (required)\n\nThe attribute key to group by (e.g. `server.address`, `http.response.status_code`, `k8s.pod.name`). Discover keys with `apm-attributes-list`.\n\n## query.breakdownType (required)\n\n- `span_attribute` — span-level attributes (e.g. `server.address`, `db.statement`)\n- `span_resource_attribute` — resource-level attributes (e.g. `k8s.pod.name`, `service.version`)\n\n## query.orderBy\n\n`count` (default) or `error_count` — rows are sorted by the chosen column, descending.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Set `compare: true` to also get the breakdown for a previous window under `compare` — useful for \"did this value's share change vs last week?\" (`compare_to: \"-7d\"`).\n\n## query.serviceNames\n\nList of service names to restrict the breakdown to. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters scoping the spans the breakdown runs over. Same filter shape and operators as `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\n# Examples\n\n## Which destinations do the errored spans hit?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"server.address\",\n \"breakdownType\": \"span_attribute\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": \"Error\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Which values drive the most errors overall?\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"http.response.status_code\",\n \"breakdownType\": \"span_attribute\",\n \"orderBy\": \"error_count\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Is the bad pod's share new? (compare vs last week)\n\n```json\n{\n \"query\": {\n \"breakdownKey\": \"k8s.pod.name\",\n \"breakdownType\": \"span_resource_attribute\",\n \"serviceNames\": [\"cdp-worker\"],\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n# Reminders\n\n- `value: ''` groups the spans that don't carry the attribute at all — often itself a signal.\n- Duration values in results are in nanoseconds (1s = 1,000,000,000). A `duration` filter value is in milliseconds.\n- Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys before guessing.\n- `error_count / count` per row is the error rate for that value — compute it when judging over-representation.",
"category": "Tracing",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8f27af6a449f..0ce3db17b019 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13324,6 +13324,351 @@ export namespace Schemas {
customer_name: string | null;
}
+ /**
+ * Detector-specific values for the bucket. The keys depend on the detector.
+ * @nullable
+ */
+ export type AnomalyBucketDetails = { [key: string]: unknown } | null;
+
+ export interface AnomalyBucket {
+ /** The start of the bucket, in the project timezone. */
+ bucket_start: string;
+ /** False for a completed bucket that has no score. Its value, score and flag are unknown, not 0. */
+ scored: boolean;
+ /**
+ * The series value of the bucket at scoring time.
+ * @nullable
+ */
+ value: number | null;
+ /**
+ * The detector score. Null on an unscored or warm-up bucket.
+ * @nullable
+ */
+ score: number | null;
+ /**
+ * Whether the detector flagged the bucket. Null on an unscored or warm-up bucket.
+ * @nullable
+ */
+ flag: boolean | null;
+ /**
+ * When the bucket was scored.
+ * @nullable
+ */
+ scored_at: string | null;
+ /**
+ * Detector-specific values for the bucket. The keys depend on the detector.
+ * @nullable
+ */
+ details: AnomalyBucketDetails;
+ }
+
+ export interface AnomalyFlaggedPoint {
+ /** The start of the flagged bucket, in the project timezone. */
+ bucket_start: string;
+ /**
+ * The series value of the bucket at scoring time.
+ * @nullable
+ */
+ value: number | null;
+ /**
+ * The detector score of the bucket. Compare it only with buckets of the same series.
+ * @nullable
+ */
+ score: number | null;
+ }
+
+ /**
+ * * `series` - Series
+ * * `insight` - Insight
+ */
+ export type AnomalyGroupByEnum = typeof AnomalyGroupByEnum[keyof typeof AnomalyGroupByEnum];
+
+
+ export const AnomalyGroupByEnum = {
+ Series: 'series',
+ Insight: 'insight',
+ } as const;
+
+ /**
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month
+ */
+ export type AnomalyIntervalEnum = typeof AnomalyIntervalEnum[keyof typeof AnomalyIntervalEnum];
+
+
+ export const AnomalyIntervalEnum = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ } as const;
+
+ export interface AnomalyInsightSeries {
+ /** Identifies the series. */
+ series_key: string;
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null;
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null;
+ /** Buckets in the range with a score. */
+ scored_buckets: number;
+ /** Scored buckets in the range that the detector flagged. */
+ flagged_buckets: number;
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null;
+ /**
+ * The anomaly rate over the 30 days before the range. Null when no bucket was scored then.
+ * @nullable
+ */
+ baseline_rate: number | null;
+ /** Completed buckets in the range, scored or not. */
+ expected_buckets: number;
+ /**
+ * `scored_buckets / expected_buckets`.
+ * @nullable
+ */
+ coverage: number | null;
+ /**
+ * The newest flagged bucket in the range.
+ * @nullable
+ */
+ last_flagged_bucket: string | null;
+ /** Oldest first, the newest result of each bucket. Empty when `include_buckets` is false. */
+ buckets: AnomalyBucket[];
+ }
+
+ export interface AnomalyInsightResponse {
+ /** Whether anomaly scoring covers this project. */
+ scoring_enabled: boolean;
+ /** The numeric id of the insight. */
+ insight_id: number;
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null;
+ /** Opens the insight with a date range around its flagged buckets. */
+ insight_url: string;
+ /** The bucket interval the scorer used.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: AnomalyIntervalEnum | null;
+ /**
+ * The scoring profile.
+ * @nullable
+ */
+ profile: string | null;
+ /**
+ * The detector type, for example `zscore`.
+ * @nullable
+ */
+ detector: string | null;
+ /**
+ * A hash of the detector settings. It changes when the settings change.
+ * @nullable
+ */
+ detector_version: string | null;
+ /** Series scored in the range. */
+ series_count: number;
+ /** Series with at least one flagged bucket in the range. */
+ flagged_series: number;
+ /** Scored buckets, summed over the series. */
+ scored_buckets: number;
+ /** Flagged buckets, summed over the series. */
+ flagged_buckets: number;
+ /**
+ * Summed `flagged_buckets / scored_buckets`. Never an average of series rates.
+ * @nullable
+ */
+ anomaly_rate: number | null;
+ /** The applied start of the range, in the project timezone. */
+ date_from: string;
+ /** The applied end of the range, in the project timezone. */
+ date_to: string;
+ /** Every scored series, most anomalous first. */
+ series: AnomalyInsightSeries[];
+ /** True when the cap of 2,000 buckets cut the history. */
+ truncated: boolean;
+ /**
+ * Says why the result is empty. Null when it is not.
+ * @nullable
+ */
+ message: string | null;
+ }
+
+ export interface AnomalyTopSeries {
+ /** Identifies the series. */
+ series_key: string;
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null;
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null;
+ /** Scored buckets of the series in the range. */
+ scored_buckets: number;
+ /** Flagged buckets of the series in the range. */
+ flagged_buckets: number;
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null;
+ /**
+ * The anomaly rate over the 30 days before the range.
+ * @nullable
+ */
+ baseline_rate: number | null;
+ }
+
+ export interface AnomalyInsightRow {
+ /** The numeric id of the insight. */
+ insight_id: number;
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null;
+ /** Opens the insight with a date range around its flagged buckets. */
+ insight_url: string;
+ /** Series of the insight scored in the range. */
+ series_count: number;
+ /** Series with at least one flagged bucket in the range. */
+ flagged_series: number;
+ /** Scored buckets, summed over the series. */
+ scored_buckets: number;
+ /** Flagged buckets, summed over the series. */
+ flagged_buckets: number;
+ /**
+ * Summed `flagged_buckets / scored_buckets`. Never an average of series rates.
+ * @nullable
+ */
+ anomaly_rate: number | null;
+ /**
+ * The newest flagged bucket of any series.
+ * @nullable
+ */
+ last_flagged_bucket: string | null;
+ /** Up to 3 flagged series, most anomalous first. */
+ top_series: AnomalyTopSeries[];
+ }
+
+ export interface AnomalySeries {
+ /** The numeric id of the insight. */
+ insight_id: number;
+ /**
+ * The name of the insight. Null when it has none.
+ * @nullable
+ */
+ insight_name: string | null;
+ /** Opens the insight with a date range around the flagged buckets of this series. */
+ insight_url: string;
+ /** Identifies the series. Pass it to anomaly insight history. */
+ series_key: string;
+ /**
+ * The series name as the insight shows it.
+ * @nullable
+ */
+ series_label: string | null;
+ /**
+ * The breakdown value of the series, if any.
+ * @nullable
+ */
+ breakdown_value: string | null;
+ /** The bucket interval of the series.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month */
+ interval: AnomalyIntervalEnum;
+ /** Buckets in the range with a score. Warm-up buckets do not count. */
+ scored_buckets: number;
+ /** Scored buckets in the range that the detector flagged. */
+ flagged_buckets: number;
+ /**
+ * `flagged_buckets / scored_buckets`.
+ * @nullable
+ */
+ anomaly_rate: number | null;
+ /** Completed buckets of the series interval in the range, scored or not. */
+ expected_buckets: number;
+ /**
+ * `scored_buckets / expected_buckets`: how much of the range was scored. Unscored buckets are unknown, not quiet.
+ * @nullable
+ */
+ coverage: number | null;
+ /**
+ * The newest scored bucket in the range. Buckets after it were not checked yet.
+ * @nullable
+ */
+ scored_through: string | null;
+ /**
+ * The anomaly rate over the 30 days before the range. Null when no bucket was scored then.
+ * @nullable
+ */
+ baseline_rate: number | null;
+ /**
+ * The oldest flagged bucket in the range, in the project timezone.
+ * @nullable
+ */
+ first_flagged_bucket: string | null;
+ /**
+ * The newest flagged bucket in the range, in the project timezone.
+ * @nullable
+ */
+ last_flagged_bucket: string | null;
+ /** Up to 5 flagged buckets in the range, newest first. */
+ flagged_points: AnomalyFlaggedPoint[];
+ }
+
+ export interface AnomalySearchResponse {
+ /** Whether anomaly scoring covers this project. */
+ scoring_enabled: boolean;
+ /** Insights that scoring watches: saved trends insights on a dashboard or viewed in the last 30 days. */
+ watched_insights: number;
+ /** Insights with at least one scored bucket in the range. Results cover only these insights. */
+ insights_scored_in_range: number;
+ /** The applied start of the range, in the project timezone. */
+ date_from: string;
+ /** The applied end of the range, in the project timezone. */
+ date_to: string;
+ /** The applied grouping.
+ *
+ * * `series` - Series
+ * * `insight` - Insight */
+ group_by: AnomalyGroupByEnum;
+ /** One row per series, most anomalous first. Empty unless `group_by` is `series`. */
+ series: AnomalySeries[];
+ /** One row per insight, most anomalous first. Empty unless `group_by` is `insight`. */
+ insights: AnomalyInsightRow[];
+ /** True when `limit` or a read cap left rows out. */
+ truncated: boolean;
+ /**
+ * Says why the result is empty. Null when it is not.
+ * @nullable
+ */
+ message: string | null;
+ }
+
export interface AppSandboxContract {
status: string;
restart_count: number;
@@ -136778,6 +137123,103 @@ export namespace Schemas {
version?: number;
};
+ export type SignalsAnomaliesInsightRetrieveParams = {
+ /**
+ * Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.
+ * @minLength 1
+ */
+ date_from?: string;
+ /**
+ * Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.
+ * @minLength 1
+ */
+ date_to?: string;
+ /**
+ * Return the buckets of each series. Set false for the per-series summary only.
+ */
+ include_buckets?: boolean;
+ /**
+ * Include warm-up buckets: scored rows with a null score and flag, written while the detector still lacks history. When false, a warm-up bucket shows as `scored: false`.
+ */
+ include_warmup?: boolean;
+ /**
+ * The insight, by numeric id.
+ */
+ insight_id: number;
+ /**
+ * Only this series, by the `series_key` of an anomaly search row.
+ * @minLength 1
+ */
+ series_key?: string;
+ };
+
+ export type SignalsAnomaliesSearchRetrieveParams = {
+ /**
+ * Only the series of the insights on this dashboard, by numeric id.
+ */
+ dashboard_id?: number;
+ /**
+ * Earliest bucket start in the range. A relative date such as `-7d` or `-24h`, or an ISO 8601 date.
+ * @minLength 1
+ */
+ date_from?: string;
+ /**
+ * Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.
+ * @minLength 1
+ */
+ date_to?: string;
+ /**
+ * `series` returns one row per series in `series`. `insight` returns one row per insight in `insights`.
+ *
+ * * `series` - Series
+ * * `insight` - Insight
+ * @minLength 1
+ */
+ group_by?: SignalsAnomaliesSearchRetrieveGroupBy;
+ /**
+ * Only the series of this insight, by numeric id.
+ */
+ insight_id?: number;
+ /**
+ * Only series with this interval.
+ *
+ * * `hour` - Hour
+ * * `day` - Day
+ * * `week` - Week
+ * * `month` - Month
+ * @minLength 1
+ */
+ interval?: SignalsAnomaliesSearchRetrieveInterval;
+ /**
+ * The most rows to return.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Only series, or insights, with at least one flagged bucket in the range. Set false to also list quiet ones.
+ */
+ only_flagged?: boolean;
+ };
+
+ export type SignalsAnomaliesSearchRetrieveGroupBy = typeof SignalsAnomaliesSearchRetrieveGroupBy[keyof typeof SignalsAnomaliesSearchRetrieveGroupBy];
+
+
+ export const SignalsAnomaliesSearchRetrieveGroupBy = {
+ Series: 'series',
+ Insight: 'insight',
+ } as const;
+
+ export type SignalsAnomaliesSearchRetrieveInterval = typeof SignalsAnomaliesSearchRetrieveInterval[keyof typeof SignalsAnomaliesSearchRetrieveInterval];
+
+
+ export const SignalsAnomaliesSearchRetrieveInterval = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ } as const;
+
export type SignalsProcessingListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index d703ce0ba7f7..d5a449104f2a 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 72 enabled ops
+ * PostHog API - MCP 74 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -45,6 +45,111 @@ export const SignalsActivitySummaryVersionsRetrieveQueryParams = () => zod.objec
.describe('Return only this version, with its full profile. Returns 404 when the version does not exist.'),
})
+/**
+ * Read-only anomaly rates of the saved trends insights that anomaly scoring checks.
+ * @summary Get the scored anomaly history of an insight
+ */
+export const SignalsAnomaliesInsightRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsAnomaliesInsightRetrieveQueryDateFromDefault = `-30d`
+
+export const signalsAnomaliesInsightRetrieveQueryIncludeBucketsDefault = true
+export const signalsAnomaliesInsightRetrieveQueryIncludeWarmupDefault = false
+
+export const SignalsAnomaliesInsightRetrieveQueryParams = () => zod.object({
+ date_from: zod
+ .string()
+ .min(1)
+ .default(signalsAnomaliesInsightRetrieveQueryDateFromDefault)
+ .describe('Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.'),
+ date_to: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe('Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.'),
+ include_buckets: zod
+ .boolean()
+ .default(signalsAnomaliesInsightRetrieveQueryIncludeBucketsDefault)
+ .describe('Return the buckets of each series. Set false for the per-series summary only.'),
+ include_warmup: zod
+ .boolean()
+ .default(signalsAnomaliesInsightRetrieveQueryIncludeWarmupDefault)
+ .describe(
+ 'Include warm-up buckets: scored rows with a null score and flag, written while the detector still lacks history. When false, a warm-up bucket shows as `scored: false`.'
+ ),
+ insight_id: zod.number().describe('The insight, by numeric id.'),
+ series_key: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe('Only this series, by the `series_key` of an anomaly search row.'),
+})
+
+/**
+ * Read-only anomaly rates of the saved trends insights that anomaly scoring checks.
+ * @summary Search anomalous insight series
+ */
+export const SignalsAnomaliesSearchRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const signalsAnomaliesSearchRetrieveQueryDateFromDefault = `-7d`
+
+export const signalsAnomaliesSearchRetrieveQueryGroupByDefault = `series`
+export const signalsAnomaliesSearchRetrieveQueryLimitDefault = 25
+export const signalsAnomaliesSearchRetrieveQueryLimitMax = 100
+
+export const signalsAnomaliesSearchRetrieveQueryOnlyFlaggedDefault = true
+
+export const SignalsAnomaliesSearchRetrieveQueryParams = () => zod.object({
+ dashboard_id: zod.number().optional().describe('Only the series of the insights on this dashboard, by numeric id.'),
+ date_from: zod
+ .string()
+ .min(1)
+ .default(signalsAnomaliesSearchRetrieveQueryDateFromDefault)
+ .describe('Earliest bucket start in the range. A relative date such as `-7d` or `-24h`, or an ISO 8601 date.'),
+ date_to: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe('Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.'),
+ group_by: zod
+ .enum(['series', 'insight'])
+ .default(signalsAnomaliesSearchRetrieveQueryGroupByDefault)
+ .describe(
+ '`series` returns one row per series in `series`. `insight` returns one row per insight in `insights`.\n\n\* `series` - Series\n\* `insight` - Insight'
+ ),
+ insight_id: zod.number().optional().describe('Only the series of this insight, by numeric id.'),
+ interval: zod
+ .enum(['hour', 'day', 'week', 'month'])
+ .optional()
+ .describe(
+ 'Only series with this interval.\n\n\* `hour` - Hour\n\* `day` - Day\n\* `week` - Week\n\* `month` - Month'
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(signalsAnomaliesSearchRetrieveQueryLimitMax)
+ .default(signalsAnomaliesSearchRetrieveQueryLimitDefault)
+ .describe('The most rows to return.'),
+ only_flagged: zod
+ .boolean()
+ .default(signalsAnomaliesSearchRetrieveQueryOnlyFlaggedDefault)
+ .describe(
+ 'Only series, or insights, with at least one flagged bucket in the range. Set false to also list quiet ones.'
+ ),
+})
+
/**
* Team-level signal autonomy config (singleton per team).
*
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 9b5d0ba93f29..22310af8f594 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -57,6 +57,60 @@ const activitySummaryVersionsList = (): ToolBase<
},
})
+const AnomalyInsightGetSchema = () => {
+ const SignalsAnomaliesInsightRetrieveQueryParams = orvalSchemas.SignalsAnomaliesInsightRetrieveQueryParams()
+ return SignalsAnomaliesInsightRetrieveQueryParams
+}
+
+const anomalyInsightGet = (): ToolBase<ReturnType<typeof AnomalyInsightGetSchema>, Schemas.AnomalyInsightResponse> => ({
+ name: 'anomaly-insight-get',
+ schema: AnomalyInsightGetSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof AnomalyInsightGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AnomalyInsightResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/anomalies/insight/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ include_buckets: params.include_buckets,
+ include_warmup: params.include_warmup,
+ insight_id: params.insight_id,
+ series_key: params.series_key,
+ },
+ })
+ return result
+ },
+})
+
+const AnomalySearchSchema = () => {
+ const SignalsAnomaliesSearchRetrieveQueryParams = orvalSchemas.SignalsAnomaliesSearchRetrieveQueryParams()
+ return SignalsAnomaliesSearchRetrieveQueryParams
+}
+
+const anomalySearch = (): ToolBase<ReturnType<typeof AnomalySearchSchema>, Schemas.AnomalySearchResponse> => ({
+ name: 'anomaly-search',
+ schema: AnomalySearchSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof AnomalySearchSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AnomalySearchResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/anomalies/search/`,
+ query: {
+ dashboard_id: params.dashboard_id,
+ date_from: params.date_from,
+ date_to: params.date_to,
+ group_by: params.group_by,
+ insight_id: params.insight_id,
+ interval: params.interval,
+ limit: params.limit,
+ only_flagged: params.only_flagged,
+ },
+ })
+ return result
+ },
+})
+
const InboxRankingOutcomesListSchema = () => z.object({})
const inboxRankingOutcomesList = (): ToolBase<
@@ -3345,6 +3399,8 @@ const signalsScoutScratchpadSearch = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'activity-summary-get': activitySummaryGet,
'activity-summary-versions-list': activitySummaryVersionsList,
+ 'anomaly-insight-get': anomalyInsightGet,
+ 'anomaly-search': anomalySearch,
'inbox-ranking-outcomes-list': inboxRankingOutcomesList,
'inbox-report-actions-list': inboxReportActionsList,
'inbox-report-actions-run': inboxReportActionsRun,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-insight-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-insight-get.json
new file mode 100644
index 000000000000..ab25c8fb51d1
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-insight-get.json
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "date_from": {
+ "default": "-30d",
+ "description": "Earliest bucket start in the range. A relative date such as `-30d`, or an ISO 8601 date.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "date_to": {
+ "description": "Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "include_buckets": {
+ "default": true,
+ "description": "Return the buckets of each series. Set false for the per-series summary only.",
+ "type": "boolean"
+ },
+ "include_warmup": {
+ "default": false,
+ "description": "Include warm-up buckets: scored rows with a null score and flag, written while the detector still lacks history. When false, a warm-up bucket shows as `scored: false`.",
+ "type": "boolean"
+ },
+ "insight_id": {
+ "description": "The insight, by numeric id.",
+ "type": "number"
+ },
+ "series_key": {
+ "description": "Only this series, by the `series_key` of an anomaly search row.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["insight_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-search.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-search.json
new file mode 100644
index 000000000000..229b94fbf4f1
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/anomaly-search.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "dashboard_id": {
+ "description": "Only the series of the insights on this dashboard, by numeric id.",
+ "type": "number"
+ },
+ "date_from": {
+ "default": "-7d",
+ "description": "Earliest bucket start in the range. A relative date such as `-7d` or `-24h`, or an ISO 8601 date.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "date_to": {
+ "description": "Latest bucket start in the range. A relative date or an ISO 8601 date. Defaults to now.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "group_by": {
+ "default": "series",
+ "description": "`series` returns one row per series in `series`. `insight` returns one row per insight in `insights`.\n\n* `series` - Series\n* `insight` - Insight",
+ "enum": ["series", "insight"],
+ "type": "string"
+ },
+ "insight_id": {
+ "description": "Only the series of this insight, by numeric id.",
+ "type": "number"
+ },
+ "interval": {
+ "description": "Only series with this interval.\n\n* `hour` - Hour\n* `day` - Day\n* `week` - Week\n* `month` - Month",
+ "enum": ["hour", "day", "week", "month"],
+ "type": "string"
+ },
+ "limit": {
+ "default": 25,
+ "description": "The most rows to return.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "number"
+ },
+ "only_flagged": {
+ "default": true,
+ "description": "Only series, or insights, with at least one flagged bucket in the range. Set false to also list quiet ones.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 463d6e51245c..b8cef96c3655 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1112,6 +1112,7 @@ describe('Tool Filtering - Feature Flags', () => {
'logs-agent-tools',
'workflows-transactional-email-api',
'activity-summary',
+ 'anomalies-search',
]
expect(allFlags).toEqual(expect.arrayContaining(branchFlags))
// The flags branches add are asserted on the line above and held out of the list and
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index e7dacf4c2f06..c2d0e2ef9809 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -110,6 +110,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
'workflows-transactional-email-api': true,
'activity-summary': true,
'aeo-citation-tracking': true,
+ 'anomalies-search': true,
}
return [...(await getToolsFromContext(createMockContext(), { featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)