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): let projects turn off anomaly scoring in self-driving settings (#125582)

posthog[bot]0ee14c27ba73
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 4f4a556f5677..d40445420bc8 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -519,6 +519,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
"github_issue_writeback_enabled": "comment back on GitHub issues",
"pull_request_label_enabled": "label self-driving PRs",
"pull_request_label": "self-driving PR label",
+ "anomaly_scoring_enabled": "anomaly scoring",
"scout_instructions": "scout instructions",
"research_instructions": "research instructions",
"implementation_instructions": "implementation instructions",
diff --git a/products/signals/backend/anomaly_scores/queue.py b/products/signals/backend/anomaly_scores/queue.py
index d222ed8d70c0..d3b618580f04 100644
--- a/products/signals/backend/anomaly_scores/queue.py
+++ b/products/signals/backend/anomaly_scores/queue.py
@@ -63,6 +63,7 @@ from products.signals.backend.anomaly_scores.selection import (
score_order,
)
from products.signals.backend.anomaly_scores.state import RunPlan, load_states, plan_run, score_ready_by_insight
+from products.signals.backend.models import SignalTeamConfig
from products.subscriptions.backend.facade.api import insight_ids_with_active_subscriptions
from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes
@@ -201,7 +202,11 @@ class QueryBudget:
def eligible_teams(config: AnomalyScoringConfig) -> list[Team]:
if not config.enabled or not config.organization_ids:
return []
- teams = Team.objects.filter(organization_id__in=config.organization_ids).exclude(id__in=config.skip_team_ids)
+ teams = (
+ Team.objects.filter(organization_id__in=config.organization_ids)
+ .exclude(id__in=config.skip_team_ids)
+ .exclude(id__in=SignalTeamConfig.objects.filter(anomaly_scoring_enabled=False).values("team_id"))
+ )
if config.allow_team_ids:
teams = teams.filter(id__in=config.allow_team_ids)
# Capture drops every event of a project over its event quota, so scoring it wastes the query.
@@ -209,6 +214,11 @@ def eligible_teams(config: AnomalyScoringConfig) -> list[Team]:
return [team for team in teams if team.api_token not in limited]
+def turned_off_in_settings(team: Team) -> bool:
+ """Whether the project turned anomaly scoring off in its self-driving settings. A team without a config row is on."""
+ return SignalTeamConfig.objects.filter(team_id=team.id, anomaly_scoring_enabled=False).exists()
+
+
def active_insights(
team_ids: list[int], intervals: tuple[IntervalType, ...], now: datetime.datetime, window_days: int
) -> list[ActiveInsight]:
diff --git a/products/signals/backend/anomaly_scores/search.py b/products/signals/backend/anomaly_scores/search.py
index c5105ec987ec..2fd6c5e8c757 100644
--- a/products/signals/backend/anomaly_scores/search.py
+++ b/products/signals/backend/anomaly_scores/search.py
@@ -21,8 +21,14 @@ 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 active_insights
+from products.signals.backend.anomaly_scores.config import (
+ MAX_LIMITS,
+ AnomalyScoringConfig,
+ covers_team,
+ parse_config,
+ read_payload,
+)
+from products.signals.backend.anomaly_scores.queue import active_insights, turned_off_in_settings
from products.signals.backend.anomaly_scores.read import (
MAX_BUCKETS,
FlaggedPoint,
@@ -47,6 +53,10 @@ 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."
+SCORING_TURNED_OFF_MESSAGE = (
+ "Anomaly scoring is turned off in this project's self-driving settings, so no insight is scored. "
+ "Scores written before it was turned off stay readable."
+)
class AnomalyInterval(models.TextChoices):
@@ -197,9 +207,18 @@ def _requested_insight_ids(team: Team, user: User, filters: AnomalySearchFilters
return insight_ids
-def _empty_message(*, scoring_enabled: bool, watched: int, scored_in_range: int) -> str:
- if not scoring_enabled:
+def _scoring_off_message(config: AnomalyScoringConfig, team: Team) -> str | None:
+ """Why the tick does not score this team's insights, or None when it does."""
+ if not covers_team(config, team):
return SCORING_DISABLED_MESSAGE
+ if turned_off_in_settings(team):
+ return SCORING_TURNED_OFF_MESSAGE
+ return None
+
+
+def _empty_message(*, off_message: str | None, watched: int, scored_in_range: int) -> str:
+ if off_message is not None:
+ return off_message
if not scored_in_range:
return f"No insight was scored in this range. Scoring checks {watched} active insights, a few at a time."
return (
@@ -211,7 +230,7 @@ def _empty_message(*, scoring_enabled: bool, watched: int, scored_in_range: int)
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)
+ off_message = _scoring_off_message(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 active_insights([team.id], intervals, now, config.active_window_days)}
@@ -277,7 +296,7 @@ def search(team: Team, user: User, filters: AnomalySearchFilters, now: datetime.
watched_count = len(watched & insights.keys())
return AnomalySearchResult(
- scoring_enabled=scoring_enabled,
+ scoring_enabled=off_message is None,
watched_insights=watched_count,
insights_scored_in_range=scored_in_range,
series=series_rows,
@@ -285,7 +304,7 @@ def search(team: Team, user: User, filters: AnomalySearchFilters, now: datetime.
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),
+ else _empty_message(off_message=off_message, watched=watched_count, scored_in_range=scored_in_range),
)
@@ -318,7 +337,7 @@ def insight_history(
if not readable:
return None
insight = readable[0]
- scoring_enabled = covers_team(parse_config(read_payload()), team)
+ off_message = _scoring_off_message(parse_config(read_payload()), team)
summaries = series_summaries(
team,
date_from=filters.date_from,
@@ -371,9 +390,9 @@ def insight_history(
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
+ message = off_message or "No bucket of this insight was scored in this range."
return AnomalyInsightHistory(
- scoring_enabled=scoring_enabled,
+ scoring_enabled=off_message is None,
insight=insight,
insight_url=insight_url(team, insight, _flagged_starts(ranked), newest.interval if newest else None),
interval=newest.interval if newest else None,
diff --git a/products/signals/backend/migrations/0216_signalteamconfig_anomaly_scoring_enabled.py b/products/signals/backend/migrations/0216_signalteamconfig_anomaly_scoring_enabled.py
new file mode 100644
index 000000000000..0ff10c92cb30
--- /dev/null
+++ b/products/signals/backend/migrations/0216_signalteamconfig_anomaly_scoring_enabled.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-29 14:48
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0215_useractivitysummary_empty_profile_status"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalteamconfig",
+ name="anomaly_scoring_enabled",
+ field=models.BooleanField(db_default=True, default=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 8f5f98de0a6f..7c5fcf181d28 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0215_useractivitysummary_empty_profile_status
+0216_signalteamconfig_anomaly_scoring_enabled
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index c2a53e11b375..9f31a443b574 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -271,6 +271,9 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):
# shares with everybody. A null or blank name falls back to DEFAULT_PULL_REQUEST_LABEL.
pull_request_label_enabled = models.BooleanField(default=False, db_default=False)
pull_request_label = models.CharField(max_length=GITHUB_LABEL_NAME_MAX_LENGTH, null=True, blank=True)
+ # Opt-out of anomaly scoring (see anomaly_scores/queue.py). The `anomaly-scoring` flag payload
+ # still decides which projects are enrolled, so turning this on cannot enroll a project.
+ anomaly_scoring_enabled = models.BooleanField(default=True, db_default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/signals/backend/presentation/anomalies.py b/products/signals/backend/presentation/anomalies.py
index 0726068a0333..10b1361e01fe 100644
--- a/products/signals/backend/presentation/anomalies.py
+++ b/products/signals/backend/presentation/anomalies.py
@@ -218,7 +218,13 @@ class AnomalyInsightRowSerializer(serializers.Serializer):
class AnomalySearchResponseSerializer(serializers.Serializer):
- scoring_enabled = serializers.BooleanField(help_text="Whether anomaly scoring covers this project.")
+ scoring_enabled = serializers.BooleanField(
+ help_text=(
+ "Whether anomaly scoring scores this project now. False when scoring does not cover the "
+ "project, or when the project turned it off in its self-driving settings. Scores written "
+ "before scoring was turned off are still returned."
+ )
+ )
watched_insights = serializers.IntegerField(
help_text=(
"Active insights that scoring checks: saved trends insights that a person viewed, that sit on a "
@@ -295,7 +301,13 @@ class AnomalyInsightSeriesSerializer(serializers.Serializer):
class AnomalyInsightResponseSerializer(serializers.Serializer):
- scoring_enabled = serializers.BooleanField(help_text="Whether anomaly scoring covers this project.")
+ scoring_enabled = serializers.BooleanField(
+ help_text=(
+ "Whether anomaly scoring scores this project now. False when scoring does not cover the "
+ "project, or when the project turned it off in its self-driving settings. Scores written "
+ "before scoring was turned off are still returned."
+ )
+ )
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."
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 21a94a0cc100..51191b2768a0 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -25,6 +25,7 @@ from posthog.models.integration import Integration, is_supported_external_issue_
from products.signals.backend import contracts
from products.signals.backend.agent_instructions import AGENT_STEERING_MAX_LENGTH, STEERING_FIELDS
+from products.signals.backend.anomaly_scores.config import covers_team, parse_config, read_payload
from products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reason
from products.signals.backend.contracts import (
DEFAULT_NOT_ACTIONABLE_KEY,
@@ -470,6 +471,21 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"when it does not exist yet. Only used while pull_request_label_enabled is true."
),
)
+ anomaly_scoring_enabled = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether anomaly scoring scores this project's active trends insights every hour and writes "
+ "the results as $anomaly_score events, which are not billed. True by default. Set false to "
+ "stop new scores; events written before stay. Turning it on does not enroll a project that "
+ "anomaly_scoring_available reports as not covered."
+ ),
+ )
+ anomaly_scoring_available = serializers.SerializerMethodField(
+ help_text=(
+ "Whether anomaly scoring covers this project, so anomaly_scoring_enabled has an effect. "
+ "PostHog decides which projects anomaly scoring covers."
+ )
+ )
reports_generated_today = serializers.SerializerMethodField(
help_text=(
"How many reports first became visible in the inbox during the current project-timezone "
@@ -511,6 +527,10 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
return 0
return self._reports_today_count(obj)
+ @extend_schema_field(serializers.BooleanField())
+ def get_anomaly_scoring_available(self, obj: SignalTeamConfig) -> bool:
+ return covers_team(parse_config(read_payload()), obj.team)
+
@extend_schema_field(serializers.BooleanField())
def get_daily_report_limit_reached(self, obj: SignalTeamConfig) -> bool:
if obj.max_reports_per_day is None:
@@ -535,12 +555,21 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"github_issue_writeback_enabled",
"pull_request_label_enabled",
"pull_request_label",
+ "anomaly_scoring_enabled",
+ "anomaly_scoring_available",
+ "reports_generated_today",
+ "daily_report_limit_reached",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = [
+ "id",
+ "anomaly_scoring_available",
"reports_generated_today",
"daily_report_limit_reached",
"created_at",
"updated_at",
]
- read_only_fields = ["id", "reports_generated_today", "daily_report_limit_reached", "created_at", "updated_at"]
extra_kwargs = {
"autostart_enabled": {
"help_text": (
diff --git a/products/signals/backend/test/test_anomaly_scoring_tick.py b/products/signals/backend/test/test_anomaly_scoring_tick.py
index 3602b3214a35..058f03159b35 100644
--- a/products/signals/backend/test/test_anomaly_scoring_tick.py
+++ b/products/signals/backend/test/test_anomaly_scoring_tick.py
@@ -84,7 +84,7 @@ from products.signals.backend.anomaly_scores.tick import (
plan_tick,
run_insight,
)
-from products.signals.backend.models import AnomalyScoringState
+from products.signals.backend.models import AnomalyScoringState, SignalTeamConfig
from products.subscriptions.backend.facade.testing import create_subscription
NEW_YORK = ZoneInfo("America/New_York")
@@ -697,16 +697,27 @@ _SPLIT_PAYLOAD = {"enabled": True, "organization_ids": [ORGANIZATION_ID], "train
class TestEligibleTeams(BaseTest):
@parameterized.expand(
[
- ("every_team_of_the_organization", [], [], False, {"main", "second"}),
- ("allowlist", ["main"], [], False, {"main"}),
- ("skip_list", [], ["main"], False, {"second"}),
- ("quota_limited", [], [], True, {"main"}),
+ ("every_team_of_the_organization", [], [], False, None, {"main", "second"}),
+ ("allowlist", ["main"], [], False, None, {"main"}),
+ ("skip_list", [], ["main"], False, None, {"second"}),
+ ("quota_limited", [], [], True, None, {"main"}),
+ ("turned_off_in_settings", [], [], False, False, {"main"}),
+ ("left_on_in_settings", [], [], False, True, {"main", "second"}),
+ ("settings_cannot_enroll_a_skipped_team", [], ["second"], False, True, {"main"}),
]
)
def test_only_allowed_teams_under_their_event_quota_are_scored(
- self, _name: str, allow: list[str], skip: list[str], second_limited: bool, expected: set[str]
+ self,
+ _name: str,
+ allow: list[str],
+ skip: list[str],
+ second_limited: bool,
+ second_setting: bool | None,
+ expected: set[str],
) -> None:
teams = {"main": self.team, "second": Team.objects.create(organization=self.organization, name="second")}
+ if second_setting is not None:
+ SignalTeamConfig.objects.create(team=teams["second"], anomaly_scoring_enabled=second_setting)
other = Organization.objects.create(name="other")
Team.objects.create(organization=other, name="other")
config = AnomalyScoringConfig(
diff --git a/products/signals/backend/test/test_anomaly_search.py b/products/signals/backend/test/test_anomaly_search.py
index f5212872b82f..d848cef44a5a 100644
--- a/products/signals/backend/test/test_anomaly_search.py
+++ b/products/signals/backend/test/test_anomaly_search.py
@@ -16,7 +16,12 @@ 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
+from products.signals.backend.anomaly_scores.search import (
+ MAX_INSIGHT_SERIES,
+ SCORING_DISABLED_MESSAGE,
+ SCORING_TURNED_OFF_MESSAGE,
+)
+from products.signals.backend.models import SignalTeamConfig
NOW = datetime.datetime(2026, 10, 23, 12, tzinfo=datetime.UTC)
@@ -173,13 +178,25 @@ class TestAnomalySearchAPI(ClickhouseTestMixin, APIBaseTest):
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": []}
+ @parameterized.expand(
+ [
+ ("search_outside_the_payload", "search", False, SCORING_DISABLED_MESSAGE),
+ ("insight_outside_the_payload", "insight", False, SCORING_DISABLED_MESSAGE),
+ ("search_turned_off_in_settings", "search", True, SCORING_TURNED_OFF_MESSAGE),
+ ("insight_turned_off_in_settings", "insight", True, SCORING_TURNED_OFF_MESSAGE),
+ ]
+ )
+ def test_explains_an_empty_result_for_a_team_that_is_not_scored(
+ self, _name: str, endpoint: str, turned_off: bool, message: str
+ ) -> None:
+ if turned_off:
+ SignalTeamConfig.objects.create(team=self.team, anomaly_scoring_enabled=False)
+ else:
+ self.payload.return_value = {"enabled": True, "organization_ids": []}
- body = self._get("search").json()
+ body = self._get(endpoint, insight_id=self.insight.id).json()
- assert (body["scoring_enabled"], body["series"]) == (False, [])
- assert body["message"] == "Anomaly scoring is not enabled for this project, so no insight is scored."
+ assert (body["scoring_enabled"], body["message"]) == (False, message)
def test_insight_returns_every_bucket_of_each_series_oldest_first(self) -> None:
self._score_history()
diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.py
index c8ecee44abc1..c0bd2059ce98 100644
--- a/products/signals/backend/test/test_signal_team_config_api.py
+++ b/products/signals/backend/test/test_signal_team_config_api.py
@@ -88,6 +88,15 @@ class TestSignalTeamConfigAPI(APIBaseTest):
assert data["default_autostart_priority"] == "P4"
# Null until a team explicitly opts out; the guard treats null as autostart-on.
assert data["autostart_enabled"] is None
+ assert data["anomaly_scoring_enabled"] is True
+
+ @parameterized.expand([("covered", True), ("not_covered", False)])
+ def test_anomaly_scoring_available_follows_the_scoring_payload(self, _name, covered):
+ payload = {"enabled": True, "organization_ids": [str(self.organization.id)] if covered else []}
+ with patch("products.signals.backend.serializers.read_payload", return_value=payload):
+ data = self.client.get(self._url()).json()
+
+ assert data["anomaly_scoring_available"] is covered
def test_get_config_lazily_creates_when_no_config_exists(self):
self.config.delete()
@@ -322,6 +331,7 @@ class TestSignalTeamConfigAPI(APIBaseTest):
False,
True,
),
+ ("anomaly_scoring", "anomaly_scoring_enabled", False, "anomaly scoring", "changed", True, False),
]
)
def test_update_is_recorded_in_the_activity_log(self, _name, field, sent, label, action, before, after):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 5e71122bbdea..ad76f3895177 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -394,7 +394,7 @@ export interface AnomalyInsightSeriesApi {
}
export interface AnomalyInsightResponseApi {
- /** Whether anomaly scoring covers this project. */
+ /** Whether anomaly scoring scores this project now. False when scoring does not cover the project, or when the project turned it off in its self-driving settings. Scores written before scoring was turned off are still returned. */
scoring_enabled: boolean
/** The numeric id of the insight. */
insight_id: number
@@ -612,7 +612,7 @@ export interface AnomalyInsightRowApi {
}
export interface AnomalySearchResponseApi {
- /** Whether anomaly scoring covers this project. */
+ /** Whether anomaly scoring scores this project now. False when scoring does not cover the project, or when the project turned it off in its self-driving settings. Scores written before scoring was turned off are still returned. */
scoring_enabled: boolean
/** Active insights that scoring checks: saved trends insights that a person viewed, that sit on a dashboard someone opened, or that were edited in the active window (90 days by default), or that have an enabled alert or subscription. */
watched_insights: number
@@ -724,6 +724,10 @@ export interface SignalTeamConfigApi {
* @nullable
*/
pull_request_label?: string | null
+ /** Whether anomaly scoring scores this project's active trends insights every hour and writes the results as $anomaly_score events, which are not billed. True by default. Set false to stop new scores; events written before stay. Turning it on does not enroll a project that anomaly_scoring_available reports as not covered. */
+ anomaly_scoring_enabled?: boolean
+ /** Whether anomaly scoring covers this project, so anomaly_scoring_enabled has an effect. PostHog decides which projects anomaly scoring covers. */
+ readonly anomaly_scoring_available: boolean
/**
* How many reports first became visible in the inbox during the current project-timezone day. This is the count the daily report limit compares against.
* @minimum 0
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 822f3ffa67e6..a3ce8dcb2586 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -119,6 +119,12 @@ export const SignalsConfigCreateBody = /* @__PURE__ */ zod.object({
.describe(
"The label name self-driving applies, at most 50 characters. Null or blank means 'self-driving'. The label is created in the repository when it does not exist yet. Only used while pull_request_label_enabled is true."
),
+ anomaly_scoring_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Whether anomaly scoring scores this project's active trends insights every hour and writes the results as $anomaly_score events, which are not billed. True by default. Set false to stop new scores; events written before stay. Turning it on does not enroll a project that anomaly_scoring_available reports as not covered."
+ ),
})
export const signalsOnboardingCreateBodyScannerIdsMax = 100
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
index d1dd3f7f61a7..9ca01a70318e 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
@@ -599,6 +599,31 @@ function PullRequestLabelRow(): JSX.Element {
)
}
+/**
+ * Team-wide opt-out of anomaly scoring. PostHog decides which projects scoring covers, so the row
+ * only renders for a covered project, and the switch can stop scoring but cannot start it.
+ */
+function AnomalyScoringRow(): JSX.Element {
+ const { anomalyScoringEnabled, teamConfigUpdating } = useValues(signalTeamConfigLogic)
+ const { patchTeamConfig } = useActions(signalTeamConfigLogic)
+
+ return (
+ <AutonomySettingRow
+ title="Anomaly scoring"
+ description="Check your active trends insights for anomalies every hour. Results are saved as $anomaly_score events, which are free. Turn this off to stop new events. Events already saved stay."
+ control={
+ <LemonSwitch
+ checked={anomalyScoringEnabled}
+ loading={teamConfigUpdating}
+ onChange={(enabled) => patchTeamConfig({ anomaly_scoring_enabled: enabled })}
+ aria-label="Score active trends insights for anomalies"
+ data-attr="signals-anomaly-scoring-enabled"
+ />
+ }
+ />
+ )
+}
+
/**
* Per-user opt-in to being added as a GitHub assignee on the implementation PR for reports that
* suggest this user as reviewer. Off by default, because being assigned is visible to everybody on
@@ -783,7 +808,7 @@ function PullRequestGenerationRow(): JSX.Element {
* applies to, and every row shares one shape (`AutonomySettingRow`).
*/
export function SelfDrivingSection(): JSX.Element {
- const { teamConfig, teamConfigLoading } = useValues(signalTeamConfigLogic)
+ const { teamConfig, teamConfigLoading, anomalyScoringAvailable } = useValues(signalTeamConfigLogic)
if (teamConfigLoading && teamConfig === null) {
return <LemonSkeleton className="h-20 w-full rounded" />
@@ -809,6 +834,7 @@ export function SelfDrivingSection(): JSX.Element {
</AutonomySettingGroup>
<AutonomySettingGroup title="Reports" description="Applies to everyone in this project.">
<DailyReportLimitRow />
+ {anomalyScoringAvailable && <AnomalyScoringRow />}
</AutonomySettingGroup>
</div>
)
diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
index bd72d2d61d6d..a11d4da785ca 100644
--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
@@ -25,6 +25,8 @@ const VISIBILITY_REFETCH_THROTTLE_MS = 5 * 1000
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalTeamConfigLogicValues {
addBaseBranchOverrideDisabledReason: string | null
+ anomalyScoringAvailable: boolean
+ anomalyScoringEnabled: boolean
autostartEnabled: boolean
baseBranchOverrides: BaseBranchOverride[]
baseBranchPickerOpen: boolean
@@ -157,6 +159,8 @@ export interface signalTeamConfigLogicMeta {
githubIssueWritebackEnabled: (teamConfig: SignalTeamConfig | null) => boolean
pullRequestLabelEnabled: (teamConfig: SignalTeamConfig | null) => boolean
pullRequestLabel: (teamConfig: SignalTeamConfig | null) => string
+ anomalyScoringEnabled: (teamConfig: SignalTeamConfig | null) => boolean
+ anomalyScoringAvailable: (teamConfig: SignalTeamConfig | null) => boolean
issueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | null
issueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>
selectedIssueTrackerIntegrationId: (
@@ -388,6 +392,14 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): string => teamConfig?.pull_request_label ?? '',
],
+ anomalyScoringEnabled: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.anomaly_scoring_enabled ?? true,
+ ],
+ anomalyScoringAvailable: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.anomaly_scoring_available ?? false,
+ ],
issueTrackerIntegrationId: [
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index 972e16b713b9..a1e01af8a088 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -412,6 +412,10 @@ export interface SignalTeamConfig {
pull_request_label_enabled?: boolean
/** The label name to apply, at most 50 characters. Null or blank means the default label. */
pull_request_label?: string | null
+ /** Whether anomaly scoring writes $anomaly_score events for this project. True by default; false opts out. */
+ anomaly_scoring_enabled?: boolean
+ /** Read-only: whether anomaly scoring covers this project, so the switch above has an effect. Never send in a patch. */
+ anomaly_scoring_available?: boolean
/** Read-only: reports that first became visible today (project timezone). Never send in a patch. */
reports_generated_today?: number
/** Read-only: whether the daily report limit is reached, pausing new report generation until local midnight. Never send in a patch. */
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index a604ef99aa10..f7ab33867bf0 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -51,8 +51,10 @@ tools:
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.
+ keys of `details` depend on the detector. `scoring_enabled: false` means the project is not scored now:
+ scoring does not cover it, or the project turned scoring off in its self-driving settings. `message` says
+ which when no bucket is returned. 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
@@ -75,8 +77,9 @@ tools:
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.
+ range, or that the project is not scored (`scoring_enabled: false`), because scoring does not cover it or
+ the project turned scoring off in its self-driving settings; `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
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8620772f55db..2a5ac0bf9038 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1130,7 +1130,7 @@
"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.",
+ "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. `scoring_enabled: false` means the project is not scored now: scoring does not cover it, or the project turned scoring off in its self-driving settings. `message` says which when no bucket is returned. 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",
@@ -1146,7 +1146,7 @@
"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.",
+ "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 the project is not scored (`scoring_enabled: false`), because scoring does not cover it or the project turned scoring off in its self-driving settings; `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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 3fdf93356762..6ee512936214 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1145,7 +1145,7 @@
"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.",
+ "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. `scoring_enabled: false` means the project is not scored now: scoring does not cover it, or the project turned scoring off in its self-driving settings. `message` says which when no bucket is returned. 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",
@@ -1161,7 +1161,7 @@
"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.",
+ "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 the project is not scored (`scoring_enabled: false`), because scoring does not cover it or the project turned scoring off in its self-driving settings; `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",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 09910cf8c034..60b435b34475 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13565,7 +13565,7 @@ export namespace Schemas {
}
export interface AnomalyInsightResponse {
- /** Whether anomaly scoring covers this project. */
+ /** Whether anomaly scoring scores this project now. False when scoring does not cover the project, or when the project turned it off in its self-driving settings. Scores written before scoring was turned off are still returned. */
scoring_enabled: boolean;
/** The numeric id of the insight. */
insight_id: number;
@@ -13757,7 +13757,7 @@ export namespace Schemas {
}
export interface AnomalySearchResponse {
- /** Whether anomaly scoring covers this project. */
+ /** Whether anomaly scoring scores this project now. False when scoring does not cover the project, or when the project turned it off in its self-driving settings. Scores written before scoring was turned off are still returned. */
scoring_enabled: boolean;
/** Active insights that scoring checks: saved trends insights that a person viewed, that sit on a dashboard someone opened, or that were edited in the active window (90 days by default), or that have an enabled alert or subscription. */
watched_insights: number;
@@ -111711,6 +111711,10 @@ export namespace Schemas {
* @nullable
*/
pull_request_label?: string | null;
+ /** Whether anomaly scoring scores this project's active trends insights every hour and writes the results as $anomaly_score events, which are not billed. True by default. Set false to stop new scores; events written before stay. Turning it on does not enroll a project that anomaly_scoring_available reports as not covered. */
+ anomaly_scoring_enabled?: boolean;
+ /** Whether anomaly scoring covers this project, so anomaly_scoring_enabled has an effect. PostHog decides which projects anomaly scoring covers. */
+ readonly anomaly_scoring_available: boolean;
/**
* How many reports first became visible in the inbox during the current project-timezone day. This is the count the daily report limit compares against.
* @minimum 0
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 281e2a2aa827..043120fbdd97 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -283,6 +283,12 @@ export const SignalsConfigCreateBody = () => zod.object({
.describe(
"The label name self-driving applies, at most 50 characters. Null or blank means 'self-driving'. The label is created in the repository when it does not exist yet. Only used while pull_request_label_enabled is true."
),
+ anomaly_scoring_enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Whether anomaly scoring scores this project's active trends insights every hour and writes the results as $anomaly_score events, which are not billed. True by default. Set false to stop new scores; events written before stay. Turning it on does not enroll a project that anomaly_scoring_available reports as not covered."
+ ),
})
export const SignalsReportsListParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 568bcbebc377..37fed2383436 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -1232,6 +1232,7 @@ const InboxSteeringInstructionsUpdateSchema = () => {
github_issue_writeback_enabled: true,
pull_request_label_enabled: true,
pull_request_label: true,
+ anomaly_scoring_enabled: true,
})
}