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 quiet hours to alerts (#81525)

Matt Pua5b6d3e460093
diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.md
index 84cac3824a64..f236e7308a79 100644
--- a/.agents/skills/adding-product-alerting/references/architecture.md
+++ b/.agents/skills/adding-product-alerting/references/architecture.md
@@ -15,7 +15,7 @@ Use this reference to decide where code belongs before editing it.
`products/logs` is the reference adopter for fixed-cadence scheduling, HogFunction destinations, delivery rollback, product-owned Temporal orchestration, and the shared product alert editor components.
-Logs and insight alerts both adapt their product state to the shared lifecycle engine. Insight alerts are also the reference adopter for shared calendar anchors, schedule restrictions, weekend skipping, and email delivery. Their model, API, query evaluation, and Django scheduling adapters live in `products/alerts/backend/` and `posthog/tasks/alerts/`. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.
+Logs and insight alerts both adapt their product state to the shared lifecycle engine. Insight alerts are the reference adopter for calendar anchors, weekend skipping, and email delivery. Both products use shared schedule restrictions for quiet hours. Each product keeps its model, due query, and scheduling persistence. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.
## Frontend contract
@@ -24,6 +24,7 @@ Shared product alert UI lives in `products/alerts/frontend/components/`. It is p
- `AlertEditor`, `AlertEditorFormDetails`, and `AlertEditorSection` provide the container-agnostic form shell.
- `AlertDefinition*` components provide composable definition, schedule, next-evaluation, and timezone presentation.
- `AlertAdvancedOptions` owns shared collapse and enabled-count behavior.
+- `QuietHoursFields` renders shared quiet-hour inputs from a normalized restriction, cadence, and project timezone.
- `AlertNotificationDestinationEditor` renders normalized saved and pending destinations.
- `AlertEvaluationHistoryChart` renders normalized evaluation points and current thresholds.
diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
index 29184e67ccbb..f8aac6de3711 100644
--- a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md
@@ -33,7 +33,8 @@ If the change crosses rows, update each row deliberately. Do not hide a cross-la
- Keep fixed-grid and calendar contracts explicit instead of branching on product names.
- Make scheduler interval assumptions explicit.
- Preserve deterministic UUID-based sharding and stable steady-state cadence.
-- Preserve local wall-clock anchors across DST changes and evaluate restrictions in the team's timezone.
+- Preserve local wall-clock anchors across DST changes and evaluate quiet-hour restrictions in the team's timezone.
+- Reuse the normalized schedule-restriction contract for each product that supports quiet hours. Product adapters own due queries and persistence.
- Test missed intervals, drift healing, cadence changes, DST transitions, overnight windows, and boundary times.
- Keep due eligibility with the product unless a real cross-product model contract exists.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 46772c24cc20..ee57cfcc46e0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4687,9 +4687,9 @@ snapshots:
products-alerts-shared-components--notifications-multiple-slack-workspaces--light:
hash: v1.k794b7964.63ec31eddf76c6f6544838a9b765e091bbe84325070fff837ed94d2cc1e85ba8.rPHnjzF-XA_HZd7mJ9KKN8iLGsZVXVdne4uww2vsx4w
products-alerts-shared-components--quiet-hours--dark:
- hash: v1.k794b7964.3a4e054512c5b607cf75f1cc3e6dd2212333d05e4fb89274b580b47f01e5aeaf.nPp2_jJIgcpjkQgHQA63v-eqzVox-oIfDi3SQKPdRis
+ hash: v1.k794b7964.5882b745c748c44c9f3b1026e1c35953d8e2034b5f31588d2030a8502bd5afdd.k0NFXRurTVmlsO_6I1VF93n7KlCAP3ye3kztNwuaV0k
products-alerts-shared-components--quiet-hours--light:
- hash: v1.k794b7964.d562af4f5d4b2eb1566f5f378227e08f8743c6fab8ceb709d19c7bde3f80d8be.SFC4RHmaGUHYuisvesHu5mP7lE-6I5qKkIGFJCxlRwo
+ hash: v1.k794b7964.fcd387116bcdd0296037b1d39ca7292a9f907f38e1de5dd3cdf7208f2b030090.qfzWLrCzf5SGKavDpoj3Kp6bw_h6tyghF8SEt3aunp4
products-dashboards--dashboard-states--dark:
hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRs
products-dashboards--dashboard-states--light:
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index c892076e9de2..bab4d76a0722 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -15,6 +15,7 @@ from posthog.rbac.user_access_control import UserAccessControl
from posthog.user_permissions import UserPermissions
from posthog.utils import relative_date_parse
+from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
from products.alerts.backend.destination_configs import (
DESTINATION_TEMPLATE_IDS,
AlertDestinationData,
@@ -31,6 +32,7 @@ from products.alerts.backend.destinations import (
from products.alerts.backend.email_notifications import send_alert_email
from products.alerts.backend.insight_alert_state_machine import apply_snooze
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts.backend.scheduling import validate_and_normalize_schedule_restriction
logger = structlog.get_logger(__name__)
@@ -158,6 +160,7 @@ __all__ = [
"DESTINATION_TEMPLATE_IDS",
"AlertDestinationData",
"AlertDestinationValidationError",
+ "AlertScheduleRestriction",
"DestinationType",
"SLACK_SNOOZE_MAX_DAYS",
"SlackSnoozeOutcome",
@@ -170,4 +173,5 @@ __all__ = [
"soft_delete_all_alert_destinations",
"send_alert_email",
"validate_destination_data",
+ "validate_and_normalize_schedule_restriction",
]
diff --git a/products/alerts/backend/scheduling.py b/products/alerts/backend/scheduling.py
index 1e361d3f9843..56ea97b085b2 100644
--- a/products/alerts/backend/scheduling.py
+++ b/products/alerts/backend/scheduling.py
@@ -220,9 +220,12 @@ def normalize_schedule_restriction_value(raw: Any) -> dict[str, Any] | None:
return None
if not isinstance(raw, dict):
raise ValueError("schedule_restriction must be an object or null")
+ unknown_keys = set(raw) - {"blocked_windows"}
+ if unknown_keys:
+ raise ValueError("schedule_restriction only supports blocked_windows")
+ if "blocked_windows" not in raw:
+ raise ValueError("schedule_restriction must include blocked_windows")
windows = raw.get("blocked_windows")
- if windows is None:
- return None
if windows == []:
return None
if not isinstance(windows, list):
@@ -351,6 +354,9 @@ def validate_and_normalize_schedule_restriction(raw: Any) -> dict[str, Any] | No
for idx, w in enumerate(windows_in):
if not isinstance(w, dict):
raise ValueError(f"blocked_windows[{idx}] must be an object")
+ unknown_keys = set(w) - {"start", "end"}
+ if unknown_keys:
+ raise ValueError(f"blocked_windows[{idx}] only supports start and end")
start_s = w.get("start")
end_s = w.get("end")
if start_s is None or end_s is None:
diff --git a/products/alerts/backend/test/test_scheduling.py b/products/alerts/backend/test/test_scheduling.py
index d4ebfc89b1cd..82e78ee2fe3f 100644
--- a/products/alerts/backend/test/test_scheduling.py
+++ b/products/alerts/backend/test/test_scheduling.py
@@ -108,6 +108,20 @@ class TestValidateAndNormalizeScheduleRestriction:
raw = {"blocked_windows": [{"start": "19:00", "end": "00:00"}]}
assert validate_and_normalize_schedule_restriction(raw) == raw
+ @parameterized.expand(
+ [
+ ("unknown_root_key", {"typo": True}),
+ ("missing_blocked_windows", {"enabled": True}),
+ (
+ "unknown_window_key",
+ {"blocked_windows": [{"start": "10:00", "end": "11:00", "typo": True}]},
+ ),
+ ]
+ )
+ def test_rejects_unknown_schedule_restriction_keys(self, _name: str, raw: dict[str, Any]) -> None:
+ with pytest.raises(ValueError):
+ validate_and_normalize_schedule_restriction(raw)
+
class TestNextCalendarCheckTime:
@parameterized.expand(
diff --git a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
index 0bdae5c059a0..2fc5d35611eb 100644
--- a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
+++ b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx
@@ -9,10 +9,16 @@ import { AlertCalculationInterval } from '~/queries/schema/schema-general'
import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
import { AlertFormType, ongoingIntervalField } from 'products/alerts/frontend/logic/alertFormLogic'
-import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { alertCadenceMinutes, isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { QuietHoursFields } from './QuietHoursFields'
+const QUIET_HOURS_COARSE_INTERVAL_LABELS: Partial<Record<AlertCalculationInterval, string>> = {
+ [AlertCalculationInterval.DAILY]: 'day',
+ [AlertCalculationInterval.WEEKLY]: 'week',
+ [AlertCalculationInterval.MONTHLY]: 'month',
+}
+
export interface AlertAdvancedOptionsSectionProps {
alertForm: AlertFormType
canCheckOngoingInterval: boolean
@@ -31,51 +37,56 @@ export function AlertAdvancedOptionsSection({
onSetAlertFormValue,
}: AlertAdvancedOptionsSectionProps): JSX.Element {
const ongoing = ongoingIntervalField(alertForm.config, canCheckOngoingInterval)
+ const quietHoursCadenceMinutes = alertCadenceMinutes(alertForm.calculation_interval)
+ const quietHoursCoarseIntervalLabel = QUIET_HOURS_COARSE_INTERVAL_LABELS[alertForm.calculation_interval]
return (
- <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount} defaultOpen={defaultOpen}>
- {ongoing.show ? (
- <Group name={['config']}>
- <div className="flex gap-1">
- <LemonField name="check_ongoing_interval">
- <LemonCheckbox
- checked={ongoing.checked}
- data-attr="alertForm-check-ongoing-interval"
- fullWidth
- label="Check ongoing period"
- disabledReason={ongoing.disabledReason}
- />
- </LemonField>
- <Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
- <IconInfo className="text-xl text-secondary shrink-0" />
- </Tooltip>
- </div>
- </Group>
- ) : null}
- <LemonField name="skip_weekend">
- <LemonCheckbox
- checked={
- (alertForm.calculation_interval === AlertCalculationInterval.DAILY ||
- isSubDailyAlertInterval(alertForm.calculation_interval)) &&
- alertForm.skip_weekend
- }
- data-attr="alertForm-skip-weekend"
- fullWidth
- label="Skip checking on weekends"
- disabledReason={
- alertForm.calculation_interval !== AlertCalculationInterval.DAILY &&
- !isSubDailyAlertInterval(alertForm.calculation_interval)
- ? 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'
- : undefined
- }
- />
- </LemonField>
+ <>
<QuietHoursFields
scheduleRestriction={alertForm.schedule_restriction}
- calculationInterval={alertForm.calculation_interval}
+ cadenceMinutes={quietHoursCadenceMinutes}
+ coarseIntervalLabel={quietHoursCoarseIntervalLabel}
teamTimezone={projectTimezone}
onChange={(next) => onSetAlertFormValue('schedule_restriction', next)}
/>
- </AlertAdvancedOptions>
+ <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount} defaultOpen={defaultOpen}>
+ {ongoing.show ? (
+ <Group name={['config']}>
+ <div className="flex gap-1">
+ <LemonField name="check_ongoing_interval">
+ <LemonCheckbox
+ checked={ongoing.checked}
+ data-attr="alertForm-check-ongoing-interval"
+ fullWidth
+ label="Check ongoing period"
+ disabledReason={ongoing.disabledReason}
+ />
+ </LemonField>
+ <Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
+ <IconInfo className="text-xl text-secondary shrink-0" />
+ </Tooltip>
+ </div>
+ </Group>
+ ) : null}
+ <LemonField name="skip_weekend">
+ <LemonCheckbox
+ checked={
+ (alertForm.calculation_interval === AlertCalculationInterval.DAILY ||
+ isSubDailyAlertInterval(alertForm.calculation_interval)) &&
+ alertForm.skip_weekend
+ }
+ data-attr="alertForm-skip-weekend"
+ fullWidth
+ label="Skip checking on weekends"
+ disabledReason={
+ alertForm.calculation_interval !== AlertCalculationInterval.DAILY &&
+ !isSubDailyAlertInterval(alertForm.calculation_interval)
+ ? 'Can only skip weekend checking for 15-minute, hourly, or daily alerts'
+ : undefined
+ }
+ />
+ </LemonField>
+ </AlertAdvancedOptions>
+ </>
)
}
diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsx
index c7b507f251f5..6a0f80360466 100644
--- a/products/alerts/frontend/components/AlertComponents.stories.tsx
+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx
@@ -12,6 +12,7 @@ import { useStorybookMocks } from '~/mocks/browser'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
import { IntegrationType } from '~/types'
+import { alertCadenceMinutes } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { alertNotificationLogic } from 'products/alerts/frontend/logic/alertNotificationLogic'
import type { ScheduleRestriction } from 'products/alerts/frontend/types'
import { InlineAlertNotifications } from 'products/alerts/frontend/views/InlineAlertNotifications'
@@ -345,9 +346,9 @@ function QuietHoursStory(): JSX.Element {
<div className="max-w-2xl border rounded bg-surface-primary p-4">
<QuietHoursFields
scheduleRestriction={scheduleRestriction}
+ cadenceMinutes={alertCadenceMinutes(AlertCalculationInterval.HOURLY)}
onChange={setScheduleRestriction}
teamTimezone="America/Toronto"
- calculationInterval={AlertCalculationInterval.HOURLY}
/>
</div>
)
diff --git a/products/alerts/frontend/components/QuietHoursFields.tsx b/products/alerts/frontend/components/QuietHoursFields.tsx
index 5685f2308afe..b6e49a78ca37 100644
--- a/products/alerts/frontend/components/QuietHoursFields.tsx
+++ b/products/alerts/frontend/components/QuietHoursFields.tsx
@@ -3,9 +3,6 @@ import { useMemo, type FocusEvent } from 'react'
import { IconTrash } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
-import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-
-import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { estimateCheckSlotsNext24h } from 'products/alerts/frontend/logic/scheduleRestrictionPreview'
import { findQuietHoursIssues, MAX_BLOCKED_WINDOWS } from 'products/alerts/frontend/logic/scheduleRestrictionValidation'
import type { BlockedWindow, ScheduleRestriction } from 'products/alerts/frontend/types'
@@ -27,14 +24,16 @@ function normalizeTimeInput(v: string): string {
export interface QuietHoursFieldsProps {
scheduleRestriction: ScheduleRestriction | null | undefined
- calculationInterval: AlertCalculationInterval
+ cadenceMinutes: number
+ coarseIntervalLabel?: string
teamTimezone: string
onChange: (next: ScheduleRestriction | null) => void
}
export function QuietHoursFields({
scheduleRestriction,
- calculationInterval,
+ cadenceMinutes,
+ coarseIntervalLabel,
teamTimezone,
onChange,
}: QuietHoursFieldsProps): JSX.Element {
@@ -79,13 +78,7 @@ export function QuietHoursFields({
}
const highFrequencySlotPreview = useMemo(() => {
- const cadenceMinutes =
- calculationInterval === AlertCalculationInterval.EVERY_15_MINUTES
- ? 15
- : calculationInterval === AlertCalculationInterval.HOURLY
- ? 60
- : null
- if (!enabled || cadenceMinutes == null) {
+ if (!enabled || cadenceMinutes > 60) {
return null
}
const slotApprox = estimateCheckSlotsNext24h(scheduleRestriction?.blocked_windows, teamTimezone, cadenceMinutes)
@@ -96,24 +89,16 @@ export function QuietHoursFields({
return {
slotApprox,
totalSlots,
- cadenceLabel: cadenceMinutes === 15 ? '15-minute' : 'hourly',
- intervalLabel: cadenceMinutes === 15 ? '15 minutes' : 'clock hour',
+ cadenceLabel: `${cadenceMinutes}-minute`,
+ intervalLabel: `${cadenceMinutes} minutes`,
}
- }, [enabled, calculationInterval, scheduleRestriction?.blocked_windows, teamTimezone])
+ }, [cadenceMinutes, enabled, scheduleRestriction?.blocked_windows, teamTimezone])
const quietIssue = useMemo(
() => (enabled && windows.length > 0 ? findQuietHoursIssues(windows) : null),
[enabled, windows]
)
- const coarseInterval = !isSubDailyAlertInterval(calculationInterval)
- ? calculationInterval === AlertCalculationInterval.DAILY
- ? 'day'
- : calculationInterval === AlertCalculationInterval.WEEKLY
- ? 'week'
- : 'month'
- : null
-
const atWindowLimit = windows.length >= MAX_BLOCKED_WINDOWS
const addWindowButtonLabel = atWindowLimit ? `Maximum of ${MAX_BLOCKED_WINDOWS} time windows` : 'Add time window'
@@ -129,15 +114,15 @@ export function QuietHoursFields({
/>
{enabled ? (
<>
- {coarseInterval ? (
+ {coarseIntervalLabel ? (
<LemonBanner type="info">
If a scheduled run would fall during quiet hours, it runs at the next allowed time in that
- same day or cycle instead of waiting until the next {coarseInterval}.
+ same day or cycle instead of waiting until the next {coarseIntervalLabel}.
</LemonBanner>
) : null}
<div className="flex flex-wrap gap-2">
<LemonButton type="secondary" size="small" onClick={applyOvernightPreset}>
- Preset: overnight (10pm–7am)
+ Preset: overnight (10 PM to 7 AM)
</LemonButton>
</div>
{highFrequencySlotPreview ? (
@@ -166,6 +151,7 @@ export function QuietHoursFields({
onBlur={(e: FocusEvent<HTMLInputElement>) =>
updateRow(index, 'start', normalizeTimeInput(e.currentTarget.value))
}
+ aria-label={`Quiet hours period ${index + 1} start time`}
data-attr={`alertForm-quiet-start-${index}`}
/>
<span className="text-muted">to</span>
@@ -182,6 +168,7 @@ export function QuietHoursFields({
onBlur={(e: FocusEvent<HTMLInputElement>) =>
updateRow(index, 'end', normalizeTimeInput(e.currentTarget.value))
}
+ aria-label={`Quiet hours period ${index + 1} end time`}
data-attr={`alertForm-quiet-end-${index}`}
/>
<LemonButton
@@ -189,6 +176,7 @@ export function QuietHoursFields({
size="small"
icon={<IconTrash className="size-4 text-danger" />}
onClick={() => removeRow(index)}
+ aria-label={`Remove quiet hours period ${index + 1}`}
data-attr={`alertForm-quiet-remove-${index}`}
/>
</div>
diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.ts b/products/alerts/frontend/logic/alertIntervalHelpers.ts
index 8334aa850bf8..7ab46b270b57 100644
--- a/products/alerts/frontend/logic/alertIntervalHelpers.ts
+++ b/products/alerts/frontend/logic/alertIntervalHelpers.ts
@@ -59,6 +59,10 @@ const CADENCE_DURATION_MINUTES: Record<AlertCalculationInterval, number> = {
[AlertCalculationInterval.MONTHLY]: 60 * 24 * 30,
}
+export function alertCadenceMinutes(interval: AlertCalculationInterval): number {
+ return CADENCE_DURATION_MINUTES[interval]
+}
+
const INSIGHT_INTERVAL_DURATION_MINUTES: Record<IntervalType, number> = {
second: 1 / 60,
minute: 1,
@@ -80,7 +84,7 @@ export function cadenceFinerThanInsightInterval(
const insightMinutes =
INSIGHT_INTERVAL_DURATION_MINUTES[(insightInterval as IntervalType | null) ?? 'day'] ??
INSIGHT_INTERVAL_DURATION_MINUTES.day
- return CADENCE_DURATION_MINUTES[cadence] < insightMinutes
+ return alertCadenceMinutes(cadence) < insightMinutes
}
type EntitlementResult =
diff --git a/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts b/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts
index 388c657502ea..6f8b80c981dd 100644
--- a/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts
+++ b/products/alerts/frontend/logic/scheduleRestrictionPreview.test.ts
@@ -6,6 +6,7 @@ describe('scheduleRestrictionPreview', () => {
it('returns full slot count when no quiet hours are configured', () => {
expect(estimateCheckSlotsNext24h(null, 'UTC', 60)).toBe(24)
expect(estimateCheckSlotsNext24h(undefined, 'UTC', 15)).toBe(96)
+ expect(estimateCheckSlotsNext24h(undefined, 'UTC', 5)).toBe(288)
})
it('counts fewer hourly slots when overnight quiet hours block most of the day', () => {
diff --git a/products/alerts/frontend/logic/scheduleRestrictionPreview.ts b/products/alerts/frontend/logic/scheduleRestrictionPreview.ts
index 32ea0e2b1af9..6831e3dd3cb0 100644
--- a/products/alerts/frontend/logic/scheduleRestrictionPreview.ts
+++ b/products/alerts/frontend/logic/scheduleRestrictionPreview.ts
@@ -52,7 +52,7 @@ export function isLocalMinuteBlocked(minute: number, windows: ParsedWindow[]): b
export function estimateCheckSlotsNext24h(
blockedWindows: BlockedWindow[] | null | undefined,
teamTimezone: string,
- cadenceMinutes: 15 | 60
+ cadenceMinutes: number
): number {
const totalSlots = (24 * 60) / cadenceMinutes
if (!blockedWindows?.length) {
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index cf335a30f5af..b73dddc32821 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -262,17 +262,8 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {
) {
n += 1
}
- if ((alertForm.schedule_restriction?.blocked_windows?.length ?? 0) > 0) {
- n += 1
- }
return n
- }, [
- alertForm.calculation_interval,
- alertForm.config,
- alertForm.schedule_restriction?.blocked_windows?.length,
- alertForm.skip_weekend,
- can_check_ongoing_interval,
- ])
+ }, [alertForm.calculation_interval, alertForm.config, alertForm.skip_weekend, can_check_ongoing_interval])
const subscribedCount = alertForm.subscribed_users?.length ?? 0
const destinationCount = existingHogFunctions.length + pendingNotifications.length
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index dda290f90663..7eb476569727 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -1,22 +1,29 @@
from __future__ import annotations
import os
-from datetime import datetime
+from datetime import UTC, datetime, timedelta
from uuid import UUID
from django.db.models import Q
+import structlog
+
from products.alerts.backend.scheduling import (
advance_next_check_at,
compute_shard_offset_seconds as shared_compute_shard_offset_seconds,
+ parse_blocked_windows_tuples,
+ scan_next_unblocked_utc,
)
+logger = structlog.get_logger(__name__)
+
__all__ = [
"MAX_BYTES_TO_READ",
"SCHEDULE_INTERVAL_SECONDS",
"advance_next_check_at",
"compute_shard_offset_seconds",
"due_alerts_q",
+ "next_allowed_check_at",
]
# How often the Temporal schedule fires. Drives shard granularity in
@@ -43,6 +50,33 @@ def compute_shard_offset_seconds(alert_id: UUID, check_interval_minutes: int) ->
)
+def next_allowed_check_at(
+ candidate: datetime,
+ *,
+ team_timezone: str,
+ schedule_restriction: dict[str, object] | None,
+) -> datetime:
+ windows = parse_blocked_windows_tuples(schedule_restriction)
+ allowed_at = scan_next_unblocked_utc(candidate, team_timezone, windows)
+ if allowed_at is not None:
+ return allowed_at
+
+ logger.warning(
+ "logs_alert.schedule_restriction.next_allowed_check_at_exceeded_cap",
+ team_timezone=team_timezone,
+ )
+ retry_candidate = candidate.astimezone(UTC) + timedelta(days=1)
+ allowed_at = scan_next_unblocked_utc(retry_candidate, team_timezone, windows)
+ if allowed_at is not None:
+ return allowed_at
+
+ logger.error(
+ "logs_alert.schedule_restriction.next_allowed_check_at_giving_up_after_retry",
+ team_timezone=team_timezone,
+ )
+ return retry_candidate.replace(second=0, microsecond=0)
+
+
def due_alerts_q(now: datetime, *, broken_state: str, snoozed_state: str) -> Q:
return (
Q(enabled=True)
diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.py
new file mode 100644
index 000000000000..7a817e0ed2de
--- /dev/null
+++ b/products/logs/backend/facade/api.py
@@ -0,0 +1,3 @@
+from products.logs.backend.alert_utils import next_allowed_check_at
+
+__all__ = ["next_allowed_check_at"]
diff --git a/products/logs/backend/migrations/0021_logsalertconfiguration_schedule_restriction.py b/products/logs/backend/migrations/0021_logsalertconfiguration_schedule_restriction.py
new file mode 100644
index 000000000000..b8cded9f0c4c
--- /dev/null
+++ b/products/logs/backend/migrations/0021_logsalertconfiguration_schedule_restriction.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-08-11 19:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0020_logsretentionrule"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="logsalertconfiguration",
+ name="schedule_restriction",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index 82796b54b219..9f0c225c1783 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0020_logsretentionrule
+0021_logsalertconfiguration_schedule_restriction
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index 3478d972f6ef..eb51c6c2973a 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -184,6 +184,7 @@ class LogsAlertConfiguration(ModelActivityMixin, CreatedMetaFields, UpdatedMetaF
# Cooldown & snooze
cooldown_minutes = models.PositiveIntegerField(default=0)
snooze_until = models.DateTimeField(null=True, blank=True)
+ schedule_restriction = models.JSONField(null=True, blank=True, default=None)
# Scheduling & tracking
next_check_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 9dff336f88a4..dee3a3403c1b 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -1,7 +1,7 @@
import os
import datetime as dt
from datetime import UTC, datetime
-from typing import Final, Literal, TypedDict, cast
+from typing import Any, Final, Literal, TypedDict, cast
from zoneinfo import ZoneInfo
from django.db import transaction
@@ -33,11 +33,13 @@ from products.alerts.backend.facade.api import (
DESTINATION_TEMPLATE_IDS,
AlertDestinationData,
AlertDestinationValidationError,
+ AlertScheduleRestriction,
DestinationType,
build_alert_destination_config,
create_alert_destination_hog_functions,
soft_delete_alert_destinations,
soft_delete_all_alert_destinations,
+ validate_and_normalize_schedule_restriction,
validate_destination_data,
)
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -64,6 +66,7 @@ from products.logs.backend.alert_state_machine import (
apply_user_reset,
evaluate_alert_check,
)
+from products.logs.backend.facade.api import next_allowed_check_at
from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
ALLOWED_WINDOW_MINUTES = {5, 10, 15, 30, 60}
@@ -152,6 +155,11 @@ class LogsAlertFiltersField(serializers.JSONField):
return value
+@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
+class ScheduleRestrictionField(serializers.JSONField):
+ pass
+
+
class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(
read_only=True,
@@ -218,6 +226,11 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
min_value=0,
help_text="Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.",
)
+ schedule_restriction = ScheduleRestrictionField(
+ required=False,
+ allow_null=True,
+ help_text="Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.",
+ )
snooze_until = serializers.DateTimeField(
required=False,
allow_null=True,
@@ -419,6 +432,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
"evaluation_periods",
"datapoints_to_alarm",
"cooldown_minutes",
+ "schedule_restriction",
"snooze_until",
"next_check_at",
"last_notified_at",
@@ -478,6 +492,14 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
if snooze_until is not None and snooze_until <= datetime.now(UTC):
raise ValidationError({"snooze_until": "Must be a future datetime."})
+ if "schedule_restriction" in attrs:
+ try:
+ attrs["schedule_restriction"] = validate_and_normalize_schedule_restriction(
+ attrs["schedule_restriction"]
+ )
+ except ValueError as e:
+ raise ValidationError({"schedule_restriction": str(e)}) from e
+
return attrs
def update(self, instance: LogsAlertConfiguration, validated_data: dict) -> LogsAlertConfiguration:
@@ -496,6 +518,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
threshold_changed = _any_field_changed(instance, validated_data, threshold_or_filter_fields)
window_changed = _any_field_changed(instance, validated_data, {"window_minutes"})
+ schedule_restriction_changed = _any_field_changed(instance, validated_data, {"schedule_restriction"})
enabled_change: bool | None = None
if "enabled" in validated_data and validated_data["enabled"] != instance.enabled:
@@ -531,8 +554,21 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
if snooze_data is not _SENTINEL:
instance.snooze_until = snooze_data
- if threshold_changed or window_changed:
- instance.clear_next_check()
+ if (
+ threshold_changed
+ or window_changed
+ or schedule_restriction_changed
+ or (enabled_change is True and instance.schedule_restriction)
+ ):
+ next_schedule_restriction = validated_data.get("schedule_restriction", instance.schedule_restriction)
+ if next_schedule_restriction:
+ validated_data["next_check_at"] = next_allowed_check_at(
+ datetime.now(UTC),
+ team_timezone=instance.team.timezone,
+ schedule_restriction=next_schedule_restriction,
+ )
+ else:
+ instance.clear_next_check()
return super().update(instance, validated_data)
@@ -550,11 +586,17 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
# select_for_update().count() doesn't acquire row locks because
# Django optimises count() to SELECT COUNT(*). Locking the team
# row instead serialises concurrent creates for this team.
- Team.objects.select_for_update().get(id=validated_data["team_id"])
+ team = Team.objects.select_for_update().get(id=validated_data["team_id"])
if validated_data["team_id"] not in UNCAPPED_ALERT_TEAM_IDS:
count = LogsAlertConfiguration.objects.filter(team_id=validated_data["team_id"]).count()
if count >= MAX_ALERTS_PER_TEAM:
raise ValidationError(f"Maximum number of alerts ({MAX_ALERTS_PER_TEAM}) reached for this team.")
+ if schedule_restriction := validated_data.get("schedule_restriction"):
+ validated_data["next_check_at"] = next_allowed_check_at(
+ datetime.now(UTC),
+ team_timezone=team.timezone,
+ schedule_restriction=schedule_restriction,
+ )
return super().create(validated_data)
@@ -890,6 +932,20 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
self.check_object_permissions(self.request, alert)
return alert
+ def update(self, request: Request, *args: object, **kwargs: Any) -> Response:
+ partial = kwargs.pop("partial", False)
+ with transaction.atomic():
+ instance = self._get_locked_alert()
+ serializer = self.get_serializer(instance, data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+
+ prefetched_objects_cache = getattr(instance, "_prefetched_objects_cache", None)
+ if prefetched_objects_cache:
+ prefetched_objects_cache.clear()
+
+ return Response(serializer.data)
+
@extend_schema(
request=LogsAlertCreateDestinationSerializer,
responses={201: LogsAlertDestinationResponseSerializer},
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 8542573a2748..0b255f666be6 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -9,6 +9,7 @@ from collections import defaultdict
from collections.abc import Iterator, Sequence
from datetime import UTC, datetime, timedelta
from itertools import batched
+from uuid import UUID
from django.db import transaction
from django.db.utils import IntegrityError
@@ -60,7 +61,12 @@ from products.logs.backend.alert_state_machine import (
apply_outcome,
evaluate_alert_check,
)
-from products.logs.backend.alert_utils import advance_next_check_at, compute_shard_offset_seconds, due_alerts_q
+from products.logs.backend.alert_utils import (
+ advance_next_check_at,
+ compute_shard_offset_seconds,
+ due_alerts_q,
+ next_allowed_check_at,
+)
from products.logs.backend.logs_url_params import build_logs_url_params
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.temporal.constants import (
@@ -287,6 +293,7 @@ class _DispatchedAlert:
evaluation: _AlertEvaluation
notification_failed: bool
produce_result: ProduceResult | None = None
+ suppressed_by_quiet_hours: bool = False
@property
def committed_outcome(self) -> AlertCheckOutcome:
@@ -374,8 +381,11 @@ def _discover_cohorts_sync() -> DiscoverCohortsOutput:
"check_interval_minutes",
"filters",
"next_check_at",
+ "schedule_restriction",
)
)
+ rescheduled_alert_ids = _reschedule_due_alerts_in_quiet_hours(rows, now)
+ rows = [row for row in rows if row["id"] not in rescheduled_alert_ids]
_safe_record("alerts_active gauge", record_alerts_active, len(rows))
@@ -410,6 +420,39 @@ def _discover_cohorts_sync() -> DiscoverCohortsOutput:
return DiscoverCohortsOutput(manifests=manifests, batch_size=MAX_COHORTS_PER_BATCH)
+def _reschedule_due_alerts_in_quiet_hours(rows: Sequence[dict], now: datetime) -> set[UUID]:
+ alert_ids = [row["id"] for row in rows if row["schedule_restriction"]]
+ if not alert_ids:
+ return set()
+
+ rescheduled_alert_ids: set[UUID] = set()
+ with transaction.atomic():
+ alerts = _due_alerts_qs(now).select_for_update(of=("self",)).select_related("team").filter(id__in=alert_ids)
+ for alert in alerts:
+ try:
+ next_check_at = next_allowed_check_at(
+ now,
+ team_timezone=alert.team.timezone,
+ schedule_restriction=alert.schedule_restriction,
+ )
+ except Exception as e:
+ logger.exception(
+ "Skipping alert with invalid quiet-hours configuration",
+ alert_id=str(alert.id),
+ team_id=alert.team_id,
+ error=str(e),
+ )
+ rescheduled_alert_ids.add(alert.id)
+ continue
+ if next_check_at <= now:
+ continue
+ alert.next_check_at = next_check_at
+ alert.save(update_fields=["next_check_at", "updated_at"])
+ rescheduled_alert_ids.add(alert.id)
+
+ return rescheduled_alert_ids
+
+
def _detect_broken_filter_config(filters: object) -> str | None:
"""Returns a human-readable reason if `filters` is structurally broken in a way
that will permanently prevent the alert from running. Returns None if the shape
@@ -686,6 +729,8 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
if delivery_slo := delivery_slo_handles.get(alert_id):
delivery_slo.fail(failure_phase="dispatch")
local_stats["errored"] += 1
+ elif result.suppressed_by_quiet_hours:
+ continue
else:
dispatched.append(result)
elapsed_ms_per_alert.append(int((phase_2_end - eval_start) * 1000))
@@ -975,11 +1020,40 @@ def _dispatch_notification(
def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _DispatchedAlert:
- """Phase 2: dispatch the Kafka notification for one alert.
+ """Phase 2: defer blocked alerts or dispatch their Kafka notification."""
+ with transaction.atomic():
+ current_alert = (
+ LogsAlertConfiguration.objects.select_for_update(of=("self",))
+ .select_related("team")
+ .get(id=evaluation.alert.id)
+ )
+ try:
+ next_check_at = next_allowed_check_at(
+ now,
+ team_timezone=current_alert.team.timezone,
+ schedule_restriction=current_alert.schedule_restriction,
+ )
+ except Exception as e:
+ logger.exception(
+ "Skipping alert with invalid quiet-hours configuration",
+ alert_id=str(current_alert.id),
+ team_id=current_alert.team_id,
+ error=str(e),
+ )
+ return _DispatchedAlert(
+ evaluation=evaluation,
+ notification_failed=False,
+ suppressed_by_quiet_hours=True,
+ )
+ if next_check_at > now:
+ current_alert.next_check_at = next_check_at
+ current_alert.save(update_fields=["next_check_at", "updated_at"])
+ return _DispatchedAlert(
+ evaluation=evaluation,
+ notification_failed=False,
+ suppressed_by_quiet_hours=True,
+ )
- Pure-effect (Kafka). The orchestrator updates `stats` serially after the
- dispatch phase so concurrent gather'd dispatches can't race on the dict.
- """
produce_result = _dispatch_notification(
evaluation.outcome,
evaluation.alert,
@@ -1048,12 +1122,26 @@ def _stage_alert_for_save(dispatched: _DispatchedAlert, now: datetime) -> tuple[
# (the per-alert fallback's `alert.save()` would honour `auto_now`, but the
# happy path is bulk_update).
alert.updated_at = now
- alert.next_check_at = advance_next_check_at(
+ next_check_at = advance_next_check_at(
alert.next_check_at,
alert.check_interval_minutes,
now,
shard_offset_seconds=compute_shard_offset_seconds(alert.id, alert.check_interval_minutes),
)
+ try:
+ alert.next_check_at = next_allowed_check_at(
+ next_check_at,
+ team_timezone=alert.team.timezone,
+ schedule_restriction=alert.schedule_restriction,
+ )
+ except Exception as e:
+ logger.exception(
+ "Ignoring invalid quiet-hours configuration while saving alert",
+ alert_id=str(alert.id),
+ team_id=alert.team_id,
+ error=str(e),
+ )
+ alert.next_check_at = next_check_at
update_fields.extend(["last_checked_at", "next_check_at", "updated_at"])
if (
@@ -1110,25 +1198,29 @@ def _save_cohort_outcomes(
save_start = time.perf_counter()
- # Stage every alert exactly once: mutates the in-memory alert (apply_outcome,
- # advance_next_check_at, etc.) and produces the (update_fields, event) tuple
- # needed to write it. We keep the staged tuples so the IntegrityError
- # fallback can save each alert individually without re-staging — calling
- # `advance_next_check_at` twice would otherwise skip a cycle slot.
- staged: list[tuple[_DispatchedAlert, list[str], LogsAlertEvent | None]] = []
- for d in dispatched:
- update_fields, event = _stage_alert_for_save(d, now)
- staged.append((d, update_fields, event))
-
- events = [event for _, _, event in staged if event is not None]
- alerts = [d.evaluation.alert for d, _, _ in staged]
-
event_insert_ms: int | None = None
update_ms: int | None = None
saved: list[_DispatchedAlert] = list(dispatched)
failed: list[_DispatchedAlert] = []
try:
with transaction.atomic():
+ current_restrictions = dict(
+ LogsAlertConfiguration.objects.select_for_update()
+ .filter(id__in=[d.evaluation.alert.id for d in dispatched])
+ .values_list("id", "schedule_restriction")
+ )
+
+ # The worker can evaluate an alert while a user saves quiet hours. Locking
+ # before staging makes either write order safe: this worker uses the saved
+ # restriction, or the API waits and then reschedules after this check.
+ staged: list[tuple[_DispatchedAlert, list[str], LogsAlertEvent | None]] = []
+ for d in dispatched:
+ d.evaluation.alert.schedule_restriction = current_restrictions.get(d.evaluation.alert.id)
+ update_fields, event = _stage_alert_for_save(d, now)
+ staged.append((d, update_fields, event))
+
+ events = [event for _, _, event in staged if event is not None]
+ alerts = [d.evaluation.alert for d, _, _ in staged]
if events:
event_insert_start = time.perf_counter()
LogsAlertEvent.objects.bulk_create(events)
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index dcc5448c83f7..2d35e38fea6c 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -87,6 +87,57 @@ class TestLogsAlertAPI(APIBaseTest):
assert mock_report.call_args.args[2]["alert_name"] == "High error rate"
assert mock_report.call_args.args[2]["threshold_count"] == 10
+ @freeze_time("2026-01-01T23:00:00Z")
+ def test_create_with_quiet_hours_defers_next_check(self):
+ data = self._create_via_api(schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]})
+
+ assert data["schedule_restriction"] == {"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
+ assert data["next_check_at"] == "2026-01-02T07:00:00Z"
+
+ @freeze_time("2026-01-01T23:00:00Z")
+ def test_update_with_quiet_hours_defers_next_check(self):
+ created = self._create_via_api()
+
+ response = self.client.patch(
+ f"{self.base_url}{created['id']}/",
+ {"schedule_restriction": {"blocked_windows": [{"start": "22:00", "end": "07:00"}]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["next_check_at"] == "2026-01-02T07:00:00Z"
+
+ def test_enabling_alert_during_quiet_hours_defers_next_check(self):
+ with freeze_time("2026-01-01T16:00:00Z"):
+ created = self._create_via_api(
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
+ )
+ self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": False}, format="json")
+
+ with freeze_time("2026-01-01T23:00:00Z"):
+ response = self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["next_check_at"] == "2026-01-02T07:00:00Z"
+
+ @parameterized.expand(
+ [
+ ("unknown_root_key", {"typo": True}),
+ (
+ "unknown_window_key",
+ {"blocked_windows": [{"start": "22:00", "end": "07:00", "typo": True}]},
+ ),
+ ]
+ )
+ def test_create_rejects_unknown_quiet_hours_keys(self, _name: str, schedule_restriction: dict[str, Any]) -> None:
+ response = self.client.post(
+ self.base_url,
+ self._valid_payload(schedule_restriction=schedule_restriction),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_list(self):
self._create_via_api(name="Alert 1")
self._create_via_api(name="Alert 2")
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 112949b3b635..95386801c01f 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -58,6 +58,8 @@ def _evaluate_and_save_one(
eval_start = time.perf_counter()
evaluation = _evaluate_single_alert(alert, now, checkpoint=checkpoint)
dispatched = _dispatch_for_alert(evaluation, now)
+ if dispatched.suppressed_by_quiet_hours:
+ return
elapsed_ms = int((time.perf_counter() - eval_start) * 1000)
saved, _failed = _save_cohort_outcomes([dispatched], now)
if saved:
@@ -795,6 +797,73 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at is not None and alert.next_check_at > now
+ @freeze_time("2025-01-01T21:58:00Z")
+ @patch("products.logs.backend.temporal.activities.AlertCheckQuery")
+ @patch("products.alerts.backend.destinations.produce_internal_event")
+ def test_advances_next_check_at_past_quiet_hours(self, _mock_produce, mock_query_cls):
+ _mock_buckets(mock_query_cls, [5])
+ alert = self._make_alert(
+ next_check_at=datetime(2025, 1, 1, 21, 55, tzinfo=UTC),
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]},
+ )
+ now = datetime(2025, 1, 1, 21, 58, tzinfo=UTC)
+
+ _evaluate_and_save_one(alert, now, _make_stats())
+
+ alert.refresh_from_db()
+ assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
+
+ @freeze_time("2025-01-01T21:58:00Z")
+ @patch("products.logs.backend.temporal.activities.AlertCheckQuery")
+ @patch("products.alerts.backend.destinations.produce_internal_event")
+ def test_uses_quiet_hours_saved_after_the_alert_loaded(self, _mock_produce, mock_query_cls):
+ _mock_buckets(mock_query_cls, [5])
+ alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 21, 55, tzinfo=UTC))
+ stale_alert = LogsAlertConfiguration.objects.get(id=alert.id)
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
+ )
+
+ _evaluate_and_save_one(stale_alert, datetime(2025, 1, 1, 21, 58, tzinfo=UTC), _make_stats())
+
+ alert.refresh_from_db()
+ assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
+
+ @freeze_time("2025-01-01T23:00:00Z")
+ @patch("products.logs.backend.temporal.activities.AlertCheckQuery")
+ @patch("products.alerts.backend.destinations.produce_internal_event")
+ def test_suppresses_notification_when_quiet_hours_start_after_evaluation(self, mock_produce, mock_query_cls):
+ _mock_buckets(mock_query_cls, [50])
+ alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 21, 55, tzinfo=UTC))
+ evaluation = _evaluate_single_alert(alert, datetime(2025, 1, 1, 21, 58, tzinfo=UTC))
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
+ )
+
+ dispatched = _dispatch_for_alert(evaluation, datetime(2025, 1, 1, 23, 0, tzinfo=UTC))
+
+ assert dispatched.suppressed_by_quiet_hours is True
+ mock_produce.assert_not_called()
+ assert LogsAlertEvent.objects.filter(alert=alert).count() == 0
+ alert.refresh_from_db()
+ assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
+
+ @freeze_time("2025-01-02T06:56:00Z")
+ @patch("products.logs.backend.temporal.activities.AlertCheckQuery")
+ @patch("products.alerts.backend.destinations.produce_internal_event")
+ def test_advances_last_quiet_hours_check_to_the_window_end(self, _mock_produce, mock_query_cls):
+ _mock_buckets(mock_query_cls, [5])
+ alert = self._make_alert(
+ next_check_at=datetime(2025, 1, 2, 6, 55, tzinfo=UTC),
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]},
+ )
+ now = datetime(2025, 1, 2, 6, 56, tzinfo=UTC)
+
+ _evaluate_and_save_one(alert, now, _make_stats())
+
+ alert.refresh_from_db()
+ assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
+
@freeze_time("2025-01-01T00:01:00Z")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1976,6 +2045,64 @@ class TestCohortManifest(unittest.TestCase):
class TestDiscoverCohortsActivity(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
+ @freeze_time("2026-05-05T23:00:00Z")
+ def test_skips_alert_with_invalid_quiet_hours_and_discovers_healthy_alerts(self):
+ from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
+
+ invalid_alert = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="invalid quiet hours",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": ["invalid"]},
+ enabled=True,
+ next_check_at=datetime(2026, 5, 5, 21, 55, tzinfo=UTC),
+ )
+ LogsAlertConfiguration.objects.filter(id=invalid_alert.id).update(
+ schedule_restriction={"blocked_windows": [{"start": "invalid", "end": "07:00"}]}
+ )
+ healthy_alert = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="healthy",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": ["healthy"]},
+ enabled=True,
+ next_check_at=datetime(2026, 5, 5, 21, 55, tzinfo=UTC),
+ )
+
+ result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))
+
+ discovered_alert_ids = [alert_id for manifest in result.manifests for alert_id in manifest.alert_ids]
+ assert discovered_alert_ids == [str(healthy_alert.id)]
+
+ @freeze_time("2026-05-05T23:00:00Z")
+ def test_reschedules_due_alert_during_quiet_hours_before_evaluation(self):
+ from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
+
+ alert = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="quiet",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": ["quiet"]},
+ enabled=True,
+ next_check_at=datetime(2026, 5, 5, 21, 55, tzinfo=UTC),
+ schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]},
+ )
+
+ result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))
+
+ assert result.manifests == []
+ alert.refresh_from_db()
+ assert alert.next_check_at == datetime(2026, 5, 6, 7, 0, tzinfo=UTC)
+
@freeze_time("2026-05-05T10:00:00Z")
def test_returns_manifests_for_due_alerts_only(self):
from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
index 3e6da089eeb3..b87199fcf0e3 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertForm.tsx
@@ -13,12 +13,14 @@ import { universalFiltersLogic } from 'lib/components/UniversalFilters/universal
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { teamLogic } from 'scenes/teamLogic'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'
import { AlertEditorSection } from 'products/alerts/frontend/components/AlertEditor'
+import { QuietHoursFields } from 'products/alerts/frontend/components/QuietHoursFields'
import { ServiceFilter } from 'products/logs/frontend/components/LogsViewer/Filters/ServiceFilter'
import { SeverityLevelsFilter } from 'products/logs/frontend/components/LogsViewer/Filters/SeverityLevelsFilter'
import { LogsAlertThresholdOperatorEnumApi } from 'products/logs/frontend/generated/api.schemas'
@@ -153,10 +155,12 @@ export function LogsAlertFilters({ filterError }: { filterError?: string }): JSX
export function LogsAlertTrigger(): JSX.Element {
const { alertForm } = useValues(logsAlertFormLogic)
+ const { timezone } = useValues(teamLogic)
const { setAlertFormValue } = useActions(logsAlertFormLogic)
const enabledAdvancedOptionsCount =
Number(alertForm.evaluationPeriods > 1 || alertForm.datapointsToAlarm > 1) +
- Number(alertForm.cooldownMinutes > 0)
+ Number(alertForm.cooldownMinutes > 0) +
+ Number(alertForm.scheduleRestriction !== null)
return (
<div className="space-y-4">
@@ -255,6 +259,12 @@ export function LogsAlertTrigger(): JSX.Element {
<span className="text-sm">minutes</span>
</div>
</LemonField.Pure>
+ <QuietHoursFields
+ scheduleRestriction={alertForm.scheduleRestriction}
+ cadenceMinutes={5}
+ teamTimezone={timezone}
+ onChange={(next) => setAlertFormValue('scheduleRestriction', next)}
+ />
</AlertAdvancedOptions>
</div>
)
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
index bfd06ce6cac5..22396ad70913 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
@@ -83,6 +83,7 @@ const VALID_FORM_VALUES: LogsAlertFormType = {
evaluationPeriods: 1,
datapointsToAlarm: 1,
cooldownMinutes: 0,
+ scheduleRestriction: null,
}
describe('logsAlertFormLogic', () => {
@@ -135,6 +136,24 @@ describe('logsAlertFormLogic', () => {
logic.unmount()
})
+ it('rejects invalid quiet hours before submitting', async () => {
+ const logic = logsAlertFormLogic({ alert: null })
+ logic.mount()
+
+ logic.actions.setAlertFormValues({
+ name: 'My Alert',
+ severityLevels: ['error'],
+ scheduleRestriction: { blocked_windows: [{ start: '10:00', end: '10:00' }] },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(mockLogsAlertsCreate).not.toHaveBeenCalled()
+ logic.unmount()
+ })
+
it('shows error toast on submit when no filter criteria are set', async () => {
const logic = logsAlertFormLogic({ alert: null })
logic.mount()
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
index af7828786363..7a3f8e7ee732 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts
@@ -26,6 +26,7 @@ const baseForm = (overrides: Partial<LogsAlertFormType> = {}): LogsAlertFormType
evaluationPeriods: 1,
datapointsToAlarm: 1,
cooldownMinutes: 0,
+ scheduleRestriction: null,
...overrides,
})
diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
index 2b252115ed2e..8006bccc5d2d 100644
--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts
@@ -13,6 +13,8 @@ import { urls } from 'scenes/urls'
import { LogMessage } from '~/queries/schema/schema-general'
import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+import { findQuietHoursIssues } from 'products/alerts/frontend/logic/scheduleRestrictionValidation'
+import type { ScheduleRestriction } from 'products/alerts/frontend/types'
import {
logsAlertsCreate,
logsAlertsPartialUpdate,
@@ -48,6 +50,7 @@ export interface LogsAlertFormType {
evaluationPeriods: number
datapointsToAlarm: number
cooldownMinutes: number
+ scheduleRestriction: ScheduleRestriction | null
}
export interface LogsAlertFormLogicProps {
@@ -87,6 +90,7 @@ export function buildFormDefaults(alert: LogsAlertConfigurationApi | null): Logs
evaluationPeriods: alert?.evaluation_periods ?? 1,
datapointsToAlarm: alert?.datapoints_to_alarm ?? 1,
cooldownMinutes: alert?.cooldown_minutes ?? 0,
+ scheduleRestriction: alert?.schedule_restriction ?? null,
}
}
@@ -324,6 +328,13 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
form.name = 'Untitled alert'
}
+ if (form.scheduleRestriction?.blocked_windows) {
+ const quietHoursIssue = findQuietHoursIssues(form.scheduleRestriction.blocked_windows)
+ if (quietHoursIssue) {
+ throw new Error(quietHoursIssue.message)
+ }
+ }
+
if (!hasAnyFilter(form.severityLevels, form.serviceNames, form.filterGroup)) {
lemonToast.error('At least one filter is required')
throw new Error('At least one filter is required')
@@ -338,6 +349,7 @@ export const logsAlertFormLogic = kea<logsAlertFormLogicType>([
evaluation_periods: form.evaluationPeriods,
datapoints_to_alarm: form.datapointsToAlarm,
cooldown_minutes: form.cooldownMinutes,
+ schedule_restriction: form.scheduleRestriction,
}
let savedAlertId: string
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 3dbfa57d9713..be1bc2642c3c 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -368,6 +368,18 @@ export const LogsAlertConfigurationStateEnumApi = {
Broken: 'broken',
} as const
+export interface AlertScheduleRestrictionWindowApi {
+ /** Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)). */
+ start: string
+ /** End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally. */
+ end: string
+}
+
+export interface AlertScheduleRestrictionApi {
+ /** Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours. */
+ blocked_windows: AlertScheduleRestrictionWindowApi[]
+}
+
export interface LogsAlertStateIntervalApi {
/** Interval start (UTC, inclusive). */
start: string
@@ -509,6 +521,8 @@ export interface LogsAlertConfigurationApi {
* @minimum 0
*/
cooldown_minutes?: number
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
/**
* ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
* @nullable
@@ -616,6 +630,8 @@ export interface PatchedLogsAlertConfigurationApi {
* @minimum 0
*/
cooldown_minutes?: number
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
/**
* ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
* @nullable
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 43e8dddf7d20..da579f046c71 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -97,6 +97,34 @@ export const LogsAlertsCreateBody = /* @__PURE__ */ zod.object({
.min(logsAlertsCreateBodyCooldownMinutesMin)
.default(logsAlertsCreateBodyCooldownMinutesDefault)
.describe('Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.'
+ ),
snooze_until: zod.iso
.datetime({ offset: true })
.nullish()
@@ -191,6 +219,34 @@ export const LogsAlertsUpdateBody = /* @__PURE__ */ zod.object({
.min(logsAlertsUpdateBodyCooldownMinutesMin)
.default(logsAlertsUpdateBodyCooldownMinutesDefault)
.describe('Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.'
+ ),
snooze_until: zod.iso
.datetime({ offset: true })
.nullish()
@@ -285,6 +341,34 @@ export const LogsAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(logsAlertsPartialUpdateBodyCooldownMinutesMin)
.default(logsAlertsPartialUpdateBodyCooldownMinutesDefault)
.describe('Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.'
+ ),
snooze_until: zod.iso
.datetime({ offset: true })
.nullish()
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 46d945e2f5a9..babf9b5c6b23 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -48,6 +48,7 @@ tools:
- evaluation_periods
- datapoints_to_alarm
- cooldown_minutes
+ - schedule_restriction
- snooze_until
- next_check_at
- last_notified_at
@@ -167,6 +168,7 @@ tools:
- threshold_count
- threshold_operator
- window_minutes
+ - schedule_restriction
- created_at
- updated_at
logs-alerts-partial-update:
@@ -181,7 +183,7 @@ tools:
title: Update log alert
description: >
Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust
- thresholds, filters, enable/disable alerts, or snooze them.
+ thresholds, filters, quiet hours, enable/disable alerts, or snooze them.
exclude_params:
- id
- state
@@ -208,6 +210,7 @@ tools:
- evaluation_periods
- datapoints_to_alarm
- cooldown_minutes
+ - schedule_restriction
- snooze_until
- next_check_at
- last_notified_at
@@ -247,6 +250,7 @@ tools:
- evaluation_periods
- datapoints_to_alarm
- cooldown_minutes
+ - schedule_restriction
- snooze_until
- next_check_at
- last_notified_at
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 142642688160..0f3b55ad02af 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6311,7 +6311,7 @@
"feature_flag": "logs-alerting"
},
"logs-alerts-partial-update": {
- "description": "Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust thresholds, filters, enable/disable alerts, or snooze them.",
+ "description": "Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust thresholds, filters, quiet hours, enable/disable alerts, or snooze them.",
"category": "Logs",
"feature": "logs",
"summary": "Update log alert",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 37d99c603891..82f1c45de945 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6676,7 +6676,7 @@
"feature_flag": "logs-alerting"
},
"logs-alerts-partial-update": {
- "description": "Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust thresholds, filters, enable/disable alerts, or snooze them.",
+ "description": "Update a log alert configuration by ID. Only the fields you provide are changed. Use this to adjust thresholds, filters, quiet hours, enable/disable alerts, or snooze them.",
"category": "Logs",
"feature": "logs",
"summary": "Update log alert",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bb1d673daa67..ec277a02fdc8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42644,6 +42644,8 @@ export namespace Schemas {
* @minimum 0
*/
cooldown_minutes?: number;
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
/**
* ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
* @nullable
@@ -56837,6 +56839,8 @@ export namespace Schemas {
* @minimum 0
*/
cooldown_minutes?: number;
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
/**
* ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
* @nullable
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index fb1d00eca595..a7cf01681cb3 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -1371,6 +1371,34 @@ export const LogsAlertsCreateBody = /* @__PURE__ */ zod.object({
.min(logsAlertsCreateBodyCooldownMinutesMin)
.default(logsAlertsCreateBodyCooldownMinutesDefault)
.describe('Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.'
+ ),
snooze_until: zod.iso
.datetime({ offset: true })
.nullish()
@@ -2729,6 +2757,34 @@ export const LogsAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(logsAlertsPartialUpdateBodyCooldownMinutesMin)
.optional()
.describe('Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours.'
+ ),
snooze_until: zod.iso
.datetime({ offset: true })
.nullish()
diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.ts
index 3ece7cf4bf2e..5772a6a3d75a 100644
--- a/services/mcp/src/tools/generated/logs.ts
+++ b/services/mcp/src/tools/generated/logs.ts
@@ -66,6 +66,9 @@ const logsAlertsCreate = (): ToolBase<typeof LogsAlertsCreateSchema, Schemas.Log
if (params.cooldown_minutes !== undefined) {
body['cooldown_minutes'] = params.cooldown_minutes
}
+ if (params.schedule_restriction !== undefined) {
+ body['schedule_restriction'] = params.schedule_restriction
+ }
if (params.snooze_until !== undefined) {
body['snooze_until'] = params.snooze_until
}
@@ -87,6 +90,7 @@ const logsAlertsCreate = (): ToolBase<typeof LogsAlertsCreateSchema, Schemas.Log
'evaluation_periods',
'datapoints_to_alarm',
'cooldown_minutes',
+ 'schedule_restriction',
'snooze_until',
'next_check_at',
'last_notified_at',
@@ -261,6 +265,7 @@ const logsAlertsList = (): ToolBase<
'threshold_count',
'threshold_operator',
'window_minutes',
+ 'schedule_restriction',
'created_at',
'updated_at',
])
@@ -307,6 +312,9 @@ const logsAlertsPartialUpdate = (): ToolBase<typeof LogsAlertsPartialUpdateSchem
if (params.cooldown_minutes !== undefined) {
body['cooldown_minutes'] = params.cooldown_minutes
}
+ if (params.schedule_restriction !== undefined) {
+ body['schedule_restriction'] = params.schedule_restriction
+ }
if (params.snooze_until !== undefined) {
body['snooze_until'] = params.snooze_until
}
@@ -328,6 +336,7 @@ const logsAlertsPartialUpdate = (): ToolBase<typeof LogsAlertsPartialUpdateSchem
'evaluation_periods',
'datapoints_to_alarm',
'cooldown_minutes',
+ 'schedule_restriction',
'snooze_until',
'next_check_at',
'last_notified_at',
@@ -365,6 +374,7 @@ const logsAlertsRetrieve = (): ToolBase<typeof LogsAlertsRetrieveSchema, Schemas
'evaluation_periods',
'datapoints_to_alarm',
'cooldown_minutes',
+ 'schedule_restriction',
'snooze_until',
'next_check_at',
'last_notified_at',