Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ jobs:
run: shellcheck -S warning lib/pgrun-ci tests/*.sh
- name: database action
run: node --test tests/database.test.js
- name: migration verification (fake pgrun)
run: bash tests/test_verify.sh
- name: public-repository guard
run: bash tests/test_public_guard.sh
- name: python syntax
run: python3 -m py_compile lib/pgrun_profile.py
- name: profiler
Expand Down
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,16 @@ Your whole test suite, in parallel. Each worker gets its own empty branch with t

Don't point your ordinary suite at production-like data: most tests assume empty tables. Write tests for populated data, such as "every model loads its newest rows" or "this report runs", and run them here.

## Migration verification with PgBot (opt-in)

Set `verify: true` to verify the migration before the run. `pgrun bot verify` runs it on its own disposable PostgreSQL branch of the Safe Copy, and on a PGX branch too. PgBot then reviews the schema change: table rewrites, blocking index builds, `SET NOT NULL`, drops, renames, type changes.

The summary separates the outcomes: success, informational warnings, dangerous operations (with PgBot's advice), confirmed failures, unsupported on PGX, incomplete reviews and infrastructure errors. `verify-block-on` chooses which of them fail the step; by default `fail,dangerous,incomplete,error`.

It verifies one migration against the Safe Copy baseline. It does not detect conflicts between parallel migrations from different pull requests or agents against a changing production schema.

Inputs, verdicts, outputs and how to get the CLI: [docs/verify.md](docs/verify.md).

## Options

| Input | Default | |
Expand All @@ -198,9 +208,16 @@ Don't point your ordinary suite at production-like data: most tests assume empty
| `ttl` | `1h` | Branch lifetime if a runner dies. PGRun caps CI-token branches at `6h`. |
| `snapshot-warn-hours` / `snapshot-max-hours` | `24` / `720` | Warn, then fail, on an old Safe Copy. |
| `profile-max-exact-rows` / `profile-budget` / `profile-statement-timeout` | `5000000` / `900` / `120` | Bounds for the data checks. |
| `allow-public-repository` | `false` | Production-like mode refuses to run in a public repository, whose logs anyone can read. |

Output: `result` (`PASS` or `FAIL`).
| `allow-public-repository` | `false` | Production-like mode refuses to run in a public repository, whose logs anyone can read. Verification refuses as well. |
| `verify` | `false` | `true`: PgBot migration verification before the run ([docs/verify.md](docs/verify.md)). |
| `verify-command` | the migrate command | The command verified. |
| `verify-compare-pgx` | `true` | Also run it on PGX and compare schemas. |
| `verify-fail-on` | `critical` | Finding severity that counts as dangerous: `critical`, `warning`, `none`. |
| `verify-block-on` | `fail,dangerous,incomplete,error` | Verdict categories that fail the step, or `none`. |

Outputs:
- `result`: `PASS` or `FAIL`.
- With `verify: true`: `verify-verdict`, `verify-blocking`, `verify-categories` and `verify-report` (the path of the JSON report).

Services and system packages your app needs (Redis, `libvips`, …) stay ordinary steps in your job before this one. The action uses whatever the job provides.

Expand Down
54 changes: 54 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,42 @@ inputs:
api-url:
description: PGRun API URL.
default: https://app.pgrun.dev
verify:
description: >-
true runs PgBot migration verification (pgrun bot verify) before the mode's run: the migration on
disposable PostgreSQL (and PGX) branches of the Safe Copy, its schema change reviewed. Off by default.
default: "false"
verify-command:
description: Migration command to verify. Default — the resolved migrate-command (Rails — bin/rails db:migrate).
default: ""
verify-compare-pgx:
description: Also run the migration on a PGX branch and compare its schema with PostgreSQL's.
default: "true"
verify-fail-on:
description: "Schema-review severity that counts as dangerous: critical, warning or none."
default: critical
verify-block-on:
description: >-
Verdict categories that fail the step (comma list of fail, dangerous, unsupported, incomplete,
error, warning; or none). warning and unsupported only report by default.
default: fail,dangerous,incomplete,error

outputs:
result:
description: PASS or FAIL
value: ${{ steps.run.outcome == 'success' && 'PASS' || 'FAIL' }}
verify-verdict:
description: "With verify: true — pass, warning, dangerous, fail, unsupported, incomplete or error."
value: ${{ steps.verify.outputs.verdict }}
verify-blocking:
description: "With verify: true — true when a category in verify-block-on applied."
value: ${{ steps.verify.outputs.blocking }}
verify-categories:
description: "With verify: true — every category that applied, comma-separated."
value: ${{ steps.verify.outputs.categories }}
verify-report:
description: "With verify: true — path of the pgrun-verify JSON report on the runner (no URL or password in it)."
value: ${{ steps.verify.outputs.report }}

runs:
using: composite
Expand All @@ -115,6 +146,29 @@ runs:
bundler-cache: true
working-directory: ${{ inputs.working-directory }}

# Opt-in. pgrun creates and deletes its own verification branches; a
# blocking verdict stops here, before the mode's run.
- name: PGRun — verify the migration
id: verify
if: inputs.verify == 'true'
shell: bash
env:
PGRUN_API_TOKEN: ${{ inputs.token }}
PGRUN_API_URL: ${{ inputs.api-url }}
PGRUN_IN_API_URL: ${{ inputs.api-url }}
PGRUN_IN_PROJECT: ${{ inputs.project }}
PGRUN_IN_MIGRATE_COMMAND: ${{ inputs.migrate-command }}
PGRUN_IN_VERIFY_COMMAND: ${{ inputs.verify-command }}
PGRUN_IN_VERIFY_COMPARE_PGX: ${{ inputs.verify-compare-pgx }}
PGRUN_IN_VERIFY_FAIL_ON: ${{ inputs.verify-fail-on }}
PGRUN_IN_VERIFY_BLOCK_ON: ${{ inputs.verify-block-on }}
PGRUN_IN_WORKING_DIRECTORY: ${{ inputs.working-directory }}
PGRUN_IN_FRAMEWORK: ${{ inputs.framework }}
PGRUN_IN_RAILS_ENV: ${{ inputs.rails-env }}
PGRUN_IN_TTL: ${{ inputs.ttl }}
PGRUN_IN_ALLOW_PUBLIC_REPOSITORY: ${{ inputs.allow-public-repository }}
run: '"$GITHUB_ACTION_PATH/lib/pgrun-ci" verify'

- name: PGRun — ${{ inputs.mode }}
id: run
shell: bash
Expand Down
25 changes: 20 additions & 5 deletions database/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ function client(base, token) {
if (res.status >= 500 && attempt < tries) { await pause(attempt * 2); continue; }
let json = {};
try { json = await res.json(); } catch { /* empty or not JSON */ }
return { status: res.status, json };
return { status: res.status, json, retryAfter: res.headers.get('retry-after') };
} catch (e) {
lastErr = e;
if (attempt < tries) await pause(attempt * 2);
Expand Down Expand Up @@ -301,17 +301,29 @@ async function createBranches(api, project, i, ledger, deadline) {
let held = [];
let seq = 0;
let waited = 0;
const body = (name) => ({ name, ttl: i.ttl, ...(i.data === 'schema-only' ? { template: i.template } : {}) });
// Sprint 2026-11 §1B: the engine travels WITH the create, so the server
// decides it before provisioning (no create-then-check). The branch name is
// unique per run/attempt/sequence, so it doubles as the idempotency key: a
// retried POST returns the branch the first one made (200, replayed).
const body = (name) => ({
name, ttl: i.ttl, request_id: name,
...(i.engine !== 'any' ? { engine: i.engine } : {}),
...(i.data === 'schema-only' ? { template: i.template } : {}),
});
while (held.length < i.branches) {
seq += 1; // never reuse a name: a released one may still be deleting
const name = `${ledger.data.prefix}-${seq}`;
ledger.add(name);
const r = await api('POST', `/api/v1/projects/${enc(project)}/branches`, body(name));
if (r.status === 201) { held.push(name); continue; }
if (r.status === 201 || (r.status === 200 && r.json && r.json.replayed)) { held.push(name); continue; }
// A 4xx answer is a refusal: nothing was created under that name.
if (r.status >= 400 && r.status < 500) ledger.remove([name]);
const msg = message(r);
const retryable = (r.status === 422 && QUOTA.test(msg)) || (r.status === 409 && r.json.error === 'template_not_ready') ||
// Admission control (server 2026-11-14, PGRUN_ADMISSION_CONTROL): 429 capacity_busy means the
// host is momentarily full and nothing was created; wait what the server asks (Retry-After),
// within capacity-wait. 503 capacity_unavailable stays fatal: no host can ever take it.
const busy = r.status === 429 && r.json && r.json.error === 'capacity_busy';
const retryable = busy || (r.status === 422 && QUOTA.test(msg)) || (r.status === 409 && r.json.error === 'template_not_ready') ||
(r.status === 422 && /being refreshed/.test(msg));
if (!retryable) throw new Failure(`creating a branch failed (${r.status}): ${msg}`);
if (waited >= i.capacityWait) {
Expand All @@ -324,7 +336,10 @@ async function createBranches(api, project, i, ledger, deadline) {
ledger.remove(held.filter((_, n) => results[n] !== 'failed'));
held = [];
}
const s = 10 + Math.floor(Math.random() * 11);
const asked = busy ? Number(r.retryAfter || (r.json && r.json.retry_after_s)) : NaN;
const s = Number.isFinite(asked) && asked > 0
? Math.min(60, Math.max(5, Math.ceil(asked)))
: 10 + Math.floor(Math.random() * 11);
await pause(s);
waited += s;
}
Expand Down
1 change: 1 addition & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ This is GitHub's model for every Actions secret, and no YAML condition changes i
## Supply chain

- The pgrun CLI is downloaded from its GitHub release and checked against a SHA-256 pinned in the action. A mismatch stops the run before the CLI is unpacked.
- Migration verification (`verify: true`) uses a pgrun CLI already on the runner. The action never downloads an unpinned one, and no release with `bot verify` is pinned yet. pgbot, when missing, comes from `pgrun bot install`, which verifies pgrun's pinned SHA-256. The migration runs under `env -u PGRUN_API_TOKEN`. Its output is redacted of URLs and the token, and printed between `::stop-commands::` markers so it cannot issue workflow commands.
- `ruby/setup-ruby` is pinned by commit.
- The action only sends the token to an `https://` API URL (or localhost, for tests).
- The action itself should be pinned by commit SHA in security-sensitive repositories.
88 changes: 88 additions & 0 deletions docs/verify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Migration verification (`verify: true`)

Opt-in, off by default. With `verify: true` the action runs
`pgrun bot verify --json` before the mode's run (production-like or fast):

1. pgrun creates its own disposable branches of the project's **Safe Copy**: a PostgreSQL branch (the canonical engine) and, with `verify-compare-pgx: true`, a PGX branch.
2. It runs your migration command on them, with `DATABASE_URL` set to the branch. The PGRun token is not in the migration's environment.
3. PgBot snapshots and lints the schema before and after, and classifies what the migration did: table rewrites, blocking index builds, `SET NOT NULL`, drops, renames, type changes.
4. With PGX, the two resulting schemas are compared.
5. pgrun deletes its branches on every exit path. Their TTL (`ttl`) is the backstop.

The action reads pgrun's report and turns it into a job summary, annotations and step outputs. A blocking verdict fails the step, and the mode's run is skipped.

```yaml
- uses: pgrundev/ci-action@<full sha>
with:
token: ${{ secrets.PGRUN_API_TOKEN }}
verify: true
# verify-command: npx prisma migrate deploy # default: the migrate command
# verify-block-on: fail,dangerous,incomplete,error
```

## What it does not do

It verifies **one** migration against the project's Safe Copy baseline. It does **not** detect conflicts between parallel migrations from different pull requests or agents against a changing production schema, for example two pull requests that each pass alone but conflict once both are merged. That check is not implemented.

## Verdicts

Every category that applied is listed. A run can be both `dangerous` and `warning`. The verdict is the highest-precedence one:

| Verdict | Summary section | Meaning | Blocks by default |
|---|---|---|---|
| `fail` | ❌ Confirmed failure | The migration exited non-zero on canonical PostgreSQL. | yes |
| `dangerous` | ⚠️ Dangerous operations | The schema review found findings at or above `verify-fail-on`. Each is listed with its advice. | yes |
| `unsupported` | 🧪 Unsupported on PGX | PGX could not run the migration, produced a different schema, or was unavailable for the project. PostgreSQL was fine. | no |
| `incomplete` | ❓ Incomplete | The schema review or lint could not run, for example with an old pgbot. **Never a pass.** | yes |
| `error` | 🛠️ Infrastructure error | A branch never became ready, an API failure, a command that could not start, the CLI missing, or a report the action cannot read. | yes |
| `warning` | ℹ️ Informational warnings | Findings below the threshold, new lint findings, or a verification branch that could not be deleted. | no |
| `pass` | ✅ Success | None of the above. | — |

`verify-block-on` sets which categories fail the step. The action passes it to pgrun and follows the report's `blocking` field. Warnings never fail the step unless you list `warning`.

The action also reports these as `error`, decided by `verify-block-on` like any other: no pgrun with `bot verify` on the runner; pgrun exiting without one pgrun-verify 1.x JSON document on stdout; exit 2 (not authenticated or not configured); exit 64 (arguments rejected, usually a CLI that is too old).

A refusal fails the step whatever `verify-block-on` says. The action refuses on:
- no token;
- `pull_request_target`;
- a public repository without `allow-public-repository: true`;
- an invalid input;
- no migration command;
- a Rails app without its bundle.

## Inputs

| Input | Default | |
|---|---|---|
| `verify` | `false` | `true` runs the verification step. |
| `verify-command` | the migrate command | The command pgrun runs on each verification branch (Rails: `bin/rails db:migrate`). It runs in `working-directory` with `RAILS_ENV` = `rails-env`. |
| `verify-compare-pgx` | `true` | Also run on PGX and compare schemas. |
| `verify-fail-on` | `critical` | Severity that makes a finding `dangerous`: `critical`, `warning` or `none`. |
| `verify-block-on` | `fail,dangerous,incomplete,error` | Comma list of categories that fail the step, or `none`. |

Shared with the rest of the action: `token`, `project`, `api-url`, `ttl`, `working-directory`, `framework`, `rails-env`, `allow-public-repository`.

## Outputs

| Output | |
|---|---|
| `verify-verdict` | `pass`, `warning`, `dangerous`, `fail`, `unsupported`, `incomplete` or `error`. |
| `verify-blocking` | `true` or `false`. |
| `verify-categories` | Every category that applied, comma-separated. |
| `verify-report` | Path of the pgrun-verify JSON report on the runner, for `actions/upload-artifact` or your own checks. Connection URLs are redacted from it. Its directory is unique per run, so several runs on one runner never share it. |

## Getting the CLI

The action never downloads a CLI it can't check against a SHA-256 it pins. The first pgrun release with `bot verify` is not pinned yet. Until it is, install pgrun in a step before this one, at an exact version. For example, with the npm package, which brings PgBot along:

```yaml
- run: npm install -g @pgrun/cli@<exact version>
```

If pgbot is missing, the action runs `pgrun bot install`. That installs pgrun's pinned pgbot release and verifies its SHA-256.

## Cleanup

pgrun deletes its verification branches itself, also when cancelled: the action forwards the signal and waits for it. A branch it could not delete is listed under **Verification branches** in the summary, with a warning annotation. Its TTL (`ttl`, default `1h`) expires it.

The verification step never touches the branches of the production-like or fast run. Their cleanup step works as before.
Loading
Loading