:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): on-demand anomaly scan endpoint (#78988)
Jon McCallumbae0ab6538b6
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex f653b5aca602..3074fd495e14 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -556,6 +556,21 @@ class SessionContextsSustainedRateThrottle(_TeamBucketRateThrottle):rate = "600/hour"+# The logs anomaly scan aggregates weeks of baseline slices from ClickHouse in one synchronous+# request — the heaviest single query the logs product exposes, budgeted at gigabytes of reads+# per call. A team-wide bucket caps the project's total spend regardless of how many users or+# keys fire scans; repeats within a minute are served from the endpoint's short-TTL cache, so+# a legitimate UI or agent session needs only a handful of cold scans per hour.+class LogsAnomalyScanBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "logs_anomaly_scan_burst"+ rate = "6/minute"+++class LogsAnomalyScanSustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "logs_anomaly_scan_sustained"+ rate = "60/hour"++# The experiment session-bucket endpoint scans every session in an experiment's recent run# window rather than a known id list, so one call is heavier than a session-context batch. Same# project-wide bucketing and same session-authenticated caller as those, at a lower rate: the UIdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 1ce3de0226a5..da21c637e2d9 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -893,6 +893,12 @@ SPECTACULAR_SETTINGS = {# `caches` list item share the same evaluation/definitions choice set. Pin to a# stable name so "cache" and "caches" don't collide into a hash name."StaffCacheKindEnum": ["evaluation", "definitions"],+ # Logs anomaly scan: `verdict` (per-bucket) and `kind` (per-issue) share the+ # spike/drop/silence choice set; pin one stable name for both. `stage` would+ # otherwise collide with EarlyAccessFeature's stage, so both sides get pinned.+ "LogsAnomalyVerdictEnum": ["spike", "drop", "silence"],+ "LogsAnomalyBaselineStageEnum": ["insufficient", "cold_start", "developing", "mature", None],+ "EarlyAccessFeatureStageEnum": "products.early_access_features.backend.models.EarlyAccessFeature.Stage",},}diff --git a/products/early_access_features/frontend/generated/api.schemas.ts b/products/early_access_features/frontend/generated/api.schemas.tsindex cb87e12a1b54..6afc29624888 100644--- a/products/early_access_features/frontend/generated/api.schemas.ts+++ b/products/early_access_features/frontend/generated/api.schemas.ts@@ -78,9 +78,10 @@ export interface MinimalFeatureFlagApi {* * `general-availability` - general availability* * `archived` - archived*/-export type StageEnumApi = (typeof StageEnumApi)[keyof typeof StageEnumApi]+export type EarlyAccessFeatureStageEnumApi =+ (typeof EarlyAccessFeatureStageEnumApi)[keyof typeof EarlyAccessFeatureStageEnumApi]-export const StageEnumApi = {+export const EarlyAccessFeatureStageEnumApi = {Draft: 'draft',Concept: 'concept',Alpha: 'alpha',@@ -175,7 +176,7 @@ export interface EarlyAccessFeatureApi {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage: StageEnumApi+ stage: EarlyAccessFeatureStageEnumApi/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800@@ -236,7 +237,7 @@ export interface EarlyAccessFeatureSerializerCreateOnlyApi {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage: StageEnumApi+ stage: EarlyAccessFeatureStageEnumApi/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800@@ -298,7 +299,7 @@ export interface PatchedEarlyAccessFeatureApi {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage?: StageEnumApi+ stage?: EarlyAccessFeatureStageEnumApi/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex c0dff7818377..01574d91cbae 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -36,9 +36,10 @@ export interface ProductPushCampaignApi {* * `medium` - medium* * `low` - low*/-export type TierEnumApi = (typeof TierEnumApi)[keyof typeof TierEnumApi]+export type IdentityMatchingLinkTierEnumApi =+ (typeof IdentityMatchingLinkTierEnumApi)[keyof typeof IdentityMatchingLinkTierEnumApi]-export const TierEnumApi = {+export const IdentityMatchingLinkTierEnumApi = {High: 'high',Medium: 'medium',Low: 'low',@@ -146,7 +147,7 @@ export interface IdentityMatchingLinkApi {* * `high` - high* * `medium` - medium* * `low` - low */- tier: TierEnumApi+ tier: IdentityMatchingLinkTierEnumApi/** When the link was computed (UTC). */computed_at: string/** Distinct (IP, day) combinations both sides were seen on. */diff --git a/products/growth/frontend/generated/api.zod.schemas.ts b/products/growth/frontend/generated/api.zod.schemas.tsindex cecf69f57ca3..9b4ded158c93 100644--- a/products/growth/frontend/generated/api.zod.schemas.ts+++ b/products/growth/frontend/generated/api.zod.schemas.ts@@ -29,12 +29,12 @@ export const ProductPushCampaignApi = zod.object({export type ProductPushCampaignApi = zod.input<typeof ProductPushCampaignApi>export type ProductPushCampaignApiOutput = zod.output<typeof ProductPushCampaignApi>-export const TierEnumApi = zod+export const IdentityMatchingLinkTierEnumApi = zod.enum(['high', 'medium', 'low']).describe('\* `high` - high\n\* `medium` - medium\n\* `low` - low')-export type TierEnumApi = zod.input<typeof TierEnumApi>-export type TierEnumApiOutput = zod.output<typeof TierEnumApi>+export type IdentityMatchingLinkTierEnumApi = zod.input<typeof IdentityMatchingLinkTierEnumApi>+export type IdentityMatchingLinkTierEnumApiOutput = zod.output<typeof IdentityMatchingLinkTierEnumApi>export const IdentityMatchingPersonApi = zod.object({diff --git a/products/logs/backend/presentation/views/anomalies_api.py b/products/logs/backend/presentation/views/anomalies_api.pynew file mode 100644index 000000000000..2be4f42a024a--- /dev/null+++ b/products/logs/backend/presentation/views/anomalies_api.py@@ -0,0 +1,240 @@+import hashlib+import datetime as dt+from typing import Any++from django.core.cache import cache++from drf_spectacular.utils import OpenApiResponse+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.response import Response++from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.permissions import PostHogFeatureFlagPermission+from posthog.rate_limit import LogsAnomalyScanBurstRateThrottle, LogsAnomalyScanSustainedRateThrottle++from products.logs.backend.anomaly_scan import MAX_EVAL_DAYS, ScanBudgetExceeded, floor_to_bucket, run_scan++SCAN_CACHE_TTL_SECONDS = 60++_STAGE_CHOICES = ["insufficient", "cold_start", "developing", "mature"]+_VERDICT_CHOICES = ["spike", "drop", "silence"]+_TIER_CHOICES = ["a", "b", "c", "d"]+_CONSTRAINT_CHOICES = ["team_retention", "byte_budget"]+++class _ScanDateRangeSerializer(serializers.Serializer):+ date_from = serializers.DateTimeField(+ help_text="Start of the evaluation window (ISO 8601). Buckets before this are only used as baseline history.",+ )+ date_to = serializers.DateTimeField(+ help_text="End of the evaluation window (ISO 8601), clamped to now.",+ )+++class LogsAnomalyScanRequestSerializer(serializers.Serializer):+ serviceName = serializers.CharField(+ help_text=(+ "Service to scan (the log record's service_name). Required: the scan aggregates weeks of "+ "baseline history from raw logs, so it is scoped to one service per call."+ ),+ )+ dateRange = _ScanDateRangeSerializer(+ help_text=f"Evaluation window to scan for anomalies. May span at most {MAX_EVAL_DAYS} days.",+ )++ def validate_dateRange(self, value: dict[str, Any]) -> dict[str, Any]:+ if value["date_to"] <= value["date_from"]:+ raise serializers.ValidationError("date_to must be after date_from.")+ if value["date_to"] - value["date_from"] > dt.timedelta(days=MAX_EVAL_DAYS):+ raise serializers.ValidationError(f"The evaluation window may span at most {MAX_EVAL_DAYS} days.")+ return value+++class LogsAnomalyScanBucketSerializer(serializers.Serializer):+ time = serializers.DateTimeField(help_text="Start of the 5 minute bucket (UTC).")+ observed = serializers.FloatField(help_text="Log records observed in this bucket.")+ expected = serializers.FloatField(+ allow_null=True,+ help_text="Expected count from the learned baseline. Null when the bucket was not scored.",+ )+ lower = serializers.FloatField(+ allow_null=True,+ help_text="Lower edge of the expected band. Observed below this is a drop or silence candidate.",+ )+ upper = serializers.FloatField(+ allow_null=True,+ help_text="Upper edge of the expected band. Observed above this is a spike candidate.",+ )+ stage = serializers.ChoiceField(+ choices=_STAGE_CHOICES,+ allow_null=True,+ help_text=(+ "How much history backed the baseline for this bucket. Wider bands and lower confidence in "+ "cold_start; mature means a full seasonal baseline. Null when the bucket was gated out "+ "(for example, traffic below the detection floor)."+ ),+ )+ verdict = serializers.ChoiceField(+ choices=_VERDICT_CHOICES,+ allow_null=True,+ help_text="Anomaly verdict for this bucket, or null when the observed count sat inside the band.",+ )+++class LogsAnomalyScanSeriesSerializer(serializers.Serializer):+ severity = serializers.CharField(help_text="Severity level of this log series (for example info, warn, error).")+ stage = serializers.ChoiceField(+ choices=_STAGE_CHOICES,+ allow_null=True,+ help_text="Baseline stage reached by the end of the evaluation window. Null if no bucket was scored.",+ )+ tier = serializers.ChoiceField(+ choices=_TIER_CHOICES,+ allow_null=True,+ help_text=(+ "Traffic tier at the end of the window, from a (0.5 or more records per second) down to "+ "d (below the detection floor of roughly 1 record per minute)."+ ),+ )+ history_start = serializers.DateTimeField(+ allow_null=True,+ help_text="Earliest bucket with data inside the fetched lookback.",+ )+ limited_by = serializers.ChoiceField(+ choices=["series_history", *_CONSTRAINT_CHOICES],+ allow_null=True,+ help_text=(+ "What limited this series' baseline maturity, or null for a full baseline. series_history: "+ "data starts inside the lookback, because the series is young or a per-stream retention rule "+ "trimmed it (indistinguishable from the data). byte_budget and team_retention mirror the "+ "scan level constraints."+ ),+ )+ buckets = LogsAnomalyScanBucketSerializer(+ many=True,+ help_text="Per bucket observed counts and expected bands across the evaluation window, for evidence charts.",+ )+++class LogsAnomalyScanIssueSerializer(serializers.Serializer):+ direction = serializers.ChoiceField(+ choices=["up", "down"],+ help_text="up covers spikes; down covers drops and silences (which share one issue per service).",+ )+ severity = serializers.CharField(+ allow_null=True,+ help_text="Severity of the spiking series. Null for down issues, which are tracked per service.",+ )+ kind = serializers.ChoiceField(+ choices=_VERDICT_CHOICES,+ help_text="Most severe verdict the issue reached. A drop that deepens into silence escalates in place.",+ )+ state = serializers.ChoiceField(+ choices=["pending", "active", "resolved"],+ help_text="Lifecycle state at the end of the evaluation window.",+ )+ opened_at = serializers.DateTimeField(help_text="Bucket where the issue first opened.")+ last_anomalous_at = serializers.DateTimeField(help_text="Most recent anomalous bucket attributed to this issue.")+ resolved_at = serializers.DateTimeField(+ allow_null=True,+ help_text="Bucket where the issue resolved, or null if it was still open at the end of the window.",+ )+ anomalous_bucket_times = serializers.ListField(+ child=serializers.DateTimeField(),+ help_text="Every anomalous bucket attributed to this issue, oldest first.",+ )+++class LogsAnomalyScanResponseSerializer(serializers.Serializer):+ service_name = serializers.CharField(help_text="Service that was scanned.")+ eval_start = serializers.DateTimeField(help_text="Actual start of the evaluated window after any clipping.")+ eval_end = serializers.DateTimeField(help_text="Actual end of the evaluated window after clamping to now.")+ lookback_days = serializers.FloatField(help_text="Days of baseline history the scan used.")+ eval_clipped = serializers.BooleanField(+ help_text="True when the evaluation window was clipped to fit the read budget. The response covers only the clipped window.",+ )+ degraded = serializers.BooleanField(+ help_text="True when the scan could not afford the full lookback and fell back to a cheaper configuration.",+ )+ binding_constraints = serializers.ListField(+ child=serializers.ChoiceField(choices=_CONSTRAINT_CHOICES),+ help_text=(+ "Everything that limited the baseline, empty for an unconstrained scan. team_retention: the "+ "project's log retention is shorter than the full lookback. byte_budget: the scan degraded "+ "to stay inside its ClickHouse read budget."+ ),+ )+ series = LogsAnomalyScanSeriesSerializer(+ many=True,+ help_text="One entry per severity level observed for the service, with per bucket evidence.",+ )+ issues = LogsAnomalyScanIssueSerializer(+ many=True,+ help_text="Anomaly issues that opened during the evaluation window, oldest first.",+ )+++class LogsAnomalyScanErrorSerializer(serializers.Serializer):+ error = serializers.CharField(help_text="Human readable description of why the scan could not run.")+++class LogsAnomalyScanViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """On-demand anomaly scan over one service's log volume.++ Experimental, behind the logs-anomalies feature flag. Computes everything+ per request from raw logs; nothing is persisted.+ """++ scope_object = "logs"+ posthog_feature_flag = "logs-anomalies"+ permission_classes = [PostHogFeatureFlagPermission]+ throttle_classes = [LogsAnomalyScanBurstRateThrottle, LogsAnomalyScanSustainedRateThrottle]++ @validated_request(+ request_serializer=LogsAnomalyScanRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=LogsAnomalyScanResponseSerializer,+ description="Scan results: per severity evidence series and any issues that opened.",+ ),+ 422: OpenApiResponse(+ response=LogsAnomalyScanErrorSerializer,+ description="The scan exceeded its read budget at every degradation step.",+ ),+ },+ summary="Scan a service's logs for volume anomalies",+ description=(+ "Runs anomaly detection on demand over one service's log volume for the given window. "+ "Learns per severity baselines from up to 6 weeks of history and returns per bucket "+ "expected bands plus any spike, drop, or silence issues. Synchronous and read only."+ ),+ )+ @action(detail=False, methods=["POST"], required_scopes=["logs:read"])+ def scan(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ data = request.validated_data+ service_name: str = data["serviceName"]+ eval_start = floor_to_bucket(data["dateRange"]["date_from"])+ eval_end = floor_to_bucket(min(data["dateRange"]["date_to"], dt.datetime.now(dt.UTC)))+ if eval_end <= eval_start:+ raise serializers.ValidationError("The evaluation window is empty after clamping to now.")++ cache_key = (+ "logs_anomaly_scan/"+ + hashlib.sha256(+ f"{self.team.id}/{service_name}/{eval_start.isoformat()}/{eval_end.isoformat()}".encode()+ ).hexdigest()+ )+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(cached)++ try:+ result = run_scan(self.team, service_name, eval_start, eval_end)+ except ScanBudgetExceeded as err:+ return Response({"error": str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)++ response_data = LogsAnomalyScanResponseSerializer(result).data+ cache.set(cache_key, response_data, SCAN_CACHE_TTL_SECONDS)+ return Response(response_data)diff --git a/products/logs/backend/routes.py b/products/logs/backend/routes.pyindex b557a37e6ba6..e7c1f729f017 100644--- a/products/logs/backend/routes.py+++ b/products/logs/backend/routes.py@@ -1,10 +1,12 @@from posthog.api.routing import RouterRegistryimport products.logs.backend.presentation.views.api as logs+from products.logs.backend.presentation.views.anomalies_api import LogsAnomalyScanViewSetdef register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"logs", logs.LogsViewSet, "project_logs", ["team_id"])+ routers.projects.register(r"logs/anomalies", LogsAnomalyScanViewSet, "project_logs_anomalies", ["team_id"])routers.projects.register(r"logs/alerts", logs.LogsAlertViewSet, "project_logs_alerts", ["team_id"])routers.projects.register(r"logs/sampling_rules", logs.LogsSamplingRuleViewSet, "project_logs_sampling_rules", ["team_id"]diff --git a/products/logs/backend/test/test_anomalies_api.py b/products/logs/backend/test/test_anomalies_api.pynew file mode 100644index 000000000000..8cb7fde3b811--- /dev/null+++ b/products/logs/backend/test/test_anomalies_api.py@@ -0,0 +1,169 @@+import datetime as dt++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from products.apm.backend.facade.api import BaselineStage, Direction, IssueState, TrafficTier, VerdictType+from products.logs.backend.anomaly_scan import ScanBucket, ScanBudgetExceeded, ScanIssue, ScanResult, ScanSeries+from products.logs.backend.presentation.views.anomalies_api import LogsAnomalyScanRequestSerializer++UTC = dt.UTC+T0 = dt.datetime(2026, 6, 1, 12, 0, tzinfo=UTC)+++def _scan_result(**overrides) -> ScanResult:+ defaults: dict = {+ "service_name": "svc",+ "eval_start": T0,+ "eval_end": T0 + dt.timedelta(hours=1),+ "lookback_buckets": 6 * 7 * 288,+ "eval_clipped": False,+ "degraded": False,+ "binding_constraints": [],+ "series": [+ ScanSeries(+ severity="info",+ stage=BaselineStage.MATURE,+ tier=TrafficTier.B,+ history_start=T0 - dt.timedelta(days=42),+ limited_by=None,+ buckets=[+ ScanBucket(+ time=T0,+ observed=120.0,+ expected=100.0,+ lower=60.0,+ upper=150.0,+ stage=BaselineStage.MATURE,+ verdict=None,+ )+ ],+ )+ ],+ "issues": [+ ScanIssue(+ direction=Direction.UP,+ severity="info",+ kind=VerdictType.SPIKE,+ state=IssueState.ACTIVE,+ opened_at=T0 + dt.timedelta(minutes=10),+ last_anomalous_at=T0 + dt.timedelta(minutes=30),+ resolved_at=None,+ anomalous_bucket_times=[T0 + dt.timedelta(minutes=10)],+ )+ ],+ }+ defaults.update(overrides)+ return ScanResult(**defaults)+++class TestScanRequestValidation(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "missing_service",+ {"dateRange": {"date_from": "2026-06-01T00:00:00Z", "date_to": "2026-06-02T00:00:00Z"}},+ ),+ ("missing_window", {"serviceName": "svc"}),+ (+ "inverted_window",+ {+ "serviceName": "svc",+ "dateRange": {"date_from": "2026-06-02T00:00:00Z", "date_to": "2026-06-01T00:00:00Z"},+ },+ ),+ (+ "window_over_seven_days",+ {+ "serviceName": "svc",+ "dateRange": {"date_from": "2026-06-01T00:00:00Z", "date_to": "2026-06-09T00:00:00Z"},+ },+ ),+ ]+ )+ def test_invalid_payloads(self, _name: str, payload: dict) -> None:+ serializer = LogsAnomalyScanRequestSerializer(data=payload)+ assert not serializer.is_valid()++ def test_valid_payload(self) -> None:+ serializer = LogsAnomalyScanRequestSerializer(+ data={+ "serviceName": "svc",+ "dateRange": {"date_from": "2026-06-01T00:00:00Z", "date_to": "2026-06-02T00:00:00Z"},+ }+ )+ assert serializer.is_valid(), serializer.errors+++class TestLogsAnomalyScanAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.url = f"/api/projects/{self.team.pk}/logs/anomalies/scan/"+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ self._ff_patcher.start()+ self.addCleanup(self._ff_patcher.stop)++ def _payload(self) -> dict:+ return {+ "serviceName": "svc",+ "dateRange": {"date_from": "2026-06-01T12:00:00Z", "date_to": "2026-06-01T13:00:00Z"},+ }++ def test_flag_off_is_forbidden(self):+ self._ff_patcher.stop()+ with patch("posthoganalytics.feature_enabled", return_value=False):+ response = self.client.post(self.url, self._payload(), format="json")+ self._ff_patcher.start()+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_invalid_body_is_rejected_before_scanning(self):+ with patch("products.logs.backend.presentation.views.anomalies_api.run_scan") as run:+ response = self.client.post(self.url, {"serviceName": "svc"}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ run.assert_not_called()++ def test_scan_response_shape(self):+ with patch(+ "products.logs.backend.presentation.views.anomalies_api.run_scan", return_value=_scan_result()+ ) as run:+ response = self.client.post(self.url, self._payload(), format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ run.assert_called_once()+ data = response.json()+ assert data["service_name"] == "svc"+ assert data["binding_constraints"] == []+ assert data["lookback_days"] == 42.0+ series = data["series"][0]+ assert series["severity"] == "info"+ assert series["buckets"][0]["observed"] == 120.0+ assert series["buckets"][0]["verdict"] is None+ issue = data["issues"][0]+ assert issue["direction"] == "up"+ assert issue["state"] == "active"+ assert issue["resolved_at"] is None++ def test_repeat_scan_is_served_from_cache(self):+ with patch(+ "products.logs.backend.presentation.views.anomalies_api.run_scan", return_value=_scan_result()+ ) as run:+ first = self.client.post(self.url, self._payload(), format="json")+ second = self.client.post(self.url, self._payload(), format="json")++ assert first.status_code == status.HTTP_200_OK+ assert second.status_code == status.HTTP_200_OK+ run.assert_called_once()+ assert first.json() == second.json()++ def test_budget_exhaustion_returns_422(self):+ with patch(+ "products.logs.backend.presentation.views.anomalies_api.run_scan",+ side_effect=ScanBudgetExceeded("over budget"),+ ):+ response = self.client.post(self.url, self._payload(), format="json")+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITYdiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex d7a68fd430ab..9275c5165685 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -811,6 +811,244 @@ export interface LogsAlertSimulateResponseApi {threshold_operator: string}+export interface _ScanDateRangeApi {+ /** Start of the evaluation window (ISO 8601). Buckets before this are only used as baseline history. */+ date_from: string+ /** End of the evaluation window (ISO 8601), clamped to now. */+ date_to: string+}++export interface LogsAnomalyScanRequestApi {+ /** Service to scan (the log record's service_name). Required: the scan aggregates weeks of baseline history from raw logs, so it is scoped to one service per call. */+ serviceName: string+ /** Evaluation window to scan for anomalies. May span at most 7 days. */+ dateRange: _ScanDateRangeApi+}++/**+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget+ */+export type BindingConstraintsEnumApi = (typeof BindingConstraintsEnumApi)[keyof typeof BindingConstraintsEnumApi]++export const BindingConstraintsEnumApi = {+ TeamRetention: 'team_retention',+ ByteBudget: 'byte_budget',+} as const++/**+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature+ */+export type LogsAnomalyBaselineStageEnumApi =+ (typeof LogsAnomalyBaselineStageEnumApi)[keyof typeof LogsAnomalyBaselineStageEnumApi]++export const LogsAnomalyBaselineStageEnumApi = {+ Insufficient: 'insufficient',+ ColdStart: 'cold_start',+ Developing: 'developing',+ Mature: 'mature',+} as const++/**+ * * `a` - a+ * * `b` - b+ * * `c` - c+ * * `d` - d+ */+export type LogsAnomalyScanSeriesTierEnumApi =+ (typeof LogsAnomalyScanSeriesTierEnumApi)[keyof typeof LogsAnomalyScanSeriesTierEnumApi]++export const LogsAnomalyScanSeriesTierEnumApi = {+ A: 'a',+ B: 'b',+ C: 'c',+ D: 'd',+} as const++/**+ * * `series_history` - series_history+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget+ */+export type LimitedByEnumApi = (typeof LimitedByEnumApi)[keyof typeof LimitedByEnumApi]++export const LimitedByEnumApi = {+ SeriesHistory: 'series_history',+ TeamRetention: 'team_retention',+ ByteBudget: 'byte_budget',+} as const++/**+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence+ */+export type LogsAnomalyVerdictEnumApi = (typeof LogsAnomalyVerdictEnumApi)[keyof typeof LogsAnomalyVerdictEnumApi]++export const LogsAnomalyVerdictEnumApi = {+ Spike: 'spike',+ Drop: 'drop',+ Silence: 'silence',+} as const++export interface LogsAnomalyScanBucketApi {+ /** Start of the 5 minute bucket (UTC). */+ time: string+ /** Log records observed in this bucket. */+ observed: number+ /**+ * Expected count from the learned baseline. Null when the bucket was not scored.+ * @nullable+ */+ expected: number | null+ /**+ * Lower edge of the expected band. Observed below this is a drop or silence candidate.+ * @nullable+ */+ lower: number | null+ /**+ * Upper edge of the expected band. Observed above this is a spike candidate.+ * @nullable+ */+ upper: number | null+ /** How much history backed the baseline for this bucket. Wider bands and lower confidence in cold_start; mature means a full seasonal baseline. Null when the bucket was gated out (for example, traffic below the detection floor).+ *+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature */+ stage: LogsAnomalyBaselineStageEnumApi | null+ /** Anomaly verdict for this bucket, or null when the observed count sat inside the band.+ *+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence */+ verdict: LogsAnomalyVerdictEnumApi | null+}++export interface LogsAnomalyScanSeriesApi {+ /** Severity level of this log series (for example info, warn, error). */+ severity: string+ /** Baseline stage reached by the end of the evaluation window. Null if no bucket was scored.+ *+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature */+ stage: LogsAnomalyBaselineStageEnumApi | null+ /** Traffic tier at the end of the window, from a (0.5 or more records per second) down to d (below the detection floor of roughly 1 record per minute).+ *+ * * `a` - a+ * * `b` - b+ * * `c` - c+ * * `d` - d */+ tier: LogsAnomalyScanSeriesTierEnumApi | null+ /**+ * Earliest bucket with data inside the fetched lookback.+ * @nullable+ */+ history_start: string | null+ /** What limited this series' baseline maturity, or null for a full baseline. series_history: data starts inside the lookback, because the series is young or a per-stream retention rule trimmed it (indistinguishable from the data). byte_budget and team_retention mirror the scan level constraints.+ *+ * * `series_history` - series_history+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget */+ limited_by: LimitedByEnumApi | null+ /** Per bucket observed counts and expected bands across the evaluation window, for evidence charts. */+ buckets: LogsAnomalyScanBucketApi[]+}++/**+ * * `up` - up+ * * `down` - down+ */+export type LogsAnomalyScanIssueDirectionEnumApi =+ (typeof LogsAnomalyScanIssueDirectionEnumApi)[keyof typeof LogsAnomalyScanIssueDirectionEnumApi]++export const LogsAnomalyScanIssueDirectionEnumApi = {+ Up: 'up',+ Down: 'down',+} as const++/**+ * * `pending` - pending+ * * `active` - active+ * * `resolved` - resolved+ */+export type LogsAnomalyScanIssueStateEnumApi =+ (typeof LogsAnomalyScanIssueStateEnumApi)[keyof typeof LogsAnomalyScanIssueStateEnumApi]++export const LogsAnomalyScanIssueStateEnumApi = {+ Pending: 'pending',+ Active: 'active',+ Resolved: 'resolved',+} as const++export interface LogsAnomalyScanIssueApi {+ /** up covers spikes; down covers drops and silences (which share one issue per service).+ *+ * * `up` - up+ * * `down` - down */+ direction: LogsAnomalyScanIssueDirectionEnumApi+ /**+ * Severity of the spiking series. Null for down issues, which are tracked per service.+ * @nullable+ */+ severity: string | null+ /** Most severe verdict the issue reached. A drop that deepens into silence escalates in place.+ *+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence */+ kind: LogsAnomalyVerdictEnumApi+ /** Lifecycle state at the end of the evaluation window.+ *+ * * `pending` - pending+ * * `active` - active+ * * `resolved` - resolved */+ state: LogsAnomalyScanIssueStateEnumApi+ /** Bucket where the issue first opened. */+ opened_at: string+ /** Most recent anomalous bucket attributed to this issue. */+ last_anomalous_at: string+ /**+ * Bucket where the issue resolved, or null if it was still open at the end of the window.+ * @nullable+ */+ resolved_at: string | null+ /** Every anomalous bucket attributed to this issue, oldest first. */+ anomalous_bucket_times: string[]+}++export interface LogsAnomalyScanResponseApi {+ /** Service that was scanned. */+ service_name: string+ /** Actual start of the evaluated window after any clipping. */+ eval_start: string+ /** Actual end of the evaluated window after clamping to now. */+ eval_end: string+ /** Days of baseline history the scan used. */+ lookback_days: number+ /** True when the evaluation window was clipped to fit the read budget. The response covers only the clipped window. */+ eval_clipped: boolean+ /** True when the scan could not afford the full lookback and fell back to a cheaper configuration. */+ degraded: boolean+ /** Everything that limited the baseline, empty for an unconstrained scan. team_retention: the project's log retention is shorter than the full lookback. byte_budget: the scan degraded to stay inside its ClickHouse read budget. */+ binding_constraints: BindingConstraintsEnumApi[]+ /** One entry per severity level observed for the service, with per bucket evidence. */+ series: LogsAnomalyScanSeriesApi[]+ /** Anomaly issues that opened during the evaluation window, oldest first. */+ issues: LogsAnomalyScanIssueApi[]+}++export interface LogsAnomalyScanErrorApi {+ /** Human readable description of why the scan could not run. */+ error: string+}+export interface _DateRangeApi {/*** Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex aa7720898ea0..26d0e6ef82a4 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -18,6 +18,8 @@ import type {LogsAlertSimulateResponseApi,LogsAlertsEventsListParams,LogsAlertsListParams,+ LogsAnomalyScanRequestApi,+ LogsAnomalyScanResponseApi,LogsAttributesRetrieveParams,LogsExportCreate201,LogsHasLogsRetrieve200,@@ -304,6 +306,27 @@ export const logsAlertsSimulateCreate = async (})}+export const getLogsAnomaliesScanCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/logs/anomalies/scan/`+}++/**+ * Runs anomaly detection on demand over one service's log volume for the given window. Learns per severity baselines from up to 6 weeks of history and returns per bucket expected bands plus any spike, drop, or silence issues. Synchronous and read only.+ * @summary Scan a service's logs for volume anomalies+ */+export const logsAnomaliesScanCreate = async (+ projectId: string,+ logsAnomalyScanRequestApi: LogsAnomalyScanRequestApi,+ options?: RequestInit+): Promise<LogsAnomalyScanResponseApi> => {+ return apiMutator<LogsAnomalyScanResponseApi>(getLogsAnomaliesScanCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(logsAnomalyScanRequestApi),+ })+}+export const getLogsAttributesRetrieveUrl = (projectId: string, params?: LogsAttributesRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex d7251f43f624..b14c84e5eb98 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -399,6 +399,30 @@ export const LogsAlertsSimulateCreateBody = /* @__PURE__ */ zod.object({date_from: zod.string().describe("Relative date string for how far back to simulate (e.g. '-24h', '-7d', '-30d')."),})+/**+ * Runs anomaly detection on demand over one service's log volume for the given window. Learns per severity baselines from up to 6 weeks of history and returns per bucket expected bands plus any spike, drop, or silence issues. Synchronous and read only.+ * @summary Scan a service's logs for volume anomalies+ */+export const LogsAnomaliesScanCreateBody = /* @__PURE__ */ zod.object({+ serviceName: zod+ .string()+ .describe(+ "Service to scan (the log record's service_name). Required: the scan aggregates weeks of baseline history from raw logs, so it is scoped to one service per call."+ ),+ dateRange: zod+ .object({+ date_from: zod.iso+ .datetime({ offset: true })+ .describe(+ 'Start of the evaluation window (ISO 8601). Buckets before this are only used as baseline history.'+ ),+ date_to: zod.iso+ .datetime({ offset: true })+ .describe('End of the evaluation window (ISO 8601), clamped to now.'),+ })+ .describe('Evaluation window to scan for anomalies. May span at most 7 days.'),+})+export const LogsCountCreateBody = /* @__PURE__ */ zod.object({query: zod.object({diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex da79f5cb218f..949d5b91f60d 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -282,6 +282,9 @@ tools:logs-alerts-update:operation: logs_alerts_updateenabled: false+ logs-anomalies-scan-create:+ operation: logs_anomalies_scan_create+ enabled: falselogs-attribute-values-list:operation: logs_values_retrieveenabled: truediff --git a/pyproject.toml b/pyproject.tomlindex f20d420ed42b..dd4df83e1ca5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -587,6 +587,7 @@ ignore_imports = ["products.logs.backend.presentation.views.retention_api -> products.logs.backend.models","products.logs.backend.presentation.views.sampling_api -> products.logs.backend.models","products.logs.backend.presentation.views.views_api -> products.logs.backend.models",+ "products.logs.backend.presentation.views.anomalies_api -> products.logs.backend.anomaly_scan",# logs presentation isolation (temporary): cross-product imports the moved viewsets# still make directly. These resolve once cdp/exports expose the needed facades, so# they outlive the in-product cleanup above.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 83fc61958715..1bdc711d0b77 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12426,6 +12426,18 @@ export namespace Schemas {Credited: 'credited',} as const;+ /**+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget+ */+ export type BindingConstraintsEnum = typeof BindingConstraintsEnum[keyof typeof BindingConstraintsEnum];+++ export const BindingConstraintsEnum = {+ TeamRetention: 'team_retention',+ ByteBudget: 'byte_budget',+ } as const;+/*** * `email` - email*/@@ -24763,10 +24775,10 @@ export namespace Schemas {* * `general-availability` - general availability* * `archived` - archived*/- export type StageEnum = typeof StageEnum[keyof typeof StageEnum];+ export type EarlyAccessFeatureStageEnum = typeof EarlyAccessFeatureStageEnum[keyof typeof EarlyAccessFeatureStageEnum];- export const StageEnum = {+ export const EarlyAccessFeatureStageEnum = {Draft: 'draft',Concept: 'concept',Alpha: 'alpha',@@ -24796,7 +24808,7 @@ export namespace Schemas {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage: StageEnum;+ stage: EarlyAccessFeatureStageEnum;/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800@@ -24848,7 +24860,7 @@ export namespace Schemas {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage: StageEnum;+ stage: EarlyAccessFeatureStageEnum;/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800@@ -38862,10 +38874,10 @@ export namespace Schemas {* * `medium` - medium* * `low` - low*/- export type TierEnum = typeof TierEnum[keyof typeof TierEnum];+ export type IdentityMatchingLinkTierEnum = typeof IdentityMatchingLinkTierEnum[keyof typeof IdentityMatchingLinkTierEnum];- export const TierEnum = {+ export const IdentityMatchingLinkTierEnum = {High: 'high',Medium: 'medium',Low: 'low',@@ -38973,7 +38985,7 @@ export namespace Schemas {* * `high` - high* * `medium` - medium* * `low` - low */- tier: TierEnum;+ tier: IdentityMatchingLinkTierEnum;/** When the link was computed (UTC). */computed_at: string;/** Distinct (IP, day) combinations both sides were seen on. */@@ -40702,6 +40714,20 @@ export namespace Schemas {Sustained: 'sustained',} as const;+ /**+ * * `series_history` - series_history+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget+ */+ export type LimitedByEnum = typeof LimitedByEnum[keyof typeof LimitedByEnum];+++ export const LimitedByEnum = {+ SeriesHistory: 'series_history',+ TeamRetention: 'team_retention',+ ByteBudget: 'byte_budget',+ } as const;+export interface LinearIssueSignalExtra {url: string;identifier: string;@@ -41142,6 +41168,221 @@ export namespace Schemas {url: string;}+ /**+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature+ */+ export type LogsAnomalyBaselineStageEnum = typeof LogsAnomalyBaselineStageEnum[keyof typeof LogsAnomalyBaselineStageEnum];+++ export const LogsAnomalyBaselineStageEnum = {+ Insufficient: 'insufficient',+ ColdStart: 'cold_start',+ Developing: 'developing',+ Mature: 'mature',+ } as const;++ /**+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence+ */+ export type LogsAnomalyVerdictEnum = typeof LogsAnomalyVerdictEnum[keyof typeof LogsAnomalyVerdictEnum];+++ export const LogsAnomalyVerdictEnum = {+ Spike: 'spike',+ Drop: 'drop',+ Silence: 'silence',+ } as const;++ export interface LogsAnomalyScanBucket {+ /** Start of the 5 minute bucket (UTC). */+ time: string;+ /** Log records observed in this bucket. */+ observed: number;+ /**+ * Expected count from the learned baseline. Null when the bucket was not scored.+ * @nullable+ */+ expected: number | null;+ /**+ * Lower edge of the expected band. Observed below this is a drop or silence candidate.+ * @nullable+ */+ lower: number | null;+ /**+ * Upper edge of the expected band. Observed above this is a spike candidate.+ * @nullable+ */+ upper: number | null;+ /** How much history backed the baseline for this bucket. Wider bands and lower confidence in cold_start; mature means a full seasonal baseline. Null when the bucket was gated out (for example, traffic below the detection floor).+ *+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature */+ stage: LogsAnomalyBaselineStageEnum | null;+ /** Anomaly verdict for this bucket, or null when the observed count sat inside the band.+ *+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence */+ verdict: LogsAnomalyVerdictEnum | null;+ }++ export interface LogsAnomalyScanError {+ /** Human readable description of why the scan could not run. */+ error: string;+ }++ /**+ * * `up` - up+ * * `down` - down+ */+ export type LogsAnomalyScanIssueDirectionEnum = typeof LogsAnomalyScanIssueDirectionEnum[keyof typeof LogsAnomalyScanIssueDirectionEnum];+++ export const LogsAnomalyScanIssueDirectionEnum = {+ Up: 'up',+ Down: 'down',+ } as const;++ /**+ * * `pending` - pending+ * * `active` - active+ * * `resolved` - resolved+ */+ export type LogsAnomalyScanIssueStateEnum = typeof LogsAnomalyScanIssueStateEnum[keyof typeof LogsAnomalyScanIssueStateEnum];+++ export const LogsAnomalyScanIssueStateEnum = {+ Pending: 'pending',+ Active: 'active',+ Resolved: 'resolved',+ } as const;++ export interface LogsAnomalyScanIssue {+ /** up covers spikes; down covers drops and silences (which share one issue per service).+ *+ * * `up` - up+ * * `down` - down */+ direction: LogsAnomalyScanIssueDirectionEnum;+ /**+ * Severity of the spiking series. Null for down issues, which are tracked per service.+ * @nullable+ */+ severity: string | null;+ /** Most severe verdict the issue reached. A drop that deepens into silence escalates in place.+ *+ * * `spike` - spike+ * * `drop` - drop+ * * `silence` - silence */+ kind: LogsAnomalyVerdictEnum;+ /** Lifecycle state at the end of the evaluation window.+ *+ * * `pending` - pending+ * * `active` - active+ * * `resolved` - resolved */+ state: LogsAnomalyScanIssueStateEnum;+ /** Bucket where the issue first opened. */+ opened_at: string;+ /** Most recent anomalous bucket attributed to this issue. */+ last_anomalous_at: string;+ /**+ * Bucket where the issue resolved, or null if it was still open at the end of the window.+ * @nullable+ */+ resolved_at: string | null;+ /** Every anomalous bucket attributed to this issue, oldest first. */+ anomalous_bucket_times: string[];+ }++ export interface _ScanDateRange {+ /** Start of the evaluation window (ISO 8601). Buckets before this are only used as baseline history. */+ date_from: string;+ /** End of the evaluation window (ISO 8601), clamped to now. */+ date_to: string;+ }++ export interface LogsAnomalyScanRequest {+ /** Service to scan (the log record's service_name). Required: the scan aggregates weeks of baseline history from raw logs, so it is scoped to one service per call. */+ serviceName: string;+ /** Evaluation window to scan for anomalies. May span at most 7 days. */+ dateRange: _ScanDateRange;+ }++ /**+ * * `a` - a+ * * `b` - b+ * * `c` - c+ * * `d` - d+ */+ export type LogsAnomalyScanSeriesTierEnum = typeof LogsAnomalyScanSeriesTierEnum[keyof typeof LogsAnomalyScanSeriesTierEnum];+++ export const LogsAnomalyScanSeriesTierEnum = {+ A: 'a',+ B: 'b',+ C: 'c',+ D: 'd',+ } as const;++ export interface LogsAnomalyScanSeries {+ /** Severity level of this log series (for example info, warn, error). */+ severity: string;+ /** Baseline stage reached by the end of the evaluation window. Null if no bucket was scored.+ *+ * * `insufficient` - insufficient+ * * `cold_start` - cold_start+ * * `developing` - developing+ * * `mature` - mature */+ stage: LogsAnomalyBaselineStageEnum | null;+ /** Traffic tier at the end of the window, from a (0.5 or more records per second) down to d (below the detection floor of roughly 1 record per minute).+ *+ * * `a` - a+ * * `b` - b+ * * `c` - c+ * * `d` - d */+ tier: LogsAnomalyScanSeriesTierEnum | null;+ /**+ * Earliest bucket with data inside the fetched lookback.+ * @nullable+ */+ history_start: string | null;+ /** What limited this series' baseline maturity, or null for a full baseline. series_history: data starts inside the lookback, because the series is young or a per-stream retention rule trimmed it (indistinguishable from the data). byte_budget and team_retention mirror the scan level constraints.+ *+ * * `series_history` - series_history+ * * `team_retention` - team_retention+ * * `byte_budget` - byte_budget */+ limited_by: LimitedByEnum | null;+ /** Per bucket observed counts and expected bands across the evaluation window, for evidence charts. */+ buckets: LogsAnomalyScanBucket[];+ }++ export interface LogsAnomalyScanResponse {+ /** Service that was scanned. */+ service_name: string;+ /** Actual start of the evaluated window after any clipping. */+ eval_start: string;+ /** Actual end of the evaluated window after clamping to now. */+ eval_end: string;+ /** Days of baseline history the scan used. */+ lookback_days: number;+ /** True when the evaluation window was clipped to fit the read budget. The response covers only the clipped window. */+ eval_clipped: boolean;+ /** True when the scan could not afford the full lookback and fell back to a cheaper configuration. */+ degraded: boolean;+ /** Everything that limited the baseline, empty for an unconstrained scan. team_retention: the project's log retention is shorter than the full lookback. byte_budget: the scan degraded to stay inside its ClickHouse read budget. */+ binding_constraints: BindingConstraintsEnum[];+ /** One entry per severity level observed for the service, with per bucket evidence. */+ series: LogsAnomalyScanSeries[];+ /** Anomaly issues that opened during the evaluation window, oldest first. */+ issues: LogsAnomalyScanIssue[];+ }+/*** * `log` - log* * `resource` - resource@@ -52464,7 +52705,7 @@ export namespace Schemas {* * `beta` - beta* * `general-availability` - general availability* * `archived` - archived */- stage?: StageEnum;+ stage?: EarlyAccessFeatureStageEnum;/*** URL to external documentation for this feature. Shown to users in the opt-in UI.* @maxLength 800