# Alerts

This page shows how to make a pipeline tell you when something needs attention: detect a condition with a query, turn the result into a message, and push it to Slack or Mattermost. It also covers the hooks that report on the pipeline run itself.

## How an alert works

An alert is an ordinary query that ends in `.push()` instead of `.output()`. The query finds the rows that matter, shapes them into the fields a message needs, and `.push()` sends **one message per row** it receives.

That gives you the most important rule for free: when the query returns no rows, nothing is sent. An alert that should stay quiet when all is well just needs a filter that removes every row in the healthy case.

```dsl
source("dq.table_health")
  .filter(status == "fail")
  .agg([count() as failing])
  .filter(failing > 0)
  .add([concat(failing.cast(string), " tables failed their data quality checks") as text])
  .select([text])
  .push("slack-push", action: "send_message",
    webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

The `.agg(...)` collapses everything into one row, so you get one message rather than one per failing table, and the `.filter(failing > 0)` drops that row when nothing failed.

## Send to Slack or Mattermost

`.push("slack-push", ...)` posts to a Slack incoming webhook. Create an incoming webhook in Slack for the channel you want, and pass the part of its URL after `https://hooks.slack.com` as `webhook_path`:

```dsl
.push("slack-push", action: "send_rich",
  webhook_path: "/services/T0000/B0000/XXXXXXXX")
```

For Mattermost, use the same connector and add the base URL of your Mattermost server:

```dsl
.push("slack-push", action: "send_rich",
  base_url: "https://mattermost.example.com",
  webhook_path: "/hooks/your-webhook-id")
```

> **Warning:** Anyone who has the webhook path can post to that channel. Keep pipeline files that contain one in a private repository.

### Message layouts

The `action` picks a message layout. Each layout reads fields from the row by column name, so name your columns to match.

| Action | What it sends | Columns it reads |
| --- | --- | --- |
| `send_message` | Plain text | `text` |
| `send_rich` | A Markdown (mrkdwn) section | `text` |
| `send_pipeline_status` | A pipeline status card | `title`, `pipeline`, `status`, `status_emoji`, `steps`, `duration`, `footer` |
| `send_alert` | An alert card | `title`, `description`, `severity`, `severity_emoji`, `source`, `footer` |
| `send_report` | A report card with a header and body | `title`, `subtitle`, `body`, `footer` |
| `send_table` | A card of up to six fields | `title`, `field1` to `field6`, `footer` |
| `send_incident` | An incident card with a button | `title`, `incident_key`, `priority`, `affected`, `detected_at`, `context`, `portal_url` |

For example, a structured alert card:

