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(logs): gate logs alert grouping behind a feature flag (#127708)

Jimmy Zhuf4c1a7661dfe
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3f380133f204..8747b538c44e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -378,6 +378,7 @@ export const FEATURE_FLAGS = {
LLM_ANALYTICS_TRACE_NAVIGATION: 'llm-analytics-trace-navigation', // owner: #team-ai-observability
LLM_OBSERVABILITY_TRACE_SEARCH: 'llm-observability-trace-search', // owner: #team-ai-observability
LOGS: 'logs', // owner: #team-logs
+ LOGS_ALERTS_GROUPING: 'logs-alerts-grouping', // owner: #team-apm, shows the Group by field on logs alerts the alerts platform runs
LOGS_ANOMALIES: 'logs-anomalies', // owner: @jonmcwest #team-logs
LOGS_IMPACT_STRIP: 'logs-impact-strip', // owner: #team-logs
LOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logs
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 565b7f9f0152..22dd40f62da4 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -31,6 +31,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.user import User
+from posthog.permissions import posthog_feature_flag_enabled
from posthog.queryset_paging import stable_queryset_ordering
from posthog.utils import relative_date_parse
@@ -58,6 +59,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationValidationError,
DestinationType,
Grouping,
+ GroupingMode,
InvalidPlatformAlertEdit,
PagerDutyRegion,
PagerDutySeverity,
@@ -130,6 +132,8 @@ DEFAULT_CHECK_INTERVAL_MINUTES = 5
_SENTINEL: Final = object()
_NOT_ANNOTATED: Final = object()
_SINGLE_INSTANCE: Final = Grouping()
+LOGS_ALERTS_GROUPING_FLAG: Final = "logs-alerts-grouping"
+GROUPING_NOT_ENABLED: Final = "Grouping isn't available for this project yet. Set the mode to single to save the alert."
def _any_field_changed(instance: LogsAlertConfiguration, validated_data: dict, fields: set[str]) -> bool:
@@ -779,8 +783,26 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
except ValueError as e:
raise ValidationError({"schedule_restriction": str(e)}) from e
+ grouping: Grouping | None = attrs.get("grouping")
+ if grouping is not None and grouping.mode != GroupingMode.SINGLE and not self._may_group(grouping):
+ raise ValidationError({"grouping": GROUPING_NOT_ENABLED})
+
return attrs
+ def _may_group(self, grouping: Grouping) -> bool:
+ team = self.context["get_team"]()
+ if posthog_feature_flag_enabled(
+ LOGS_ALERTS_GROUPING_FLAG,
+ str(cast(User, self.context["request"].user).distinct_id),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ ):
+ return True
+ # An alert that already groups keeps its keys with the flag off, so it can still change its
+ # group limit or be ungrouped.
+ runtime = _platform_runtime_of([self.instance]).get(self.instance.id) if self.instance else None
+ return runtime is not None and runtime.grouping.splits_like(grouping)
+
def update(self, instance: LogsAlertConfiguration, validated_data: dict) -> LogsAlertConfiguration:
if "name" in validated_data and not validated_data.get("name", "").strip():
validated_data["name"] = "Untitled alert"
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 19a7241c9ff0..d435902c1b4c 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -75,6 +75,7 @@ def _make_log_row(*, team_id: int, service: str, uuid: str, ts: datetime, body:
# Where a request-side delivery meets Temporal and the transports, which the tests stand in for.
_WEB_START = "products.alerts_platform.backend.temporal.web_start"
+_ALERTS_API = "products.logs.backend.presentation.views.alerts_api"
_NATIVE_PAGERDUTY_DELIVER = "products.alerts_platform.backend.delivery.pagerduty.PagerDutyTransport.deliver"
@@ -2648,22 +2649,26 @@ class TestLogsAlertAPI(APIBaseTest):
@parameterized.expand(
[
- ("cut_over", True, "severity_text", status.HTTP_201_CREATED),
- ("not_cut_over", False, "severity_text", status.HTTP_400_BAD_REQUEST),
- ("cut_over_unknown_key", True, "host", status.HTTP_400_BAD_REQUEST),
+ ("cut_over", True, True, "severity_text", status.HTTP_201_CREATED),
+ ("cut_over_flag_off", True, False, "severity_text", status.HTTP_400_BAD_REQUEST),
+ ("not_cut_over", False, True, "severity_text", status.HTTP_400_BAD_REQUEST),
+ ("cut_over_unknown_key", True, True, "host", status.HTTP_400_BAD_REQUEST),
]
)
- def test_creating_a_grouped_alert(self, _name: str, cut_over: bool, key: str, expected_status: int) -> None:
+ def test_creating_a_grouped_alert(
+ self, _name: str, cut_over: bool, flag_on: bool, key: str, expected_status: int
+ ) -> None:
self._keep_the_team_on_logs()
if cut_over:
self._owned_by_the_platform()
alerts_before = LogsAlertConfiguration.objects.filter(team=self.team).count()
- response = self.client.post(
- self.base_url,
- self._valid_payload(name="Grouped", grouping={"mode": "by_result_labels", "keys": [key]}),
- format="json",
- )
+ with patch(f"{_ALERTS_API}.posthog_feature_flag_enabled", return_value=flag_on):
+ response = self.client.post(
+ self.base_url,
+ self._valid_payload(name="Grouped", grouping={"mode": "by_result_labels", "keys": [key]}),
+ format="json",
+ )
assert response.status_code == expected_status, response.json()
if expected_status == status.HTTP_201_CREATED:
@@ -2672,6 +2677,36 @@ class TestLogsAlertAPI(APIBaseTest):
assert response.json()["attr"] == "grouping"
assert LogsAlertConfiguration.objects.filter(team=self.team).count() == alerts_before
+ @parameterized.expand(
+ [
+ (
+ "new_limit",
+ {"mode": "by_result_labels", "keys": ["service_name"], "max_instances": 5},
+ status.HTTP_200_OK,
+ ),
+ ("ungrouped", {"mode": "single"}, status.HTTP_200_OK),
+ ("new_keys", {"mode": "by_result_labels", "keys": ["severity_text"]}, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_with_the_grouping_flag_off_a_grouped_alert_keeps_only_its_keys(
+ self, _name: str, grouping: dict, expected_status: int
+ ) -> None:
+ self._keep_the_team_on_logs()
+ created = self._owned_by_the_platform()
+ self.client.patch(
+ f"{self.base_url}{created['id']}/",
+ {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}},
+ format="json",
+ )
+
+ with patch(f"{_ALERTS_API}.posthog_feature_flag_enabled", return_value=False):
+ response = self.client.patch(f"{self.base_url}{created['id']}/", {"grouping": grouping}, format="json")
+
+ assert response.status_code == expected_status, response.json()
+ if expected_status == status.HTTP_400_BAD_REQUEST:
+ assert response.json()["attr"] == "grouping"
+ assert self._copy_grouping_keys(created["id"]) == ("service_name",)
+
@parameterized.expand(
[
("source_owned_grouped", False, {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}}),
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx
index 5f1f37d7b852..ac64ff215123 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx
@@ -2,6 +2,8 @@ import { Meta, StoryObj } from '@storybook/react'
import { BindLogic, useActions, useValues } from 'kea'
import { useEffect } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
+
import type { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
import { LogsAlertTrigger } from './LogsAlertForm'
@@ -65,6 +67,7 @@ const meta: Meta = {
layout: 'padded',
viewMode: 'story',
mockDate: '2026-10-19',
+ featureFlags: [FEATURE_FLAGS.LOGS_ALERTS_GROUPING],
// The simulation placeholder draws skeletons as decoration, so they never disappear.
testOptions: { waitForLoadersToDisappear: false },
},
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx
index c912b45be5c2..b3714bf102bc 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx
@@ -7,7 +7,13 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LogsAlertConfigurationThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { logsAlertFormLogic } from './logsAlertFormLogic'
-import { GROUP_BY_LABELS, GROUPING_NEEDS_ABOVE, LogsAlertGroupBy, MAX_INSTANCES_LIMIT } from './logsAlertGrouping'
+import {
+ GROUP_BY_LABELS,
+ GROUP_BY_NOT_AVAILABLE,
+ GROUPING_NEEDS_ABOVE,
+ LogsAlertGroupBy,
+ MAX_INSTANCES_LIMIT,
+} from './logsAlertGrouping'
const GROUP_BY_HELP: Record<LogsAlertGroupBy, string> = {
none: 'Split the count by service or severity to alert on each one separately.',
@@ -20,7 +26,7 @@ const GROUP_BY_HELP: Record<LogsAlertGroupBy, string> = {
}
export function LogsAlertGroupByField(): JSX.Element | null {
- const { alertForm, alertFormValidationErrors, canGroup } = useValues(logsAlertFormLogic)
+ const { alertForm, alertFormValidationErrors, canGroup, lockedGroupBy } = useValues(logsAlertFormLogic)
const { setGroupBy, setAlertFormValue } = useActions(logsAlertFormLogic)
if (!canGroup) {
@@ -32,6 +38,15 @@ export function LogsAlertGroupByField(): JSX.Element | null {
? undefined
: GROUPING_NEEDS_ABOVE
const isGrouped = alertForm.groupBy !== 'none'
+ const disabledReasonFor = (groupBy: LogsAlertGroupBy): string | undefined => {
+ if (groupBy === 'none') {
+ return undefined
+ }
+ if (lockedGroupBy !== null && groupBy !== lockedGroupBy) {
+ return GROUP_BY_NOT_AVAILABLE
+ }
+ return groupingDisabledReason
+ }
return (
<LemonField.Pure
@@ -46,7 +61,7 @@ export function LogsAlertGroupByField(): JSX.Element | null {
options={(Object.keys(GROUP_BY_LABELS) as LogsAlertGroupBy[]).map((groupBy) => ({
value: groupBy,
label: GROUP_BY_LABELS[groupBy],
- disabledReason: groupBy === 'none' ? undefined : groupingDisabledReason,
+ disabledReason: disabledReasonFor(groupBy),
}))}
size="small"
data-attr="logs-alert-group-by"
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
index 699c578ba814..9e79ccade74b 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
@@ -5,6 +5,9 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
@@ -531,6 +534,13 @@ describe('logsAlertFormLogic', () => {
})
describe('grouping', () => {
+ const setGroupingFlag = (enabled: boolean): void => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.LOGS_ALERTS_GROUPING]: enabled })
+ }
+
+ beforeEach(() => setGroupingFlag(true))
+
it.each<[string, LogsAlertConfigurationApi | null, LogsAlertConfigurationApi[], boolean]>([
['alert the source owns', MOCK_ALERT, [], false],
['alert the source owns in a team that has cut over', MOCK_ALERT, [PLATFORM_ALERT], false],
@@ -549,6 +559,23 @@ describe('logsAlertFormLogic', () => {
logic.unmount()
})
+ it.each<[string, LogsAlertConfigurationApi | null, LogsAlertConfigurationApi[], boolean, LogsAlertGroupBy]>([
+ ['alert the platform owns', PLATFORM_ALERT, [], false, 'none'],
+ ['alert that already groups', GROUPED_BY_SERVICE_ALERT, [], true, 'service'],
+ ['new alert in a team that has cut over', null, [MOCK_ALERT, PLATFORM_ALERT], false, 'none'],
+ ])('with the flag off, can group for %s', async (_, alert, teamAlerts, expected, lockedGroupBy) => {
+ setGroupingFlag(false)
+ givenTeamAlerts(teamAlerts)
+ const logic = logsAlertFormLogic({ alert })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.canGroup).toBe(expected)
+ expect(logic.values.lockedGroupBy).toBe(lockedGroupBy)
+ logic.unmount()
+ })
+
it.each<[string, LogsAlertConfigurationApi, string]>([
[
'an ungrouped alert that is not firing',
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
index 67ea42647f63..56d2a6a860eb 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
@@ -8,6 +8,8 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -121,6 +123,7 @@ export function buildFormDefaults(alert: LogsAlertConfigurationApi | null): Logs
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertFormLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
pendingNotifications: PendingLogsAlertNotification[] // logsAlertNotificationLogic
alerts: LogsAlertConfigurationApi[] // logsAlertingLogic
currentTeamId: number | null // teamLogic
@@ -134,12 +137,14 @@ export interface logsAlertFormLogicValues {
alertFormTouches: Record<string, boolean>
alertFormValidationErrors: DeepPartialMap<LogsAlertFormType, ValidationErrorType>
canGroup: boolean
+ groupingFlagEnabled: boolean
isAlertFormSubmitting: boolean
isAlertFormValid: boolean
isEditing: boolean
isRegroupConfirmationOpen: boolean
isRegroupConfirmed: boolean
isSimulationPanelOpen: boolean
+ lockedGroupBy: LogsAlertGroupBy | null
needsRegroupConfirmation: boolean
regroupConfirmation: string
showAlertFormErrors: boolean
@@ -260,7 +265,9 @@ export interface logsAlertFormLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
isEditing: (arg: any) => boolean
- canGroup: (arg: any, alerts: LogsAlertConfigurationApi[]) => boolean
+ groupingFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ canGroup: (arg: any, alerts: LogsAlertConfigurationApi[], groupingFlagEnabled: boolean) => boolean
+ lockedGroupBy: (arg: any, groupingFlagEnabled: boolean) => LogsAlertGroupBy | null
regroupConfirmation: (arg: any) => string
needsRegroupConfirmation: (arg: any, canGroup: boolean, alertForm: LogsAlertFormType) => boolean
simulationDisabledReason: (canGroup: boolean, alertForm: LogsAlertFormType) => string | undefined
@@ -285,6 +292,8 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
['currentTeamId'],
logsAlertingLogic,
['alerts'],
+ featureFlagLogic,
+ ['featureFlags'],
logsAlertNotificationLogic({ alertId: alert?.id }),
['pendingNotifications'],
],
@@ -394,10 +403,22 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
selectors({
isEditing: [() => [(_, props) => props.alert], (alert: LogsAlertConfigurationApi | null) => alert !== null],
+ groupingFlagEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.LOGS_ALERTS_GROUPING],
+ ],
canGroup: [
- (s) => [(_, props) => props.alert, s.alerts],
- (alert: LogsAlertConfigurationApi | null, alerts: LogsAlertConfigurationApi[]): boolean =>
- canGroupAlert(alert, alerts),
+ (s) => [(_, props) => props.alert, s.alerts, s.groupingFlagEnabled],
+ (
+ alert: LogsAlertConfigurationApi | null,
+ alerts: LogsAlertConfigurationApi[],
+ groupingFlagEnabled: boolean
+ ): boolean => canGroupAlert(alert, alerts, groupingFlagEnabled),
+ ],
+ lockedGroupBy: [
+ (s) => [(_, props) => props.alert, s.groupingFlagEnabled],
+ (alert: LogsAlertConfigurationApi | null, groupingFlagEnabled: boolean): LogsAlertGroupBy | null =>
+ groupingFlagEnabled ? null : groupByOf(alert?.grouping),
],
regroupConfirmation: [
() => [(_, props) => props.alert],
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts b/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts
index f4ab4090d526..638b8beb3084 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts
@@ -23,6 +23,8 @@ export const SIMULATION_NEEDS_UNGROUPED =
export const MAX_INSTANCES_LIMIT = 100
+export const GROUP_BY_NOT_AVAILABLE = "Grouping by other fields isn't available for this project yet."
+
const GROUP_BY_KEYS: Record<LogsAlertGroupBy, string[]> = {
none: [],
service: ['service_name'],
@@ -77,16 +79,21 @@ export function isRegroup(alert: LogsAlertConfigurationApi | null, groupBy: Logs
/**
* Only an alert the alerts platform evaluates can group. A new alert goes to the platform once the
- * team has any logs alert there, which mirrors the backend's cutover check.
+ * team has any logs alert there, which mirrors the backend's cutover check. An alert that already
+ * groups keeps the field even with the flag off, so its grouping stays visible and can be removed.
*/
export function canGroupAlert(
alert: LogsAlertConfigurationApi | null,
- teamAlerts: LogsAlertConfigurationApi[]
+ teamAlerts: LogsAlertConfigurationApi[],
+ groupingFlagEnabled: boolean
): boolean {
- if (!alert) {
- return teamAlerts.some((candidate) => candidate.platform_owned)
+ if (alert?.grouping?.mode === GroupingModeEnumApi.ByResultLabels) {
+ return true
+ }
+ if (!groupingFlagEnabled) {
+ return false
}
- return alert.platform_owned || alert.grouping?.mode === GroupingModeEnumApi.ByResultLabels
+ return alert ? alert.platform_owned : teamAlerts.some((candidate) => candidate.platform_owned)
}
/** What a save that changes the grouping does to the state the alert tracks now. */
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
index bf9b7400489e..42f89da44da6 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
@@ -1,5 +1,8 @@
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { initKeaTests } from '~/test/init'
import { logsAlertFormLogic } from 'products/logs/frontend/components/LogsAlerting/logsAlertFormLogic'
@@ -149,6 +152,8 @@ describe('logsAlertDetailSceneLogic — save-then-enable chain', () => {
it('keeps the pending enable while a regroup waits for confirmation, then enables once confirmed', async () => {
const platformAlert: LogsAlertConfigurationApi = { ...MOCK_ALERT, platform_owned: true }
mockedApi.logsAlertsRetrieve.mockResolvedValue(platformAlert)
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.LOGS_ALERTS_GROUPING]: true })
const logic = await mountSceneLogic()
// The scene renders the form with the loaded alert, which is what tells the form it can group.
const formLogic = logsAlertFormLogic({ alert: platformAlert })