# Configuration

These instructions apply to the legacy Admin Console.

{% hint style="info" %}
Alerts are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that Alerts be enabled for your tenant.
{% endhint %}

All routes use the [authentication and tenant scope](https://docs.contextual.io/legacy/tenants/tenant-apis/alerts-api.md#base-url-and-authentication) described in the API overview. The four configuration resources are rules, subscriptions, destinations, and silences.

## CRUD Routes and Permissions

| Resource | Collection route | Permission prefix |
| --- | --- | --- |
| Rules | `/rules` | `contextual:alert-rules` |
| Subscriptions | `/subscriptions` | `contextual:alert-subscriptions` |
| Destinations | `/destinations` | `contextual:alert-destinations` |
| Silences | `/silences` | `contextual:alert-silences` |

Each collection supports `GET` (read) and `POST` (create). Each `/{id}` supports `GET` (read), `PUT` (update), and `DELETE` (delete). Append the verb to the permission prefix, for example `contextual:alert-rules:update`.

When you create or update a rule, the service derives and checks source-data read permissions regardless of any caller-supplied `requiredPermission`. Enabled metrics rules require a ready metrics enrollment. Reference and capability checks can impose additional requirements; a granted CRUD verb alone is not a guarantee that a particular body is accepted.

Successful create returns `201` and the record; get/update return `200` and the record; delete returns `204`. Read records flatten the resource fields alongside `_metaData`. Use `_metaData.id` as the resource identifier and `_metaData.hash` for concurrency. Destination records omit the URL credential.

### Pagination

Configuration collection reads accept `pageSize` (1–200), `pageToken`, and `includeTotal` (literal `true` or `false`). Responses contain `items`, optional `nextPageToken`, and optional `totalCount` when requested. Follow `nextPageToken` until exhausted. Only the listed pagination parameters are supported on configuration lists. Filters such as `since` or `severity` apply to alert history instead.

### Safe Writes

Ordinary POST creation uses server-generated IDs: omit `id`. Send the resource object itself, without a `data` wrapper or `_metaData`.

PUT is a complete replacement of writable configuration. Send `x-if-hash-match` with the hash from a fresh read on updates and deletes. The service supports unguarded writes, but automation should use the guard. A stale hash returns `412`; read and reconcile before retrying.

Destination updates must include the URL in `secret`. Ordinary reads omit it. To keep the existing URL, use a copy you stored or [reveal the destination URL](#reveal-a-destination-url). Explicit signing-key retrieval uses `POST /destinations/{id}/signing-key`, no body, and `contextual:alert-destinations:update`. The response includes the signing algorithm and the headers a generic webhook receiver uses to verify delivery.

### Reveal a Destination URL

`POST /destinations/{id}/webhook-url` retrieves the stored URL for either destination kind. It requires fresh organization membership, `contextual:alert-destinations:update`, and authoring availability. Unlike ordinary configuration writes, **`x-if-hash-match` is required**: read the destination and send its current `_metaData.hash`. Send no body or an empty JSON object.

The response contains `destinationId`, `webhookUrl`, and `hash`, with `Cache-Control: no-store`. Revealing the URL does not update the destination or rotate its signing key. Keep the response out of logs and support records.

Missing hash or invalid body returns `400`; an unknown destination returns `404`; a changed destination returns `412`; unavailable credential retrieval returns a sanitized `503`. On a conflict, read and review the destination again. Retry with the hash returned by that read.

## Resource Bodies

| Resource | Key fields |
| --- | --- |
| Rule | `name`, `source: clickhouse-metric`, `definitionKind: threshold`, `metricRefKind`, metric or query, comparator and threshold; window, for, severity, enabled |
| Subscription | Optional `ruleId` and label `matchers`; `targetKind: destination`, `destinationId`, `channels: ["webhook"]`, enabled, notifyOnResolve |
| Destination | `label`, `kind: webhook` or `slack-webhook`, `secret` omitted from ordinary responses; optional non-secret `config` |
| Silence | Nonempty `matchers`, `startsAt`, `endsAt`, `comment` |

Rule comparators are `gt`, `gte`, `lt`, `lte`, `eq`, and `neq`. Severity defaults to `warning`; enabled defaults to `true`. Set these fields explicitly in reusable examples to make intent clear. Generic `event-match` authoring is unsupported; render lifecycle subscription templates instead.

### AI Gateway Attempt Failure Rate Rule

Send this rule body to [the validation endpoint](https://docs.contextual.io/legacy/tenants/tenant-apis/alerts-api/validation-and-preview.md) to check a 5% AI Gateway attempt failure threshold over a five-minute window.

```json
{
  "name": "AI Gateway attempt failure rate above 5%",
  "enabled": true,
  "severity": "warning",
  "notify": "destinations",
  "source": "clickhouse-metric",
  "definitionKind": "threshold",
  "metricRefKind": "platform-metric",
  "metric": "ai.attempt-failure-rate",
  "target": { "service": "ai-gateway-api" },
  "comparator": "gt",
  "threshold": 0.05,
  "window": "5m",
  "for": "0s"
}
```

The threshold is a ratio. A window without attempts has no failure-rate observation. See [AI Gateway metrics](https://docs.contextual.io/legacy/tenants/monitoring/metrics.md#ai-gateway-dashboard) for how failures are counted. With `for: 0s`, the rule can fire on the first observed breach. Set a sustained duration to require the condition to persist.

`minSamples` is an optional positive integer at the top level of a rule. It sets a sample floor per series in each evaluation window. Custom rules have no floor by default. The three supported metrics count attempts for `ai.attempt-failure-rate` and total requests for `ai.failed-requests` and `ai.fallback-rate`. Live evaluation and preview omit observations below the floor. A firing series that stays below the floor past its staleness threshold can become stale without a recovery.

## Alertable Metric Catalog

`GET /metric-catalog` requires `contextual:alert-rules:read` and returns the supported `platform` and `ai` metric catalog used by chart authoring. Consult it before translating a dashboard metric into a rule, then validate the complete metric, target, and output combination. Catalog membership does not replace source-read permission checks or guarantee that every chart filter is supported.

For metrics that accept `minSamples`, the catalog entry includes `sampleUnit` (`attempts` or `requests`).

## Stored Query Shape

Supply the query object in the rule configuration. Alerts determines the tenant and evaluation interval from the rule and the caller’s tenant scope.

The `query` object allows only `coll_name`, `select`, `where`, `group_by`, and `dedup`. Do not add `db_name`, `coll_name_prefix`, `time_field`, `last`, `from`, `to`, or `output`; Alerts determines tenant scope, time bounds, and output shape.

* `select`: 1–20 scalar aggregates with unique aliases. The **first** drives the threshold. `count` and `count_distinct` are numeric; otherwise the first select must explicitly use `type: number`.
* Aggregates: `sum`, `avg`, `min`, `max`, `count`, `count_distinct`, `p05`, `p25`, `p50`, `p75`, `p90`, `p95`, `p99`, `latest`, and `earliest`, subject to the source and path restrictions enforced by rule validation. `count` must omit `path`.
* `where`: at most 20 predicates. Scalar comparisons use `=`, `!=`, `>`, `<`, `>=`, `<=`, `IN`, `NOT IN`, or `LIKE`. Supported array paths use `has`, `has_all`, or `has_any`; token matching uses `has_token` or `has_token_ci` with a single valid token.
* `group_by`: at most 10 unique objects with a `path`, not string shorthand. Supported dimensions include scalar paths, `$document_key`, `$operation`, and at most one supported array-explode path. Source restrictions still apply.

The stored-query grammar is only the first check. Use the [validation endpoint](https://docs.contextual.io/legacy/tenants/tenant-apis/alerts-api/validation-and-preview.md) to check source support and permissions. Grouped activity counts can zero-fill previously active series after a successful observation; they do not create unseen groups from nothing. Keep the population under the 100-series limit.

## Templates

`GET /templates` returns `{ "items": [...] }`. Each entry includes `id`, `version`, `kind`, `title`, `description`, `scope`, prerequisites, contexts, and parameter definitions. Catalog reads and rendering require `contextual:alert-rules:read`.

To render an `ai.attempt-failure-rate` rule, send these parameters to `POST /templates/ai-error-rate-high/render`.

```json
{ "parameters": { "threshold": 0.05, "window": "5m" } }
```

The response contains `kind`, `templateId`, `templateVersion`, and `config`. It is a draft, not a saved record. Validate and create a rule when `kind` is `rule`; create a subscription when `kind` is `subscription`. Later template changes do not mutate saved configurations.

Send `{ "parameters": {} }` to `POST /templates/{id}/render` to use the defaults for these AI Gateway rules.

| Template ID | Default condition | `window` | `minSamples` |
| --- | --- | --- | --- |
| `ai-model-hard-down` | 100% of attempts fail per provider/model (`gte`, `threshold: 1`) | `1h` | 5 attempts |
| `ai-failed-requests` | 5 or more requests fail per node (`gte`, `threshold: 5`) | `1h` | No floor. The template accepts only `threshold` and `window`. |
| `ai-fallback-rate-high` | More than 50% of requests use multiple traces per node (`gt`, `threshold: 0.5`) | `24h` | 20 requests |

For latency, render `ai-latency-high` with `thresholdMs` (default `5000`) and `window` (default `5m`). It uses p95 latency. For spending, render `ai-spend-high` with `thresholdUsd` (default `50`) and `window` (default `1h`). The template compares estimated USD over the window with the threshold.

## Apply a Configuration Bundle

`POST /config/apply` accepts optional `rules`, `subscriptions`, `destinations`, and `silences` arrays plus `dryRun` and `prune`. Unlike ordinary creation, each resource in an apply bundle must have an authored `id`. Use stable IDs managed by your deployment process.

The following plan contains one disabled draft and cannot enable evaluation:

```json
{
  "dryRun": true,
  "prune": false,
  "rules": [{
    "id": "docs-ai-attempt-failure-rate",
    "name": "AI Gateway attempt failure rate above 5%",
    "enabled": false,
    "severity": "warning",
    "source": "clickhouse-metric",
    "definitionKind": "threshold",
    "metricRefKind": "platform-metric",
    "metric": "ai.attempt-failure-rate",
    "target": { "service": "ai-gateway-api" },
    "comparator": "gt",
    "threshold": 0.05,
    "window": "5m",
    "for": "0s"
  }]
}
```

Use `dryRun: true` first; the default is `false`. The plan requires permissions for its intended operations, including source permissions. `prune` defaults to `false`:

* An omitted resource section is untouched.
* A present section leaves unlisted stored resources alone when pruning is false.
* A present section with `prune: true` deletes unlisted resources of that section. An empty array can therefore delete all resources in that section.

Inspect the plan before submitting with `dryRun: false`. The response includes `atomic: false`, explanatory notes, `plan`, and a `summary` of create/update/delete/noop/skip/failed counts. Executed applies also return per-item `results`.

Validation occurs before execution, but a bundle can partially succeed. HTTP `200` may contain failures and partial changes. Inspect `summary.failed` and every result, read the resulting state, and re-plan a repair. Do not assume the entire bundle rolled back.