```dsl
source("dq.table_health")
  .filter(status == "fail")
  .agg([count() as failing])
  .filter(failing > 0)
  .add([
    concat(failing.cast(string), " tables failing") as title,
    "Data quality checks failed on the latest run." as description,
    "critical" as severity,
    ":rotating_light:" as severity_emoji,
    "Data Quality Pipeline" as source,
    "Check the connector pipelines" as footer
  ])
  .push("slack-push", action: "send_alert",
    webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

## Detect the condition

Three transforms are built for alerting. Each returns only the rows that should alert, so they combine naturally with the "no rows, no message" rule.

### Anomalies: values far from normal

`.anomaly(column, window: N)` compares each row's value with the mean and standard deviation of the `N` rows before it, and flags values more than `threshold` standard deviations away (default `3.0`; lower is more sensitive). `window` is required. Rows are compared in the order they arrive, so sort by time first.

It adds four columns:

| Column | Meaning |
| --- | --- |
| `<column>_is_anomaly` | `true` when the value is beyond the threshold |
| `<column>_expected` | The mean of the preceding window |
| `<column>_deviation` | The value minus the expected value |
| `<column>_score` | How unusual the value is, from 0.0 to 1.0 |

```dsl
source("ai.cost_daily")
  .sort([date: asc])
  .anomaly(amount, window: 7, threshold: 2.0)
  .filter(amount_is_anomaly == true and amount_deviation > 0)
  .since(date, "24h")
  .add([concat(
    "AI spend spike: $", round(amount, 2).cast(string),
    " (expected $", round(amount_expected, 2).cast(string), ")"
  ) as text])
  .select([text])
  .push("slack-push", action: "send_rich", webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

The detection runs over the whole history so the statistics are meaningful; the `.since(date, "24h")` afterwards keeps only today's anomalies. `amount_deviation > 0` limits the alert to spikes, since a drop is flagged too.

The detection uses the z-score method. Other methods are not available yet, and the query is rejected if you ask for one.

### Breaches: a condition that holds for a while

`.breach(condition, for: duration)` fires when an aggregate crosses a threshold in every time bucket over a period. It needs `time:` and `granularity:` on the source, which set the time column and the bucket size. Put `.by(...)` before it to check each group separately.

```dsl
source("gh.pr_enriched", time: opened_at, granularity: 1d)
  .by(team)
  .breach(avg(cycle_time_hours) > 48, for: 7d)
  .add([concat(team, ": average cycle time above 48h for 7 days") as text])
  .select([text])
  .push("slack-push", action: "send_rich", webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

The condition is an aggregate compared with a value: `>`, `>=`, `<`, `<=`, `==` or `!=`. The result has one row per group that breached in every bucket (here, 7 daily buckets in a row), with the groups' columns and the aggregate's value in `_agg_value`.

### Absence: data that stopped arriving

`.absent(for: duration)` fires when no rows have arrived within the period. It needs `time:` on the source. With `.by(...)`, it checks each group separately and returns the groups that went quiet, with the time of their last row in `_last_seen`.

```dsl
source("gh.pr_enriched", time: opened_at, granularity: 1d)
  .by(repo)
  .absent(for: 48h)
  .add([concat(repo, ": no new pull requests in 48 hours") as text])
  .select([text])
  .push("slack-push", action: "send_rich", webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

Grouped absence only knows about groups that appear in the table at all. A repository that never had a row can't go quiet.

## Build good messages

### One message, many lines

Turn each row into a line, then collapse the lines into one row with `string_agg`. `chr(10)` is a newline:

```dsl
source("gh.pr_enriched", time: opened_at, granularity: 1d)
  .by(repo)
  .absent(for: 48h)
  .add([concat("- ", repo) as line])
  .agg([string_agg(line, chr(10)) as lines, count() as quiet])
  .filter(quiet > 0)
  .add([concat(quiet.cast(string), " repositories with no activity:", chr(10), lines) as text])
  .select([text])
  .push("slack-push", action: "send_rich", webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

### Combine numbers from different queries

To put results from two queries in one message, give each a constant key and join on it:

```dsl
prs = source("gh.pr_enriched").since(opened_at, "7d").agg([1 as k, count() as opened])
cost = source("ai.cost_daily").since(date, "7d").agg([1 as k, sum(amount) as spend])

prs
  .join(cost, left_on: [k], right_on: [k], type: inner, prefix: "c_")
  .add([concat(
    "Last 7 days: ", opened.cast(string), " PRs opened, $",
    round(c_spend, 2).cast(string), " AI spend"
  ) as text])
  .select([text])
  .push("slack-push", action: "send_message", webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

The shipped `examples/alert-pipeline.yaml` has a longer version of this pattern that detects a cost anomaly and lists the top five consumers on that day in the same message.

## Alert steps in a pipeline

Put an alert in a pipeline as a step with `type: alert`:

```yaml
steps:
  - name: data_quality_check
    type: materialize
    dsl: |
      ...

  - name: quality_alert
    type: alert
    depends_on:
      - data_quality_check
    dsl: |
      source("dq.table_health")
        .filter(status == "fail")
        .agg([count() as failing])
        .filter(failing > 0)
        .add([concat(failing.cast(string), " tables failed their checks") as text])
        .select([text])
        .push("slack-push", action: "send_rich",
          webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

An alert step runs as part of the pipeline like any other step, so give it `depends_on` when it reads a table the pipeline builds. Without it, the alert starts at the beginning of the run and checks yesterday's data.

If the alert query itself fails, for example because a column was renamed, the step fails and so does the run, like any other step. To hear about failed runs, use a lifecycle hook.

## Lifecycle hooks

An alert step with a `trigger` is a lifecycle hook. It doesn't take part in the normal run order; it runs once the rest of the pipeline has finished.

| Trigger | Runs when |
| --- | --- |
| `on_success` | The run completed with every step succeeding. |
| `on_failure` | The run failed, or ended as `partial`. |
| `on_complete` | Either way. |

A hook never changes the run's status. If the hook itself fails, the run keeps the status it already had. Hooks usually build their message with `mock([...])`, which makes rows from a literal list, because the message doesn't depend on any table.

Inside a hook's DSL you can use these placeholders, which are filled in before the hook runs:

| Placeholder | Value |
| --- | --- |
| `${run.name}` | The pipeline's name |
| `${run.status}` | `completed` or `failed` |
| `${run.failed_step}` | The first failed step, or empty |
| `${run.error_message}` | That step's error, or empty |
| `${run.completed_steps}` | How many steps completed |
| `${run.total_steps}` | How many steps the pipeline has, not counting hooks |
| `${run.duration}` | How long the run took, such as `42.3s` or `3m 12s` |
| `${run.started_at}`, `${run.completed_at}` | Timestamps, ISO 8601 |
| `${run.step_summary}` | Every step with `[ok]`, `[FAIL]` or `[skip]` |
| `${run.triggered_by}` | `trigger` when another pipeline started this run, otherwise `manual` |
| `${run.id}`, `${run.pipeline_id}`, `${run.environment_id}` | Ids |

```yaml
  - name: success_notify
    type: alert
    trigger: on_success
    dsl: |
      mock([{
        title: "Pipeline Completed",
        pipeline: "${run.name}",
        status: "Completed",
        status_emoji: ":white_check_mark:",
        steps: "${run.completed_steps}/${run.total_steps}",
        duration: "${run.duration}",
        footer: "All steps passed"
      }]).push("slack-push", action: "send_pipeline_status",
        webhook_path: "/services/YOUR/WEBHOOK/PATH")

  - name: failure_notify
    type: alert
    trigger: on_failure
    dsl: |
      mock([{
        title: "Pipeline Failed",
        pipeline: "${run.name}",
        status: "Failed",
        status_emoji: ":x:",
        steps: "${run.completed_steps}/${run.total_steps}",
        duration: "${run.duration}",
        footer: "Failed step: ${run.failed_step}"
      }]).push("slack-push", action: "send_pipeline_status",
        webhook_path: "/services/YOUR/WEBHOOK/PATH")
```

The validator rejects any `trigger` value other than these three.

## Avoid repeat alerts

Solidafy doesn't remember which messages it already sent. Every run evaluates the query again and sends whatever it returns. So an alert on a pipeline that runs every hour will repeat every hour for as long as the condition holds, unless the query rules that out.

- **Look at new data only.** Keep the detection over the full history, then filter the result to the period since the last run. If the pipeline runs daily, `.since(date, "24h")` after `.anomaly(...)` alerts on each anomaly once.
- **Match the schedule to how often you want to hear about it.** A breach or absence check in a pipeline that runs every 6 hours reports the same ongoing problem 4 times a day. If that is too much, move the alert into its own pipeline with a daily schedule.
- **Send one summary, not one message per row.** Collapse rows with `.agg(...)` and `string_agg` as shown above.

## Notification channels

The portal also has **notification channels** under **Settings > Notifications**: named destinations of type email, Slack (an incoming webhook URL) or internal users (in-app notifications for chosen members of your organisation). You can manage them with `solidafy channels` and the [API](/docs/reference/api#notification-channels) as well. A channel's handler is a lowercase name made of letters, digits and hyphens.

Pipeline alerts in this guide deliver through `.push()` directly and don't need a channel.
