# Alerts

**Last updated:** 2026-11-26T00:47:12-03:00 (UTC-3)

Send alerts when a team crosses a budget threshold, a guardrail blocks a request, an MCP server fails its health check, or someone creates or revokes a key. PostgreSQL stores delivery state for Slack, Microsoft Teams, email, PagerDuty and webhooks, with bounded retries and recovery after a replica stops.

| Flag | What it turns on |
| --- | --- |
| `alert_channels` | Delivery and reading of channels |
| `alert_channel_management` | Creating, testing, and resending from the console and the API |
| `alert_digests` | Default off; additive durable periodic summaries for channels whose `digest.enabled` is true; requires `alert_channels` |
| `operational_alerts` | The [operational events](#operational-events): open circuit, provider errors or latency, database down, usage write, secret manager and telemetry export failures (requires `alert_channels`) |
| `alert_rules` | Default off; [alert rules](/docs/features/alert-rules/): rules you configure over the request log and the stored spans, the Alerts screen, a backtest and built-in rules. Their alerts are delivered by the channels below |
| `alert_signing_rotation` | Default off; [rotate a webhook signing secret](#rotate-a-webhook-signing-secret) with an overlap in which every delivery carries a signature with the new and with the previous secret (requires `alert_channels`) |

## Events

| Event | When |
| --- | --- |
| `quota_budget_threshold` | A budget crosses one of the `alert_thresholds` (see [budget alerts](/docs/features/quota-governance/#soft-budget-and-alerts)) |
| `quota_reservation_overrun` | A provider billed more, in tokens or USD, than a [budget or TPM](/docs/features/budgets-and-tpm/) reservation bounded; the excess is debited in full. One event per reservation by default, written in the settlement's own transaction so a burst loses none: each names its reservation, request, model and the reserved and measured amounts. The [quota settings](/docs/features/budgets-and-tpm/#quota-settings) can raise it only above a tolerance, or fold overruns with the same model and set of billed policy subjects into bounded events; queued events are immutable, so later overruns create a new event |
| `customer_budget_crossed` | A [customer portal](/docs/features/customer-portal/) organization, team or member reaches one of its alert thresholds; once per level, window and threshold, with the team, organization, level, customer ID, threshold, budget and committed USD |
| `customer_override_requested` | A [customer portal](/docs/features/customer-portal/#override-approval-requests) member override request awaits a decision; with the team, organization, member, request ID, amount, expiry and requester |
| `customer_override_decided` | That request was approved or denied; with the same fields, the state and who decided |
| `guardrail_blocked` | A [guardrail](/docs/features/guardrails/) blocks a request |
| `evaluator_health_changed` | With [evaluation tracing](/docs/features/evaluation-tracing/#evaluator-health-and-cost): a judge run leaves an evaluator blocked (the evaluator was auto-paused) or degraded (judge errors); with the team, the evaluator, the state and the reason code; one per evaluator and state per hour |
| `mcp_health_failed` | The health check of an [MCP](/docs/features/mcp-execution/) server fails |
| `key_created`, `key_revoked`, `key_deleted` | A key is created, revoked, or deleted |
| `model_follow_changed` | A [moving model alias](/docs/features/model-aliases/#moving-aliases-follows) starts serving another model, or no model, after a configuration change; one event per change and control version across replicas, with the previous and new model and upstream model |
| `evaluation_monitor_alert`, `evaluation_monitor_recovered` | With [`evaluation_monitors`](/docs/features/evaluation-monitors/): a monitor entered warning or alert (also each renotification and a test notification), or returned to OK. The payload carries a typed `monitor` object with the value, the threshold, the window and a link to the matching traces. Subscribing only makes the channel selectable by the monitors of the teams in `rule_teams` and of the organizations in `rule_organizations`: an event goes to the channels its monitor names, never to every subscriber |
| `rate_limit_would_limit` | With [`rate_limit_observe_mode`](/docs/features/rate-limits/#observe-only-policies): an observe-only rate policy admitted a request past its limit; at most one event per policy every 15 minutes, with the policy, its subject, limit and window |
| `prompt_created`, `prompt_version_published`, `prompt_deleted` | With [`prompt_events`](/docs/features/prompt-registry/#prompt-events): a prompt was created (in the console, through the admin API, by a team-delegated write, or added to the YAML file), a revision was published, or a console prompt was deleted. Written once per change, in the change's own transaction, whatever path made it; the detail holds `prompt_id`, `team`, `organization`, `revision`, `previous_revision`, `name`, `path` (`console`, `api`, `yaml`), `actor` and `request_id`, never the prompt's text |
| `prompt_label_deployed` | With [`prompt_labels`](/docs/features/prompt-registry/#labels-and-deploy-to): Deploy to moved a prompt label to a revision; the detail names the label, the revision and the previous one |
| `alert_rule` | With [`alert_rules`](/docs/features/alert-rules/): an alert of a rule fired (`state: firing`) or was resolved (`state: resolved`). Subscribing only makes the channel selectable by rules: an alert goes to the channels its rule names, never to every subscriber |
| `provider_circuit_open`, `provider_error_rate`, `provider_slow`, `database_down`, `usage_write_failures`, `secret_manager_failures`, `telemetry_export_drops` | With `operational_alerts`: a condition starts (`state: firing`) or ends (`state: resolved`); see [operational events](#operational-events) |

Events contain bounded metadata, not prompts, responses or credentials. An overrun is one event per reservation by default. With a deduplication window, folding requires the same model and the same set of billed policy subjects; two different owners are never combined. Once any channel queues an event, its details stop changing. A later overrun, or a full metadata list, starts another event. See [quota settings](/docs/features/budgets-and-tpm/#quota-settings).

## Key expiry notices

The optional key_expiry_warnings operator flag produces key_expiring and key_expired for current managed credentials with an explicit deadline. Never credentials produce neither. Thresholds, interval, timeout and batch size are configurable through security.key_lifecycle and the guarded API/console policy editor. A transactional generation/expiry/threshold identity deduplicates notices across replicas; delivery reuses this outbox and configured channels. Notices contain safe identity/deadline and request/trace correlation, never the secret, confirmation nonce or arbitrary tag values. See [key policy](/docs/features/key-policy/#expiry-notifications) for defaults, recovery and exact bounds.

## Operational events

With `features.operational_alerts` (off by default; it requires `alert_channels`), every replica evaluates its own state once per `interval` in the background and records an event when a condition **changes state**. They watch the same signals as the [Prometheus alert rules](/docs/features/observability/#alert-rules), for installations that have no Prometheus or want the gateway's channels too, but per replica, over the evaluation interval and without a `for` delay, so they are faster and noisier than the rules.

| Event | Subject | Firing when (per interval) | Detail |
| --- | --- | --- | --- |
| `provider_circuit_open` | `provider/model` | a circuit-breaker destination is open or half open (waiting for its trial call) | `open_destinations` |
| `provider_error_rate` | provider ID | failed attempts / attempts ≥ `provider_error_ratio`, with at least `provider_min_attempts` attempts | `error_ratio`, `attempts`, `threshold` |
| `provider_slow` | provider ID | p95 latency to response headers > `provider_slow_p95`, with at least `provider_min_attempts` answers | `p95_seconds`, `threshold_seconds` |
| `database_down` | `postgresql` | this replica's PostgreSQL ping fails within `storage.database.acquire_timeout`; a pool saturated past that timeout also counts | none |
| `usage_write_failures` | `usage` | at least one usage record could not be written | `failures` |
| `secret_manager_failures` | `secret_manager` | a secret from the [secret manager](/docs/operate/secret-managers/) failed its last refresh | `failing_secrets` |
| `telemetry_export_drops` | `logs`, `traces` or `metrics` | the OTLP exporter dropped records | `dropped` |

Every event carries `state` (`firing` or `resolved`) and `replica` (the host name of the replica that judged it); a resolved one also carries `firing_since`, and `reason: no_traffic` when a provider stopped receiving traffic. Failed attempts are transport errors and timeouts, invalid answers, 5xx and 429; client cancellations are not counted.

```yaml
features:
  alert_channels: true
  operational_alerts: true
alerting:
  operational:
    interval: 1m              # 10s-15m: evaluation period and measurement window
    cooldown: 15m             # 1m-24h: minimum time between two events of one condition and subject
    provider_error_ratio: 0.2 # 0.01-1
    provider_min_attempts: 20 # 1-100000: below it, ratio and latency are not judged
    provider_slow_p95: 30s    # 1s-2m (the last finite latency bucket)
  channels:
    - id: oncall
      name: On-call
      kind: pagerduty
      url_env: ONCALL_PAGERDUTY_URL
      events: [provider_circuit_open, provider_error_rate, database_down, usage_write_failures]
```

Every field shown is its default; leave it out to keep it. The values are read at every evaluation, so a configuration reload applies from the next one without a restart. `GET /api/v1/admin/alert-channels` returns them under `alerting.operational` (next to `alerting.signing_overlap`) with their source (`yaml` or `default`), and **Alert channels** in the console shows them under the event list.

How it behaves:

- **Transitions only.** A condition that stays down records nothing more.
- **Low traffic.** A provider with fewer than `provider_min_attempts` attempts (or answers, for latency) in an interval is not judged: its attempts accumulate over up to 10 intervals until there are enough, and older ones are dropped. An interval with no traffic at all resolves a firing provider condition (`reason: no_traffic`), for example after failover or removal from the configuration.
- **Rate limited.** Two `firing` events of the same condition and subject are at least `cooldown` apart; a `resolved` is sent as soon as it is observed, so a short incident is not left open. A flapping condition gives at most one `firing` and one `resolved` per cooldown; when the cooldown ends, the current state is reported if it differs from the last one sent, so the channel always converges.
- **Per replica, deduplicated.** Each replica judges its own breakers, traffic and database connection, so each reports its own transitions: with three replicas, an outage they all see gives three `firing` events. The event key contains the condition, subject, replica, state and cooldown bucket, so a retried write is recorded once.
- **Never on the request path.** Requests only increment counters; evaluation and writes run in their own goroutine, each write bounded by 2 s.
- **Only what someone subscribed to.** A transition that no enabled channel subscribes to is not written. Turning the flag off forgets every state, so turning it on again starts clean.
- **Database outages.** The outbox is in PostgreSQL. An event that cannot be written waits in a queue of 64 per replica (the oldest is dropped past that, with an `operational_alerts_dropped` log). `database_down` is therefore delivered once the database is back, followed by its `resolved` at the next evaluation. For live paging on an outage, use the `GatewayDatabaseDown` rule.
- **PagerDuty:** firing triggers and resolved resolves one incident per replica, with `dedup_key` `<event>:<subject>:<replica>`.
- **State is in memory.** A restart, or turning the flag off, forgets what was firing: a condition that ends meanwhile sends no `resolved`, so close such an incident by hand. Deliveries are retried independently, so a destination can receive a retried `firing` after its `resolved`.

## How to turn it on

```yaml
features:
  alert_channels: true
  alert_channel_management: true
alerting:
  allowed_private_cidrs: []   # allowed destinations on a private network (e.g., an internal webhook)
  allow_loopback_http: false  # local testing only
  channels:
    - id: finance-slack
      name: Finance Slack
      kind: slack              # slack | teams | webhook | email | pagerduty
      url_env: FINANCE_SLACK_WEBHOOK_URL
      events: [quota_budget_threshold]
    - id: siem
      name: SIEM
      kind: webhook
      url_env: SIEM_WEBHOOK_URL
      signing_secret_env: SIEM_WEBHOOK_SECRET
      events: [quota_budget_threshold, key_created, key_revoked]
```

| Key | Default | What it does |
| --- | --- | --- |
| `channels[].id` | required | Lower-case identifier, up to 64 characters |
| `channels[].name` | required | Display name of the channel, 1–80 characters without control characters or surrounding spaces |
| `channels[].kind` | required | `slack`, `teams`, `webhook`, `email` or `pagerduty` (see below) |
| `channels[].url_env` | required | Variable holding the destination URL, which is a secret |
| `channels[].signing_secret_env` | empty | Webhooks only: variable holding the secret that signs each delivery |
| `channels[].events` | required | The events the channel receives |
| `channels[].disabled` | `false` | Stops deliveries without removing the channel |
| `channels[].headers` | empty | Webhooks only, with `alert_webhook_headers`: up to 10 headers sent with every delivery, each `name` with `value` or `value_env` ([below](#send-your-own-headers)) |
| `channels[].rule_organizations`, `channels[].rule_teams` | empty | With the `alert_rule` event: the organizations and teams (up to 64 each) whose administrators may attach the channel to their own [alert rules](/docs/features/alert-rules/#open-a-channel-to-the-rules). Global rules may use any channel with the event |

`allowed_private_cidrs` and `allow_loopback_http` take effect at startup.

**In the console:** **Alert channels** creates channels whose URL and signing secret are **encrypted** with the control plane key (`storage.provider_encryption_key_env`). No read returns the URL or the secret, only the origin (`https://host`). **Test** sends a synthetic message right away. The API is `PUT /api/v1/admin/alert-channels/{id}`. Channels from the YAML cannot be edited in the console.

### By channel type

| Type | Configuration | What it receives |
| --- | --- | --- |
| `slack`, `teams` | Incoming webhook URL | `{"text": ...}` |
| `webhook` | Any HTTPS URL; `signing_secret_env` optional | `{event, delivery_id, sent_at, alert, message}` |
| `email` | `smtps://user:pass@smtp.example.com:465?from=gw@example.com&to=finops@example.com` | One email per alert. `smtp://` requires STARTTLS |
| `pagerduty` | `https://events.pagerduty.com/v2/enqueue?routing_key=<integration key>` | One event; the `dedup_key` is the delivery ID, `<event>:<subject>:<replica>` for [operational events](#operational-events) or `alert_rule:<alert id>` for [alert rules](/docs/features/alert-rules/), whose `resolved` resolves the incident |

**Webhook signature:** with a secret, every delivery carries `X-Gateway-Signature: t=<unix>,v1=<hex>`, the HMAC-SHA256 of `t + "." + body`. Verify the signature and the timestamp before you trust the content.

### Verify a webhook delivery

`t` is the time of **this attempt**, not of the alert: a retry hours later carries a fresh `t` and a fresh signature over the same body. A receiver should:

1. Split the header on `,`. Take `t`, and every `v1` entry (there are two during a [rotation](#rotate-a-webhook-signing-secret)).
2. Refuse the delivery when `|now - t|` is more than its tolerance. **300 seconds** is a good default; the gateway's own send timeout is 10 seconds, so the tolerance only has to cover clock skew.
3. Compute `hex(HMAC-SHA256(secret, t + "." + raw_body))` over the raw bytes, before any JSON parsing, and accept when it equals **any** `v1` entry, compared in constant time.
4. Discard a repeated `Idempotency-Key` (`<channel>:<alert>`); within the tolerance that also stops a replayed request.

```python
import hashlib, hmac, time

def verify(header: str, body: bytes, secrets: list[bytes], tolerance: int = 300) -> bool:
    parts = [p.split("=", 1) for p in header.split(",")]
    stamp = next((v for k, v in parts if k == "t"), "")
    signatures = [v for k, v in parts if k == "v1"]
    if not stamp.isdigit() or abs(time.time() - int(stamp)) > tolerance:
        return False
    for secret in secrets:
        expected = hmac.new(secret, stamp.encode() + b"." + body, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, s) for s in signatures):
            return True
    return False
```

### Send your own headers

Some receivers want a header of their own: a bearer token, an API key, a tenant or routing header. With the operator flag `alert_webhook_headers` (off by default; requires `alert_channels`), a `webhook` channel sends up to 10 headers with every delivery, test notifications included:

```yaml
features:
  alert_webhook_headers: true
alerting:
  # The variables a channel made in the console may name. A channel declared
  # here in YAML may name any variable: you write both.
  webhook_header_envs: [SIEM_TOKEN]
  channels:
    - id: siem
      name: SIEM
      kind: webhook
      url_env: SIEM_WEBHOOK_URL
      events: [key_created, key_revoked]
      headers:
        - name: Authorization
          value_env: SIEM_TOKEN        # the variable holds "Bearer ..."
        - name: X-Source
          value: ai-gateway
```

| Key | What it does |
| --- | --- |
| `headers[].name` | An HTTP header name, 1–64 characters. Names the gateway or HTTP set cannot be used: `Content-Type`, `Content-Length`, `Content-Encoding`, `Host`, `User-Agent`, `Idempotency-Key`, `traceparent`, `tracestate`, `baggage`, `Cookie`, the hop-by-hop headers and any `X-Gateway-*`; a name may appear once |
| `headers[].value` | A plain value: up to 1,024 visible ASCII characters, no line break. Shown by the API and the console, so never a secret: a name that looks like a credential (`Authorization`, `Proxy-Authorization`, or one containing `token`, `secret`, `key`, `auth`, `password`, `signature`, `session` or `credential`) is refused with a plain value |
| `headers[].value_env` | The name of the gateway's environment variable that holds the value, read at each send. The API and the console show the name and whether it is set, never the value |
| `alerting.webhook_header_envs` | The variables a console channel may name in `value_env` (up to 64; default none). Read with the configuration |

- **The secret stays out of the API.** A value read from a variable is never stored, logged or returned; the channel list reports only `header_status` (`set`, `allowed`) per header.
- **Missing value, no delivery.** When a variable is unset, holds a value that is not safe in a header, or (for a console channel) is no longer listed in `webhook_header_envs`, the delivery fails with `credentials_unavailable` and is retried: the gateway never sends without the header the receiver expects.
- **In the console**, **Alert channels → Edit** lists the headers the gateway always sends, read-only, and lets you add rows of a name and a plain value or a variable name; a credential typed as a plain value is refused before it is saved. The API takes the same `headers` in `PUT /api/v1/admin/alert-channels/{id}`.
- **Flag off:** headers are kept but not sent, and a write cannot add or change them; a channel's other fields stay editable.

### Rotate a webhook signing secret

With `alert_signing_rotation` on, a secret can change without any delivery failing at a receiver that has not switched yet. During the overlap every delivery carries two entries, the new secret first:

```text
X-Gateway-Signature: t=1763300000,v1=<hex with the new secret>,v1=<hex with the previous secret>
```

A receiver that holds either secret accepts it (step 3 above). Install the new secret at the receiver during the overlap, then end it.

**Console channels.** Edit the channel, type the new secret and tick **Rotate**. The API is the same `PUT /api/v1/admin/alert-channels/{id}` with `"signing_secret": "<new>", "rotate_signing_secret": true`. The stored secret becomes the previous one and keeps signing for `alerting.signing_overlap`, measured on the database clock so every replica stops at the same instant. **End the overlap now** (`"end_signing_overlap": true`) drops the previous secret early; it works with the flag off too, so an overlap can always be cut short.

| Field | Default | Bounds | Notes |
| --- | --- | --- | --- |
| `alerting.signing_overlap` | `24h` | `5m`–`720h` | Read when a rotation starts; changing it does not move the end of an overlap already running |

- Rotating needs a stored secret (`409 no_signing_secret`) and a new one (`400`); with the flag off it is refused (`403 feature_disabled`).
- A second rotation during an overlap retires the older previous secret: only the newest two sign.
- A new secret **without** `rotate_signing_secret` replaces the current one at once and drops any overlap, as before; so does removing the secret or changing the channel type.
- Both secrets are encrypted with the control-plane key and included in [provider secret re-encryption](/docs/security/keyring-rotation/). The list shows only whether a previous secret overlaps and until when (`previous_signing_secret_configured`, `previous_signing_secret_until`), never a value. Each rotation is audited as `alert_channel.rotate_signing_secret`, and an early end as `alert_channel.end_signing_overlap`. Once an overlap ends, the dispatcher removes the retired ciphertext from storage within one cycle (10 s).
- Turning the flag off stops the second signature on the next delivery; the stored previous secret still expires on time.

**YAML channels.** Set `previous_signing_secret_env` to the variable that holds the secret being retired, and `signing_secret_env` to the new one; restart. Deliveries carry both signatures while the variable is set and the flag is on. Remove `previous_signing_secret_env` to end the overlap. It must differ from `signing_secret_env`.

```yaml
alerting:
  channels:
    - id: siem
      name: SIEM
      kind: webhook
      url_env: SIEM_WEBHOOK_URL
      signing_secret_env: SIEM_WEBHOOK_SECRET_2026_11
      previous_signing_secret_env: SIEM_WEBHOOK_SECRET_2026_05
      events: [quota_budget_threshold]
```

**Upgrade:** schema migration 168 adds two nullable columns; older replicas ignore them and keep signing with the current secret only, so finish the rollout before rotating.

## How delivery works

- Alerts sit in a queue in PostgreSQL. Each replica checks the queue every 10 s; a delivery is attempted by one replica at a time and picked up again if that replica goes down.
- Every attempt carries `Idempotency-Key: <channel>:<alert>` and `X-Gateway-Event`, so the destination can discard repeats. Delivery is at least once: a destination may receive a duplicate if it accepted a request but the acknowledgment was lost.
- **Success:** HTTP 2xx.
- **Retried:** network error, timeout, 408, 429, 5xx (and 4xx from the mail server), with a 30 s wait that doubles up to 1 h, for up to 8 attempts.
- **Fails immediately:** other 4xx (and 5xx from the mail server) and a refused destination. **Retry**, in the console, requeues it.
- A new channel only receives alerts created **after** it; the history is not dumped into it.

**SSRF protection:** HTTPS is required; every resolved address is validated and dialed directly. Loopback, link-local, special ranges, and private networks (outside `allowed_private_cidrs`) are refused before connecting. Redirects are not followed.

## Limits

- Periodic digests summarize eligible queued alerts; they are not spend reports, invoices or proof of complete source history. Provider failures are [operational events](#operational-events), judged per replica.
- Delivery history has no automatic retention.
- Metric: `gateway_alert_deliveries_total{channel,outcome}` at `/metrics`.

## Admin API routes

Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/).

| Route | What it does |
| --- | --- |
| `POST /api/v1/admin/alert-channels/{id}/test` | Sends one synthetic message to the channel now, bounded to 10 seconds |
| `GET /api/v1/admin/alert-deliveries` | The delivery outbox, newest first, with each delivery's state and attempts |
| `POST /api/v1/admin/alert-deliveries/{channel}/{alert}/retry` | Queues a failed delivery again with a fresh attempt budget |

## See also

- [Alert rules and the Alerts screen](/docs/features/alert-rules/).
- [Budgets and TPM](/docs/features/budgets-and-tpm/).
- [Logs, traces, and metrics](/docs/features/observability/).

## Channel name schema

The existing YAML, API and console channel workflow uses names of `1`–`80` Unicode code points (Go runes), without leading/trailing whitespace or control characters. The console preserves valid names containing supplementary Unicode characters; it does not truncate them by UTF-16 code-unit length. The server remains authoritative for invalid-name rejection. Channel IDs retain their existing ASCII pattern and maximum `64` characters. Channel targets and signing references remain private, with the existing version, authorization and audit rules.

## Periodic additive digests

Enable `features.alert_digests` (default `false`, requiring `alert_channels`) and opt a channel in with `digest.enabled: true`. Individual budget, overrun and operational notifications continue through their original outbox. A digest never suppresses, acknowledges or replaces them. This is an operator feature; the global alert permissions, encrypted destinations, CSRF, trust rules and retries still apply.

```yaml
features:
  alert_channels: true
  alert_digests: true
alerting:
  channels:
    - id: finance-summary
      name: Finance alerts and summary
      kind: webhook
      url_env: FINANCE_WEBHOOK_URL
      events: [quota_budget_threshold, quota_reservation_overrun]
      digest:
        enabled: true
        interval: 24h
        max_alerts: 100
```

| Field | Default | Bounds / meaning |
| --- | --- | --- |
| `digest` | Absent | Existing individual-only behavior; no serialized member is added to an unchanged channel |
| `digest.enabled` | `false` | Opts this channel into additional periodic summaries |
| `digest.interval` | `24h` | Whole-second Go duration from1m to168h; omit or use an empty string for the default |
| `digest.max_alerts` | `100` | Effective1–500 source references per snapshot; omitted or raw0 uses100; overflow remains for later bounded batches |

Use the same `digest` object in `PUT /api/v1/admin/alert-channels/{id}` or **Alert channels** in the console. The existing global `version` protects edits; blank secrets retain their encrypted values. YAML channels remain operator-owned and read-only in the console. A policy may be staged while the global flag is off, with its inactive state shown. The flag never grants administrative rights.

### API update example

For an existing **console-created** channel, reuse its current destination without sending it again. Supply your authenticated session cookie file and CSRF token, and the actual channel ID; the command reads the current control version before saving. An intervening edit returns409 for review rather than overwriting it. YAML-owned channels return409 and are edited in YAML.

```sh
BASE_URL='http://localhost:8080'
: "${COOKIE_JAR:?Set the authenticated console cookie file}"
: "${CSRF_TOKEN:?Set the session CSRF token}"
: "${CHANNEL_ID:?Set an existing console-created channel ID}"
export CHANNEL_ID
VERSION=$(curl --fail-with-body -sS -b "$COOKIE_JAR" \
  "$BASE_URL/api/v1/admin/alert-channels" | \
  python3 -c 'import json,sys; print(json.load(sys.stdin)["version"])')
export VERSION
python3 -c 'import json,os; json.dump({"version":int(os.environ["VERSION"]),"channel":{"id":os.environ["CHANNEL_ID"],"name":"Finance alerts and summary","kind":"webhook","events":["quota_budget_threshold","quota_reservation_overrun"],"disabled":False,"digest":{"enabled":True,"interval":"24h","max_alerts":100}}},__import__("sys").stdout)' | \
  curl --fail-with-body -sS -b "$COOKIE_JAR" -X PUT \
    -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \
    --data-binary @- "$BASE_URL/api/v1/admin/alert-channels/$CHANNEL_ID"
```

This replaces that channel's name, kind, subscriptions and digest policy. Set the fields to your reviewed values before running it; leaving out `url` and the signing-secret fields preserves the encrypted values. It does not turn on the global feature flag. Use the existing feature API or **Settings & sources** to enable `alert_digests` separately.

### Windows, ownership and incomplete history

First activation starts a durable observation window in PostgreSQL. Original alerts from before activation are excluded, including old alerts whose individual enqueue was delayed. Windows are rolling intervals with explicit UTC timestamps; they are not calendar, billing or budget periods. Digests consume only already queued immutable source alerts. The existing individual enqueue scans at most500 alerts per event type per pass and has a7-day original-event eligibility horizon; a digest does not certify recovery of alerts never enqueued inside that horizon.

Each snapshot belongs to one exact owner/group. Budget threshold alerts group by exact subject kind and ID. When an overrun's owner cannot be proven from its durable source, it remains isolated by that source event's identity; a shared model name never combines owners. Other event groups preserve their provable event/subject/team boundary. Counts describe included source alerts, without adding financial amounts or implying ledger settlement.

PostgreSQL locks the channel cursor and commits snapshot, source memberships and outbox row together. Unique membership prevents an alert entering another snapshot for that channel. Late committed rows remain eligible rather than disappearing behind a moving timestamp cursor. Each snapshot is additionally capped at192KiB compact JSON, leaving reserve below the256KiB PostgreSQL JSONB text ceiling. Long metadata can therefore produce multiple parts with fewer than `max_alerts` sources, each preserving the exact group/window. A full batch leaves the closed window pending until its remaining eligible rows drain; no remainder is silently dropped. Empty windows send no message. Missing source proof produces an explicit failure, never an invented empty or complete report.

### Pause, edits, delivery and recovery

Turning off `alert_digests`, disabling the channel or setting `digest.enabled: false` pauses digest materialization and claims **before** incrementing attempts or leases. Existing individual deliveries retain their own behavior. An attempt already admitted under a captured configuration may finish; disabling is not a recall of an in-flight notification. Cursor, membership, frozen snapshots and failures survive restart. Reenabling resumes bounded catch-up of eligible alerts after first activation, including alerts queued while paused; it does not reset history or replay already included sources. Interval/maximum-size edits take effect in the next window after the current captured-policy window drains. Pending snapshots never change. Reusing an existing channel ID preserves its existing pending history; use a new ID for a separate destination history.

Digests reuse the existing at-least-once retries. Their stable delivery ID and `Idempotency-Key` let a destination discard repeats after a lost acknowledgment. A delivery is not externally exactly once. Manual retry does not bypass disabled dispatch. As for individual alerts, a pending delivery uses the channel's current approved destination and secret; changing that destination does not rewrite its snapshot.

The generic webhook envelope has `event: alert_digest`, `delivery_id`, `sent_at`, `message` and `digest`. The immutable `digest` contains `id`, `channel_id`, `window_start`, `window_end`, `alert_count`, `group_type`, `group_id`, `sources`, `request_id` and `traceparent`. Each source has `id`, `event`, original `subject`, `created_at`, and optional safely available `request_id`/`trace_id`. `group_type` is `quota_subject/<subject>` with the exact subject ID, `event_subject_team/<event>` with compact JSON `[sourceSubject, explicitTeam]`, or `source_event` with the source alert ID when ownership cannot be proven. All overruns use that last conservative fallback. Sources and snapshots carry bounded metadata, without raw source details or amounts; the [OpenAPI contract](/docs/api/) includes their exact schemas. `alert_digest` cannot be selected in the subscription list, preventing summaries of summaries. Slack, Teams, email and PagerDuty receive a bounded summary using their existing transport. Every digest has a stable request ID/trace context for retries; its source IDs link back to the individual alerts. Payloads and secrets remain absent from telemetry.

Delivery history adds an optional `digest` summary containing `id`, `window_start`, `window_end`, `alert_count`, `group_type` and `group_id`; ordinary delivery records retain their shape. The console labels summaries separately and uses the same retry action. Channel delivery counts include individual notifications and digests, not unique financial incidents.

### Upgrade

Migration116 adds digest cursor, immutable snapshot and membership storage; it does not rewrite existing alert/ledger rows. Run the normal backup/migration procedure before the new gateway when automatic migration is off. Upgrade all replicas before enabling the flag or policy. Older binaries do not understand the new configuration or newer database version; rollback requires the established pre-upgrade backup/configuration procedure. No provider call, external scheduler or cache service is required.
