Repository navigation
[RFC] Implement route labels - #5328
Conversation
Add support for defining labels on routes in the routing configuration. Route labels are merged from parent to child routes, allowing label inheritance and overrides at each level of the routing tree. This enables: - Injecting labels into the notification context even when the label is not used for grouping - Using the same dedup key across alert groups with different group_by label sets The Labels field is added to config.Route, propagated through dispatch.RouteOpts (merged into a fresh LabelSet so parents are never mutated), and passed to the notification context via notify.WithRouteLabels. Templates can access route labels through the new routeLabels template function, which renders each label value as a template (so values can reference group labels, other route labels, etc., including recursively). Signed-off-by: Guido Trotter <[email protected]>
Thread the notification template through the dispatcher and into each
aggregation group so route label values can be rendered as templates
against the group's current alerts (e.g. a label value referencing
{{ .GroupLabels.x }} or another route label).
Rendering is lazy: an aggrGroup tracks a routeLabelsDirty flag set on
insert and on deletion of resolved alerts, and only re-renders when the
rendered labels are actually requested (RouteLabels()) or when flushing.
Access is guarded by an RWMutex with a read-fast-path / write-on-dirty
lock upgrade. When all alerts are resolved and deleted, the last rendered
labels are retained rather than re-rendered against an empty group.
Route labels rendered against the flush batch are placed on the
notification context, superseding the static route labels set in run().
Signed-off-by: Guido Trotter <[email protected]>
Add a routeLabels field to the alertGroup API model and populate it in the GetAlertGroups handler from the dispatcher's per-group rendered route labels (dispatch.AlertGroup.RouteLabels). Signed-off-by: Guido Trotter <[email protected]>
Replace the aggrGroup route-label cache's RWMutex + dirty-flag + RLock→Lock upgrade dance with a lock-free scheme: an atomic.Pointer to the rendered labels plus an atomic generation counter. - invalidateRouteLabels() (called by insert() and the resolved-alert deletion in flush(), both on the hot alert-ingestion path) is now a single atomic add on the generation counter. - RouteLabels() loads the cached value, then the generation, and treats the cache as valid only if the value's tagged generation still matches. On a miss it renders and stores the result tagged with the generation it observed before reading the alert list. Correctness rests on two orderings: - Writers mutate ag.alerts before bumping the generation, so a render that races an invalidation is tagged with a now-stale generation and is never served (the next reader sees the mismatch and re-renders). - The reader loads the value before the generation; loading them in the other order could pair an old generation with a value cached for it and wrongly accept a stale render. Concurrent cold readers may render redundantly, which is fine: the only caller is the /alerts/groups API path. The mutex never protected rendering itself — renderRouteLabels only reads immutable or self-synchronized state, as the lock-free render on the notify path in run() already demonstrated. Behavior is unchanged except the previously unobservable "retain last rendered labels once the group is empty" case: RouteLabels() now returns an empty set for an empty group (without rendering, to avoid logging errors from templates that reference .Alerts). Empty groups are excluded from the /alerts/groups response anyway, so this is not observable via the API. Signed-off-by: Guido Trotter <[email protected]>
The routeLabels template function rendered a label's value by re-running it through ExecuteTextString, which rebuilt the funcmap (and so re-bound routeLabels) on every recursive reference. This had no cycle protection: a config where two route labels reference each other (or a label references itself) recursed until the goroutine stack overflowed. Replace makeRouteLabelFunc with a per-render routeLabelResolver shared across the whole recursion: - caches each label's final value, so a label referenced multiple times (e.g. via a diamond) is rendered once; - tracks the labels currently being rendered and returns a descriptive "route label cycle detected: a -> b -> a" error instead of recursing forever. ExecuteTextString/ExecuteHTMLString now create a resolver and delegate to private execText/execHTML helpers that thread it through nested renders. Signed-off-by: Guido Trotter <[email protected]>
GetTemplateData logged l.Error("Missing route labels") whenever the
keyRouteLabels context value was absent. Unlike the receiver, group labels,
and notification reason — which the dispatcher always sets, so their absence
indicates a real bug — route labels are legitimately absent: a route may have
none configured, and callers such as notifier integration tests build the
context without them (e.g. notify/webhook/webhook_test.go). The absent value
yields a nil LabelSet, which Data() handles safely (ranging a nil map is zero
iterations), so the log was spurious noise that pollutes error-rate
monitoring.
Drop the error and use the (possibly nil) value directly.
Signed-off-by: Guido Trotter <[email protected]>
The dispatcher renders route label values (renderRouteLabels), stores the
resulting strings on the context, and GetTemplateData copies them into
Data.RouteLabels. When a notification template then calls
{{ routeLabels "x" }}, the resolver executed those strings as templates a
second time.
Signed-off-by: Guido Trotter <[email protected]>
renderRouteLabels rendered each route label with a separate
ExecuteTextString call, so every label got its own routeLabelResolver
(empty memo) and its own template Clone. When one label cross-referenced
another via {{ routeLabels "x" }}, the referenced label was rendered both
as part of the referrer and again on its own loop iteration, with a fresh
Clone each time.
Add Template.RouteLabelRenderer, which returns a render-by-name function
backed by a single shared resolver. renderRouteLabels now renders each
label through it, so a label and anything it references are rendered at
most once per group.
Signed-off-by: Guido Trotter <[email protected]>
The notification reason is per-notification and not known at render time, so
renderRouteLabels passes ReasonUnknown and {{ .NotificationReason }} always
renders "unknown" in route label templates.
Signed-off-by: Guido Trotter <[email protected]>
Groups() built the AlertGroup (calling ag.RouteLabels()) before filtering the group's alerts, then discarded the group if no alert passed the filter. RouteLabels() can render templates on a cache miss, so this wasted that work for every filtered-out group — noticeable on large deployments hitting the alerts/groups API with selective filters. Move the AlertGroup construction (and the RouteLabels() call) after the empty-filter check so it only runs for groups that are actually returned. Signed-off-by: Guido Trotter <[email protected]>
config.Route.UnmarshalYAML validated matcher and group_by label names but not the keys of the new Labels field, so invalid names (hyphens, digit-prefixed, empty) were accepted and propagated to route opts, templates, and the /api/v2/alerts/groups response. Signed-off-by: Guido Trotter <[email protected]>
renderRouteLabels built template data (tmpl.Data, which clones alerts and computes common labels/annotations, O(n_alerts)) and a resolver even when the route had no labels, then ran an empty loop and returned an empty set. Routes without labels are the common case and this ran on every flush and every RouteLabels() cache miss. Return early when ag.opts.Labels is empty, folding in the existing nil-tmpl guard since both return an empty LabelSet. Signed-off-by: Guido Trotter <[email protected]>
The notification path for route labels was untested: GetTemplateData's
route-label extraction and the flush-time WithRouteLabels injection were only
exercised by the API read path (ag.RouteLabels()).
Add two tests:
- notify: GetTemplateData populates Data.RouteLabels from the context, marks
them resolved, and the routeLabels template function returns them verbatim
(including a value containing {{ $value }}, which must not be re-executed).
- dispatch: during run(), the flush puts rendered route labels on the notify
context, so notify.RouteLabels(ctx) returns both a static label and a
templated one rendered against the flushed batch.
Signed-off-by: Guido Trotter <[email protected]>
📝 WalkthroughWalkthroughRoute labels are added to routing configuration, carried through template and notification data, rendered in dispatcher output, and exposed in the alert-group API response, schemas, and UI models. ChangesRoute-label propagation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
dispatch/dispatch.go (1)
808-839: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
WithRouteLabels(ctx, ag.opts.Labels)at Line 811 is always overwritten and stores unrendered templates.In the flush closure (Line 838) the context is unconditionally re-set with
ag.renderRouteLabels(alerts...)beforenfis called, so the Line 811 value never reaches any consumer. Worse, the Line 811 value is the rawag.opts.Labels(unrendered template strings like{{ ... }}), so the intermediate state is misleading and could surface raw templates if a future reader consumed route labels earlier in the flush ctx. Consider dropping Line 811 and relying solely on the per-batch render.♻️ Suggested change
ctx = notify.WithGroupKey(ctx, ag.GroupKey()) ctx = notify.WithGroupLabels(ctx, ag.labels) - ctx = notify.WithRouteLabels(ctx, ag.opts.Labels) ctx = notify.WithReceiverName(ctx, ag.opts.Receiver)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@dispatch/dispatch.go` around lines 808 - 839, The context setup in AggregationGroup.flush is storing route labels twice, but the earlier notify.WithRouteLabels(ctx, ag.opts.Labels) is always overwritten by the later per-batch render inside the flush callback. Remove the initial raw ag.opts.Labels assignment and keep only the rendered ag.renderRouteLabels(alerts...) value so route labels are sourced from the batch-specific render path and no unrendered templates are placed in context.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@dispatch/dispatch.go`:
- Around line 808-839: The context setup in AggregationGroup.flush is storing
route labels twice, but the earlier notify.WithRouteLabels(ctx, ag.opts.Labels)
is always overwritten by the later per-batch render inside the flush callback.
Remove the initial raw ag.opts.Labels assignment and keep only the rendered
ag.renderRouteLabels(alerts...) value so route labels are sourced from the
batch-specific render path and no unrendered templates are placed in context.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 31538433-73a4-4aab-8beb-ba4d2c91e8fd
📒 Files selected for processing (20)
api/v2/api.goapi/v2/api_test.goapi/v2/models/alert_group.goapi/v2/openapi.yamlapi/v2/restapi/embedded_spec.goapp/reloader.goconfig/config.goconfig/config_test.godispatch/dispatch.godispatch/dispatch_bench_test.godispatch/dispatch_test.godispatch/route.godispatch/route_test.godocs/configuration.mdnotify/context.gonotify/jira/jira_test.gonotify/util.gonotify/util_test.gotemplate/template.gotemplate/template_test.go
siavashs
left a comment
There was a problem hiding this comment.
Left a few comments, otherwise LGTM
add the RouteLabels data field and the routeLabels function to docs/notifications.md, an inheritance/override example in docs/configuration.md, and a standalone doc/examples/route_labels.yml. Signed-off-by: Guido Trotter <[email protected]>
Signed-off-by: Guido Trotter <[email protected]>
The "resolved" naming was easy to confuse with resolved alerts, even though the flag only tracks whether route label templates have already been rendered. Rename MarkRouteLabelsResolved -> MarkRouteLabelsRendered, the routeLabelsResolved field, and related locals/tests accordingly. Signed-off-by: Guido Trotter <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
ui/app/src/Views/AlertList/Views.elm (1)
113-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce the positional surface of
alertGroup.These two adjacent
Labelsparameters are now easy to swap accidentally, and Elm will not catch it because both have the same type. Passing a record (or theAlertGroupitself) would make the newrouteLabelscontract much harder to misuse at Lines 101 and 107.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ui/app/src/Views/AlertList/Views.elm` around lines 113 - 114, The alertGroup function now has two adjacent Labels arguments that are easy to swap because they share the same type, so reduce the positional API surface. Update alertGroup to take a single record or the AlertGroup value instead of separate labels and routeLabels parameters, then adjust the call sites in the alert rendering flow to pass that structured value and use its fields inside alertGroup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@ui/app/src/Views/AlertList/Views.elm`:
- Around line 113-114: The alertGroup function now has two adjacent Labels
arguments that are easy to swap because they share the same type, so reduce the
positional API surface. Update alertGroup to take a single record or the
AlertGroup value instead of separate labels and routeLabels parameters, then
adjust the call sites in the alert rendering flow to pass that structured value
and use its fields inside alertGroup.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 6132eb66-0eab-4419-b953-ba7342b668bd
📒 Files selected for processing (11)
doc/examples/route_labels.ymldocs/configuration.mddocs/notifications.mdnotify/util.gonotify/util_test.gotemplate/template.gotemplate/template_test.goui/app/src/Data/AlertGroup.elmui/app/src/Views/AlertList/Updates.elmui/app/src/Views/AlertList/Views.elmui/mantine-ui/src/data/groups.ts
✅ Files skipped from review due to trivial changes (4)
- docs/notifications.md
- doc/examples/route_labels.yml
- docs/configuration.md
- notify/util_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- template/template_test.go
Alertmanager v0.34.0 added templatable route labels, inherited by child routes and exposed to notification templates via `routeLabels` (prometheus/alertmanager#5328). Render them for `spec.route.labels` and nested routes, keep them at the base config root route, and reject invalid label names when parsing routes.
Alertmanager v0.34.0 added templatable route labels, inherited by child routes and exposed to notification templates via `routeLabels` (prometheus/alertmanager#5328). Render them for `spec.route.labels` and nested routes, keep them at the base config root route, and reject invalid label names when parsing routes.
Alertmanager v0.34.0 added templatable route labels, inherited by child routes and exposed to notification templates via `routeLabels` (prometheus/alertmanager#5328). Render them for `spec.route.labels` and nested routes, keep them at the base config root route, and reject invalid label names when parsing routes.
Alertmanager v0.34.0 added templatable route labels, inherited by child routes and exposed to notification templates via `routeLabels` (prometheus/alertmanager#5328). Render them for `spec.route.labels` and nested routes, keep them at the base config root route, and reject invalid label names when parsing routes.
Alertmanager v0.34.0 added templatable route labels, inherited by child routes and exposed to notification templates via `routeLabels` (prometheus/alertmanager#5328). Render them for `spec.route.labels` and nested routes, keep them at the base config root route, and reject invalid label names when parsing routes.
….1 ➔ v0.34.0) (#224) This PR contains the following updates: | Package | Update | Change | |---|---|---| | [quay.io/prometheus/alertmanager](https://github.com/prometheus/alertmanager) | minor | `v0.33.1` → `v0.34.0` | --- >⚠️ **Warning** > > Some dependencies could not be looked up. Check the [Dependency Dashboard](issues/13) for more information. --- ### Release Notes <details> <summary>prometheus/alertmanager (quay.io/prometheus/alertmanager)</summary> ### [`v0.34.0`](https://github.com/prometheus/alertmanager/releases/tag/v0.34.0): 0.34.0 / 2026-08-16 [Compare Source](prometheus/alertmanager@v0.33.1...v0.34.0) - \[CHANGE] notify: The `reason` label on `alertmanager_notifications_failed_total` now distinguishes `authError` (HTTP 401/403) and `rateLimited` (HTTP 429) from the generic `clientError`. Dashboards/alerts matching `reason="clientError"` for these codes must be updated. [#​5332](prometheus/alertmanager#5332) - \[FEATURE] Add optional templatable labels to alert routes. [#​5328](prometheus/alertmanager#5328) - \[FEATURE] eventrecorder: Add inhibit rule names to `inhibition_muted_alert` events. [#​5315](prometheus/alertmanager#5315) - \[FEATURE] eventrecorder: Add stdout output type. [#​5311](prometheus/alertmanager#5311) - \[FEATURE] silences: Add active, expired, and pending boolean filter parameters to GET /api/v2/silences to allow filtering silences by state server-side. [#​5406](prometheus/alertmanager#5406) - \[FEATURE] sns: Add aws `external_id` support in sigv4 configuration. [#​5157](prometheus/alertmanager#5157) - \[FEATURE] template: Add `toDate` and `mustToDate` functions. [#​5327](prometheus/alertmanager#5327) - \[ENHANCEMENT] doc: Add AlertmanagerClusterFailedPeers alertmanager-mixin. [#​5301](prometheus/alertmanager#5301) - \[ENHANCEMENT] doc: Add description for Rocketchat parameters in global config. [#​5181](prometheus/alertmanager#5181) - \[ENHANCEMENT] doc: Add top level tracing configuration key. [#​5314](prometheus/alertmanager#5314) - \[ENHANCEMENT] doc: Fix Alertmanager port in amtool config routes example. [#​5312](prometheus/alertmanager#5312) - \[ENHANCEMENT] eventrecorder: Add optional webhook batching. [#​5392](prometheus/alertmanager#5392) - \[ENHANCEMENT] notify: The discord and webex integrations now report a failure `reason` on `alertmanager_notifications_failed_total`. [#​5332](prometheus/alertmanager#5332) - \[ENHANCEMENT] ui: Improve responsiveness of UI when loading thousands of alerts. [#​5357](prometheus/alertmanager#5357) - \[BUGFIX] eventrecorder: Fixed a minor performance regression when the event recorder is enabled. [#​5307](prometheus/alertmanager#5307) - \[BUGFIX] msteamsv2: Inherit global `proxy_url` into partial `http_config`. [#​5379](prometheus/alertmanager#5379) - \[BUGFIX] webhook: Keep custom `payload` string values verbatim instead of reinterpreting JSON leaves that look like YAML (e.g. values ending with a colon). [#​5304](prometheus/alertmanager#5304) </details> --- ### Configuration 📅 **Schedule**: (in timezone America/Toronto) - Branch creation - At any time (no schedule defined) - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4zMC40IiwidXBkYXRlZEluVmVyIjoiNDQuMzIuMiIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsicHJpb3JpdHkvbWVkaXVtIiwicmVub3ZhdGUvY29udGFpbmVyIiwidHlwZS9taW5vciJdfQ==--> Reviewed-on: https://git.dcunha.io/Exikle/frostlink/pulls/224
This change adds templatable lables to a Route, which are then inherited and overridable in children routes.
These are shared with notifiers, and also available via the /groups call, and thus can be displayed consistently between the notifications and the UI. They are calculated on the fly at notification time, and calculated but then cached on Groups() calls. When the alerts list is changed, in the dispatcher, the cache is invalidated.
Pull Request Checklist
Please check all the applicable boxes.
Which user-facing changes does this PR introduce?