# Automatic approval

> When Visto AI approves a pull request on its own, how to turn it on, how an approval is withdrawn, and how the audit sample works.

Web page: https://visto-ai.com/docs/automatic-approval/

With automatic approval on, Visto AI posts its review as an approving review when the pull request needs no person: every file is reviewed, nothing scores at or above the threshold, and no major or blocker finding is open. A new commit withdraws the approval. When any condition fails, the review is posted as a comment, as it is with approval off, and its last paragraph says which condition did not hold.

A small share of the pull requests it would approve, 5% by default, is drawn for an audit sample and posted as a comment for a person to review anyway, so that people keep checking what the bot approves.

Automatic approval is off unless you switch it on for a repository.

## When it approves

The decision is made after the review is computed and recorded, just before it is posted, with the repository's settings as they read at that moment. The service checks these conditions in order, and every one must hold:

1. **The pull request is unchanged.** It is still open, at the head and merge base the review was computed for. Otherwise nothing is posted at all, as with approval off, and the job ends `closed` or `head_moved`.
2. **Its stored reviews can be read.** The pull request's earlier runs and the app's stored comments are read from the database.
3. **Everything is covered.** Every file is reviewed and scored at this head, by this review or an earlier one, and none is listed as not reviewed.
4. **Nothing needs a person.** The verdict says no person is needed, and the highest score and every file's final score are below the threshold in force now, whatever threshold the review was scored with (see [The score](https://visto-ai.com/docs/the-score/)).
5. **This review has no major or blocker finding**, whether on the diff, not placed on it, or on code unchanged since the last review.
6. **No earlier finding is stuck.** No published review of the pull request left a major or blocker finding without a thread that a later review can clear.
7. **It is a normal pull request.** It is not a draft, and its branch is in the repository itself, not in a fork.
8. **No blocking thread is open.** No major or blocker thread of the app's own is open, as GitHub's review threads read now (see [Which threads hold it back](#which-threads-hold-it-back)).
9. **The base branch protects the approval.** The base branch dismisses stale approvals when new commits are pushed, or, where the [merge gate](https://visto-ai.com/docs/merge-gate/) enforces on it, requires the gate's check from this app (see [Turn it on](#turn-it-on)).
10. **It is not drawn for the audit sample** (see [The audit sample](#the-audit-sample)).

Each condition is checked only when the ones before it held, and the review's paragraph names the first that failed. A person who fixes that one may meet the next one only at the next review.

The service reads GitHub in the same order: the threads only when conditions 1 to 7 held, the base branch's rule only when condition 8 did, and the audit draw is made only when condition 9 did. A pull request drawn for the audit is therefore always one the service would otherwise have approved.

### Reasons for not approving

Every decision has a code, stored with the review and shown in its last paragraph:

| Code | What failed |
|---|---|
| `record_unreadable` | A stored review or stored comment of this pull request could not be read. Any stored result that cannot be read, at any step, gives this code, never an approval |
| `not_covered` | Not every file is reviewed and scored at this commit |
| `needs_human` | A block or file is at or above the threshold |
| `blocking_finding` | This review has a major or blocker finding |
| `finding_without_thread` | A review raised a major or blocker finding that no later review can clear: one not placed on the diff, the placed findings of a review posted without its inline comments, one on code unchanged since the review before, or one dropped as a repeat of a thread that was closed for approval at the time. It holds approval for as long as the pull request is open |
| `draft` | The pull request is a draft |
| `from_fork` | Its branch is in a fork. A pull request from a fork is never approved automatically |
| `origin_unknown` | GitHub's answer does not tell whether its branch is in this repository |
| `threads_unreadable` | The review threads could not be read; the paragraph gives the read's code |
| `open_thread` | A major or blocker thread of the app's own is open, or its comment is gone |
| `rule_off` | The base branch neither dismisses stale approvals nor requires the gate's check from this app |
| `rule_unreadable` | Whether the base branch does either could not be read; the paragraph gives the read's code |
| `audit_sample` | Every other condition holds, and the pull request was drawn for the audit sample |
| `refused` | GitHub refused the review as an approval, so it was posted as a comment (see [A refused approval](#a-refused-approval)) |
| `approved` | Every condition held |

## Turn it on

You need four things: a branch rule on GitHub that withdraws a stale approval, a branch rule that requires an approving review, the `Administration` read permission for the app, and the `autoApprove` switch.

### Make the base branch dismiss stale approvals

The service approves only where the base branch's own rules dismiss an approval when new commits are pushed. In a ruleset that applies to the base branch, or in its branch protection, turn on **Require a pull request before merging** and, under it, **Dismiss stale pull request approvals when new commits are pushed**. A new commit then needs a new approval, whatever the app does.

Where the repository's [merge gate](https://visto-ai.com/docs/merge-gate/) is on for the base branch in `enforce` mode, there is a second way: require the gate's check, with this app as its only source. In a ruleset, that is **Require status checks to pass** with the check (its `checkName`, `AI Review` by default) and its source set to the app; in branch protection, the required check with the app as its source. A new commit then cannot be merged until its own check passes, which takes a review of that commit or a skip, and the check waits while an approval of another commit stands (see [The merge gate's check while an approval stands](#the-merge-gates-check-while-an-approval-stands)). A check that any source may report does not count, since anyone who can write a commit status could pass it.

The gate route differs from GitHub's own dismissal in two ways: a person's approval of an earlier commit keeps counting, and the app's own approval of an earlier commit stands for the seconds its withdrawal takes, while the check waits. A branch in `shadow` or `bypass` mode, or not gated, needs the dismissal of stale approvals.

### Require an approving review

Require an approving review on the base branch too, so that the bot's approval is what lets a low-risk pull request merge, and a pull request it does not approve waits for a person. **The service does not check this**, nor whether a code owner's review is required, and nothing warns you when no approving review is required. Without it, an audited or flagged pull request can be merged with no one looking at it.

### Give the app `Administration` read

The service reads the base branch's protection with `Administration` read. An app made by `npm run app:create` already has it. For an existing app, add `Administration` read by hand in the app's settings, have each installation accept it, and restart the service: it reads the app's permissions once, at start.

Out of dry run, when any repository has approval on, the service checks at start that the app has `administration` read, `pull_requests` write and the event `pull_request_review`. For each one missing it logs `feature_off` with the feature `approval` and the missing item (`administration:read`, `pull_requests:write` or `event:pull_request_review`), raises the alert of that name, and keeps running. It checks what the app asks for, not what each installation has accepted: an installation that has not accepted gets `rule_unreadable` when GitHub refuses the protection read, unless a ruleset already says the rule is on.

### Switch it on

Three keys of the `score` block control it, under `repositories.defaults.score` for every repository or under `repositories.overrides.<owner/name>.score` for one. Each key written in an override replaces the default's.

```yaml
repositories:
  overrides:
    acme/shop:
      score:
        autoApprove: true
        approvalThreads: strict   # or gate
        auditShare: 5             # percent; 0 switches the sample off
```

| Key | Default | What it does |
|---|---|---|
| `autoApprove` | `false` | Posts a review as an approval when every condition holds |
| `approvalThreads` | `strict` | Which threads hold approval back: `strict` or `gate` (see [Which threads hold it back](#which-threads-hold-it-back)) |
| `auditShare` | `5` | Of the pull requests it would approve, the percentage sent to a person anyway, from 0 to 100, fractions allowed. `0` switches the sample off |

These are the deployment's settings. Nothing in a reviewed repository, `.visto-ai.yml` included, can set them. Once the service has started, an admin can also change them in the UI's Settings, under Repositories (see [Configuration](https://visto-ai.com/docs/configuration/)). A change saved there is read at each pull request's next publication, but the app's `Administration` read is checked only at the next start.

You do not need an audit key: with none written, the service generates one (see [The audit key](#the-audit-key)).

## Which threads hold it back

Only the app's own threads count: a thread whose first comment is the app's, with the severity stored for that comment, major or blocker. A thread whose first comment has no stored row counts as one of unknown severity, as it does for the merge gate. Minor findings and notes never count.

A person here is an account that is neither the app nor a bot. A person has access when GitHub reports their comment's `authorAssociation` as `OWNER`, `MEMBER` or `COLLABORATOR`; any other value, or none, is no access. The service looks up nothing more.

### `strict`, the default

A thread is closed for approval in two cases:

- **A verified fix.** This review kept a `fixed` verdict for it, on a file that changed since the thread was opened, and nobody but the app wrote in the thread after the replies the review judged.
- **Resolved, with a reason.** The thread is resolved, and either the app resolved it and the newest verdict a published review kept for it is `fixed` on a changed file, or a person with access who is not the pull request's author (ignoring letter case) replied in it. When that newest verdict is `open`, only a reply written after the comments that review judged counts. When the review did not record how many comments it judged, or its entry cannot be read, no reply counts.

A thread of the app's own with no stored finding closes only by such a reply and a resolve.

### `gate`

A thread is open when the merge gate's rule would block it, with this review as the head's review and the repository's `clearByReply`, whether or not the gate is on (see [The merge gate](https://visto-ai.com/docs/merge-gate/)).

### Under both rules

- A thread this review kept `open` is open, even when it is resolved and a member replied.
- A lost thread is open. A stored major or blocker finding of a published run, not a dry run, whose comment is not the first comment of a thread GitHub lists as the app's own, counts once: the comment was deleted, or the thread's first comment is no longer the app's. So does a stored row whose severity is unknown, or whose run is not among those read.
- A thread, a comment or a run that cannot be read counts as open.

### Which threads a later review judges again

With approval on, a thread is settled, and so not judged again by later reviews (see [Leaving dry run](https://visto-ai.com/docs/leave-dry-run/)), only when the settling rule and the thread rule both accept it. Under `strict`, that is the resolved case above. Under `gate`, it is the app's resolve after a `fixed` or `answered` verdict, or, with `clearByReply` on, a person's reply and a resolve. So under `strict` a thread the author replied to and resolved is judged again by every review, and under `gate` with `clearByReply` off a thread a person replied to and resolved is judged again, also on a pull request that is not gated. A verdict can then close it.

### Trade-offs of each rule

More threads are judged at each review, and their files read.

Under `strict`:

- A wrong finding costs one person's look, since the bot does not approve.
- A thread the app resolved after an `answered` verdict is judged again at every review until someone with access who is not the author replies. With the gate on, a new `open` verdict on it can make it block the gate again.
- A thread whose fix a review of an older head verified, and that nobody resolved, holds approval until a review of the present head verifies it again.
- A member who replied before a review kept the thread open must reply again after it, or a review must verify a fix.

Under `gate`:

- The author alone can close a thread, by a reply the review accepts or, with `clearByReply` on, by a reply and a resolve.
- A thread a person replied to and resolved, which this review judged `open`, holds approval though the gate lets the merge through.

Under both, a finding whose comment anyone deleted, or whose thread GitHub no longer lists as the app's, holds approval for the rest of the pull request, and a person reviews it instead.

## How the base branch's rule is read

The rule is read for the base branch GitHub names at the post, after the threads and before the audit draw.

1. **Rulesets.** `GET /repos/<owner>/<repo>/rules/branches/<branch>` returns the rules of every ruleset that applies to the branch, 100 to a page, at most 10 pages. An entry of type `pull_request` whose `parameters.dismiss_stale_reviews_on_push` is `true` means the rule is on, and nothing more is read. Where the gate enforces on the branch, so does an entry of type `required_status_checks` that lists the gate's check name exactly, with `integration_id` the app's id. Every entry is checked first: an entry that is not an object with a type, or a list that fills its tenth page, makes the list no answer, whatever its other entries say.
2. **Branch protection**, when the rulesets do not say the rule is on. `GET /repos/<owner>/<repo>/branches/<branch>/protection`: `required_pull_request_reviews.dismiss_stale_reviews` `true` means the rule is on. Where the gate enforces, so does an entry of `required_status_checks.checks` with the gate's check name and `app_id` the app's id. A name in `contexts` alone may come from any source, and does not count. Any other answer of 200, and a 404 (no protection), mean the rule is off.

Either read saying the rule is on is enough. When both are read and neither says so, the code is `rule_off`. When one could not be read and the other does not say so, the code is `rule_unreadable`, with the first failure's code (the rulesets read's, when both failed). Every other answer is a failure, a 403 included, whatever GitHub's message says. A server error, or no answer, is tried once more.

The branch name is sent encoded, a slash as `%2F`. An empty name, `.`, `..` and a name that cannot be encoded are refused before any request, with `github_bad_path`.

On GitHub's permissions page, the rulesets read falls under `Metadata` read, which every app has, and the protection read under `Administration` read. A private repository on a plan with neither rulesets nor branch protection answers 403 to both reads, so the service cannot approve there and says `rule_unreadable`.

## The review's last paragraph

With approval on, every review ends with one paragraph, after the `Overall` line. It sits in the end of the body that is kept when a body is cut to GitHub's size limit. With approval off, the body has no such paragraph.

The approval reads:

```text
**Approved automatically** for commit `<commit>`: every file is reviewed, nothing is at or above <threshold>%, and no major or blocker finding is open. A new commit withdraws this approval.
```

Every other paragraph is `**Not approved automatically:**`, a space, and the sentence for its code:

```text
record_unreadable:      a stored review of this pull request could not be read.
not_covered:            not every file of this pull request is reviewed and scored at this commit.
needs_human:            a part of this change is at or above <threshold>%, so a person should review it.
blocking_finding:       this review has a major or blocker finding.
finding_without_thread: a review of this pull request raised a major or blocker finding that no later review can clear: one not placed on the diff, one whose inline comment GitHub refused, one on code unchanged since an earlier review, or one that repeats a thread already closed. It holds approval for as long as the pull request is open.
draft:                  this pull request is a draft.
from_fork:              its branch is in a fork, and a pull request from a fork is never approved automatically.
origin_unknown:         the reviewer could not tell whether its branch is in this repository.
threads_unreadable:     the review threads of this pull request could not be read (`<code>`).
open_thread, strict:    a major or blocker thread of this reviewer is still open, or its comment is gone. Here a thread counts as closed when a review verified a fix in changed code, or when it is resolved and someone other than the author, with access to the repository, replied in it.
open_thread, gate:      a major or blocker thread of this reviewer is still open, or its comment is gone.
rule_unreadable:        the reviewer could not read whether the base branch dismisses an approval when new commits are pushed, or requires the merge gate's check (`<code>`).
rule_off:               the base branch does not dismiss an approval when new commits are pushed, nor hold a new commit to the merge gate. The reviewer approves only where a ruleset or the branch protection of the base branch dismisses stale approvals, or, where the gate enforces, requires the gate's check from this reviewer.
audit_sample:           this pull request was drawn for the audit sample. Every other condition for an automatic approval holds, and a share of the pull requests this reviewer would approve is sent to a person anyway, so that people keep checking what it approves. A person should review it.
refused:                GitHub refused this review as an approval (`<code>`), so it was posted as a comment.
```

`<commit>` is the first 12 characters of the reviewed head, `<threshold>` the threshold in force, and `<code>` a short code (`internal_error` when the code is not one). A decision code the running release does not know never reads as an approval: it is shown as `record_unreadable`.

Only one reason is given. A body the service cannot write again from the stored result is posted as it was recorded, followed by the paragraph decided now, and the decision stands.

## The audit sample

Of the pull requests the service would approve, a share is sent to a person anyway, so that people keep checking what it approves. The draw is the last condition, made only when every other one held.

### The share

`auditShare` sets the share as a percentage from 0 to 100, fractions such as `37.5` included. It is `5` when not written, and is read with the other settings when the review is about to be posted. At `0` nothing is drawn and no key is read.

### How a pull request is drawn

The draw is an HMAC-SHA-256 keyed with the audit key (its characters as the variable holds them, or the 64 of a generated key) in UTF-8, over the pull request as the service stores it, also in UTF-8: the JSON of the git service, the owner and the repository in lower case, and the number, such as `["github","acme","shop",7]`. The first four bytes of the digest, read big-endian as a number `u` below 2^32, draw the pull request exactly when `u * 100 < share * 2^32`. Both sides are exact, so a share is drawn as written, with no rounding: at 0 nothing, at 100 everything.

The draw reads no head, no base branch and no time, and makes no request and no model call. Because of the key, nobody without it can tell beforehand which pull request will be drawn.

### Every head draws the same

The draw holds no head, so a pull request drawn is drawn again at every head at which every other condition holds, until the share or the key changes. Pushing again does not get it out of the sample. A new pull request for the same change is a new draw; that gap is accepted, and the audit paragraph, which says the pull request would otherwise have been approved, makes it easy to see. Once one head of a pull request is approved or audited, its author knows how every later head of it will draw, until the share or the key changes.

### When the share or the key changes

Draws nest: a pull request drawn at one share is drawn at every higher share. Raising the share only adds pull requests to the sample, and lowering it only takes some out. A change takes effect at each pull request's next publication; nothing is withdrawn or posted because of the change alone.

- An approval posted before a raise stands until the pull request's next push or review.
- A pull request a lower share no longer draws can be approved at its next review. A push that tells nothing new after an audited review still ends `nothing_new`, since the newest review was no approval, so it waits for a push with something new, or for `/review` (see [A push that tells nothing new](#a-push-that-tells-nothing-new)).
- A new key draws every pull request again at its next review, unrelated to the old draw. Writing a key in the file later, or removing one, is a new key.
- A rename or a transfer of the repository that changes more than letter case changes the owner or name the draw is made over, so each of its open pull requests is drawn again at its next publication.

### What an audited review looks like

An audited review is posted as a comment, like any review that does not approve, and ends with the `audit_sample` paragraph. The paragraph is the same under both thread rules and has no code. It does not start with the word "audit", and it says that every other condition holds, so the author knows the pull request would otherwise have been approved.

Nothing else on GitHub marks an audited pull request: no label, no requested reviewer, no assignee, no check, no alert and no new permission. Nothing makes a person review it except the repository's own rule that requires an approving review (see [Require an approving review](#require-an-approving-review)).

An audited review counts as a review that does not approve, so if the pull request has a standing approval, its publication asks for a withdrawal (see [Withdrawal](#withdrawal)). An earlier approval can be standing then only when the share or the key changed since it was posted. The merge gate does not read the decision, and neither does receiving.

### Finding audited pull requests

The review is recorded with `approved` false and `approval_code` `audit_sample`, and its `review` log line carries `approved: false` and `approval: 'audit_sample'`. Nothing records the share or the key that drew it. The draw gives out only whether the pull request is drawn: the key, the digest and `u` appear in no log line, record, review, issue or alert.

```sql
-- the reviews drawn for the audit sample, newest first
select id, number, head_sha, published_at from visto_ai.review_runs
where owner = 'acme' and repo = 'shop' and published and approval_code = 'audit_sample' order by id desc;
```

An audit is told by its code only. An audited review that a later start adopts (posted, then not recorded, then found on GitHub as a comment) is stored with `approval_code` null, as every adopted comment is, and logged with no `approval`. It cannot be told from a comment, and the statement above does not list it.

### The audit key

The draw is keyed with a secret of the deployment's. You do not have to set one.

**Generated key (the default).** With no `auditKey` written, the service generates the key at its first start, after the migrations: 32 random bytes, kept as 64 hexadecimal characters in the table `visto_ai.generated_secrets`. Every later start reads the same key from there, and two starts at once keep one. A key that cannot be stored or read fails the start, as a failed migration does.

**Your own key.** To set one, name it by reference at the top level of the config, and keep it like the webhook secret:

```yaml
auditKey: { env: AUDIT_KEY }   # the variable's name is yours to choose
```

Its value must hold at least 32 characters, for example the output of `openssl rand -hex 32`, and is used as it is, spaces included. A key written in the file wins: the table is then neither read nor written, and a key generated before stays there, unused, until the file writes none again. A written key is read whatever the repositories say, so it must be set. These problems stop the start with exit code 2, in dry run too, and never quote the value:

| Message | Cause |
|---|---|
| `config: auditKey: environment variable <NAME> is not set` | The variable is not set, or is empty |
| `config: auditKey: environment variable <NAME> must hold at least 32 characters` | The value is too short |

The placeholder in [env.example](https://raw.githubusercontent.com/visto-ai/visto-ai/0faf484aa43f4fcdc1f30c1d5c056ea26c1c0d32/env.example), `change-me-audit-key`, is shorter than 32 characters on purpose, so it is refused and never used as a key.

Each start logs where the key came from, `{ event: 'audit_key', from: 'config.yml' }` or `{ event: 'audit_key', from: 'database' }`. The key is never shown, logged, exported or sent; the UI's Settings says only where it comes from. Anyone who can read the database can compute the draw, and so tell beforehand which pull request would be drawn, as can anyone who can read a written key's variable.

The eval commands that read the config (`eval:replay`, `eval:backtest`, `eval:judge` and `eval:seed-memory`) read a written key the same way and stop on the same problems, though they draw nothing. With the deployment's config, run them with the variable set to any value of at least 32 characters, never the deployment's real key. With no key written they need none.

## Withdrawal

A standing approval is a review of the app's own, posted as an approval, recorded as published, not in dry run, and not recorded as dismissed. The service withdraws it when it no longer holds: its head or base branch is no longer the live one, or the newest published review of the pull request is not an approval that stands. The dismissal message is:

```text
This approval was for commit <commit>. A new commit, a change of the base branch, or a later review of this reviewer that does not approve means it no longer holds.
```

### When a withdrawal is asked for

A withdraw job is stored for a pull request with a standing approval:

- in the delivery's transaction, on a push, a retarget, a reopening and a merge, whatever the review filters say (a draft, an ignored author, a filtered base branch, the gate);
- on a `pull_request_review` delivery of action `dismissed` that names one of these approvals;
- in the transaction that records each publication of the pull request, the approving one included;
- when a start finds that GitHub holds as an approval a recorded review of a commit other than the live head;
- at start, out of dry run, after the gate's sweep and before listening, for each pull request stored as open whose standing approval carries a failed withdrawal. This logs `withdraw_sweep`, with the count, when it asks for at least one.

Each job is due at once. In dry run none is stored.

Withdraw jobs run in a lane of their own with 2 places, which is never paused, neither by the daily limit nor by the model's key. A pull request has at most one waiting: another ask moves its time to now and keeps its count of starts.

### What a withdraw job does

The job reads the pull request from GitHub. A closed pull request, and one GitHub does not find, are left as they are. On an open one, it withdraws each standing approval whose head or base branch is not the live one, and every standing approval when the newest published review is not an approval that stands.

For each approval it withdraws, it first reads the review:

- One GitHub holds as dismissed, or no longer as an approval, is recorded as dismissed by the git service, and nothing is sent.
- One GitHub holds as approved is dismissed with the message above and recorded as dismissed by the app. When the dismissal fails, the review is read once more, and if it is dismissed by then, that is no failure.
- One GitHub does not find is a failure (`review_not_found`), never a dismissal, and so is one in another state (`review_state_other`).

On an open pull request, every other standing approval is read too, once at each start of a job. One that carries a recorded failure is handled as in [How a recorded failure ends](#how-a-recorded-failure-ends). Any other needs no withdrawal: when GitHub holds it as dismissed, or no longer as an approval (by GitHub's own rule or by hand), it is recorded as dismissed by the git service, and on a gated pull request the check is asked for again. One GitHub holds as approved is left as it is. A read that fails, a review GitHub does not find and one in another state change nothing and are no failure.

A job ends `none` when there is no standing approval, `no_installation` when no installation is known, and `kept` when it withdrew nothing, had no recorded failure to read and recorded nothing.

### A later review of the same head

A later review of the same head that does not approve also withdraws the earlier approval of that head. So a re-check whose thread read or rule read fails takes back an approval that was right. Where GitHub then refuses the app's dismissal and no push follows, it becomes a failed withdrawal, with its alert and, under the gate, a failing check.

### Drafts

Converting a pull request to draft asks for nothing: the draft keeps the bot's approval. A push while it is a draft asks for a withdrawal, as any push does.

### When a withdrawal fails

A job that fails is tried again after 10 seconds, then after 60. At its third failing start, before it ends, it records the failure's code on each approval it could not dismiss and, when it could not read the pull request at that start, on every standing approval, with that read's code. When a failure is recorded for the first time, or cannot be recorded, it raises `dismissal_failed` once (with `reason`, `repo` and `number`) and asks for the gate's check.

The job runner drops a withdraw job that is a day old (`too_old`) or out of starts (`attempts_exhausted`). It records that reason on every standing approval of the pull request, raises `dismissal_failed` when a failure is recorded for the first time or cannot be recorded (so not for a pull request with no standing approval, nor one whose standing approvals all carried a failure already), and, out of dry run where the repository's gate is enabled, asks for the check.

Out of dry run, a job dropped as `too_old` is asked for again at once, as a new job. On an open pull request, that re-check withdraws the approvals that no longer hold and clears the failure of those GitHub still holds as approved. On a merged one, the targets are recorded as having stood at the merge (`stood_at_merge`), and a recorded failure on an approval that is not a target stays. A job dropped as `attempts_exhausted` is not asked for again, since a crash that repeats would loop.

No timer retries a failed withdrawal. The next push, retarget, reopening, publication, dismissed review or start of the service does.

### How a recorded failure ends

When a later withdraw job finds that approval dismissed, by the app, by GitHub's own rule or by hand, it is recorded as dismissed. On an open pull request, a job also reads each standing approval with a recorded failure that it does not withdraw (one at the live head and base, while the newest published review is an approval that stands): one GitHub holds as approved has its failure cleared, and is never dismissed this way. Either way, the gate's check is asked for again. A read that fails keeps the failure, with no new alert.

### The merge gate's check while an approval stands

On a gated pull request, the gate's check of the live head reflects any approval that is being withdrawn. In both states below, only `bypass` mode passes the check, whatever a skip or a review says.

| State | Check |
|---|---|
| A standing approval of another head or base branch stands, with no recorded failure | In progress, titled `Withdrawing an earlier approval` |
| A standing approval carries a recorded failure | Completed, `failure`, titled `Earlier approval not withdrawn (<code>)` |

The first state is what holds a merge on a branch approved under the gate alone. The withdraw job asks for the check again once it records the approval dismissed, or its failure. A recorded code that is not a short code shows as `internal_error`. When the recorded failures cannot be read, the evaluation fails as it does when a skip cannot be read: it is tried again, then raises `gate_check_failed`. The failing check's summary is:

```text
This reviewer approved an earlier commit of this pull request, or gave an approval it no longer stands behind, and could not dismiss it (`<code>`). While it stands it may count toward the approvals this branch requires, so this check fails.
Dismiss that approval on the pull request's page. The service also tries again at the next commit, the next review of this pull request and its next start, and this check is decided again once the approval is gone.
```

### A merge under a stale approval

On a merge's delivery, the job reads the standing approvals it would withdraw on an open pull request: each one whose head or base branch is not the merged pull request's, and every one when the newest published review is not an approval that stands (a dismissed newest approval counts too). None is dismissed after a merge.

- One GitHub still holds as approved is recorded as having stood at the merge (`stood_at_merge`) and raises `stale_approval_merged` (with `repo` and `number`), once.
- One GitHub holds as dismissed, or no longer as an approval, is recorded as dismissed by the git service.
- One GitHub does not find is left as it is, and so is an approval of the merged head and base while the newest published review is an approval that stands.

A review read that fails three times records and alerts nothing. An approval a person dismissed after the merge reads as never having stood.

### Dismissals on GitHub

The service reads GitHub's `pull_request_review` delivery of action `dismissed`, an event the app already needs. It stores nothing of its own, and asks for a withdraw job when it names a standing approval of the app's own. So while the pull request is open, a dismissal by GitHub's own rule or by hand is recorded seconds after GitHub delivers it, and on a gated pull request the check is asked for again. Once the pull request is merged, only the approvals a merge reads are read, so the dismissal of an approval of the merged head and base, while the newest published review is an approval that stands, is not recorded. Once it is closed, none is read. With approval off, the delivery is recorded as handled.

## Edge cases

### A refused approval

An approval is sent once. When GitHub refuses it (`review_rejected`), the decision becomes `refused`: the same review, with its inline comments, is posted once more as a comment ending with the `refused` paragraph. If GitHub refuses that too, it is posted as with approval off: without the inline notes, then with the body written whole, all as comments.

Any other failure of the approval's post is a failed publication, as for a comment: the review stays recorded, and the later start, 15 minutes on, asks GitHub for the app's own reviews first and otherwise decides again. When GitHub refused an inline comment and not the approval, that head is not approved.

### A push that tells nothing new

Normally, a push whose review would show a person nothing new ends `nothing_new` and posts nothing (see [Leaving dry run](https://visto-ai.com/docs/leave-dry-run/)). With approval on, when the newest published review was posted as an approval, dismissed since or not, the review is recorded, posted and decided instead: an approval belongs to one head, and the new head needs its own. It makes no model call, and its scores are stored as any recorded review's are. When that read of the newest review fails, the review is posted as a comment whose paragraph gives `record_unreadable`.

A push to a head whose review is the newest published one still ends `already_reviewed`. So a head that comes back to the newest review's head after its approval was withdrawn stays unapproved until someone comments `/review`. Each such push adds one review to the pull request.

### Resumed and adopted reviews

A recorded review that a later start posts is decided at its post like any other. One that another job recorded keeps the text it was recorded with: its body is the recorded one, followed, with approval on, by the paragraph decided now. When GitHub refuses its inline comments, the body written whole keeps that job's trigger and names no requester, with approval on or off; so the body of a `/review` another job recorded says it was requested and names nobody.

A review the service finds already posted on GitHub is adopted, not decided again. When GitHub holds it as an approval, or as dismissed (only an approval can be dismissed), it is recorded as an approval with no decision code and, when dismissed, as dismissed by the git service. For an adopted approval at a commit other than the live head, not dismissed, a withdrawal is asked for. The stored body of an adopted approval lacks the paragraph GitHub's copy has. A review of the app's own whose commit GitHub gives as none (a commit pushed away and collected) is not listed, so it is never adopted.

### A push between the decision and the post

A push that lands between the read of the pull request and the post leaves an approval on the commit that was read. The publication's withdraw job reads the live head and dismisses it, so such an approval can stand for a few seconds on a head it was not decided for.

### A renamed or transferred repository

After a rename or a transfer that changes more than letter case, the service's records stay under the old name, so it does not see an approval posted before it. That approval stands until GitHub's own rule dismisses it at a push, or a person dismisses it.

### Dry run

In dry run nothing is decided, nothing is drawn and nothing is posted as an approval. No withdraw job is stored, and one found is dropped as `dry_run`. Every call that reads the rule, reads a review or dismisses one is refused.

## Alerts and log lines

| Alert | When |
|---|---|
| `feature_off` | At start, with the feature `approval`, for each permission or event the app lacks |
| `dismissal_failed` | A withdrawal failed for the first time on an approval, or its failure could not be recorded. Carries `reason`, `repo` and `number` |
| `stale_approval_merged` | A pull request was merged while an approval that no longer held still stood. Carries `repo` and `number` |
| `gate_check_failed` | The gate's check could not be evaluated, for example because recorded failures could not be read |

| Log line | What it carries |
|---|---|
| `review` | `approved` and `approval` (the code, or null for an adopted approval), only when the publication made a decision or adopted an approval |
| `withdraw` | One line for each start of a withdraw job, so a job put back twice logs three: the job, the repository, the number, the live state, the counts `standing`, `targets` (the approvals it withdraws, or reads at a merge), `dismissed`, `by_git_service` and `failed`, the first failure's code, the outcome, and whether it was put back. `dismissed` and `by_git_service` count only the approvals this start's own records changed |
| `job` | For a withdraw job the runner drops: `dropped`, with its reason, in place of a `withdraw` line |
| `accepted` | `withdraw: true` when its delivery asked for a withdraw job |
| `withdraw_sweep` | At start, the count of withdrawals asked for again |
| `audit_key` | At start, where the audit key came from |

No line holds a login, a branch, a path or a message.

## What is recorded

Each published review records, in `visto_ai.review_runs`, whether it was posted as an approval (`approved`) and the decision (`approval_code`). An approval also records:

| Column | Meaning |
|---|---|
| `dismissed_at` | When it was dismissed |
| `dismissed_by` | `app`, or `git_service` for one GitHub already held as dismissed, or no longer as an approval |
| `dismiss_failure` | The code of a withdrawal that failed, while the approval stands |
| `stood_at_merge` | When it still stood at a merge though it no longer held |

To read them, run `docker compose exec db psql -U postgres -d visto`:

```sql
-- approvals of the app's own that are not known as dismissed
select id, number, head_sha, review_id, approval_code, dismiss_failure, stood_at_merge from visto_ai.review_runs
where owner = 'acme' and repo = 'shop' and approved and dismissed_at is null order by id desc;
-- why the reviews of a pull request did or did not approve
select id, head_sha, published_at, approved, approval_code, dismissed_at, dismissed_by from visto_ai.review_runs
where owner = 'acme' and repo = 'shop' and number = 7 and published order by id;
```

## What it costs

- **Database reads.** Every publication with approval on reads the pull request's runs and stored comments from the database before it reads the pull request from GitHub, whether or not it then posts: also for one that then ends `closed` or `head_moved`, one held for the wait after a failed post, and one that adopts a review already posted.
- **GitHub reads.** A publication that gets to condition 8 reads the review threads: one request for each 100 threads, and one more for each 100 comments of a thread past its first 50. One that gets to condition 9 reads the rule: the rulesets list, one request for each 100 rules up to 10, then, when the list does not say the rule is on, the branch protection. A server error, or no answer, is tried once more.
- **Audited pull requests.** A pull request drawn for the audit sample has made every read above, as one that is approved, and is posted as a comment. The draw itself makes no read and no request. A condition that fails before the draw is named instead, so a pull request drawn at a head where another condition fails shows only that reason.
- **Withdraw jobs.** A withdraw job runs after each publication on a pull request with a standing approval, the approving one included, and usually finds nothing to do. Each start reads the pull request and, on an open one, every standing approval, so the job after an approving publication reads that approval once. An approval withdrawn takes two or three calls.
- **The paragraph.** Every review of a repository with approval on carries one more paragraph.
- **Notifiers.** An extension module's notifier is told of an approval, and of an audited review, as of any published review. Nothing in the notice tells them apart except the body's last paragraph, which the body of an adopted review lacks.
- **With approval off too.** Out of dry run, every delivery of a push, a retarget, a reopening, a merge and a dismissed review reads `review_runs` once in its transaction, and so do each publication, each start and each gate evaluation. The withdraw lane looks for due jobs with the other lanes. The state of the app's listed reviews and the access of thread comments are read and not stored. A review GitHub holds as an approval, found already posted, is recorded as one. A review another job recorded, when GitHub refuses its inline comments, is written whole naming no requester.

## Related

- [The score](https://visto-ai.com/docs/the-score/): the threshold that decides whether a person is needed.
- [The merge gate](https://visto-ai.com/docs/merge-gate/): the required check, and the other route to a safe approval.
- [Leaving dry run](https://visto-ai.com/docs/leave-dry-run/): posting, later reviews and earlier threads.
- [Configuration](https://visto-ai.com/docs/configuration/): where settings live and when a change applies.
