# Canary comparison

During a gradual rollout you run the new version on a few hosts next to the old one, and before you go further you
want one answer: is the canary worse? Compare answers it from your logs. You write one query for the lines of the
version you trust (the baseline) and one for the new version (the canary), and Tailcove counts both over the same
window on the same source.

It's the same question a [deploy check](https://tailcove.dev/docs/deploy-checks) asks after a release, asked side by side instead of
before and after. That matters during a rollout: the canary and the baseline see traffic at the same moment, so a
busy hour or a quiet night hits both.

## The Compare page

Open **Compare** in the sidebar (under Analysis), pick a source and fill in the two boxes. Both take the
[query language](https://tailcove.dev/docs/query-language) you use in the log viewer:

| Baseline               | Canary                 | When                                                   |
| ---------------------- | ---------------------- | ------------------------------------------------------ |
| `-host:canary-*`       | `host:canary-*`        | Canary hosts are named `canary-…`                      |
| `release:v2.3.9`       | `release:v2.4.0`       | Your lines carry the version in a `release` field      |
| `host:web-6f9c7d8b4-*` | `host:web-5b8d6c9f7-*` | Kubernetes pods, told apart by their ReplicaSet's hash |
| `-region:eu-west-1`    | `region:eu-west-1`     | You roll out one region first                          |

The two buttons under the boxes fill in the first two rows. **Two releases** uses the two newest versions you recorded
[deploys](https://tailcove.dev/docs/api/deploys) of on that source, or example versions when there are none.

The window is the last 5, 15, 30 or 60 minutes, or a custom range of up to 24 hours. For each side you get the lines,
the error lines (levels `error`, `critical`, `alert` and `emergency`, the same ones a deploy check counts), errors a
minute and the error share: error lines divided by lines. Below that:

- **Errors only the canary logged**: error patterns with at least 3 error lines on the canary and no line at all on
  the baseline in the window, each with an example line. **View lines** opens the source's logs with the canary query
  and the pattern's fixed words.
- **Errors that grew most on the canary**: patterns both sides logged, ranked by how much more of the canary's lines
  they take up than of the baseline's.
- **Errors a minute**: one line per side over the window.

Everything you typed is in the page's address, so **Copy link** gives your team the same comparison. They see it only
if they can see the source (client group restrictions apply, and the Billing role has no access to log data).

## When the canary counts as worse

The verdict is one of `worse`, `ok` or `not_enough_data`, checked in this order:

1. **Not enough data** when the baseline has fewer than 50 lines in the window. With nothing to compare against,
   every error on the canary would look new.
2. **Worse** when the canary logged an error pattern 3 times or more that the baseline didn't log once (at any level)
   in the window. This holds even when the canary itself is under 50 lines: a brand new kind of error is evidence on
   its own, and we'd rather stop a rollout than call it "not enough data".
3. **Not enough data** when the canary has fewer than 50 lines.
4. **Worse** when the canary's error share is above both 1.5 times the baseline's and the baseline's plus one
   percentage point, and the canary has at least 5 error lines.
5. **OK** otherwise.

Shares, not rates, because the two sides rarely carry the same traffic. A canary on 1 host of 10 logs about a tenth as
much, so its errors a minute are always lower; its share of errors isn't. The page and the API both say which rule
decided, in words, for example:

> The canary logged 1 kind of error the baseline didn't log once in the window. Errors are 5% of 400 lines on the
> canary against 1% of 1,000 on the baseline, over the limit of 2%.

The one point of margin keeps a clean baseline from making a single error on the canary look like a regression: with
the baseline at 0.2%, the canary can go up to 1.2% before it counts.

## From a rollout tool

The same comparison is an API call, so a rollout tool can gate on it. Make a token under **Settings → API tokens**
with the `logs:read` ability, then:

```
GET /api/v1/sources/{id}/compare?baseline=…&canary=…&minutes=15
```

The answer's `data.verdict` is the word to check. The full contract is on the [Compare API](https://tailcove.dev/docs/api/compare) page.

### Argo Rollouts

Argo Rollouts' [web metric provider](https://argo-rollouts.readthedocs.io/en/stable/analysis/web/) can call it as a
canary analysis. Put the token in a Kubernetes secret first:

```bash
kubectl create secret generic tailcove --from-literal=api-token=YOUR_API_TOKEN
```

Then an `AnalysisTemplate` that compares the pods of the new ReplicaSet with the stable one. Argo hands the template
both pod template hashes, and a pod's hostname is `<deployment>-<hash>-<random>`, so a `host` prefix picks out each
side. This assumes each line's `host` is its pod's name, which is what the
[agent sends from Kubernetes](https://tailcove.dev/docs/sending-logs/agent#kubernetes) by default.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
    name: tailcove-canary
spec:
    args:
        - name: stable-hash
        - name: canary-hash
        - name: api-token
          valueFrom:
              secretKeyRef:
                  name: tailcove
                  key: api-token
    metrics:
        - name: tailcove-canary
          initialDelay: 5m
          interval: 5m
          count: 3
          # One "worse" is a warning; a second one aborts the rollout.
          failureLimit: 1
          successCondition: result == 'ok' || result == 'not_enough_data'
          provider:
              web:
                  url: 'https://tailcove.dev/api/v1/sources/src_01jbx5q8k7m3n2p4r6s8t0v1w3/compare?baseline=host%3Aweb-{{args.stable-hash}}-%2A&canary=host%3Aweb-{{args.canary-hash}}-%2A&minutes=15'
                  headers:
                      - key: Authorization
                        value: 'Bearer {{args.api-token}}'
                  jsonPath: '{$.data.verdict}'
```

And in the `Rollout`, run it between steps:

```yaml
strategy:
    canary:
        steps:
            - setWeight: 10
            - analysis:
                  templates:
                      - templateName: tailcove-canary
                  args:
                      - name: stable-hash
                        valueFrom:
                            podTemplateHashValue: Stable
                      - name: canary-hash
                        valueFrom:
                            podTemplateHashValue: Latest
            - setWeight: 50
            - pause: { duration: 10m }
```

`not_enough_data` passes on purpose: a canary at 10% of a quiet service may not reach 50 lines in 15 minutes, and
failing the rollout for that would stop every deploy at night. If you'd rather wait, make the window longer
(`minutes=30`) or add `initialDelay`. Replace the source id with your own (it's in the address of the source's page)
and the `web-` prefix with your Deployment's name.

### Any other tool

It's one GET, so a pipeline step can do the same with `curl` and `jq`:

```bash
verdict=$(curl -sf -G "https://tailcove.dev/api/v1/sources/$TAILCOVE_SOURCE_ID/compare" \
  -H "Authorization: Bearer $TAILCOVE_API_TOKEN" \
  --data-urlencode "baseline=-host:canary-*" \
  --data-urlencode "canary=host:canary-*" \
  --data-urlencode "minutes=15" | jq -r '.data.verdict')

if [ "$verdict" = "worse" ]; then
  echo "The canary is worse than the baseline, rolling back"
  exit 1
fi
```

Print `.data.reason` too if you want the why in your pipeline's log.

## Limits

- One source per comparison. If the canary and the baseline log to different sources, a deploy check's
  [preview mode](https://tailcove.dev/docs/deploy-checks#previews-and-pull-requests) is closer to what you need.
- The window ends now and is at most 24 hours long. Lines reach Tailcove a few seconds after they're written, so the
  last seconds of the window are a little thin on both sides.
- The canary's 50 busiest error patterns are compared with the baseline; a canary with more kinds of error than that
  is worse long before the 51st.
- The API's usual [rate limits](https://tailcove.dev/docs/api/errors-and-rate-limits) apply: one call every few minutes per rollout is
  plenty.
