From 4467017fd5232bf8c44f833aed3ea9912efb338a Mon Sep 17 00:00:00 2001 From: John Hu Date: Wed, 29 Jul 2026 21:31:27 +0800 Subject: [PATCH 1/7] feat(infra): deploy the Compose stack on push to `deploy`, with rollback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updating the server was manual, and doing it twice in one session exposed the trap: the two updates needed different procedures. One was docs-only and `up -d` sufficed; the other touched apps/api and apps/web, which are baked into the api image, so `git pull && docker compose up -d` would have restarted the old code and reported success. Automation that guesses wrong here fails silently, so infra/deploy.sh always builds — the cache keeps a docs-only deploy cheap. Rollback was impossible before this: `docker compose build` overwrites :latest and leaves the previous image dangling and unnameable, on the only environment, with no staging. The script tags images with the deployed commit through the AGRIPPA_VERSION plumbing compose already had, so the prior tag survives and rollback is a re-up. It waits on /healthz and rolls back automatically when the new version doesn't come up, exiting non-zero so a pipeline reports failure rather than a false success. A flock serializes deploys, since manual runs bypass Janus's own concurrency group. Only the current and previous tags are kept — each pair is ~4 GB. .janus/deploy.yml triggers it on the `deploy` branch rather than main: main takes doc-only commits, so going live should be a deliberate fast-forward, and rolling back is moving the branch. It passes ${{ sha }} so a deploy applies the commit that triggered it rather than whatever the tip drifted to. The pipeline lives at .janus/deploy.yml rather than the default ci.yml, selected by the webhook's ?pipeline_path=, leaving ci.yml free if Janus ever runs tests here. Janus reaches root through one NOPASSWD sudoers entry for that one script, and the deploy tree stays root-owned. That ownership is the whole boundary: a janus-writable /opt/agrippa plus `sudo docker compose up` would let janus mount any host path as root, which makes "janus fetches, root deploys" no safer than putting janus in the docker group. It also fetches from GitCode rather than GitHub, because the webhook's SHA is guaranteed to exist there — fetching from GitHub races whatever mirrors between the two. Verified on the deployment host before committing: a real deploy produced SHA-tagged images and passed health, and a commit engineered to build cleanly but fail /healthz rolled back to the previous tag, left the instance healthy, and exited non-zero. --- .janus/deploy.yml | 32 +++++++ CHANGELOG.md | 4 + docs/design/08-deployment.md | 8 +- docs/manual/en/06-operations.md | 4 + docs/manual/zh-CN/06-operations.md | 4 + infra/deploy.sh | 143 +++++++++++++++++++++++++++++ 6 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 .janus/deploy.yml create mode 100755 infra/deploy.sh 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..861f450 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,10 @@ 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. + +- **`.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..86ca61b 100644 --- a/docs/design/08-deployment.md +++ b/docs/design/08-deployment.md @@ -52,7 +52,13 @@ 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. +- **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..3e04f35 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -111,6 +111,10 @@ 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). + 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..36ba5f7 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -110,6 +110,10 @@ 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)。 + 拉取新镜像后 `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..b4197cd --- /dev/null +++ b/infra/deploy.sh @@ -0,0 +1,143 @@ +#!/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. +# +# Usage: +# deploy.sh [] # default: the deploy ref on $DEPLOY_REMOTE +# +# Overridable via environment: +# APP_DIR (/opt/agrippa) DEPLOY_REMOTE (gitcode) DEPLOY_REF (deploy) +# HEALTH_TIMEOUT (120) LOCK_WAIT (1800) +set -euo pipefail + +APP_DIR="${APP_DIR:-/opt/agrippa}" +DEPLOY_REMOTE="${DEPLOY_REMOTE:-gitcode}" +DEPLOY_REF="${DEPLOY_REF:-deploy}" +HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-120}" +LOCK_WAIT="${LOCK_WAIT:-1800}" +LOCK_FILE="${LOCK_FILE:-/var/lock/agrippa-deploy.lock}" + +COMPOSE_FILE="$APP_DIR/infra/docker-compose.yml" +ENV_FILE="$APP_DIR/infra/env/.env" + +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" + +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 ──────────────────────────────────────────────── +# An explicit SHA (what the webhook pipeline passes) makes the deploy +# deterministic: we deploy what triggered the run, not whatever the branch tip +# has drifted to since. +log "fetch $DEPLOY_REMOTE" +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)" +fetched=0 +for attempt in 1 2 3; do + if git fetch --prune "$DEPLOY_REMOTE" "+refs/heads/*:refs/remotes/${DEPLOY_REMOTE}/*"; then + fetched=1 + break + fi + echo "fetch attempt $attempt failed; retrying" >&2 + sleep $((attempt * 5)) +done +[ "$fetched" -eq 1 ] || die "could not fetch from $DEPLOY_REMOTE" + +target="${1:-${DEPLOY_REMOTE}/${DEPLOY_REF}}" +sha="$(git rev-parse --verify "${target}^{commit}" 2>/dev/null)" || + die "cannot resolve '$target' — is the commit on $DEPLOY_REMOTE?" +short_sha="${sha:0:7}" + +# ── record the rollback target BEFORE changing anything ────────────────────── +# The tag the api container is actually running is the authoritative answer to +# "what do we go back to", more trustworthy than a state file we might have +# failed to write last time. +previous="$(docker inspect --format '{{.Config.Image}}' agrippa-api-1 2>/dev/null | sed 's/.*://')" || previous="" +[ -n "$previous" ] || previous="latest" +log "deploying $short_sha (rollback target: $previous)" + +git reset --hard "$sha" --quiet +git --no-pager log -1 --format=' %h %s' | cat + +# ── build ──────────────────────────────────────────────────────────────────── +# Always build: the cache makes a docs-only deploy cheap, and change-detection +# that guesses wrong fails silently by running stale code. +export AGRIPPA_VERSION="$short_sha" +log "build ($AGRIPPA_VERSION)" +# Prove the tag actually reached compose before spending minutes on a build — +# 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:${short_sha}" || + die "AGRIPPA_VERSION did not reach compose; images would be mistagged" +compose build + +health_ok() { + local port + # AGRIPPA_PORT may carry an interface (127.0.0.1:3001) — take the last field + port="$(grep -E '^AGRIPPA_PORT=' "$ENV_FILE" | tail -n1 | sed 's/.*[:=]//')" + port="${port:-3000}" + local waited=0 + while [ "$waited" -lt "$HEALTH_TIMEOUT" ]; do + if curl -sf --max-time 3 "http://127.0.0.1:${port}/healthz" >/dev/null; then + return 0 + fi + sleep 3 + waited=$((waited + 3)) + done + return 1 +} + +# ── start, verify, roll back on failure ────────────────────────────────────── +log "up -d" +compose up -d + +log "waiting for /healthz (${HEALTH_TIMEOUT}s)" +if health_ok; then + log "healthy — deployed $short_sha" +else + echo "health check failed; rolling back to $previous" >&2 + compose logs --tail 40 api >&2 || true + export AGRIPPA_VERSION="$previous" + compose up -d || + die "ROLLBACK FAILED — instance is down, previous tag '$previous' did not start" + if health_ok; then + die "rolled back to $previous after a failed deploy of $short_sha" + fi + die "ROLLBACK UNHEALTHY — instance is down; previous tag '$previous' also fails /healthz" +fi + +# ── prune superseded images ────────────────────────────────────────────────── +# Each pair is ~4 GB, so keeping every deploy fills the disk. The rollback +# target is retained; anything older is not (rollback is one step by design). +log "prune" +for repo in agrippa-api agrippa-worker; do + docker images --format '{{.Repository}}:{{.Tag}}' | + grep "/${repo}:" | + grep -vE ":(${short_sha}|${previous}|latest)$" | + xargs -r docker rmi >/dev/null 2>&1 || true +done + +log "deployed $short_sha ($(git rev-parse --short HEAD))" From 235481eb791cfe236f75c4751de6ebe51ba56c21 Mon Sep 17 00:00:00 2001 From: John Hu Date: Wed, 29 Jul 2026 22:20:32 +0800 Subject: [PATCH 2/7] fix(infra): constrain, verify and roll back the deploy properly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four P1s from review, all real. One of them falsified a security claim I made in the previous commit message and the PR body. I wrote that a compromised janus "cannot change what is deployed without pushing to the repo". False: the script fetched every branch and accepted any commit-ish as $1, and the pipeline passes ${{ sha }}, which janus controls. Any commit anywhere in the repo — including a feature branch carrying a compose file that mounts the host — was deployable as root, so the root-owned-tree boundary was bypassed by the script's own argument handling. It now fetches only the deploy ref and refuses anything not reachable from it. An explicit SHA stays supported because the pipeline pins the triggering commit, but it is verified rather than trusted. `compose up -d` was bare under set -e, so a port collision or mount failure exited immediately — after the tree was reset to the new commit and images built, with no rollback. It now routes through the same rollback path. Rollback re-upped previous images while the working tree was already at the failed commit, so compose config came from the version being rolled back from. It now restores the last-good commit first, recorded in a state file that only advances on success. Rollback still cannot revert the database: the api applies migrations on boot before it is healthy and some are irreversible, so the script dumps Postgres first and prints the exact pg_restore command instead of implying the schema came back. Verification only checked the api, so a worker-only regression deployed "successfully" and pruned the image that worked. It now waits on the api's compose healthcheck and on a fresh executor_registrations heartbeat, which proves the worker booted and registered its executors. That also replaces parsing AGRIPPA_PORT, which broke for a binding on a specific non-loopback interface. Each fix was exercised against the live host: an off-branch SHA is refused before any build; an unstartable service makes up -d fail and roll back; a commit that breaks only the worker fails the deploy and restores both the previous images and the previous compose config, printing the restore command. The last-good marker stayed put through every failure. --- CHANGELOG.md | 2 + docs/design/08-deployment.md | 7 + docs/manual/en/06-operations.md | 2 + docs/manual/zh-CN/06-operations.md | 2 + infra/deploy.sh | 203 ++++++++++++++++++++--------- 5 files changed, 157 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 861f450..738c676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,8 @@ All notable changes to Agrippa are documented here. The format follows - **`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. + 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`. diff --git a/docs/design/08-deployment.md b/docs/design/08-deployment.md index 86ca61b..f207745 100644 --- a/docs/design/08-deployment.md +++ b/docs/design/08-deployment.md @@ -58,6 +58,13 @@ Secrets policy: the master key and the deployment's **fallback** provider API ke `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). diff --git a/docs/manual/en/06-operations.md b/docs/manual/en/06-operations.md index 3e04f35..0fae97e 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -115,6 +115,8 @@ Compose deployments use **`sudo infra/deploy.sh []`**: it fetches from G 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 (kept in `/var/lib/agrippa-deploy`, last 5 retained) and, if it rolls back, prints the exact `pg_restore` command instead of implying the schema was restored too. A deploy is only reported successful once **both** the api reports healthy *and* the worker has registered its executors — a worker-only regression fails the deploy rather than passing silently. + 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 36ba5f7..597981a 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -114,6 +114,8 @@ Compose 部署请使用 **`sudo infra/deploy.sh []`**:它从 GitCode 它每次都会重新构建,这是刻意为之:SPA 与 API 都在构建镜像时打包进 api 镜像,因此单纯的 `git pull && docker compose up -d` 会重启**旧**代码,且看起来像是成功了。构建缓存让纯文档变更的部署依然很快。脚本用 `flock` 串行化并发部署,并且只保留当前与上一个镜像标签(每组约 4 GB)。 +有两点它不会做。它**只部署能从 `deploy` 分支追溯到的提交**——任意 SHA 会被拒绝,这正是那条 root 级 sudo 规则得以成立的前提。以及**回滚不会还原数据库**:API 在启动、尚未健康之前就会执行迁移,其中部分不可逆。因此脚本会在每次部署前做一次 `pg_dump`(存放于 `/var/lib/agrippa-deploy`,保留最近 5 份),一旦回滚就打印出确切的 `pg_restore` 命令,而不是让人误以为数据库也一并还原了。只有在 api 报告健康**且** 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 index b4197cd..eb8c6e0 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -10,23 +10,38 @@ # 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 (120) LOCK_WAIT (1800) +# 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:-120}" +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() { @@ -37,6 +52,7 @@ die() { [ "$(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" +mkdir -p "$STATE_DIR" compose() { docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" "$@"; } @@ -48,90 +64,159 @@ flock -w "$LOCK_WAIT" 9 || die "another deploy holds $LOCK_FILE (waited ${LOCK_W cd "$APP_DIR" -# ── resolve the target commit ──────────────────────────────────────────────── -# An explicit SHA (what the webhook pipeline passes) makes the deploy -# deterministic: we deploy what triggered the run, not whatever the branch tip -# has drifted to since. -log "fetch $DEPLOY_REMOTE" +# ── 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/*:refs/remotes/${DEPLOY_REMOTE}/*"; then + 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 from $DEPLOY_REMOTE" +[ "$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 the commit on $DEPLOY_REMOTE?" + 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 the rollback target BEFORE changing anything ────────────────────── -# The tag the api container is actually running is the authoritative answer to -# "what do we go back to", more trustworthy than a state file we might have -# failed to write last time. -previous="$(docker inspect --format '{{.Config.Image}}' agrippa-api-1 2>/dev/null | sed 's/.*://')" || previous="" -[ -n "$previous" ] || previous="latest" +# ── 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:0:7}" +else + previous="$(docker inspect --format '{{.Config.Image}}' agrippa-api-1 2>/dev/null | sed 's/.*://')" || previous="" + [ -n "$previous" ] || previous="latest" + previous_sha="" +fi log "deploying $short_sha (rollback target: $previous)" -git reset --hard "$sha" --quiet -git --no-pager log -1 --format=' %h %s' | cat +# ── 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 -# ── build ──────────────────────────────────────────────────────────────────── -# Always build: the cache makes a docs-only deploy cheap, and change-detection -# that guesses wrong fails silently by running stale code. -export AGRIPPA_VERSION="$short_sha" -log "build ($AGRIPPA_VERSION)" -# Prove the tag actually reached compose before spending minutes on a build — -# 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:${short_sha}" || - die "AGRIPPA_VERSION did not reach compose; images would be mistagged" -compose build - -health_ok() { - local port - # AGRIPPA_PORT may carry an interface (127.0.0.1:3001) — take the last field - port="$(grep -E '^AGRIPPA_PORT=' "$ENV_FILE" | tail -n1 | sed 's/.*[:=]//')" - port="${port:-3000}" - local waited=0 +rollback() { + local reason="$1" + echo "$reason; rolling back to $previous" >&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 + git reset --hard -q "$previous_sha" || echo "WARNING: could not restore tree to $previous" >&2 + else + echo "WARNING: no recorded last-good commit; config stays at $short_sha" >&2 + fi + + export AGRIPPA_VERSION="$previous" + compose up -d || + die "ROLLBACK FAILED — instance is down; '$previous' did not start.${dump:+ DB dump: $dump}" + if stack_ok; then + if [ -n "$dump" ]; then + # Say this even when the deploy carried no migration: the operator cannot + # tell from here, and silence would read as "the database is fine". + echo "NOTE: the database was NOT rolled back. If $short_sha applied a migration, restore with:" >&2 + echo " docker compose -f $COMPOSE_FILE --env-file $ENV_FILE exec -T postgres \\" >&2 + echo " pg_restore -U agrippa -d agrippa --clean --if-exists < $dump" >&2 + fi + die "rolled back to $previous after a failed deploy of $short_sha" + fi + die "ROLLBACK UNHEALTHY — instance is down; '$previous' also fails verification.${dump:+ DB dump: $dump}" +} + +# ── 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, but it upserts into +# executor_registrations at boot. A row newer than the deploy start proves it +# came up AND registered its executors — stronger than process liveness. +worker_ok() { + local since="$1" n + n="$(compose exec -T 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 +} + +stack_ok() { + local since=$(($(date +%s) - 5)) waited=0 while [ "$waited" -lt "$HEALTH_TIMEOUT" ]; do - if curl -sf --max-time 3 "http://127.0.0.1:${port}/healthz" >/dev/null; then + if api_ok && worker_ok "$since"; then return 0 fi - sleep 3 - waited=$((waited + 3)) + sleep 5 + waited=$((waited + 5)) done + api_ok || echo " api never became healthy" >&2 + worker_ok "$since" || echo " worker never registered an executor" >&2 return 1 } -# ── start, verify, roll back on failure ────────────────────────────────────── +# ── 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 + +export AGRIPPA_VERSION="$short_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:${short_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" -compose 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 "waiting for /healthz (${HEALTH_TIMEOUT}s)" -if health_ok; then - log "healthy — deployed $short_sha" -else - echo "health check failed; rolling back to $previous" >&2 - compose logs --tail 40 api >&2 || true - export AGRIPPA_VERSION="$previous" - compose up -d || - die "ROLLBACK FAILED — instance is down, previous tag '$previous' did not start" - if health_ok; then - die "rolled back to $previous after a failed deploy of $short_sha" - fi - die "ROLLBACK UNHEALTHY — instance is down; previous tag '$previous' also fails /healthz" -fi +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 (rollback is one step by design). +# 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}}' | @@ -140,4 +225,4 @@ for repo in agrippa-api agrippa-worker; do xargs -r docker rmi >/dev/null 2>&1 || true done -log "deployed $short_sha ($(git rev-parse --short HEAD))" +log "deployed $short_sha" From b6bb675670ae16c3a5d28bb6f56add9aa2052d41 Mon Sep 17 00:00:00 2001 From: John Hu Date: Thu, 30 Jul 2026 06:48:28 +0800 Subject: [PATCH 3/7] fix(infra): stop leaking database dumps, and verify what rollback claims MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four findings from review. The first is one I introduced in the previous commit, while adding a safety feature. The pre-deploy pg_dump was written with the inherited umask into a directory created without a mode, so it landed 0644 in a 0755 directory. Verified on the host: `sudo -u janus test -r ` succeeded. That is a full copy of production readable by exactly the account the root-owned tree exists to keep out. Adding the dump made recovery possible and data exposure certain. The script now sets umask 077 and pins the directory to 0700; the dumps already written on the server were chmodded separately, since a fix that only applies to future dumps leaves the exposure in place. On a first deploy there is no last-good file, so previous_sha was empty and rollback deliberately left the failed commit's compose file in place. HEAD is the configuration currently deployed, so it is now recorded as the fallback — strictly better than the warning-and-continue it replaces. A fresh executor_registrations row did not prove the worker works: it registers before starting its pg-boss consumers, so it can register and then die during startup and still pass. Registrations are also global per executor, so with WORKER_REPLICAS > 1 one healthy replica masked the rest. Verification now also requires every expected replica to be running, which catches the crash case because compose sets no restart policy and a dead worker leaves an exited container. A worker that stays up but wedges after registering is still not detected; that needs a readiness signal in apps/worker and is documented rather than papered over. The restore command was printed only when the rolled-back stack came back healthy — not in the case that most needs it, where an irreversible migration is why it is unhealthy. It is now printed from one helper on every failure path, and stops api and worker first, because pg_restore --clean cannot drop objects those still hold connections to. The procedure was tested by restoring a real dump into a scratch database and comparing row counts; production was not the test subject. --- CHANGELOG.md | 1 + docs/manual/en/06-operations.md | 12 ++++- docs/manual/zh-CN/06-operations.md | 12 ++++- infra/deploy.sh | 78 +++++++++++++++++++++++------- 4 files changed, 83 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 738c676..549f3bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ All notable changes to Agrippa are documented here. The format follows - **`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. + 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. 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. diff --git a/docs/manual/en/06-operations.md b/docs/manual/en/06-operations.md index 0fae97e..50f75c9 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -115,7 +115,17 @@ Compose deployments use **`sudo infra/deploy.sh []`**: it fetches from G 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 (kept in `/var/lib/agrippa-deploy`, last 5 retained) and, if it rolls back, prints the exact `pg_restore` command instead of implying the schema was restored too. A deploy is only reported successful once **both** the api reports healthy *and* the worker has registered its executors — a worker-only regression fails the deploy rather than passing silently. +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 +docker compose ... stop api worker # pg_restore --clean needs the app's connections gone +docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < +docker compose ... start api worker +``` + +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`. diff --git a/docs/manual/zh-CN/06-operations.md b/docs/manual/zh-CN/06-operations.md index 597981a..fe565e0 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -114,7 +114,17 @@ Compose 部署请使用 **`sudo infra/deploy.sh []`**:它从 GitCode 它每次都会重新构建,这是刻意为之:SPA 与 API 都在构建镜像时打包进 api 镜像,因此单纯的 `git pull && docker compose up -d` 会重启**旧**代码,且看起来像是成功了。构建缓存让纯文档变更的部署依然很快。脚本用 `flock` 串行化并发部署,并且只保留当前与上一个镜像标签(每组约 4 GB)。 -有两点它不会做。它**只部署能从 `deploy` 分支追溯到的提交**——任意 SHA 会被拒绝,这正是那条 root 级 sudo 规则得以成立的前提。以及**回滚不会还原数据库**:API 在启动、尚未健康之前就会执行迁移,其中部分不可逆。因此脚本会在每次部署前做一次 `pg_dump`(存放于 `/var/lib/agrippa-deploy`,保留最近 5 份),一旦回滚就打印出确切的 `pg_restore` 命令,而不是让人误以为数据库也一并还原了。只有在 api 报告健康**且** worker 已注册执行器之后,部署才算成功——仅 worker 出问题时部署会失败,而不会悄悄放行。 +有两点它不会做。它**只部署能从 `deploy` 分支追溯到的提交**——任意 SHA 会被拒绝,这正是那条 root 级 sudo 规则得以成立的前提。以及**回滚不会还原数据库**:API 在启动、尚未健康之前就会执行迁移,其中部分不可逆。 + +因此脚本会在每次部署前做一次 `pg_dump`,存放于 `/var/lib/agrippa-deploy`(目录 `0700`、转储文件 `0600`,保留最近 5 份——它们是生产数据的完整副本,而本机上还运行着非特权的 CI 用户)。任何失败都会打印还原步骤,而不是让人误以为数据库也一并还原了: + +```sh +docker compose ... stop api worker # pg_restore --clean 需要先断开应用连接 +docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < +docker compose ... start api worker +``` + +只有当 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`。 diff --git a/infra/deploy.sh b/infra/deploy.sh index eb8c6e0..15d98ca 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -52,7 +52,14 @@ die() { [ "$(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" "$@"; } @@ -98,13 +105,17 @@ short_sha="${sha:0:7}" # 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:0:7}" + 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="" + previous_sha="$(git rev-parse --verify HEAD 2>/dev/null || true)" fi -log "deploying $short_sha (rollback target: $previous)" +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 @@ -125,6 +136,25 @@ else 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 @@ -140,19 +170,17 @@ rollback() { fi export AGRIPPA_VERSION="$previous" - compose up -d || - die "ROLLBACK FAILED — instance is down; '$previous' did not start.${dump:+ DB dump: $dump}" + 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 - if [ -n "$dump" ]; then - # Say this even when the deploy carried no migration: the operator cannot - # tell from here, and silence would read as "the database is fine". - echo "NOTE: the database was NOT rolled back. If $short_sha applied a migration, restore with:" >&2 - echo " docker compose -f $COMPOSE_FILE --env-file $ENV_FILE exec -T postgres \\" >&2 - echo " pg_restore -U agrippa -d agrippa --clean --if-exists < $dump" >&2 - fi - die "rolled back to $previous after a failed deploy of $short_sha" + die "rolled back to ${previous:0:12} after a failed deploy of $short_sha" fi - die "ROLLBACK UNHEALTHY — instance is down; '$previous' also fails verification.${dump:+ DB dump: $dump}" + die "ROLLBACK UNHEALTHY — instance is down; '${previous:0:12}' also fails verification" } # ── verification: both services, using the stack's own signals ────────────── @@ -163,11 +191,25 @@ api_ok() { [ "$(compose ps --format '{{.Health}}' api 2>/dev/null | head -n1)" = "healthy" ] } -# The worker has no HTTP surface and no healthcheck, but it upserts into -# executor_registrations at boot. A row newer than the deploy start proves it -# came up AND registered its executors — stronger than process liveness. +# 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 + local since="$1" n running expected + expected="$(grep -E '^WORKER_REPLICAS=' "$ENV_FILE" | tail -n1 | cut -d= -f2)" + 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 n="$(compose exec -T 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 From 54e8f85a05ca8dec7b72cd53561312b0e61754a7 Mon Sep 17 00:00:00 2001 From: John Hu Date: Thu, 30 Jul 2026 06:48:49 +0800 Subject: [PATCH 4/7] fix(infra): tag images with the full SHA and let stale :latest be pruned MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review findings, both about tags rather than behaviour under failure. Image tags used the 7-char prefix. A prefix collision would overwrite an existing tag, and if that tag happened to be a rollback target the rollback would restore the wrong image silently. The probability is small, but the insurance costs nothing, so tags are the full SHA now. Log messages keep the short form, since a 40-char SHA in every line reads badly. The prune filter excluded :latest unconditionally, so the pre-SHA-tagging images were pinned forever even once they were no longer anyone's rollback target — on this deployment that was a ~4 GB pair held for nothing. It is now excluded only when it IS the rollback target, which is the case on a first deploy, before any SHA tag exists. --- CHANGELOG.md | 1 + infra/deploy.sh | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 549f3bc..25ed11b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ All notable changes to Agrippa are documented here. The format follows - **`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. 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. diff --git a/infra/deploy.sh b/infra/deploy.sh index 15d98ca..ba3ad70 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -235,12 +235,15 @@ stack_ok() { git reset --hard -q "$sha" git --no-pager log -1 --format=' %h %s' | cat -export AGRIPPA_VERSION="$short_sha" +# 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:${short_sha}" || +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" @@ -263,7 +266,7 @@ log "prune" for repo in agrippa-api agrippa-worker; do docker images --format '{{.Repository}}:{{.Tag}}' | grep "/${repo}:" | - grep -vE ":(${short_sha}|${previous}|latest)$" | + grep -vE ":(${sha}|${previous})$" | xargs -r docker rmi >/dev/null 2>&1 || true done From 3a1437d725542c1883eb9feabfa3a656e26f0a46 Mon Sep 17 00:00:00 2001 From: John Hu Date: Thu, 30 Jul 2026 07:03:56 +0800 Subject: [PATCH 5/7] fix(infra): abort rollback on a failed restore, and bound the worker check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from CodeRabbit's review of 54e8f85. A fourth — that the Chinese manual was not updated alongside the English one — is declined: b6bb675 changed both in the same commit, and the zh-CN file carries the same material. Rollback treated a failed `git reset --hard` as a warning and carried on to `compose up -d`, which would start the previous images against the FAILED commit's compose file. That is exactly the config/image mismatch the restore was added to prevent, so a warning was the wrong severity. It now aborts without restarting anything and says the tree needs fixing by hand, which is a worse-looking but honest outcome compared with a stack nobody can reason about. worker_ok parsed WORKER_REPLICAS with `cut`, so an inline comment or CRLF ending produced a non-numeric value and the comparison errored on every attempt. It now extracts digits only. The registration query was also unbounded: a wedged Postgres would block there indefinitely, and the caller's HEALTH_TIMEOUT loop cannot fire while the command hangs. Connect and statement timeouts are now set. statement_timeout is passed through PGOPTIONS rather than an inline `set`, because `set` prints "SET" to stdout and the count is read from there — the first attempt returned "SET3" and would have failed every deploy. Caught by running it against the live database before committing, along with confirming the timeout actually cancels a slow statement. The documented restore procedure used a literal `< ` placeholder, which does not run if pasted. It now assigns the dump path to a variable and quotes the redirect, in both locales. --- CHANGELOG.md | 1 + docs/manual/en/06-operations.md | 12 +++++++++--- docs/manual/zh-CN/06-operations.md | 12 +++++++++--- infra/deploy.sh | 26 ++++++++++++++++++++++---- 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25ed11b..39e2cf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ All notable changes to Agrippa are documented here. The format follows - **`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. + 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. diff --git a/docs/manual/en/06-operations.md b/docs/manual/en/06-operations.md index 50f75c9..8f43c72 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -120,11 +120,17 @@ Two things it will not do. It **only deploys commits reachable from the `deploy` 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 -docker compose ... stop api worker # pg_restore --clean needs the app's connections gone -docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < -docker compose ... start api worker +# 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 + +docker compose -f infra/docker-compose.yml --env-file infra/env/.env stop api worker +docker compose -f infra/docker-compose.yml --env-file infra/env/.env exec -T postgres \ + pg_restore -U agrippa -d agrippa --clean --if-exists < "$DUMP" +docker compose -f infra/docker-compose.yml --env-file infra/env/.env start api worker ``` +Stopping the app first is not optional: `pg_restore --clean` cannot drop objects the api and worker still hold connections to. + 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`. diff --git a/docs/manual/zh-CN/06-operations.md b/docs/manual/zh-CN/06-operations.md index fe565e0..1e4a2eb 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -119,11 +119,17 @@ Compose 部署请使用 **`sudo infra/deploy.sh []`**:它从 GitCode 因此脚本会在每次部署前做一次 `pg_dump`,存放于 `/var/lib/agrippa-deploy`(目录 `0700`、转储文件 `0600`,保留最近 5 份——它们是生产数据的完整副本,而本机上还运行着非特权的 CI 用户)。任何失败都会打印还原步骤,而不是让人误以为数据库也一并还原了: ```sh -docker compose ... stop api worker # pg_restore --clean 需要先断开应用连接 -docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < -docker compose ... start api worker +# 部署失败时会打印所用的转储文件路径;请把它赋给变量,而不是照抄占位符 +DUMP=/var/lib/agrippa-deploy/pgdump-20260730-064413-070e868.dump + +docker compose -f infra/docker-compose.yml --env-file infra/env/.env stop api worker +docker compose -f infra/docker-compose.yml --env-file infra/env/.env exec -T postgres \ + pg_restore -U agrippa -d agrippa --clean --if-exists < "$DUMP" +docker compose -f infra/docker-compose.yml --env-file infra/env/.env start api worker ``` +先停掉应用不是可选项:`pg_restore --clean` 无法删除 api 与 worker 仍持有连接的对象。 + 只有当 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`。 diff --git a/infra/deploy.sh b/infra/deploy.sh index ba3ad70..4fd31fe 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -164,7 +164,16 @@ rollback() { # 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 - git reset --hard -q "$previous_sha" || echo "WARNING: could not restore tree to $previous" >&2 + # 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 @@ -206,12 +215,21 @@ api_ok() { # boss.work() returns, which is an apps/worker change. worker_ok() { local since="$1" n running expected - expected="$(grep -E '^WORKER_REPLICAS=' "$ENV_FILE" | tail -n1 | cut -d= -f2)" + # 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 - n="$(compose exec -T postgres psql -U agrippa -d agrippa -tAc \ - "select count(*) from executor_registrations where registered_at > to_timestamp($since);" 2>/dev/null | tr -d '[:space:]')" + # Bounded: a wedged Postgres would otherwise block here indefinitely, and the + # caller's HEALTH_TIMEOUT loop cannot fire while this command hangs. + # statement_timeout goes through PGOPTIONS, not an inline `set`: a `set` + # statement prints "SET" to stdout, which would corrupt the count this reads. + n="$(compose exec -T -e PGCONNECT_TIMEOUT=5 -e PGOPTIONS='-c statement_timeout=10s' \ + 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 } From 146c4e0add3de9a6247b7dd05a54854b8b7d88ab Mon Sep 17 00:00:00 2001 From: John Hu Date: Thu, 30 Jul 2026 07:43:03 +0800 Subject: [PATCH 6/7] fix(infra): make the restore actually revert, bound the timeout, and test it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from review round 4, one of them declined. The documented recovery used pg_restore --clean, which only drops objects the archive contains. Tables a failed migration ADDED would survive it, and can block the restore outright through dependencies — so the procedure could not deliver what it promised. It now stops the app, drops and recreates the database, then restores with --exit-on-error --single-transaction so a partial restore rolls back rather than leaving a half-populated database. Verified by restoring a real dump into a scratch database on the host and comparing row counts; production was not the subject. HEALTH_TIMEOUT was never a wall-clock bound: stack_ok counted only its own 5s sleeps, ignoring the time each probe takes. The 10s statement timeout added last commit to stop a wedged Postgres blocking forever made that worse, pushing a nominal 180s past nine minutes. It now tracks an absolute deadline and hands the remaining budget to the database probe, capped by `timeout`. Declined: worker readiness cannot be fully proven without a signal written after boss.work() returns, which is an apps/worker change. The gap needs a worker that starts, registers, and then hangs specifically in consumer setup — a crash or a config error are both caught today. The comment in worker_ok names it and it is tracked as an issue rather than re-argued each review. The script had no automated tests, which is why four rounds of review found things a test would have caught. infra/deploy.test.ts covers the failure paths with stubbed docker/id/sleep/flock/timeout and a real git repo, so it runs in CI with no daemon: off-branch refusal, up -d failure, unhealthy api, a worker replica down, the tag failing to reach compose, dump permissions, and the wall-clock bound. git stays real because commit reachability IS the privilege boundary and stubbing it would assert nothing. Mutation-checked — removing the reachability check or making up -d bare each turn the relevant cases red. --- CHANGELOG.md | 1 + docs/manual/en/06-operations.md | 15 +- docs/manual/zh-CN/06-operations.md | 15 +- infra/deploy.sh | 50 ++++-- infra/deploy.test.ts | 243 +++++++++++++++++++++++++++++ 5 files changed, 301 insertions(+), 23 deletions(-) create mode 100644 infra/deploy.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 39e2cf7..74b009b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ All notable changes to Agrippa are documented here. The format follows - **`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 with stubbed `docker`/`git` 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. diff --git a/docs/manual/en/06-operations.md b/docs/manual/en/06-operations.md index 8f43c72..88bcf6e 100644 --- a/docs/manual/en/06-operations.md +++ b/docs/manual/en/06-operations.md @@ -122,14 +122,17 @@ The script therefore takes a `pg_dump` before every deploy, into `/var/lib/agrip ```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 - -docker compose -f infra/docker-compose.yml --env-file infra/env/.env stop api worker -docker compose -f infra/docker-compose.yml --env-file infra/env/.env exec -T postgres \ - pg_restore -U agrippa -d agrippa --clean --if-exists < "$DUMP" -docker compose -f infra/docker-compose.yml --env-file infra/env/.env start api worker +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 ``` -Stopping the app first is not optional: `pg_restore --clean` cannot drop objects the api and worker still hold connections to. +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. diff --git a/docs/manual/zh-CN/06-operations.md b/docs/manual/zh-CN/06-operations.md index 1e4a2eb..cdf9fdb 100644 --- a/docs/manual/zh-CN/06-operations.md +++ b/docs/manual/zh-CN/06-operations.md @@ -121,14 +121,17 @@ Compose 部署请使用 **`sudo infra/deploy.sh []`**:它从 GitCode ```sh # 部署失败时会打印所用的转储文件路径;请把它赋给变量,而不是照抄占位符 DUMP=/var/lib/agrippa-deploy/pgdump-20260730-064413-070e868.dump - -docker compose -f infra/docker-compose.yml --env-file infra/env/.env stop api worker -docker compose -f infra/docker-compose.yml --env-file infra/env/.env exec -T postgres \ - pg_restore -U agrippa -d agrippa --clean --if-exists < "$DUMP" -docker compose -f infra/docker-compose.yml --env-file infra/env/.env start api worker +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` 无法删除 api 与 worker 仍持有连接的对象。 +要先删库重建,而不是用 `pg_restore --clean`:`--clean` 只会删除归档中存在的对象,因此失败迁移**新增**的表会残留下来,并可能因依赖关系导致还原失败。`--single-transaction` 配合 `--exit-on-error` 可保证部分还原会整体回滚,而不是留下一个半成品数据库。先停掉应用不是可选项——api 与 worker 仍持有连接时 `dropdb` 会拒绝执行。 只有当 api 报告健康、**且**每个预期的 worker 副本都在运行、**且**已有 worker 注册了执行器时,部署才算成功。副本数之所以重要,是因为 worker 在开始消费队列之前就会先注册,仅凭一条新注册记录会放过一个启动途中就挂掉的 worker。已知残留缺口:worker 起来了但注册后卡死,这种情况检测不到。 diff --git a/infra/deploy.sh b/infra/deploy.sh index 4fd31fe..385cfc1 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -148,10 +148,22 @@ restore_hint() { cat >&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. - # statement_timeout goes through PGOPTIONS, not an inline `set`: a `set` - # statement prints "SET" to stdout, which would corrupt the count this reads. - n="$(compose exec -T -e PGCONNECT_TIMEOUT=5 -e PGOPTIONS='-c statement_timeout=10s' \ + # 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)) waited=0 - while [ "$waited" -lt "$HEALTH_TIMEOUT" ]; do + 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 sleep 5 - waited=$((waited + 5)) done + probe_budget=5 api_ok || echo " api never became healthy" >&2 - worker_ok "$since" || echo " worker never registered an executor" >&2 + worker_ok "$since" || echo " worker never became ready" >&2 return 1 } diff --git a/infra/deploy.test.ts b/infra/deploy.test.ts new file mode 100644 index 0000000..2bd4bd1 --- /dev/null +++ b/infra/deploy.test.ts @@ -0,0 +1,243 @@ +/** + * 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 { mkdtempSync, readFileSync, rmSync, statSync, 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("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); +}); From dca53d734a5f610954947a96ff824e39a979fcc6 Mon Sep 17 00:00:00 2001 From: John Hu Date: Thu, 30 Jul 2026 08:30:02 +0800 Subject: [PATCH 7/7] test(infra): cover dump retention, and cap the health sleep by the deadline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review items; a third is declined below. The 5-dump retention cap had no test — it was only ever checked by hand on the host. Dumps are a full copy of production, so unbounded growth is a disk and an exposure problem, not just untidiness. The new case seeds stale dumps with distinct mtimes and asserts the oldest are the ones dropped. Mutation-checked: disabling the retention line turns it red. stack_ok slept a flat 5s between probes, so the final iteration could overshoot the deadline it had just been given. It now sleeps only what remains. Small, but a stated bound should hold exactly — the previous round's finding was the same mistake at a larger scale. Declined: always preserving the `:latest` tag during prune. CodeRabbit asked for the opposite one round earlier — that latest be removable unless it equals the rollback target — and that is what is implemented. The reasoning still holds: `previous` comes from the last-good file, which stores a full SHA, so after one successful deploy latest can never be a rollback target again and retaining it just pins ~4 GB. The one case where it IS the target, a first deploy against pre-SHA images, is already covered by equality with `previous`. --- CHANGELOG.md | 2 +- infra/deploy.sh | 6 +++++- infra/deploy.test.ts | 36 +++++++++++++++++++++++++++++++++++- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74b009b..a79feb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,7 @@ All notable changes to Agrippa are documented here. The format follows - **`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 with stubbed `docker`/`git` so they run in CI without a daemon — the script had none, and every property it asserts is one a review previously broke. + 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. diff --git a/infra/deploy.sh b/infra/deploy.sh index 385cfc1..acaca54 100755 --- a/infra/deploy.sh +++ b/infra/deploy.sh @@ -267,7 +267,11 @@ stack_ok() { if api_ok && worker_ok "$since"; then return 0 fi - sleep 5 + # 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 diff --git a/infra/deploy.test.ts b/infra/deploy.test.ts index 2bd4bd1..e85f5eb 100644 --- a/infra/deploy.test.ts +++ b/infra/deploy.test.ts @@ -13,7 +13,15 @@ * privilege boundary and stubbing it would test nothing. */ import { afterEach, beforeEach, describe, expect, it } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +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"; @@ -186,6 +194,32 @@ describe("infra/deploy.sh", () => { 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);