diff --git a/.janus/deploy.yml b/.janus/deploy.yml new file mode 100644 index 0000000..a5d479e --- /dev/null +++ b/.janus/deploy.yml @@ -0,0 +1,32 @@ +# Janus deploy pipeline — runs on the Agrippa host itself. +# +# Deliberately not .janus/ci.yml (the default path): the GitCode webhook selects +# this file with ?pipeline_path=.janus/deploy.yml, which leaves ci.yml free if +# Janus ever runs tests for this repo too, rather than conflating deploy and CI. +# +# Trigger is the `deploy` branch, not main: main takes doc-only commits, and +# this is the only environment — going live should be a deliberate +# fast-forward, and rolling back is moving the branch. +# +# Janus checks the repo out into its own workspace as the `janus` user; that +# checkout is only the trigger vehicle. The deploy acts on /opt/agrippa, which +# is root-owned and holds the untracked .env. See docs/design/08-deployment.md +# for why the tree is not janus-writable. +name: deploy + +on: + push: + branches: [deploy] + +# Serialize deploys. infra/deploy.sh also takes a flock, which covers manual +# runs that never reach Janus; this stops the queue forming inside the script. +concurrency: + group: deploy-${{ branch }} + +jobs: + deploy: + steps: + # Passing the exact SHA makes the deploy deterministic: it applies the + # commit that triggered this run, not whatever the branch tip has moved + # to since. sudo is a single NOPASSWD rule for this one script. + - run: sudo /opt/agrippa/infra/deploy.sh ${{ sha }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d39cd3..a79feb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,16 @@ All notable changes to Agrippa are documented here. The format follows - **SSE keepalive frames** — `GET /runs/:id/events` emitted nothing between events, so a run parked on a long agent turn or an approval looked like a dead connection to every intermediary: nginx cuts at `proxy_read_timeout` (60s default) and Cloudflare at ~100s. The stream now sends a comment frame every 15s (`AGRIPPA_SSE_KEEPALIVE_MS` to tune). Comment frames carry no `id:`, so they cannot disturb the `Last-Event-ID` cursor a client reconnects with. Previously the failure was survivable but noisy — EventSource reconnects and replays — now it doesn't happen. The knob is forwarded through compose and listed in both configuration tables, so it is actually settable. +- **`infra/deploy.sh` — a real deploy path for the Compose topology, with rollback.** The VM had `infra/vm/deploy.sh`; Docker had nothing, so updating meant remembering that `git pull && docker compose up -d` is *wrong here* — the SPA and API are baked into the api image, so it restarts the old code and reports success. The script always builds, tags images with the deployed commit (via the `AGRIPPA_VERSION` plumbing compose already had), waits on `/healthz`, and **rolls back to the previous tag** when the new one doesn't come up. Previously rollback was impossible at all: `build` overwrote `:latest` and left the prior image dangling and unnameable. A `flock` serializes concurrent deploys; only the current and previous tags are kept, since each pair is ~4 GB. + + The printed recovery drops and recreates the database rather than using `pg_restore --clean`, which only drops what the archive contains — tables a failed migration *added* would otherwise survive and can block the restore through dependencies; `--single-transaction --exit-on-error` makes a partial restore roll back instead of leaving a half-populated database. `HEALTH_TIMEOUT` is now a real wall-clock bound: it was counting only its own sleeps, so probe time (up to 10s each once a statement timeout was added) could push a nominal 180s past nine minutes. `infra/deploy.test.ts` covers the failure paths and the dump-retention cap with stubbed `docker` so they run in CI without a daemon — the script had none, and every property it asserts is one a review previously broke. + Rollback aborts rather than continuing if it cannot restore the previous commit, since starting the old images against the failed commit's compose file is the mismatch that restore exists to prevent. The worker check bounds its database query with a connect and statement timeout, so a wedged Postgres fails within the health timeout instead of blocking past it. + Pre-deploy dumps live in a `0700` directory with mode `0600`: they are a full copy of production, and the host also runs an unprivileged CI user that the deploy design treats as untrusted, so an inherited umask would have exposed them. The restore procedure is printed on **every** failure path — including the one where the rolled-back stack is also unhealthy, which is exactly when an irreversible migration is the cause — and it stops the app first, since `pg_restore --clean` cannot drop objects the api and worker still hold connections to. + Images are tagged with the full commit SHA rather than a 7-char prefix, so a prefix collision cannot overwrite a tag that is someone's rollback target, and a stale `:latest` is pruned once it is no longer that target. + It deploys **only commits reachable from `deploy`**: the script runs as root via a NOPASSWD sudoers rule, so an unconstrained argument would let its caller deploy any branch — including a compose file that mounts the host — and root-owning the tree would buy nothing. Verification covers both services (the api's compose healthcheck plus a fresh `executor_registrations` heartbeat), because a worker-only regression would otherwise deploy "successfully" and prune the image that worked. Rollback restores the previous commit's code *and config*, since re-upping old images against the failed commit's compose file is a mismatched state. It does **not** revert the database — the api migrates on boot before health is exposed and some migrations are irreversible — so a `pg_dump` is taken before every deploy and the exact restore command is printed on rollback rather than the schema being silently left behind. + +- **`.janus/deploy.yml` — push to `deploy`, and the server updates itself.** A [Janus](https://github.com/hutusi/janus) pipeline running on the host calls `deploy.sh` with the exact triggering SHA, so a deploy applies the commit that triggered it rather than whatever the branch tip drifted to. Trigger is the `deploy` branch rather than `main`, because `main` takes doc-only commits and this is the only environment — going live is a deliberate fast-forward, and rolling back is moving the branch. Janus reaches root through a single `NOPASSWD` sudoers entry for that one script, and the deploy tree stays root-owned: a janus-writable tree plus `sudo docker compose up` would let janus mount any host path as root, which would make the narrow rule worthless. + - **`.dockerignore`** — both images `COPY apps ./apps` / `COPY packages ./packages`, so every workspace `node_modules` in a developer's tree entered the build context and host-native binaries were layered into a Linux image. CI never caught it because it builds from a fresh checkout. Patterns are matched from the context root, so secrets and noise are listed in their `**/` form too: an unqualified `.env` would not have covered a git-ignored `apps/api/.env.local`. - **Template format v3 — flat authoring format (ADR-0016)** — templates can now be authored in a flat, GitHub-Actions-style `version: 3` format with no `apiVersion`/`kind`/`metadata`/`spec` wrappers: top-level `slug`/`scenario`/`name`, `faber`-or-`slots` agent declaration, flat `skills`/`mcpServers`/`subagents`, `models` (no `.roles` wrapper), top-level `limits`, and `outputs` (no `.artifacts` wrapper). v3 is source-only — `normalizeV3ToCompiled` flattens it into the unchanged v2 IR (`CompiledTemplate`), so the engine, API, and DB are untouched; `compileTemplate` routes on `version: 3` before the existing `apiVersion` branches. Six builtins converted (`pm/status-report`, `pm/plan-breakdown`, `swdev/requirement-delivery`, `swdev/requirements-dev`, `test/test-plan`, `test/regression-verify`); `swdev/bug-localize-fix.yaml` is intentionally kept on v1 as the v1→v2 upgrade-path fixture. v1/v2 sources keep working; the bilingual template-authoring manual and `docs/design/02` now teach v3 first. diff --git a/docs/design/08-deployment.md b/docs/design/08-deployment.md index bc1a259..f207745 100644 --- a/docs/design/08-deployment.md +++ b/docs/design/08-deployment.md @@ -52,7 +52,20 @@ Secrets policy: the master key and the deployment's **fallback** provider API ke - **First-run onboarding**: self-registration is closed (invite-only — see [05](05-api-and-auth.md#authentication)). The api/worker do **not** create users on boot. An operator runs `apps/api/src/cli/bootstrap-admin.ts` once (reads `AGRIPPA_BOOTSTRAP_EMAIL`/`PASSWORD` from the env file, creates the first `org_admin`, idempotent on email) — then signs in and invites members from the UI. Runbook in [Operations → First-run](../manual/en/06-operations.md#first-run-create-the-admin). - **Backup**: Postgres volume (pg_dump schedule is the operator's choice) + `ARTIFACT_STORAGE_ROOT` volume + the `AGRIPPA_SECRET_KEY`. Redis is disposable. -- **Upgrade**: pull images → `docker compose up -d` → api migrates on boot. Workers drain gracefully (in-flight runs resume on new workers via step-granular resume — see [04](04-execution-runtime.md)); the compose `stop_grace_period` must exceed the drain, so it is set to 60s rather than the 10s default. +- **Upgrade (Compose)**: `infra/deploy.sh []` — fetches from GitCode, builds images tagged + with the deployed commit, `up -d`, waits on `/healthz`, and **rolls back to the previous tag** if + that fails. It always builds: the SPA and API are baked into the api image, so a bare + `git pull && docker compose up -d` restarts the *old* code and reports success. A `flock` keeps + concurrent deploys from racing on the image tags. Automated by Janus on push to the `deploy` + branch (`.janus/deploy.yml`); the same script is the supported manual path. + It refuses any commit **not reachable from `deploy`** — the sudoers rule that lets Janus call it + as root would otherwise make every branch deployable, and root-owning the tree would buy nothing. + Verification covers **both** services: the api's compose healthcheck, and a fresh + `executor_registrations` heartbeat proving the worker registered its executors. Rollback restores + the previous commit's *code and config*, not the database — the api migrates on boot before it is + healthy and some migrations are irreversible, so Postgres is dumped beforehand and the restore + command is printed if a rollback happens. +- **Upgrade (images)**: pull images → `docker compose up -d` → api migrates on boot. Workers drain gracefully (in-flight runs resume on new workers via step-granular resume — see [04](04-execution-runtime.md)); the compose `stop_grace_period` must exceed the drain, so it is set to 60s rather than the 10s default. - **TLS / ingress**: out of scope; operators front the stack with their own reverse proxy. SSE requires the proxy to disable response buffering for `/api/v1/runs/*/events`, or live progress arrives in bursts. The stream emits a comment frame every 15s (`AGRIPPA_SSE_KEEPALIVE_MS`) so an idle run — a long agent turn, or one parked on an approval — never looks like a dead connection; a generous `proxy_read_timeout` remains worth setting as defence in depth for intermediaries whose idle limits you do not control. - **Health**: `GET /healthz` (api: DB ping). A per-worker heartbeat row for the admin UI is deferred past M1. Executor availability is observable via `executor_registrations` (workers upsert at boot and on the 60s sweeper tick). - **Sandboxing under Docker — bubblewrap does not work, and that is the accepted posture.** The worker image installs bubblewrap, but under Docker's default profiles it cannot create the namespaces it needs, and both executors treat an unavailable sandbox as a **silent** degradation (the Claude SDK is configured `failIfUnavailable: false`). Measured on Ubuntu 24.04 / Docker 29: the default seccomp profile blocks namespace creation outright; with `seccomp=unconfined` the namespace is created but mount setup then fails (`Failed to make / slave`) without `CAP_SYS_ADMIN`. Restoring the inner sandbox therefore costs `seccomp=unconfined` **plus** `CAP_SYS_ADMIN` — dismantling most of the outer boundary to rebuild a weaker inner one, which is a bad trade. **The container is the boundary**: the container itself, the non-root `bun` user, `/app` staying root-owned, the throwaway per-run workspace, and the env allow-list that keeps `DATABASE_URL`/`AGRIPPA_SECRET_KEY` out of agent subprocesses. Deployments that want OS-level sandboxing on top should use the VM/systemd topology, where bwrap works. Probe with `docker compose exec worker bwrap --unshare-all --ro-bind / / /bin/true` if you need to confirm the state on a given host. diff --git a/docs/manual/en/06-operations.md b/docs/manual/en/06-operations.md index 1bb1a2d..88bcf6e 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -111,6 +111,31 @@ A registered executor still needs a credential for the provider a step resolves ## Upgrades & scaling +Compose deployments use **`sudo infra/deploy.sh []`**: it fetches from GitCode, builds images tagged with the deployed commit, starts them, waits on `/healthz`, and **rolls back to the previous tag** if the new one doesn't come up. Run it by hand any time; pushing to the `deploy` branch runs the same script automatically via Janus (`.janus/deploy.yml`). + +It always rebuilds, deliberately: the SPA and the API are baked into the api image, so a bare `git pull && docker compose up -d` restarts the **old** code and looks like it worked. Build cache keeps a docs-only deploy cheap. A `flock` serializes concurrent deploys, and only the current and previous image tags are kept (each pair is ~4 GB). + +Two things it will not do. It **only deploys commits reachable from the `deploy` branch** — an arbitrary SHA is refused, which is what keeps the root-level sudo rule meaningful. And **rollback does not revert the database**: the API applies migrations on boot before it is healthy, and some are irreversible. + +The script therefore takes a `pg_dump` before every deploy, into `/var/lib/agrippa-deploy` (mode `0700`, dumps `0600`, last 5 retained — they are a full copy of production and the host also runs an unprivileged CI user). On any failure it prints the restore procedure rather than implying the schema came back: + +```sh +# the deploy prints the dump path it took; assign it rather than pasting a placeholder +DUMP=/var/lib/agrippa-deploy/pgdump-20260730-064413-070e868.dump +C="docker compose -f infra/docker-compose.yml --env-file infra/env/.env" + +$C stop api worker # dropdb needs zero connections +$C exec -T postgres dropdb -U agrippa --if-exists agrippa +$C exec -T postgres createdb -U agrippa agrippa +$C exec -T postgres pg_restore -U agrippa -d agrippa \ + --exit-on-error --single-transaction < "$DUMP" +$C start api worker # only once the restore succeeded +``` + +Drop and recreate rather than `pg_restore --clean`: `--clean` only drops what the archive contains, so tables the failed migration *added* would survive, and can block the restore through dependencies. `--single-transaction` with `--exit-on-error` means a partial restore rolls back instead of leaving a half-populated database. Stopping the app first is not optional — `dropdb` refuses while the api and worker hold connections. + +A deploy is reported successful only once the api reports healthy **and** every expected worker replica is running **and** a worker has registered its executors. The replica count matters because the worker registers before it starts consuming the queue, so a fresh registration alone would pass a worker that died during startup. Residual gap: a worker that stays up but wedges after registering is not detected. + Pull new images and `docker compose up -d` (VM: `sudo /opt/agrippa/infra/vm/deploy.sh`, which restarts the api first — see the VM section above). The api migrates on boot under an advisory lock, so rolling multiple replicas is safe. Draining workers is safe too: a killed worker's in-flight runs stay `running`, the queue retries them, and the engine **resumes step-granularly** — completed steps are never re-executed and token usage is never double-counted. Scale run throughput with `WORKER_REPLICAS` × `WORKER_SLOTS`. ### Upgrading from a deployment created before the compose project was named diff --git a/docs/manual/zh-CN/06-operations.md b/docs/manual/zh-CN/06-operations.md index 1c0c184..cdf9fdb 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -110,6 +110,31 @@ docker compose exec -T postgres psql -U agrippa -d agrippa \ ## 升级与扩容 +Compose 部署请使用 **`sudo infra/deploy.sh []`**:它从 GitCode 拉取代码、构建以所部署提交号打标签的镜像、启动、等待 `/healthz`,若新版本起不来则**回滚到上一个标签**。可随时手动执行;向 `deploy` 分支推送时,Janus 会通过 `.janus/deploy.yml` 自动运行同一个脚本。 + +它每次都会重新构建,这是刻意为之:SPA 与 API 都在构建镜像时打包进 api 镜像,因此单纯的 `git pull && docker compose up -d` 会重启**旧**代码,且看起来像是成功了。构建缓存让纯文档变更的部署依然很快。脚本用 `flock` 串行化并发部署,并且只保留当前与上一个镜像标签(每组约 4 GB)。 + +有两点它不会做。它**只部署能从 `deploy` 分支追溯到的提交**——任意 SHA 会被拒绝,这正是那条 root 级 sudo 规则得以成立的前提。以及**回滚不会还原数据库**:API 在启动、尚未健康之前就会执行迁移,其中部分不可逆。 + +因此脚本会在每次部署前做一次 `pg_dump`,存放于 `/var/lib/agrippa-deploy`(目录 `0700`、转储文件 `0600`,保留最近 5 份——它们是生产数据的完整副本,而本机上还运行着非特权的 CI 用户)。任何失败都会打印还原步骤,而不是让人误以为数据库也一并还原了: + +```sh +# 部署失败时会打印所用的转储文件路径;请把它赋给变量,而不是照抄占位符 +DUMP=/var/lib/agrippa-deploy/pgdump-20260730-064413-070e868.dump +C="docker compose -f infra/docker-compose.yml --env-file infra/env/.env" + +$C stop api worker # dropdb 要求没有任何连接 +$C exec -T postgres dropdb -U agrippa --if-exists agrippa +$C exec -T postgres createdb -U agrippa agrippa +$C exec -T postgres pg_restore -U agrippa -d agrippa \ + --exit-on-error --single-transaction < "$DUMP" +$C start api worker # 仅在还原成功之后 +``` + +要先删库重建,而不是用 `pg_restore --clean`:`--clean` 只会删除归档中存在的对象,因此失败迁移**新增**的表会残留下来,并可能因依赖关系导致还原失败。`--single-transaction` 配合 `--exit-on-error` 可保证部分还原会整体回滚,而不是留下一个半成品数据库。先停掉应用不是可选项——api 与 worker 仍持有连接时 `dropdb` 会拒绝执行。 + +只有当 api 报告健康、**且**每个预期的 worker 副本都在运行、**且**已有 worker 注册了执行器时,部署才算成功。副本数之所以重要,是因为 worker 在开始消费队列之前就会先注册,仅凭一条新注册记录会放过一个启动途中就挂掉的 worker。已知残留缺口:worker 起来了但注册后卡死,这种情况检测不到。 + 拉取新镜像后 `docker compose up -d` 即可(虚拟机:`sudo /opt/agrippa/infra/vm/deploy.sh`,会先重启 api——见上文虚拟机一节)。api 在启动时于咨询锁下迁移,多副本滚动升级安全。worker 排空同样安全:被终止的 worker 上进行中的执行保持 `running`,队列会重试,引擎**按步骤粒度续跑**——已完成的步骤不会重跑,Token 用量也不会重复计入。吞吐量 = `WORKER_REPLICAS` × `WORKER_SLOTS`。 ### 从「compose 项目未命名」时期的部署升级 diff --git a/infra/deploy.sh b/infra/deploy.sh new file mode 100755 index 0000000..acaca54 --- /dev/null +++ b/infra/deploy.sh @@ -0,0 +1,323 @@ +#!/usr/bin/env bash +# Agrippa Docker deploy/update — fetch, build, restart, verify, roll back. +# +# The VM topology has infra/vm/deploy.sh; this is its Compose counterpart, and +# it exists because "git pull && docker compose up -d" is WRONG here. The SPA +# and the API are baked into the api image at build time, so a pull-then-up +# restarts the OLD code and reports success. This script always builds. +# +# Images are tagged with the deployed commit rather than :latest, which is what +# makes rollback possible at all — a plain `build` overwrites :latest and leaves +# the previous image dangling and unnameable. +# +# ROLLBACK DOES NOT REVERT THE DATABASE. The API applies migrations on boot +# before it serves (apps/api/src/index.ts), and this repo has irreversible ones +# (0011_drop_money). A failed deploy can therefore leave older code against a +# newer schema. The pre-deploy dump below is what makes that recoverable; on +# rollback the exact restore command is printed rather than pretended away. +# +# Usage: +# deploy.sh [] # default: the deploy ref on $DEPLOY_REMOTE +# +# The commit must be reachable from $DEPLOY_REMOTE/$DEPLOY_REF. That is the +# privilege boundary: this script runs as root via a NOPASSWD sudoers rule, so +# an unconstrained argument would let its caller deploy any branch — including +# a compose file that mounts the host — and root-owning the tree would buy +# nothing. +# +# Overridable via environment: +# APP_DIR (/opt/agrippa) DEPLOY_REMOTE (gitcode) DEPLOY_REF (deploy) +# HEALTH_TIMEOUT (180) LOCK_WAIT (1800) STATE_DIR (/var/lib/agrippa-deploy) +set -euo pipefail + +APP_DIR="${APP_DIR:-/opt/agrippa}" +DEPLOY_REMOTE="${DEPLOY_REMOTE:-gitcode}" +DEPLOY_REF="${DEPLOY_REF:-deploy}" +HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-180}" +LOCK_WAIT="${LOCK_WAIT:-1800}" +LOCK_FILE="${LOCK_FILE:-/var/lock/agrippa-deploy.lock}" +STATE_DIR="${STATE_DIR:-/var/lib/agrippa-deploy}" +KEEP_DUMPS="${KEEP_DUMPS:-5}" + +COMPOSE_FILE="$APP_DIR/infra/docker-compose.yml" +ENV_FILE="$APP_DIR/infra/env/.env" +LAST_GOOD="$STATE_DIR/last-good" + +log() { printf '\n==> %s\n' "$*"; } +die() { + echo "deploy failed: $*" >&2 + exit 1 +} + +[ "$(id -u)" -eq 0 ] || die "run as root: sudo $0" +[ -f "$COMPOSE_FILE" ] || die "no compose file at $COMPOSE_FILE" +[ -f "$ENV_FILE" ] || die "no env file at $ENV_FILE" + +# The dumps below are a full copy of production, and this host also runs Janus +# as an unprivileged `janus` user that the deploy design treats as untrusted. +# An inherited 022 umask would write them 0644 in a 0755 directory — readable by +# exactly the account the root-owned tree exists to keep out. +umask 077 +mkdir -p "$STATE_DIR" +chmod 700 "$STATE_DIR" + +compose() { docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" "$@"; } + +# Only one deploy at a time. Janus's `concurrency:` already serializes webhook +# runs, but a manual invocation bypasses Janus entirely — and two concurrent +# builds racing on the same image tags corrupt each other's rollback target. +exec 9>"$LOCK_FILE" +flock -w "$LOCK_WAIT" 9 || die "another deploy holds $LOCK_FILE (waited ${LOCK_WAIT}s)" + +cd "$APP_DIR" + +# ── resolve the target commit, and prove it belongs to the deploy branch ───── +log "fetch ${DEPLOY_REMOTE}/${DEPLOY_REF}" +git remote get-url "$DEPLOY_REMOTE" >/dev/null 2>&1 || + die "remote '$DEPLOY_REMOTE' is not configured in $APP_DIR (see docs/design/08-deployment.md)" +# Only the deploy ref: fetching every branch would make every branch deployable. +fetched=0 +for attempt in 1 2 3; do + if git fetch --prune "$DEPLOY_REMOTE" \ + "+refs/heads/${DEPLOY_REF}:refs/remotes/${DEPLOY_REMOTE}/${DEPLOY_REF}"; then + fetched=1 + break + fi + echo "fetch attempt $attempt failed; retrying" >&2 + sleep $((attempt * 5)) +done +[ "$fetched" -eq 1 ] || die "could not fetch ${DEPLOY_REF} from $DEPLOY_REMOTE" + +target="${1:-${DEPLOY_REMOTE}/${DEPLOY_REF}}" +sha="$(git rev-parse --verify "${target}^{commit}" 2>/dev/null)" || + die "cannot resolve '$target' — is it on ${DEPLOY_REMOTE}/${DEPLOY_REF}?" + +# An explicit SHA is how the pipeline pins the triggering commit, so it stays +# supported — but it is verified, not trusted. Anything not reachable from the +# deploy branch is refused, which is what keeps the sudoers rule meaningful. +git merge-base --is-ancestor "$sha" "${DEPLOY_REMOTE}/${DEPLOY_REF}" || + die "refusing '$target' (${sha:0:7}): not reachable from ${DEPLOY_REMOTE}/${DEPLOY_REF}" + +short_sha="${sha:0:7}" + +# ── record what to go back to, BEFORE changing anything ───────────────────── +# The state file holds the last commit that actually passed verification. Fall +# back to the running image tag when it is absent (the first SHA-tagged deploy). +if [ -s "$LAST_GOOD" ]; then + previous_sha="$(cat "$LAST_GOOD")" + previous="$previous_sha" +else + # No state file yet (first deploy under this script). The image tag is the + # rollback target, but HEAD *is* the configuration currently deployed — record + # it too, so a first-deploy failure restores config instead of leaving the + # failed commit's compose file in place. + previous="$(docker inspect --format '{{.Config.Image}}' agrippa-api-1 2>/dev/null | sed 's/.*://')" || previous="" + [ -n "$previous" ] || previous="latest" + previous_sha="$(git rev-parse --verify HEAD 2>/dev/null || true)" +fi +log "deploying $short_sha (rollback target: ${previous:0:12})" + +# ── database dump, before the new API can migrate ─────────────────────────── +# Rollback restores code and config; it cannot undo a migration. This is what +# makes a bad deploy across a destructive migration recoverable at all. +dump="" +if [ "$(compose ps --status running --services 2>/dev/null | grep -cx postgres)" -eq 1 ]; then + dump="$STATE_DIR/pgdump-$(date +%Y%m%d-%H%M%S)-${short_sha}.dump" + log "database dump → $dump" + if compose exec -T postgres pg_dump -U agrippa -Fc agrippa > "$dump" 2>/dev/null; then + # keep the most recent few; each is small but they accumulate per deploy + ls -1t "$STATE_DIR"/pgdump-*.dump 2>/dev/null | tail -n +$((KEEP_DUMPS + 1)) | xargs -r rm -f + else + rm -f "$dump" + die "pre-deploy database dump failed — refusing to deploy without a recovery point" + fi +else + # nothing is running yet (first deploy) — there is no data to lose + log "database dump skipped (postgres not running)" +fi + +# Printed on EVERY failure path, not just the recoverable one. The case that +# most needs it is the one where the rolled-back stack is *also* unhealthy — +# typically because an irreversible migration already ran — and that is exactly +# where the old code fell through without saying anything. +# +# The procedure stops the application first: pg_restore --clean drops objects +# the running api and worker still hold connections to. +restore_hint() { + [ -n "$dump" ] || return 0 + cat >&2 <&2 + compose logs --tail 40 api worker >&2 2>/dev/null || true + + # Restore the previous COMMIT, not just the image tag: compose config, .env + # defaults and Dockerfiles all come from the tree, so re-upping old images + # against the failed commit's config would be a mismatched state. + if [ -n "$previous_sha" ]; then + # Fatal, not a warning: continuing would start the previous images against + # the FAILED commit's compose file — the exact config/image mismatch this + # restore exists to prevent. Better to stop with the tree visibly wrong + # than to bring the stack up in a state nobody can reason about. + git reset --hard -q "$previous_sha" || { + restore_hint + die "ROLLBACK ABORTED — could not restore the tree to ${previous_sha:0:12}; \ +the stack was NOT restarted and is still on ${short_sha}'s config. Fix the working \ +tree in $APP_DIR, then re-run this script." + } + else + echo "WARNING: no recorded last-good commit; config stays at $short_sha" >&2 + fi + + export AGRIPPA_VERSION="$previous" + compose up -d || { + restore_hint + die "ROLLBACK FAILED — instance is down; '${previous:0:12}' did not start" + } + # Said on both outcomes: the operator cannot tell from here whether a + # migration ran, and silence would read as "the database is fine". + restore_hint + if stack_ok; then + die "rolled back to ${previous:0:12} after a failed deploy of $short_sha" + fi + die "ROLLBACK UNHEALTHY — instance is down; '${previous:0:12}' also fails verification" +} + +# ── verification: both services, using the stack's own signals ────────────── +# Not a host-port probe: AGRIPPA_PORT may bind a specific non-loopback +# interface, where curling 127.0.0.1 fails on a perfectly good deploy. +api_ok() { + # the api service defines a healthcheck in compose, so this is authoritative + [ "$(compose ps --format '{{.Health}}' api 2>/dev/null | head -n1)" = "healthy" ] +} + +# The worker has no HTTP surface and no healthcheck, so verify two things. +# +# A fresh executor_registrations row alone is NOT enough: the worker registers +# (apps/worker/src/index.ts) before it starts its pg-boss consumers, so it can +# register and then die during consumer setup and still look deployed. And +# registrations are global per executor, so with WORKER_REPLICAS > 1 one healthy +# replica would mask the rest. Also require every expected replica to be +# running — compose sets no restart policy, so a crashed worker leaves an exited +# container that this catches. +# +# Residual gap, accepted: a worker that stays up but wedges *after* registering +# is not detected. Closing that needs a readiness signal written after +# boss.work() returns, which is an apps/worker change. +worker_ok() { + local since="$1" n running expected + # Take digits only: the env file may carry an inline comment or CRLF endings, + # and a non-numeric value would make the comparison below error out on every + # attempt rather than compare anything. + expected="$(sed -nE 's/^WORKER_REPLICAS=[[:space:]]*([0-9]+).*/\1/p' "$ENV_FILE" | tail -n1)" + expected="${expected:-1}" + running="$(compose ps --status running --format '{{.Service}}' 2>/dev/null | grep -cx worker || true)" + [ "$running" -eq "$expected" ] 2>/dev/null || return 1 + # Bounded: a wedged Postgres would otherwise block here indefinitely, and the + # caller's HEALTH_TIMEOUT loop cannot fire while this command hangs. + # Bounded by whatever is left of HEALTH_TIMEOUT, so a wedged Postgres cannot + # push the total past the stated budget. statement_timeout goes through + # PGOPTIONS, not an inline `set`: a `set` statement prints "SET" to stdout, + # which would corrupt the count this reads. + local budget="${probe_budget:-10}" + [ "$budget" -gt 1 ] 2>/dev/null || budget=1 + [ "$budget" -le 10 ] || budget=10 + # spelled out rather than via compose(): `timeout` needs a real command + n="$(timeout "$budget" \ + docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" \ + exec -T -e PGCONNECT_TIMEOUT=2 -e PGOPTIONS="-c statement_timeout=${budget}s" \ + postgres psql -U agrippa -d agrippa -tAc \ + "select count(*) from executor_registrations where registered_at > to_timestamp($since);" \ + 2>/dev/null | tr -d '[:space:]')" + [ -n "$n" ] && [ "$n" -gt 0 ] 2>/dev/null +} + +# HEALTH_TIMEOUT is a wall-clock bound, so this tracks an absolute deadline +# rather than counting its own sleeps. Counting sleeps understates the real +# elapsed time badly: each iteration also pays for a `compose ps` and a psql +# round trip, so a nominal 180s could run for many minutes. `probe_budget` +# hands the remaining time to the database probe, which is otherwise the +# slowest step. +stack_ok() { + local since=$(($(date +%s) - 5)) + local deadline=$(($(date +%s) + HEALTH_TIMEOUT)) + while [ "$(date +%s)" -lt "$deadline" ]; do + probe_budget=$((deadline - $(date +%s))) + if api_ok && worker_ok "$since"; then + return 0 + fi + # capped by what is left, so the final iteration cannot sleep past the + # deadline — a stated bound should be honoured exactly, not approximately + remaining=$((deadline - $(date +%s))) + [ "$remaining" -gt 0 ] || break + sleep "$((remaining < 5 ? remaining : 5))" + done + probe_budget=5 + api_ok || echo " api never became healthy" >&2 + worker_ok "$since" || echo " worker never became ready" >&2 + return 1 +} + +# ── build ──────────────────────────────────────────────────────────────────── +# Always build: the cache makes a docs-only deploy cheap, and change-detection +# that guesses wrong fails silently by running stale code. +git reset --hard -q "$sha" +git --no-pager log -1 --format=' %h %s' | cat + +# Tag with the FULL sha, not the 7-char prefix: a prefix collision would +# overwrite an existing tag, and if that tag were the rollback target the +# rollback would silently restore the wrong image. Log messages stay short. +export AGRIPPA_VERSION="$sha" +log "build ($AGRIPPA_VERSION)" +# Prove the tag reached compose before spending minutes building — the .env +# file also defines AGRIPPA_VERSION, and shell precedence is the only reason +# ours wins. +compose config 2>/dev/null | grep -q "agrippa-api:${sha}" || + rollback "AGRIPPA_VERSION did not reach compose; images would be mistagged" +compose build || rollback "image build failed" + +# ── start, verify, roll back on any failure ───────────────────────────────── +log "up -d" +# Not bare: under `set -e` a port collision or mount failure would exit here, +# leaving the new commit checked out and never rolling back. +compose up -d || rollback "docker compose up -d failed" + +log "verifying api + worker (${HEALTH_TIMEOUT}s)" +stack_ok || rollback "health check failed" + +# ── success ───────────────────────────────────────────────────────────────── +echo "$sha" > "$LAST_GOOD" +log "healthy — deployed $short_sha" + +# Prune superseded images. Each pair is ~4 GB, so keeping every deploy fills +# the disk. The rollback target is retained; anything older is not. +log "prune" +for repo in agrippa-api agrippa-worker; do + docker images --format '{{.Repository}}:{{.Tag}}' | + grep "/${repo}:" | + grep -vE ":(${sha}|${previous})$" | + xargs -r docker rmi >/dev/null 2>&1 || true +done + +log "deployed $short_sha" diff --git a/infra/deploy.test.ts b/infra/deploy.test.ts new file mode 100644 index 0000000..e85f5eb --- /dev/null +++ b/infra/deploy.test.ts @@ -0,0 +1,277 @@ +/** + * Behavioural tests for infra/deploy.sh. + * + * Every property asserted here is one a review has actually broken at least + * once — an off-branch commit being deployable as root, `up -d` failing without + * rollback, images tagged with a short SHA, dumps landing world-readable. They + * were each verified by hand against the live host, which does not survive the + * next refactor; this does. + * + * Deliberately no Docker. The script's dependencies (`docker`, `id`, `sleep`, + * `timeout`) are replaced by stubs earlier on PATH, so these run in CI where no + * daemon exists. `git` stays real — the commit-reachability check is the whole + * privilege boundary and stubbing it would test nothing. + */ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from "node:fs"; +import { mkdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const SCRIPT = path.resolve(import.meta.dirname, "deploy.sh"); + +/** A `docker` stub: enough of the surface deploy.sh touches, scenario-driven by env. */ +const DOCKER_STUB = `#!/usr/bin/env bash +# Records what it was asked to do so tests can assert on ordering, and answers +# the handful of queries deploy.sh makes. Scenarios come from STUB_* env vars. +# AGRIPPA_VERSION is logged because it arrives via the environment, not argv — +# it is the tag the build actually uses, so tests must be able to see it. +echo "$* [AGRIPPA_VERSION=\${AGRIPPA_VERSION:-}]" >> "$STUB_LOG" + +# flags precede the subcommand (docker compose -f X --env-file Y ), so +# scan for it rather than indexing positionally +for a in "$@"; do + case "$a" in config|ps|build|up|exec|logs|stop|start) sub="$a"; break;; esac +done + +case "$1" in + compose) + case "$sub" in + config) + # deploy.sh greps this for the tag it expects to have set + [ "\${STUB_CONFIG_TAG:-1}" = "1" ] && + echo " image: ghcr.io/ainaive/agrippa-api:\${AGRIPPA_VERSION}" + exit 0 ;; + ps) + case "$*" in + *"--services"*) printf 'postgres\\napi\\nworker\\n' ;; + *"{{.Health}}"*) echo "\${STUB_API_HEALTH:-healthy}" ;; + *"{{.Service}}"*) + for _ in $(seq 1 "\${STUB_WORKERS_RUNNING:-1}"); do echo worker; done ;; + esac + exit 0 ;; + build) exit "\${STUB_BUILD_RC:-0}" ;; + up) exit "\${STUB_UP_RC:-0}" ;; + logs) exit 0 ;; + exec) + case "$*" in + *pg_dump*) printf 'FAKEDUMP'; exit "\${STUB_DUMP_RC:-0}" ;; + *psql*) + # the worker readiness probe; STUB_PROBE_DELAY makes it slow + [ -n "\${STUB_PROBE_DELAY:-}" ] && /bin/sleep "$STUB_PROBE_DELAY" + echo "\${STUB_REGISTRATIONS:-1}"; exit 0 ;; + esac + exit 0 ;; + esac + exit 0 ;; + inspect) echo "ghcr.io/ainaive/agrippa-api:\${STUB_RUNNING_TAG:-latest}"; exit 0 ;; + images) exit 0 ;; + rmi) exit 0 ;; +esac +exit 0 +`; + +type Scenario = Record; + +let dir: string; +let appDir: string; +let stateDir: string; +let binDir: string; +let stubLog: string; +let deploySha: string; + +const run = async (scenario: Scenario = {}, args: string[] = []) => { + const proc = Bun.spawn(["bash", SCRIPT, ...args], { + env: { + ...process.env, + PATH: `${binDir}:${process.env.PATH}`, + APP_DIR: appDir, + STATE_DIR: stateDir, + LOCK_FILE: path.join(dir, "lock"), + DEPLOY_REMOTE: "selftest", + DEPLOY_REF: "deploy", + // small: sleeps are stubbed, so only probe time accrues, and failure + // scenarios must finish inside bun's per-test timeout + HEALTH_TIMEOUT: "2", + STUB_LOG: stubLog, + ...scenario, + }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { stdout, stderr, exitCode, log: readFileSync(stubLog, "utf8") }; +}; + +const git = (cwd: string, ...args: string[]) => + Bun.spawnSync(["git", "-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd }); + +beforeEach(async () => { + dir = mkdtempSync(path.join(tmpdir(), "deploysh-")); + appDir = path.join(dir, "app"); + stateDir = path.join(dir, "state"); + binDir = path.join(dir, "bin"); + stubLog = path.join(dir, "stub.log"); + writeFileSync(stubLog, ""); + + await mkdir(binDir, { recursive: true }); + for (const [name, body] of [ + ["docker", DOCKER_STUB], + // the script refuses to run unless euid 0; tests are not root + ["id", "#!/usr/bin/env bash\necho 0\n"], + // no-op so the probe loop costs nothing; the stub's own delay uses /bin/sleep + ["sleep", "#!/usr/bin/env bash\nexit 0\n"], + // macOS ships neither; both exist on the Linux hosts this runs on, so they + // are stubbed rather than skipped. Consequence: the lock and the per-probe + // kill are NOT exercised here — `timeout` passes the command straight + // through, so what these cases prove is the deadline loop, not the kill. + ["flock", "#!/usr/bin/env bash\nexit 0\n"], + ["timeout", '#!/usr/bin/env bash\nshift\nexec "$@"\n'], + ] as const) { + const p = path.join(binDir, name); + writeFileSync(p, body, { mode: 0o755 }); + } + + // a real repo: reachability is enforced with git, so it must be genuine + await mkdir(path.join(appDir, "infra", "env"), { recursive: true }); + writeFileSync(path.join(appDir, "infra", "docker-compose.yml"), "services:\n api:\n"); + writeFileSync(path.join(appDir, "infra", "env", ".env"), "AGRIPPA_PORT=127.0.0.1:3001\n"); + git(appDir, "init", "-q", "-b", "main"); + git(appDir, "add", "-A"); + git(appDir, "commit", "-qm", "base"); + git(appDir, "branch", "-f", "deploy", "HEAD"); + // fetched from itself, so `git fetch selftest` resolves without a network + git(appDir, "remote", "add", "selftest", appDir); + deploySha = new TextDecoder().decode(git(appDir, "rev-parse", "deploy").stdout).trim(); +}); + +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe("infra/deploy.sh", () => { + it("refuses a commit that is not reachable from the deploy branch", async () => { + // the privilege boundary: janus passes this argument, so it must be verified + git(appDir, "checkout", "-q", "-b", "feature"); + writeFileSync(path.join(appDir, "infra", "docker-compose.yml"), "services:\n evil:\n"); + git(appDir, "commit", "-aqm", "hostile"); + const offBranch = new TextDecoder().decode(git(appDir, "rev-parse", "HEAD").stdout).trim(); + git(appDir, "checkout", "-q", "main"); + + const r = await run({}, [offBranch]); + expect(r.exitCode).not.toBe(0); + expect(r.stderr).toContain("not reachable from"); + // and it bailed before doing anything expensive or destructive + expect(r.log).not.toContain("build"); + expect(r.log).not.toContain("up -d"); + }); + + it("deploys the happy path, tagging with the full SHA", async () => { + const r = await run(); + expect(r.exitCode).toBe(0); + expect(r.stdout).toContain("healthy"); + // the build ran with the FULL 40-char SHA as its tag, not a 7-char prefix + // that a collision could overwrite + expect(r.log).toContain(`build [AGRIPPA_VERSION=${deploySha}]`); + expect(readFileSync(path.join(stateDir, "last-good"), "utf8").trim()).toBe(deploySha); + }); + + it("keeps the dump private to root", async () => { + await run(); + const dumps = [...new Bun.Glob("pgdump-*.dump").scanSync(stateDir)]; + expect(dumps.length).toBe(1); + expect(statSync(path.join(stateDir, dumps[0] as string)).mode & 0o777).toBe(0o600); + expect(statSync(stateDir).mode & 0o777).toBe(0o700); + }); + + it("retains only the newest KEEP_DUMPS dumps", async () => { + // dumps are a full copy of production, so unbounded retention is both a + // disk and an exposure problem. Seed more than the cap with distinct mtimes + // so "newest" is well defined, then check the oldest are the ones dropped. + mkdirSync(stateDir, { recursive: true }); + const seeded = ["0001", "0002", "0003", "0004", "0005", "0006"].map((n) => { + const f = path.join(stateDir, `pgdump-2026010${n[3]}-000000-seed${n}.dump`); + writeFileSync(f, "old"); + return f; + }); + for (const [i, f] of seeded.entries()) { + const t = new Date(1e9 + i * 1000); + utimesSync(f, t, t); + } + + const r = await run({ KEEP_DUMPS: "3" }); + expect(r.exitCode).toBe(0); + + const left = [...new Bun.Glob("pgdump-*.dump").scanSync(stateDir)].sort(); + expect(left.length).toBe(3); + // the run's own dump survives, and so do the two newest seeds + expect(left.some((f) => f.includes("seed0006"))).toBe(true); + expect(left.some((f) => f.includes("seed0005"))).toBe(true); + expect(left.some((f) => f.includes("seed0001"))).toBe(false); + }); + + it("rolls back when docker compose up -d fails", async () => { + const r = await run({ STUB_UP_RC: "1" }); + expect(r.exitCode).not.toBe(0); + expect(r.stderr).toContain("up -d failed"); + expect(r.stderr).toContain("rolling back"); + }, 20_000); + + it("rolls back when the api never becomes healthy", async () => { + const r = await run({ STUB_API_HEALTH: "starting" }); + expect(r.exitCode).not.toBe(0); + expect(r.stderr).toContain("api never became healthy"); + expect(r.stderr).toContain("rolling back"); + }, 20_000); + + it("fails when a worker replica is not running, even with a fresh registration", async () => { + // the case that used to pass: api healthy, registration present, worker dead + const r = await run({ STUB_WORKERS_RUNNING: "0", STUB_REGISTRATIONS: "1" }); + expect(r.exitCode).not.toBe(0); + expect(r.stderr).toContain("worker never became ready"); + }, 20_000); + + it("aborts before building when the version does not reach compose", async () => { + // guards the class of bug where the tag silently fails to propagate + const r = await run({ STUB_CONFIG_TAG: "0" }); + expect(r.exitCode).not.toBe(0); + expect(r.stderr).toContain("did not reach compose"); + }); + + it("treats HEALTH_TIMEOUT as wall-clock even when probes are slow", async () => { + // each probe sleeps 2s; with sleep stubbed out, only probe time accumulates. + // Counting sleeps instead of elapsed time would loop far past the budget. + const started = Date.now(); + const r = await run({ + HEALTH_TIMEOUT: "3", + STUB_API_HEALTH: "starting", + STUB_PROBE_DELAY: "1", + }); + const elapsed = (Date.now() - started) / 1000; + expect(r.exitCode).not.toBe(0); + // budget + one in-flight probe + process startup. Counting sleeps instead + // of elapsed time would run several multiples of this. + expect(elapsed).toBeLessThan(12); + }, 20_000); + + it("prints a recovery procedure that drops and recreates, not --clean", async () => { + const r = await run({ STUB_UP_RC: "1" }); + expect(r.stderr).toContain("dropdb"); + expect(r.stderr).toContain("createdb"); + expect(r.stderr).toContain("--single-transaction"); + // the pg_restore invocation itself must not use --clean: it only drops what + // the archive holds, so it cannot remove tables a failed migration added. + // (The surrounding prose explains that, so match the command, not the word.) + expect(r.stderr).not.toContain("-d agrippa --clean"); + }, 20_000); +});