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): add a group by control to the logs alert form (#119997)

Jimmy Zhu3b5853c22580
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ac122d775fda..4fd53534c903 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7394,6 +7394,30 @@ snapshots:
hash: v1.k794b7964.07fbb23b3942035a85dc6d01935b8bd6ac19d0dabeeb9e791e4927d5baf4ef72.axXUR1_1SAlWjxI7MO8me8EhFHP-K4K8BK7nz9MYixk
products-growth-enrichment-scoring--ten-companies--light:
hash: v1.k794b7964.0408b3b6fd529316505baa5fead85a26cbac63ccc65cd2c969e1e76429ac7378.gGeycoxbfN15Ye7CZYv6cM1xGDS3zD_ba9rJKHpj354
+ products-logs-alerting-group-by--group-firing-alert-confirmation--dark:
+ hash: v1.k794b7964.290738f433db9582da1a4b88791af12198cf8ff6ec5ec3ab093980fd0873d85a.gTiEBLZZbJ7o1Sk04fInxFlrfIlaedm4Ek9THJnjpTQ
+ products-logs-alerting-group-by--group-firing-alert-confirmation--light:
+ hash: v1.k794b7964.75a91aec6007d7bdc350d5b93d400ea27f3b90ebd5bdf6ad683d37d9927f5f2f.Fis5m55hg7q_SZyUgLe4mDYveFiTyYuMwLaWx0ZRvTQ
+ products-logs-alerting-group-by--group-limit-out-of-range--dark:
+ hash: v1.k794b7964.10afb442752f92f7bec6c8c730292c6e79f09d0cf386f68317ff40868cabf4cc.Yitnk2TD6Vt8vBK27Y_aytdlouMsZUWxz4uuepAMbPA
+ products-logs-alerting-group-by--group-limit-out-of-range--light:
+ hash: v1.k794b7964.52f7e282bc5f9b15ed7da0295056cf8bbef5acf6c179a267c0a4ca1cf86669ea.9exy1BYwSaqaB57xYnD6wI9e37Zx8msshSQQXXKu3po
+ products-logs-alerting-group-by--grouped-by-service--dark:
+ hash: v1.k794b7964.be221a1ac5d999374bec56104be50b09c1cf1deab974629cd891ac8a5c7bbce6.L7UPr3B5tJq8MCmV6t58mEyJLsHDxK6Pdolsxnct-rU
+ products-logs-alerting-group-by--grouped-by-service--light:
+ hash: v1.k794b7964.9843ec9753d92f2376b1589e6342147829c94099be930b2338f3ac19e60cf8f3.2WoR21D11d1cUOakQk18UrN_x69pFAE8XKZ34QkvQ6Q
+ products-logs-alerting-group-by--grouped-by-service-narrow--dark:
+ hash: v1.k794b7964.6c95308004becdd1443fdca3eb77d32f2241722376d54c76113ad5542ffe1334.pZ4Gaqb-J-xHMGRtjopaTZH9KwJYFcNV37O8D7U6hos
+ products-logs-alerting-group-by--grouped-by-service-narrow--light:
+ hash: v1.k794b7964.2fef9a44569587ce95b8111b7b64c54b486bc584aeb2788f331c0ac39c488b1a.HPvRL7lns5R1uLrscIqv_3oMMHBN4cFdMXtNJ3b2bPs
+ products-logs-alerting-group-by--regroup-confirmation--dark:
+ hash: v1.k794b7964.9f43995beecfa4a7217dcbd4cd12fe7b56ff280e4da78ca628c17f092147c529.4En13fN0SKhDSaPEVJiKcChgoOuLzHlK2r9ORChRZ_w
+ products-logs-alerting-group-by--regroup-confirmation--light:
+ hash: v1.k794b7964.5e2c72f756e107885621f42fbc1f1edc494cb4e24e29fa2f5cf17ca4c3841630.GPR9xF9SvNKlw-yS186LzTpSGrsn7kvsahIXRHiKhbo
+ products-logs-alerting-group-by--ungrouped--dark:
+ hash: v1.k794b7964.58a264d2615832f3e96be1bb5a7f07cc9fc5858adce4b7582aab491f4e34281b.F6Uvo-RwN6NUscIkcmR-BHShSAuHtkpW5NX-XLChMJU
+ products-logs-alerting-group-by--ungrouped--light:
+ hash: v1.k794b7964.bbe4c79ee9117cc0df57531110e19b7e2584fe3bc8075bfd08b7f35cd9d3a5b8.hyGeBtgGbsX5I0W6XUtLOayiFlXZPxoEJfaIkg_jtC8
products-mcp-analytics-brand-marks--all-marks--dark:
hash: v1.k794b7964.7c7d7c7233c5a27dbfa3aa4b3487fa34fdf05b7f0434b3e333eb5fb1cbb9fc5a.f8oq1fyw6uRkercF_yNDT5tdUIRZ7h9ONcxngwkQtqE
products-mcp-analytics-brand-marks--all-marks--light:
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
index 11402eee506b..f8912307a29c 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx
@@ -10,6 +10,7 @@ import { AlertWizard, AlertWizardStep } from 'products/alerts/frontend/component
import { LogsAlertFilters, LogsAlertTrigger } from './LogsAlertForm'
import { logsAlertFormLogic, LogsAlertFormType } from './logsAlertFormLogic'
+import { GROUP_BY_LABELS } from './logsAlertGrouping'
import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
import { LogsAlertNotifications } from './LogsAlertNotifications'
import { LogsAlertSimulation } from './LogsAlertSimulation'
@@ -30,7 +31,9 @@ export function LogsAlertCreateModal({ isOpen, onClose }: LogsAlertCreateModalPr
function LogsAlertCreateModalContent({ onClose }: { onClose: () => void }): JSX.Element {
const formLogicProps = { alert: null, onSubmitSuccess: onClose }
- const { isAlertFormSubmitting, alertFormChanged, alertForm } = useValues(logsAlertFormLogic(formLogicProps))
+ const { isAlertFormSubmitting, alertFormChanged, alertForm, alertFormValidationErrors, canGroup } = useValues(
+ logsAlertFormLogic(formLogicProps)
+ )
const { touchAlertFormField } = useActions(logsAlertFormLogic(formLogicProps))
const { pendingNotifications } = useValues(logsAlertNotificationLogic({}))
const hasLogFilter = hasAnyFilter(alertForm.severityLevels, alertForm.serviceNames, alertForm.filterGroup)
@@ -39,12 +42,15 @@ function LogsAlertCreateModalContent({ onClose }: { onClose: () => void }): JSX.
? undefined
: 'Select at least one severity or service, or add an attribute filter.'
const configurationCannotAdvanceReason = nameError ?? filterError
+ const triggerCannotAdvanceReason = alertFormValidationErrors.maxInstances as string | undefined
const steps = buildLogsAlertWizardSteps({
alertForm,
pendingNotifications,
configurationCannotAdvanceReason,
+ triggerCannotAdvanceReason,
nameError,
filterError,
+ canGroup,
})
return (
@@ -75,14 +81,18 @@ function buildLogsAlertWizardSteps({
alertForm,
pendingNotifications,
configurationCannotAdvanceReason,
+ triggerCannotAdvanceReason,
nameError,
filterError,
+ canGroup,
}: {
alertForm: LogsAlertFormType
pendingNotifications: PendingLogsAlertNotification[]
configurationCannotAdvanceReason: string | undefined
+ triggerCannotAdvanceReason: string | undefined
nameError: string | undefined
filterError: string | undefined
+ canGroup: boolean
}): AlertWizardStep[] {
return [
{
@@ -102,6 +112,8 @@ function buildLogsAlertWizardSteps({
key: 'trigger',
title: 'Set trigger',
description: 'Set the log count that fires the alert and reduce notification noise if needed.',
+ canAdvance: !triggerCannotAdvanceReason,
+ cannotAdvanceReason: triggerCannotAdvanceReason,
content: (
<div className="space-y-6">
<LogsAlertTrigger />
@@ -123,7 +135,13 @@ function buildLogsAlertWizardSteps({
key: 'review',
title: 'Review',
description: 'Confirm the alert before you create it.',
- content: <LogsAlertReview alertForm={alertForm} pendingNotifications={pendingNotifications} />,
+ content: (
+ <LogsAlertReview
+ alertForm={alertForm}
+ pendingNotifications={pendingNotifications}
+ canGroup={canGroup}
+ />
+ ),
},
]
}
@@ -131,9 +149,11 @@ function buildLogsAlertWizardSteps({
function LogsAlertReview({
alertForm,
pendingNotifications,
+ canGroup,
}: {
alertForm: LogsAlertFormType
pendingNotifications: PendingLogsAlertNotification[]
+ canGroup: boolean
}): JSX.Element {
const severity = alertForm.severityLevels.length ? alertForm.severityLevels.join(', ') : 'all severities'
const services = alertForm.serviceNames.length ? alertForm.serviceNames.join(', ') : 'all services'
@@ -165,6 +185,17 @@ function LogsAlertReview({
label: 'Fires when',
value: `log count is ${alertForm.thresholdOperator} ${alertForm.thresholdCount} in ${alertForm.windowMinutes} minutes`,
},
+ ...(canGroup
+ ? [
+ {
+ label: 'Group by',
+ value:
+ alertForm.groupBy === 'none'
+ ? GROUP_BY_LABELS.none
+ : `${GROUP_BY_LABELS[alertForm.groupBy]}, up to ${alertForm.maxInstances} groups`,
+ },
+ ]
+ : []),
{
label: 'Noise reduction',
value: `${alertForm.datapointsToAlarm} of ${alertForm.evaluationPeriods} checks must match`,
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx
index 0170f5828a78..2d7889fd8ddc 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEditModal.tsx
@@ -18,6 +18,7 @@ import { logsAlertFormLogic } from './logsAlertFormLogic'
import { logsAlertingLogic } from './logsAlertingLogic'
import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
import { LogsAlertNotifications } from './LogsAlertNotifications'
+import { LogsAlertRegroupConfirmModal } from './LogsAlertRegroupConfirmModal'
import { LogsAlertSimulation } from './LogsAlertSimulation'
import { LogsAlertStateIndicator } from './LogsAlertStateIndicator'
import { LogsAlertStateTimeline } from './LogsAlertStateTimeline'
@@ -235,6 +236,7 @@ function LogsAlertEditModalContent({
/>
</AlertEditor>
</Form>
+ <LogsAlertRegroupConfirmModal />
</BindLogic>
</BindLogic>
)
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
index 7d55a8e37173..cf34870b817d 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
@@ -26,6 +26,8 @@ import { SeverityLevelsFilter } from 'products/logs/frontend/components/LogsView
import { LogsAlertConfigurationThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { logsAlertFormLogic } from './logsAlertFormLogic'
+import { LogsAlertGroupByField } from './LogsAlertGroupByField'
+import { GROUPING_NEEDS_ABOVE } from './logsAlertGrouping'
const WINDOW_OPTIONS = [
{ value: 5, label: '5 minutes' },
@@ -172,7 +174,11 @@ export function LogsAlertTrigger(): JSX.Element {
onChange={(value) => setAlertFormValue('thresholdOperator', value)}
options={[
{ value: LogsAlertConfigurationThresholdOperatorEnumApi.Above, label: 'above' },
- { value: LogsAlertConfigurationThresholdOperatorEnumApi.Below, label: 'below' },
+ {
+ value: LogsAlertConfigurationThresholdOperatorEnumApi.Below,
+ label: 'below',
+ disabledReason: alertForm.groupBy === 'none' ? undefined : GROUPING_NEEDS_ABOVE,
+ },
]}
size="small"
/>
@@ -194,6 +200,7 @@ export function LogsAlertTrigger(): JSX.Element {
/>
</AlertDefinitionRow>
</div>
+ <LogsAlertGroupByField />
<AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
<LemonField.Pure
label={
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx
new file mode 100644
index 000000000000..5f1f37d7b852
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupBy.stories.tsx
@@ -0,0 +1,140 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic, useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import type { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { LogsAlertTrigger } from './LogsAlertForm'
+import { logsAlertFormLogic } from './logsAlertFormLogic'
+import type { LogsAlertGroupBy } from './logsAlertGrouping'
+import { LogsAlertRegroupConfirmModal } from './LogsAlertRegroupConfirmModal'
+import { LogsAlertSimulation } from './LogsAlertSimulation'
+
+const UNGROUPED_ALERT: LogsAlertConfigurationApi = {
+ id: '0192a5b0-0000-7000-8000-0000000000aa',
+ name: 'Checkout errors',
+ enabled: true,
+ filters: { severityLevels: ['error'], serviceNames: ['checkout', 'payments'] },
+ threshold_count: 100,
+ threshold_operator: 'above',
+ window_minutes: 5,
+ check_interval_minutes: 5,
+ state: 'not_firing',
+ evaluation_periods: 1,
+ datapoints_to_alarm: 1,
+ cooldown_minutes: 0,
+ schedule_restriction: null,
+ snooze_until: null,
+ next_check_at: null,
+ last_notified_at: null,
+ last_checked_at: null,
+ consecutive_failures: 0,
+ last_error_message: null,
+ state_timeline: [],
+ destination_types: [],
+ grouping: { mode: 'single', keys: [], max_instances: 100, on_overflow: 'degrade_visible' },
+ platform_owned: true,
+ first_enabled_at: '2026-10-01T09:00:00Z',
+ created_at: '2026-10-01T09:00:00Z',
+ created_by: {
+ id: 1,
+ uuid: '0192a5b0-0000-7000-8000-000000000999',
+ distinct_id: 'user-distinct-id',
+ first_name: 'Jane',
+ email: '[email protected]',
+ hedgehog_config: null,
+ },
+ updated_at: null,
+}
+
+const GROUPED_ALERT: LogsAlertConfigurationApi = {
+ ...UNGROUPED_ALERT,
+ id: '0192a5b0-0000-7000-8000-0000000000bb',
+ grouping: { mode: 'by_result_labels', keys: ['service_name'], max_instances: 20, on_overflow: 'degrade_visible' },
+}
+
+const FIRING_UNGROUPED_ALERT: LogsAlertConfigurationApi = {
+ ...UNGROUPED_ALERT,
+ id: '0192a5b0-0000-7000-8000-0000000000cc',
+ state: 'firing',
+}
+
+const meta: Meta = {
+ title: 'Products/Logs/Alerting/Group by',
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ mockDate: '2026-10-19',
+ // The simulation placeholder draws skeletons as decoration, so they never disappear.
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+function GroupByForm({
+ alert,
+ width,
+ regroupTo,
+ maxInstances,
+}: {
+ alert: LogsAlertConfigurationApi
+ width?: string
+ regroupTo?: LogsAlertGroupBy
+ maxInstances?: number
+}): JSX.Element {
+ const props = { alert }
+ const { canGroup } = useValues(logsAlertFormLogic(props))
+ const { setGroupBy, submitAlertForm, setAlertFormValue } = useActions(logsAlertFormLogic(props))
+
+ useEffect(() => {
+ if (maxInstances !== undefined) {
+ setAlertFormValue('maxInstances', maxInstances)
+ }
+ }, [maxInstances, setAlertFormValue])
+
+ useEffect(() => {
+ if (regroupTo && canGroup) {
+ setGroupBy(regroupTo)
+ submitAlertForm()
+ }
+ }, [regroupTo, canGroup, setGroupBy, submitAlertForm])
+
+ return (
+ <BindLogic logic={logsAlertFormLogic} props={props}>
+ <div className={`space-y-6 ${width}`}>
+ <LogsAlertTrigger />
+ <LogsAlertSimulation embedded />
+ </div>
+ <LogsAlertRegroupConfirmModal />
+ </BindLogic>
+ )
+}
+
+export const Ungrouped: Story = {
+ render: () => <GroupByForm alert={UNGROUPED_ALERT} width="max-w-2xl" />,
+}
+
+export const GroupedByService: Story = {
+ render: () => <GroupByForm alert={GROUPED_ALERT} width="max-w-2xl" />,
+}
+
+// Pinned to the width a scene has with the nav and the side panel open.
+export const GroupedByServiceNarrow: Story = {
+ render: () => <GroupByForm alert={GROUPED_ALERT} width="w-[360px]" />,
+}
+
+export const GroupLimitOutOfRange: Story = {
+ render: () => <GroupByForm alert={GROUPED_ALERT} width="max-w-2xl" maxInstances={0} />,
+}
+
+export const GroupFiringAlertConfirmation: Story = {
+ render: () => <GroupByForm alert={FIRING_UNGROUPED_ALERT} width="max-w-2xl" regroupTo="service" />,
+ parameters: { layout: 'fullscreen', testOptions: { waitForSelector: '.LemonModal' } },
+}
+
+export const RegroupConfirmation: Story = {
+ render: () => <GroupByForm alert={GROUPED_ALERT} width="max-w-2xl" regroupTo="severity" />,
+ parameters: { layout: 'fullscreen', testOptions: { waitForSelector: '.LemonModal' } },
+}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx
new file mode 100644
index 000000000000..c912b45be5c2
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertGroupByField.tsx
@@ -0,0 +1,73 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput, LemonSelect } from '@posthog/lemon-ui'
+
+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'
+
+const GROUP_BY_HELP: Record<LogsAlertGroupBy, string> = {
+ none: 'Split the count by service or severity to alert on each one separately.',
+ service:
+ 'Each service fires and notifies on its own, so several services over the threshold send several notifications.',
+ severity:
+ 'Each severity fires and notifies on its own, so several severities over the threshold send several notifications.',
+ service_and_severity:
+ 'Each service and severity pair fires and notifies on its own, so several pairs over the threshold send several notifications.',
+}
+
+export function LogsAlertGroupByField(): JSX.Element | null {
+ const { alertForm, alertFormValidationErrors, canGroup } = useValues(logsAlertFormLogic)
+ const { setGroupBy, setAlertFormValue } = useActions(logsAlertFormLogic)
+
+ if (!canGroup) {
+ return null
+ }
+
+ const groupingDisabledReason =
+ alertForm.thresholdOperator === LogsAlertConfigurationThresholdOperatorEnumApi.Above
+ ? undefined
+ : GROUPING_NEEDS_ABOVE
+ const isGrouped = alertForm.groupBy !== 'none'
+
+ return (
+ <LemonField.Pure
+ label="Group by"
+ error={alertFormValidationErrors.maxInstances}
+ help={<span>{GROUP_BY_HELP[alertForm.groupBy]}</span>}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <LemonSelect<LogsAlertGroupBy>
+ value={alertForm.groupBy}
+ onChange={(value) => setGroupBy(value)}
+ options={(Object.keys(GROUP_BY_LABELS) as LogsAlertGroupBy[]).map((groupBy) => ({
+ value: groupBy,
+ label: GROUP_BY_LABELS[groupBy],
+ disabledReason: groupBy === 'none' ? undefined : groupingDisabledReason,
+ }))}
+ size="small"
+ data-attr="logs-alert-group-by"
+ />
+ {isGrouped ? (
+ <span className="inline-flex flex-wrap items-center gap-2 text-sm">
+ <span>Track up to</span>
+ <LemonInput
+ type="number"
+ min={1}
+ max={MAX_INSTANCES_LIMIT}
+ value={alertForm.maxInstances}
+ onChange={(value) => setAlertFormValue('maxInstances', value ?? NaN)}
+ className="w-20"
+ size="small"
+ data-attr="logs-alert-group-max-instances"
+ />
+ <span>groups</span>
+ </span>
+ ) : null}
+ </div>
+ </LemonField.Pure>
+ )
+}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertRegroupConfirmModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertRegroupConfirmModal.tsx
new file mode 100644
index 000000000000..9c3a9d748c41
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertRegroupConfirmModal.tsx
@@ -0,0 +1,31 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { logsAlertFormLogic } from './logsAlertFormLogic'
+
+export function LogsAlertRegroupConfirmModal(): JSX.Element {
+ const { isRegroupConfirmationOpen, regroupConfirmation } = useValues(logsAlertFormLogic)
+ const { closeRegroupConfirmation, confirmRegroup } = useActions(logsAlertFormLogic)
+
+ return (
+ <LemonModal
+ isOpen={isRegroupConfirmationOpen}
+ onClose={closeRegroupConfirmation}
+ title="Change how this alert groups?"
+ maxWidth="32rem"
+ footer={
+ <div className="flex flex-wrap justify-end gap-2">
+ <LemonButton type="secondary" onClick={closeRegroupConfirmation}>
+ Cancel
+ </LemonButton>
+ <LemonButton type="primary" onClick={confirmRegroup} data-attr="logs-alert-regroup-confirm">
+ Save and reset
+ </LemonButton>
+ </div>
+ }
+ >
+ <p className="m-0">{regroupConfirmation}</p>
+ </LemonModal>
+ )
+}
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
index bea790b12030..323f1b209cea 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertSimulation.tsx
@@ -261,7 +261,7 @@ function SimulationResults({ result }: { result: LogsAlertSimulateResponseApi })
)
}
-function SimulationPlaceholder(): JSX.Element {
+function SimulationPlaceholder({ disabledReason }: { disabledReason: string | undefined }): JSX.Element {
return (
<div className="relative h-56 overflow-hidden rounded border border-dashed border-border bg-bg-light">
<div aria-hidden className="space-y-4 p-4 opacity-60">
@@ -272,10 +272,14 @@ function SimulationPlaceholder(): JSX.Element {
</div>
<div className="absolute inset-0 flex items-center justify-center bg-bg-light/80 p-4 text-center">
<div>
- <div className="text-sm font-medium">Select a time range, then run a simulation</div>
- <p className="m-0 mt-1 text-xs text-secondary">
- Historical log counts and alert outcomes will appear here.
- </p>
+ <div className="text-sm font-medium">
+ {disabledReason ?? 'Select a time range, then run a simulation'}
+ </div>
+ {disabledReason ? null : (
+ <p className="m-0 mt-1 text-xs text-secondary">
+ Historical log counts and alert outcomes will appear here.
+ </p>
+ )}
</div>
</div>
</div>
@@ -283,7 +287,8 @@ function SimulationPlaceholder(): JSX.Element {
}
export function LogsAlertSimulation({ embedded = false }: { embedded?: boolean }): JSX.Element {
- const { simulationResult, simulationResultLoading, simulationDateFrom } = useValues(logsAlertFormLogic)
+ const { simulationResult, simulationResultLoading, simulationDateFrom, simulationDisabledReason } =
+ useValues(logsAlertFormLogic)
const { simulateAlert, setSimulationDateFrom } = useActions(logsAlertFormLogic)
const simulation = (
@@ -301,7 +306,13 @@ export function LogsAlertSimulation({ embedded = false }: { embedded?: boolean }
onChange={(value) => setSimulationDateFrom(value)}
options={SIMULATION_RANGE_OPTIONS}
/>
- <LemonButton type="primary" size="small" onClick={simulateAlert} loading={simulationResultLoading}>
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={simulateAlert}
+ loading={simulationResultLoading}
+ disabledReason={simulationDisabledReason}
+ >
Run simulation
</LemonButton>
</div>
@@ -315,7 +326,9 @@ export function LogsAlertSimulation({ embedded = false }: { embedded?: boolean }
{simulationResult && <SimulationResults result={simulationResult} />}
- {!simulationResult && !simulationResultLoading && <SimulationPlaceholder />}
+ {!simulationResult && !simulationResultLoading && (
+ <SimulationPlaceholder disabledReason={simulationDisabledReason} />
+ )}
</div>
)
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
index c2be901decb3..699c578ba814 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
@@ -1,27 +1,40 @@
import { MOCK_TEAM_ID } from '~/lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
-import { logsAlertsCreate, logsAlertsPartialUpdate } from 'products/logs/frontend/generated/api'
import {
+ logsAlertsCreate,
+ logsAlertsList,
+ logsAlertsPartialUpdate,
+ logsAlertsSimulateCreate,
+} from 'products/logs/frontend/generated/api'
+import {
+ GroupingModeEnumApi,
LogsAlertConfigurationApi,
LogsAlertConfigurationStateEnumApi,
+ LogsAlertGroupingApi,
+ LogsAlertSimulateResponseApi,
} from 'products/logs/frontend/generated/api.schemas'
import { buildFormDefaults, LogsAlertFormType, logsAlertFormLogic } from '../logsAlertFormLogic'
+import { LogsAlertGroupBy } from '../logsAlertGrouping'
jest.mock('products/logs/frontend/generated/api', () => ({
logsAlertsCreate: jest.fn(),
logsAlertsPartialUpdate: jest.fn(),
logsAlertsList: jest.fn(),
logsAlertsDestroy: jest.fn(),
+ logsAlertsSimulateCreate: jest.fn(),
}))
+jest.mock('posthog-js')
+
jest.mock('@posthog/lemon-ui', () => ({
lemonToast: {
success: jest.fn(),
@@ -31,6 +44,8 @@ jest.mock('@posthog/lemon-ui', () => ({
const mockLogsAlertsCreate = logsAlertsCreate as jest.MockedFunction<typeof logsAlertsCreate>
const mockLogsAlertsPartialUpdate = logsAlertsPartialUpdate as jest.MockedFunction<typeof logsAlertsPartialUpdate>
+const mockLogsAlertsList = logsAlertsList as jest.MockedFunction<typeof logsAlertsList>
+const mockLogsAlertsSimulateCreate = logsAlertsSimulateCreate as jest.MockedFunction<typeof logsAlertsSimulateCreate>
const MOCK_PROJECT_ID = String(MOCK_TEAM_ID)
@@ -85,6 +100,19 @@ const VALID_FORM_VALUES: LogsAlertFormType = {
datapointsToAlarm: 1,
cooldownMinutes: 0,
scheduleRestriction: null,
+ groupBy: 'none',
+ maxInstances: 20,
+}
+
+function givenTeamAlerts(alerts: LogsAlertConfigurationApi[]): void {
+ mockLogsAlertsList.mockResolvedValue({ count: alerts.length, next: null, previous: null, results: alerts })
+}
+
+const PLATFORM_ALERT: LogsAlertConfigurationApi = { ...MOCK_ALERT, platform_owned: true }
+
+const GROUPED_BY_SERVICE_ALERT: LogsAlertConfigurationApi = {
+ ...MOCK_ALERT,
+ grouping: { mode: 'by_result_labels', keys: ['service_name'], max_instances: 30 },
}
describe('logsAlertFormLogic', () => {
@@ -502,6 +530,204 @@ describe('logsAlertFormLogic', () => {
})
})
+ describe('grouping', () => {
+ 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],
+ ['alert the platform owns', PLATFORM_ALERT, [], true],
+ ['alert that already groups', GROUPED_BY_SERVICE_ALERT, [], true],
+ ['new alert in a team that has not cut over', null, [MOCK_ALERT], false],
+ ['new alert in a team that has cut over', null, [MOCK_ALERT, PLATFORM_ALERT], true],
+ ])('can group for %s', async (_, alert, teamAlerts, expected) => {
+ givenTeamAlerts(teamAlerts)
+ const logic = logsAlertFormLogic({ alert })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.canGroup).toBe(expected)
+ logic.unmount()
+ })
+
+ it.each<[string, LogsAlertConfigurationApi, string]>([
+ [
+ 'an ungrouped alert that is not firing',
+ PLATFORM_ALERT,
+ "Saving resets this alert's state, and it starts tracking each group on its own.",
+ ],
+ [
+ 'an ungrouped alert that is firing',
+ { ...PLATFORM_ALERT, state: LogsAlertConfigurationStateEnumApi.Firing },
+ "Saving resets this alert's state, and it starts tracking each group on its own. The alert is firing now, so its open notification won't get a resolve message.",
+ ],
+ [
+ 'a grouped alert',
+ GROUPED_BY_SERVICE_ALERT,
+ "Saving resets every group this alert tracks. Groups that are firing now won't get a resolve message for their open notifications.",
+ ],
+ ])('describes regrouping %s', (_, alert, expected) => {
+ const logic = logsAlertFormLogic({ alert })
+ logic.mount()
+
+ expect(logic.values.regroupConfirmation).toBe(expected)
+ logic.unmount()
+ })
+
+ it('leaves grouping out of the payload when the alert cannot group', async () => {
+ mockLogsAlertsPartialUpdate.mockResolvedValue(MOCK_ALERT)
+ const logic = logsAlertFormLogic({ alert: MOCK_ALERT })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setAlertFormValues(VALID_FORM_VALUES)
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(mockLogsAlertsPartialUpdate.mock.calls[0][2]).not.toHaveProperty('grouping')
+ logic.unmount()
+ })
+
+ it('creates a grouped alert with the default group limit in a cut-over team', async () => {
+ givenTeamAlerts([PLATFORM_ALERT])
+ mockLogsAlertsCreate.mockResolvedValue(MOCK_CREATED_ALERT)
+ const logic = logsAlertFormLogic({ alert: null })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setAlertFormValues(VALID_FORM_VALUES)
+ logic.actions.setGroupBy('service_and_severity')
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(logic.values.isRegroupConfirmationOpen).toBe(false)
+ expect(mockLogsAlertsCreate.mock.calls[0][1]).toMatchObject({
+ grouping: { mode: 'by_result_labels', keys: ['service_name', 'severity_text'], max_instances: 20 },
+ })
+ expect(posthog.capture).toHaveBeenCalledWith('logs alert grouping changed', {
+ group_by: 'service_and_severity',
+ previous_group_by: 'none',
+ is_editing: false,
+ })
+ logic.unmount()
+ })
+
+ it('asks before regrouping a platform alert and saves once confirmed', async () => {
+ mockLogsAlertsPartialUpdate.mockResolvedValue(PLATFORM_ALERT)
+ const logic = logsAlertFormLogic({ alert: PLATFORM_ALERT })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setGroupBy('service')
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(logic.values.isRegroupConfirmationOpen).toBe(true)
+ expect(mockLogsAlertsPartialUpdate).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => {
+ logic.actions.confirmRegroup()
+ }).toFinishAllListeners()
+
+ expect(mockLogsAlertsPartialUpdate).toHaveBeenCalledWith(
+ MOCK_PROJECT_ID,
+ PLATFORM_ALERT.id,
+ expect.objectContaining({
+ grouping: { mode: 'by_result_labels', keys: ['service_name'], max_instances: 20 },
+ })
+ )
+ expect(posthog.capture).toHaveBeenCalledWith('logs alert regroup confirmed', {
+ group_by: 'service',
+ previous_group_by: 'none',
+ })
+ logic.unmount()
+ })
+
+ it.each<[string, LogsAlertConfigurationApi, Partial<LogsAlertFormType>, LogsAlertGroupingApi | undefined]>([
+ [
+ 'a new group limit',
+ GROUPED_BY_SERVICE_ALERT,
+ { maxInstances: 50 },
+ { mode: GroupingModeEnumApi.ByResultLabels, keys: ['service_name'], max_instances: 50 },
+ ],
+ [
+ 'a rename, keeping the stored key order',
+ {
+ ...MOCK_ALERT,
+ grouping: {
+ mode: GroupingModeEnumApi.ByResultLabels,
+ keys: ['severity_text', 'service_name'],
+ max_instances: 30,
+ },
+ },
+ { name: 'Renamed' },
+ {
+ mode: GroupingModeEnumApi.ByResultLabels,
+ keys: ['severity_text', 'service_name'],
+ max_instances: 30,
+ },
+ ],
+ [
+ 'a rename of an alert grouped by keys the form cannot show',
+ {
+ ...MOCK_ALERT,
+ grouping: {
+ mode: GroupingModeEnumApi.ByResultLabels,
+ keys: ['service_name', 'http_route'],
+ max_instances: 30,
+ },
+ },
+ { name: 'Renamed' },
+ undefined,
+ ],
+ ])('saves %s without regrouping', async (_, alert, change, expectedGrouping) => {
+ mockLogsAlertsPartialUpdate.mockResolvedValue(alert)
+ const logic = logsAlertFormLogic({ alert })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setAlertFormValues(change)
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(logic.values.isRegroupConfirmationOpen).toBe(false)
+ expect(mockLogsAlertsPartialUpdate.mock.calls[0][2]?.grouping).toEqual(expectedGrouping)
+ logic.unmount()
+ })
+
+ it.each([NaN, 0, 101, 2.5])('blocks a save with a group limit of %s', async (maxInstances) => {
+ const logic = logsAlertFormLogic({ alert: GROUPED_BY_SERVICE_ALERT })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setAlertFormValue('maxInstances', maxInstances)
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(logic.values.alertFormValidationErrors.maxInstances).toBe('Enter a whole number from 1 to 100.')
+ expect(mockLogsAlertsPartialUpdate).not.toHaveBeenCalled()
+ logic.unmount()
+ })
+
+ it.each<[LogsAlertGroupBy, boolean]>([
+ ['service', false],
+ ['none', true],
+ ])('simulates an alert grouped by %s: %s', async (groupBy, simulates) => {
+ mockLogsAlertsSimulateCreate.mockResolvedValue({} as LogsAlertSimulateResponseApi)
+ const logic = logsAlertFormLogic({ alert: GROUPED_BY_SERVICE_ALERT })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setGroupBy(groupBy)
+ logic.actions.simulateAlert()
+ }).toFinishAllListeners()
+
+ expect(mockLogsAlertsSimulateCreate).toHaveBeenCalledTimes(simulates ? 1 : 0)
+ logic.unmount()
+ })
+ })
+
describe('isEditing selector', () => {
it('is false when props.alert is null', () => {
const logic = logsAlertFormLogic({ alert: null })
@@ -537,6 +763,8 @@ describe('logsAlertFormLogic', () => {
evaluationPeriods: 1,
datapointsToAlarm: 1,
cooldownMinutes: 0,
+ groupBy: 'none',
+ maxInstances: 20,
})
logic.unmount()
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
index f42195efb232..c870d7573949 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
@@ -23,6 +23,8 @@ const baseForm = (overrides: Partial<LogsAlertFormType> = {}): LogsAlertFormType
datapointsToAlarm: 1,
cooldownMinutes: 0,
scheduleRestriction: null,
+ groupBy: 'none',
+ maxInstances: 20,
...overrides,
})
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
index 3cb433acf20f..67ea42647f63 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
@@ -3,6 +3,7 @@ import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -27,6 +28,17 @@ import {
LogsAlertConfigurationThresholdOperatorEnumApi,
} from 'products/logs/frontend/generated/api.schemas'
+import {
+ DEFAULT_GROUPED_MAX_INSTANCES,
+ LogsAlertGroupBy,
+ canGroupAlert,
+ groupByOf,
+ groupingPayloadOf,
+ isRegroup,
+ maxInstancesError,
+ regroupConfirmationText,
+ SIMULATION_NEEDS_UNGROUPED,
+} from './logsAlertGrouping'
import { logsAlertingLogic } from './logsAlertingLogic'
import { logsAlertNotificationLogic } from './logsAlertNotificationLogic'
import { buildAlertFilters, hasAnyFilter } from './logsAlertUtils'
@@ -37,6 +49,9 @@ const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {
values: [],
}
+/** Thrown by the form submit to stop a save until the person confirms the regroup. */
+export class RegroupConfirmationRequired extends Error {}
+
const DEFAULT_SEVERITY_LEVELS: LogMessage['severity_text'][] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']
export interface LogsAlertFormType {
@@ -51,6 +66,8 @@ export interface LogsAlertFormType {
datapointsToAlarm: number
cooldownMinutes: number
scheduleRestriction: ScheduleRestriction | null
+ groupBy: LogsAlertGroupBy
+ maxInstances: number
}
export interface LogsAlertFormLogicProps {
@@ -77,6 +94,7 @@ function saveErrorMessage(error: ApiError): string {
export function buildFormDefaults(alert: LogsAlertConfigurationApi | null): LogsAlertFormType {
const filters = (alert?.filters ?? {}) as Record<string, unknown>
+ const groupBy = groupByOf(alert?.grouping)
return {
name: alert?.name ?? '',
@@ -92,12 +110,19 @@ export function buildFormDefaults(alert: LogsAlertConfigurationApi | null): Logs
datapointsToAlarm: alert?.datapoints_to_alarm ?? 1,
cooldownMinutes: alert?.cooldown_minutes ?? 0,
scheduleRestriction: alert?.schedule_restriction ?? null,
+ groupBy,
+ // An ungrouped alert stores the platform's ceiling, which is too many groups to notify on.
+ maxInstances:
+ groupBy === 'none'
+ ? DEFAULT_GROUPED_MAX_INSTANCES
+ : (alert?.grouping?.max_instances ?? DEFAULT_GROUPED_MAX_INSTANCES),
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertFormLogicValues {
pendingNotifications: PendingLogsAlertNotification[] // logsAlertNotificationLogic
+ alerts: LogsAlertConfigurationApi[] // logsAlertingLogic
currentTeamId: number | null // teamLogic
alertForm: LogsAlertFormType
alertFormAllErrors: Record<string, any>
@@ -108,12 +133,18 @@ export interface logsAlertFormLogicValues {
alertFormTouched: boolean
alertFormTouches: Record<string, boolean>
alertFormValidationErrors: DeepPartialMap<LogsAlertFormType, ValidationErrorType>
+ canGroup: boolean
isAlertFormSubmitting: boolean
isAlertFormValid: boolean
isEditing: boolean
+ isRegroupConfirmationOpen: boolean
+ isRegroupConfirmed: boolean
isSimulationPanelOpen: boolean
+ needsRegroupConfirmation: boolean
+ regroupConfirmation: string
showAlertFormErrors: boolean
simulationDateFrom: string
+ simulationDisabledReason: string | undefined
simulationResult: LogsAlertSimulateResponseApi | null
simulationResultLoading: boolean
}
@@ -145,9 +176,18 @@ export interface logsAlertFormLogicActions {
value: true
}
}
+ closeRegroupConfirmation: () => {
+ value: true
+ }
closeSimulationPanel: () => {
value: true
}
+ confirmRegroup: () => {
+ value: true
+ }
+ openRegroupConfirmation: () => {
+ value: true
+ }
openSimulationPanel: () => {
value: true
}
@@ -167,6 +207,9 @@ export interface logsAlertFormLogicActions {
setAlertFormValues: (values: DeepPartial<LogsAlertFormType>) => {
values: DeepPartial<LogsAlertFormType>
}
+ setGroupBy: (groupBy: LogsAlertGroupBy) => {
+ groupBy: LogsAlertGroupBy
+ }
setSimulationDateFrom: (dateFrom: string) => {
dateFrom: string
}
@@ -217,6 +260,10 @@ export interface logsAlertFormLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
isEditing: (arg: any) => boolean
+ canGroup: (arg: any, alerts: LogsAlertConfigurationApi[]) => boolean
+ regroupConfirmation: (arg: any) => string
+ needsRegroupConfirmation: (arg: any, canGroup: boolean, alertForm: LogsAlertFormType) => boolean
+ simulationDisabledReason: (canGroup: boolean, alertForm: LogsAlertFormType) => string | undefined
}
}
@@ -236,6 +283,8 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
values: [
teamLogic,
['currentTeamId'],
+ logsAlertingLogic,
+ ['alerts'],
logsAlertNotificationLogic({ alertId: alert?.id }),
['pendingNotifications'],
],
@@ -253,6 +302,10 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
setSimulationDateFrom: (dateFrom: string) => ({ dateFrom }),
openSimulationPanel: true,
closeSimulationPanel: true,
+ setGroupBy: (groupBy: LogsAlertGroupBy) => ({ groupBy }),
+ openRegroupConfirmation: true,
+ closeRegroupConfirmation: true,
+ confirmRegroup: true,
}),
reducers({
@@ -269,6 +322,14 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
setSimulationDateFrom: (_, { dateFrom }) => dateFrom,
},
],
+ isRegroupConfirmationOpen: [
+ false,
+ {
+ openRegroupConfirmation: () => true,
+ closeRegroupConfirmation: () => false,
+ confirmRegroup: () => false,
+ },
+ ],
}),
loaders(({ values }) => ({
@@ -277,6 +338,9 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
{
simulateAlert: async (): Promise<LogsAlertSimulateResponseApi | null> => {
const form = values.alertForm
+ if (values.simulationDisabledReason) {
+ return null
+ }
if (!hasAnyFilter(form.severityLevels, form.serviceNames, form.filterGroup)) {
lemonToast.error('At least one filter is required to simulate')
return null
@@ -298,10 +362,31 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
],
})),
- listeners(({ actions }) => ({
+ listeners(({ actions, values, props }) => ({
setAlertFormValue: () => {
actions.clearSimulation()
},
+ setGroupBy: ({ groupBy }) => {
+ const previous = values.alertForm.groupBy
+ if (groupBy === previous) {
+ return
+ }
+ actions.setAlertFormValue('groupBy', groupBy)
+ // pinned: analytics event name and properties, renaming breaks dashboards
+ posthog.capture('logs alert grouping changed', {
+ group_by: groupBy,
+ previous_group_by: previous,
+ is_editing: props.alert !== null,
+ })
+ },
+ confirmRegroup: () => {
+ // pinned: analytics event name and properties, renaming breaks dashboards
+ posthog.capture('logs alert regroup confirmed', {
+ group_by: values.alertForm.groupBy,
+ previous_group_by: groupByOf(props.alert?.grouping),
+ })
+ actions.submitAlertForm()
+ },
simulateAlertFailure: ({ error }) => {
lemonToast.error(`Simulation failed: ${error || 'Unknown error'}`)
},
@@ -309,6 +394,15 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
selectors({
isEditing: [() => [(_, props) => props.alert], (alert: LogsAlertConfigurationApi | null) => alert !== null],
+ canGroup: [
+ (s) => [(_, props) => props.alert, s.alerts],
+ (alert: LogsAlertConfigurationApi | null, alerts: LogsAlertConfigurationApi[]): boolean =>
+ canGroupAlert(alert, alerts),
+ ],
+ regroupConfirmation: [
+ () => [(_, props) => props.alert],
+ (alert: LogsAlertConfigurationApi | null): string => regroupConfirmationText(alert),
+ ],
}),
afterMount(({ actions, props }) => {
@@ -321,8 +415,9 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
alertForm: {
// Provides typed shape for kea-forms; afterMount resets with fresh values on every remount
defaults: buildFormDefaults(props.alert),
- errors: ({ name }) => ({
+ errors: ({ name, groupBy, maxInstances }) => ({
name: !name?.trim() ? 'Name is required' : undefined,
+ maxInstances: groupBy ? maxInstancesError(groupBy, maxInstances) : undefined,
}),
submit: async (form) => {
if (!form.name?.trim()) {
@@ -340,8 +435,18 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
lemonToast.error('At least one filter is required')
throw new Error('At least one filter is required')
}
+ if (values.needsRegroupConfirmation && !values.isRegroupConfirmed) {
+ actions.openRegroupConfirmation()
+ throw new RegroupConfirmationRequired()
+ }
+
const projectId = String(values.currentTeamId)
+ // Left out when the alert cannot group, or keeps a grouping the form can't show, so the API keeps it.
+ const grouping = values.canGroup
+ ? groupingPayloadOf(form.groupBy, form.maxInstances, props.alert?.grouping)
+ : undefined
const payload = {
+ ...(grouping ? { grouping } : {}),
name: form.name.trim(),
filters: buildAlertFilters(form.severityLevels, form.serviceNames, form.filterGroup),
threshold_count: form.thresholdCount,
@@ -398,4 +503,28 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
},
},
})),
+ // After `forms`, so the form value and submit actions it adds exist when these bind to them.
+ selectors({
+ needsRegroupConfirmation: [
+ (s) => [(_, props) => props.alert, s.canGroup, s.alertForm],
+ (alert: LogsAlertConfigurationApi | null, canGroup: boolean, alertForm: LogsAlertFormType): boolean =>
+ canGroup && isRegroup(alert, alertForm.groupBy),
+ ],
+ simulationDisabledReason: [
+ (s) => [s.canGroup, s.alertForm],
+ (canGroup: boolean, alertForm: LogsAlertFormType): string | undefined =>
+ canGroup && alertForm.groupBy !== 'none' ? SIMULATION_NEEDS_UNGROUPED : undefined,
+ ],
+ }),
+ reducers({
+ // Holds only for the save the person confirmed, so a failed save asks again.
+ isRegroupConfirmed: [
+ false,
+ {
+ confirmRegroup: () => true,
+ submitAlertFormSuccess: () => false,
+ submitAlertFormFailure: () => false,
+ },
+ ],
+ }),
])
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts b/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts
new file mode 100644
index 000000000000..f4ab4090d526
--- /dev/null
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertGrouping.ts
@@ -0,0 +1,105 @@
+import {
+ GroupingModeEnumApi,
+ LogsAlertConfigurationApi,
+ LogsAlertConfigurationStateEnumApi,
+ LogsAlertGroupingApi,
+} from 'products/logs/frontend/generated/api.schemas'
+
+export type LogsAlertGroupBy = 'none' | 'service' | 'severity' | 'service_and_severity'
+
+export const DEFAULT_GROUPED_MAX_INSTANCES = 20
+
+export const GROUP_BY_LABELS: Record<LogsAlertGroupBy, string> = {
+ none: "Don't group",
+ service: 'Service',
+ severity: 'Severity',
+ service_and_severity: 'Service and severity',
+}
+
+export const GROUPING_NEEDS_ABOVE = 'Grouping only works when the alert fires above a threshold.'
+
+export const SIMULATION_NEEDS_UNGROUPED =
+ 'Simulation can\'t show grouped alerts. Set Group by to "Don\'t group" to run one.'
+
+export const MAX_INSTANCES_LIMIT = 100
+
+const GROUP_BY_KEYS: Record<LogsAlertGroupBy, string[]> = {
+ none: [],
+ service: ['service_name'],
+ severity: ['severity_text'],
+ service_and_severity: ['service_name', 'severity_text'],
+}
+
+export function groupByOf(grouping: LogsAlertGroupingApi | undefined): LogsAlertGroupBy {
+ if (!grouping || grouping.mode !== GroupingModeEnumApi.ByResultLabels) {
+ return 'none'
+ }
+ const keys = new Set(grouping.keys ?? [])
+ const match = (Object.keys(GROUP_BY_KEYS) as LogsAlertGroupBy[]).find(
+ (groupBy) => GROUP_BY_KEYS[groupBy].length === keys.size && GROUP_BY_KEYS[groupBy].every((key) => keys.has(key))
+ )
+ return match ?? 'none'
+}
+
+/**
+ * The grouping a save sends, or undefined to keep the stored one. The API compares keys in order, so
+ * an unchanged selection sends the stored keys as they are. Otherwise a reordered or unrecognized
+ * stored grouping would regroup the alert on an unrelated save.
+ */
+export function groupingPayloadOf(
+ groupBy: LogsAlertGroupBy,
+ maxInstances: number,
+ stored: LogsAlertGroupingApi | undefined
+): LogsAlertGroupingApi | undefined {
+ const unchanged = stored !== undefined && groupByOf(stored) === groupBy
+ if (groupBy === 'none') {
+ return unchanged ? undefined : { mode: GroupingModeEnumApi.Single }
+ }
+ const keys = unchanged && stored.keys ? stored.keys : GROUP_BY_KEYS[groupBy]
+ return { mode: GroupingModeEnumApi.ByResultLabels, keys, max_instances: maxInstances }
+}
+
+export function maxInstancesError(groupBy: LogsAlertGroupBy, maxInstances: number | undefined): string | undefined {
+ if (groupBy === 'none') {
+ return undefined
+ }
+ const valid =
+ maxInstances !== undefined &&
+ Number.isInteger(maxInstances) &&
+ maxInstances >= 1 &&
+ maxInstances <= MAX_INSTANCES_LIMIT
+ return valid ? undefined : `Enter a whole number from 1 to ${MAX_INSTANCES_LIMIT}.`
+}
+
+export function isRegroup(alert: LogsAlertConfigurationApi | null, groupBy: LogsAlertGroupBy): boolean {
+ return alert !== null && groupByOf(alert.grouping) !== groupBy
+}
+
+/**
+ * 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.
+ */
+export function canGroupAlert(
+ alert: LogsAlertConfigurationApi | null,
+ teamAlerts: LogsAlertConfigurationApi[]
+): boolean {
+ if (!alert) {
+ return teamAlerts.some((candidate) => candidate.platform_owned)
+ }
+ return alert.platform_owned || alert.grouping?.mode === GroupingModeEnumApi.ByResultLabels
+}
+
+/** What a save that changes the grouping does to the state the alert tracks now. */
+export function regroupConfirmationText(alert: LogsAlertConfigurationApi | null): string {
+ if (alert?.grouping?.mode === GroupingModeEnumApi.ByResultLabels) {
+ return "Saving resets every group this alert tracks. Groups that are firing now won't get a resolve message for their open notifications."
+ }
+ const reset = "Saving resets this alert's state, and it starts tracking each group on its own."
+ const hasOpenNotification =
+ alert?.state === LogsAlertConfigurationStateEnumApi.Firing ||
+ alert?.state === LogsAlertConfigurationStateEnumApi.PendingResolve
+ if (hasOpenNotification) {
+ return `${reset} The alert is firing now, so its open notification won't get a resolve message.`
+ }
+ return reset
+}
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
index 269cb8ffeeef..49fa4f72ac38 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/LogsAlertDetailScene.tsx
@@ -20,6 +20,7 @@ import { LogsAlertForm } from 'products/logs/frontend/components/LogsAlerting/Lo
import { logsAlertFormLogic } from 'products/logs/frontend/components/LogsAlerting/logsAlertFormLogic'
import { logsAlertNotificationLogic } from 'products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic'
import { LogsAlertNotifications } from 'products/logs/frontend/components/LogsAlerting/LogsAlertNotifications'
+import { LogsAlertRegroupConfirmModal } from 'products/logs/frontend/components/LogsAlerting/LogsAlertRegroupConfirmModal'
import { LogsAlertSimulation } from 'products/logs/frontend/components/LogsAlerting/LogsAlertSimulation'
import { LogsAlertStateIndicator } from 'products/logs/frontend/components/LogsAlerting/LogsAlertStateIndicator'
import { LogsAlertStateTimeline } from 'products/logs/frontend/components/LogsAlerting/LogsAlertStateTimeline'
@@ -108,6 +109,7 @@ export function LogsAlertDetailScene(): JSX.Element {
>
<LogsAlertSimulation />
</LemonModal>
+ <LogsAlertRegroupConfirmModal />
</SceneContent>
</BindLogic>
</BindLogic>
@@ -119,17 +121,22 @@ function primaryDisabledReason({
alertForm,
alertFormChanged,
nameError,
+ maxInstancesError,
hasPendingNotifications,
}: {
isDraft: boolean
alertForm: { name: string; severityLevels: string[]; serviceNames: string[]; filterGroup: UniversalFiltersGroup }
alertFormChanged: boolean
nameError: string | undefined
+ maxInstancesError: string | undefined
hasPendingNotifications: boolean
}): string | undefined {
if (nameError) {
return nameError
}
+ if (maxInstancesError) {
+ return maxInstancesError
+ }
if (isDraft) {
return !hasAnyFilter(alertForm.severityLevels, alertForm.serviceNames, alertForm.filterGroup)
? 'Add at least one filter to enable'
@@ -143,7 +150,8 @@ function AlertHeader(): JSX.Element {
const { toggleEnabled, snoozeAlert, unsnoozeAlert, resetAlert, deleteAlert, enableAlert } =
useActions(logsAlertDetailSceneLogic)
- const { isAlertFormSubmitting, alertFormChanged, alertForm, alertFormErrors } = useValues(logsAlertFormLogic)
+ const { isAlertFormSubmitting, alertFormChanged, alertForm, alertFormErrors, alertFormValidationErrors } =
+ useValues(logsAlertFormLogic)
const { submitAlertForm, setAlertFormValue } = useActions(logsAlertFormLogic)
const { pendingNotifications } = useValues(logsAlertNotificationLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
@@ -170,6 +178,7 @@ function AlertHeader(): JSX.Element {
alertForm,
alertFormChanged,
nameError: typeof alertFormErrors?.name === 'string' ? alertFormErrors.name : undefined,
+ maxInstancesError: alertFormValidationErrors.maxInstances as string | undefined,
hasPendingNotifications: pendingNotifications.length > 0,
})}
/>
@@ -224,6 +233,7 @@ function AlertHeader(): JSX.Element {
alertForm,
alertFormChanged,
nameError: typeof alertFormErrors?.name === 'string' ? alertFormErrors.name : undefined,
+ maxInstancesError: alertFormValidationErrors.maxInstances as string | undefined,
hasPendingNotifications: pendingNotifications.length > 0,
})}
data-attr={isDraft ? 'logs-alert-enable-primary' : 'logs-alert-save-primary'}
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
index 395d465744ed..bf9b7400489e 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
@@ -146,6 +146,35 @@ describe('logsAlertDetailSceneLogic — save-then-enable chain', () => {
logic.unmount()
})
+ 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)
+ 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 })
+ formLogic.actions.setGroupBy('service')
+
+ await expectLogic(logic, () => {
+ logic.actions.enableAlert()
+ })
+ .toDispatchActions(['markPendingEnable', 'submitAlertFormFailure'])
+ .toFinishAllListeners()
+
+ expect(formLogic.values.isRegroupConfirmationOpen).toBe(true)
+ expect(logic.values.pendingEnableAfterSave).toBe(true)
+
+ await expectLogic(logic, () => {
+ formLogic.actions.confirmRegroup()
+ })
+ .toDispatchActions(['submitAlertFormSuccess', logic.actionCreators.applyEnabledChange(true)])
+ .toFinishAllListeners()
+
+ expect(mockedApi.logsAlertsPartialUpdate).toHaveBeenCalledWith(expect.anything(), MOCK_ALERT_ID, {
+ enabled: true,
+ })
+ logic.unmount()
+ })
+
it('does not call applyEnabledChange when submitAlertFormSuccess fires without pending', async () => {
const logic = await mountSceneLogic()
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
index 47d848bf18dd..47b4eb5cf41e 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
@@ -17,6 +17,7 @@ import { Breadcrumb } from '~/types'
import { logsAlertEventHistoryLogic } from 'products/logs/frontend/components/LogsAlerting/logsAlertEventHistoryLogic'
import {
+ RegroupConfirmationRequired,
buildFormDefaults,
logsAlertFormLogic,
} from 'products/logs/frontend/components/LogsAlerting/logsAlertFormLogic'
@@ -76,6 +77,9 @@ export interface logsAlertDetailSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAlertDetailSceneLogicActions {
loadEvents: () => any // logsAlertEventHistoryLogic
+ closeRegroupConfirmation: () => {
+ value: true
+ } // logsAlertFormLogic
resetAlertForm: (values?: LogsAlertFormType | undefined) => {
values?: LogsAlertFormType
} // logsAlertFormLogic
@@ -207,6 +211,7 @@ export const logsAlertDetailSceneLogic = kea<logsAlertDetailSceneLogicType>([
'submitAlertFormFailure',
'resetAlertForm',
'setAlertFormValue',
+ 'closeRegroupConfirmation',
],
logsAlertNotificationLogic({ alertId: props.id }),
['destinationsChanged'],
@@ -253,7 +258,10 @@ export const logsAlertDetailSceneLogic = kea<logsAlertDetailSceneLogicType>([
{
markPendingEnable: () => true,
applyEnabledChange: () => false,
- submitAlertFormFailure: () => false,
+ // A save that waits for the regroup confirmation has not failed, so its enable still applies once confirmed.
+ submitAlertFormFailure: (state, { error }) =>
+ error instanceof RegroupConfirmationRequired ? state : false,
+ closeRegroupConfirmation: () => false,
},
],
}),