Skip to content

Deploy the Compose stack on push to deploy, with SHA-tagged images and rollback - #14

Merged
hutusi merged 7 commits into
mainfrom
infra/janus-deploy
Jul 30, 2026
Merged

hutusi merged 7 commits into
mainfrom
infra/janus-deploy

Conversation

@hutusi

@hutusi hutusi commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

infra/deploy.sh therefore always builds. Change-detection that guesses wrong fails silently by running stale code, and the build cache keeps a docs-only deploy cheap anyway.

Rollback, which was impossible before

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, rolls back automatically when the new version doesn't come up, and exits non-zero so a pipeline reports failure instead of 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).

Trigger

.janus/deploy.yml runs it on the deploy branch, not main. main takes doc-only commits, so going live should be a deliberate fast-forward, and rolling back is moving the branch. The pipeline passes ${{ sha }}, so a deploy applies the commit that triggered it rather than whatever the tip drifted to since.

It lives at .janus/deploy.yml rather than the default ci.yml, selected via the webhook's ?pipeline_path=, leaving ci.yml free if Janus ever runs tests for this repo.

Why the tree stays root-owned

Janus reaches root through a single NOPASSWD sudoers entry for that one script. The ownership is the entire boundary: a janus-writable /opt/agrippa plus sudo docker compose up would let janus mount any host path into a container as root — so "janus fetches, root deploys" is no safer than putting janus in the docker group, just more complex. Root 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.

Verification

Gate: bun run check, 295 pass / 0 fail / 0 skipped, templates:validate, build, shellcheck -S warning clean, and janus validate accepts the pipeline.

Exercised on the deployment host before committing:

  • Real deploy — produced SHA-tagged images (:070e868), passed health, pruned to current + previous.
  • Rollback drill — a commit engineered to build cleanly but fail /healthz:
    ==> deploying 64fe0e1 (rollback target: 070e868)
    ==> up -d
    ==> waiting for /healthz (60s)
    health check failed; rolling back to 070e868
    deploy failed: rolled back to 070e868 after a failed deploy of 64fe0e1
    
    Instance came back healthy on the previous tag; script exited non-zero.
  • Sudoers is narrow — sudo -u janus sudo -l lists only that one script.

Server-side pieces (not in git, already applied): the sudoers rule, root's GitCode deploy key, and the gitcode remote on /opt/agrippa.

Sequencing after merge

.janus/deploy.yml is inert until it exists on the deploy branch. So: merge → add the GitCode webhook → fast-forward deploy to main, which becomes the first automated deploy and the end-to-end test.

Summary by CodeRabbit

  • New Features

    • Added deterministic deployments gated to commits reachable from the deployment branch, with automated runs on branch pushes and serialized rollout.
    • Improved deploy verification to cover both API and worker readiness more thoroughly.
    • Enhanced health-check timing and bounded retry behavior, plus safer rollback and database recovery.
  • Documentation

    • Updated operations and deployment design guides (English and Chinese) with clarified upgrade/rollback semantics and the failure recovery procedure.
  • Tests

    • Added Bun test coverage for the deploy script, including success paths, multiple failure scenarios, and database dump retention behavior.

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.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Updates the Compose deployment script with deploy-branch commit validation, bounded API and worker checks, fatal rollback errors, and drop-and-recreate database recovery. Adds Janus automation, isolated deployment tests, and operational documentation.

Changes

Deployment rollout

Layer / File(s) Summary
Deployment preparation and commit validation
infra/deploy.sh, .janus/deploy.yml
Resolves deploy-reachable commits, selects rollback state, builds full-SHA images, and runs serialized deployment automation for the deploy branch.
Health-gated rollback and database recovery
infra/deploy.sh
Bounds health-probe timing, validates API and worker readiness, provides transactional database recovery instructions, and aborts when code restoration fails.
Deployment behavior tests and artifact controls
infra/deploy.test.ts
Adds stub-based scenarios for authorization, image tagging, permissions, dump retention, rollback, readiness failures, timeout enforcement, and recovery output.
Deployment automation and operational guidance
docs/design/08-deployment.md, docs/manual/en/06-operations.md, docs/manual/zh-CN/06-operations.md, CHANGELOG.md
Documents commit restrictions, verification criteria, rollback behavior, database restoration, and expanded deployment test coverage.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Janus
  participant deploy.sh
  participant GitRemote
  participant DockerCompose
  participant PostgreSQL
  Janus->>deploy.sh: invoke with triggering commit SHA
  deploy.sh->>GitRemote: fetch and validate deploy-reachable commit
  deploy.sh->>DockerCompose: build and start full-SHA images
  deploy.sh->>DockerCompose: verify API health and worker readiness
  deploy.sh->>DockerCompose: redeploy previous code after failure
  deploy.sh-->>PostgreSQL: print drop, recreate, and pg_restore recovery procedure
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: automated Compose deployment on pushes to deploy with SHA-tagged images and rollback support.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch infra/janus-deploy

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@infra/deploy.sh`:
- Around line 136-140: Update the image-pruning pipeline in the repo loop so
latest is excluded only when it equals the rollback target stored in $previous;
otherwise allow latest to be removed while still preserving $short_sha and
$previous. Adjust the grep -vE pattern accordingly without changing the existing
docker rmi flow.
- Around line 72-82: Update the deployment and rollback flow around the
image-tag assignment, git reset, and rollback handling to use the full sha value
rather than short_sha, ensuring image tags remain immutable. Snapshot the
currently deployed docker-compose configuration before switching to the
candidate commit, and restore that snapshot during rollback along with the
previous image tag so failed Compose changes are not retained.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 64073505-5cd9-4e27-8f0a-9d0e3b33e3cb

📥 Commits

Reviewing files that changed from the base of the PR and between 070e868 and 4467017.

📒 Files selected for processing (6)
  • .janus/deploy.yml
  • CHANGELOG.md
  • docs/design/08-deployment.md
  • docs/manual/en/06-operations.md
  • docs/manual/zh-CN/06-operations.md
  • infra/deploy.sh

Comment thread infra/deploy.sh Resolved
Comment thread infra/deploy.sh
Comment on lines +136 to +140
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Prune latest when it is not a rollback target.

Line 139 always excludes latest, retaining a third image pair after successful SHA-tagged deployments. This contradicts the documented/current-and-previous-only retention policy and can consume an additional ~4 GB. Let $previous preserve latest only when it actually is the rollback target.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infra/deploy.sh` around lines 136 - 140, Update the image-pruning pipeline in
the repo loop so latest is excluded only when it equals the rollback target
stored in $previous; otherwise allow latest to be removed while still preserving
$short_sha and $previous. Adjust the grep -vE pattern accordingly without
changing the existing docker rmi flow.

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.
@hutusi

hutusi commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 235481e, addressing all four review findings. Each was verified against the live host rather than by inspection.

Correction to this PR's original description. I claimed a compromised janus "cannot change what is deployed without pushing to the repo." That was false — the script fetched +refs/heads/* and accepted any commit-ish as $1, while the pipeline passes ${{ sha }}, which janus controls. Any commit in the repo, including a feature branch with a compose file that mounts the host, was deployable as root. The root-owned-tree argument was bypassed by the script's own argument handling. Fixed, and the claim now holds only because of that fix.

Finding Fix Proven by
Any commit deployable fetch only the deploy ref; require reachability from it off-branch SHA refused before any build or tree change
up -d failure bypassed rollback routed through the rollback path unstartable service → docker compose up -d failed; rolling back
Rollback restored images, not config restore last-good commit first, from a state file that advances only on success compose marker gone after rollback; HEAD back to last-good
Worker not verified api compose healthcheck + fresh executor_registrations heartbeat worker-only break → worker never registered an executor, deploy failed

Migrations can't be undone by a script — the api migrates on boot before it is healthy, and this repo has irreversible examples. So a pg_dump is taken before every deploy and the exact pg_restore command is printed on rollback rather than the schema being silently left behind. Retention verified: exactly 5 dumps after six deploys.

Two things worth stating plainly:

  • The rollback drill in the original PR exercised one branch (build succeeds, health fails). It passed, which made the script look better tested than it was — up -d failure, config rollback and the worker were all untested.
  • My first attempt at the up -d test was invalid: I tried to occupy the port with python3 -m http.server, but docker-proxy already held it, so there was no blocker and the rollback I saw came from the still-broken worker. The second attempt appended the service to the end of the compose file, landing it under volumes: — which caught the compose config guard instead. Only the third placement actually tested the intended path.

Gate: bun run check, 295 pass / 0 fail / 0 skipped, templates:validate, build, shellcheck -S warning, git diff --check. Server cleaned up: main @ 070e868, clean tree, api healthy.

hutusi added 2 commits July 30, 2026 06:48
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 <dump>` 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.
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/manual/en/06-operations.md (1)

114-119: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update the Chinese manual in the same commit.

These deployment, rollback, backup, and readiness changes must also be reflected in docs/manual/zh-CN/06-operations.md to prevent the two user manuals from diverging.

As per coding guidelines, docs/manual/{en,zh-CN}/**/*.md must keep the English and zh-CN manuals synchronized in the same commit.

Also applies to: 120-126, 128-129

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/manual/en/06-operations.md` around lines 114 - 119, Update the
corresponding deployment operations section in
docs/manual/zh-CN/06-operations.md to reflect the same Compose deployment,
rebuild, locking, image-retention, commit-reachability, rollback,
database-migration, backup, and readiness behavior documented in the English
operations manual, keeping both manuals synchronized.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/manual/en/06-operations.md`:
- Around line 120-126: Update the restore procedure in the deployment
documentation so its pg_restore command uses the actual dump path produced by
deploy.sh, or assigns that path to a DUMP_PATH variable and redirects with
proper shell quoting. Keep the surrounding stop and start commands unchanged.

In `@infra/deploy.sh`:
- Around line 158-184: Make rollback stop immediately when restoring the
previous commit fails: in rollback(), replace the warning-only handling around
git reset --hard -q "$previous_sha" with the existing fatal failure path, such
as die, before exporting AGRIPPA_VERSION or running compose up. Preserve the
no-previous_sha warning branch and ensure compose is never started against the
failed commit’s tree.
- Around line 207-216: Harden worker_ok’s WORKER_REPLICAS parsing by extracting
only the value, stripping inline comments and CRLF/trailing whitespace, and
retaining the default of 1 when absent or invalid so the numeric comparison
remains reliable. Add statement and connection timeouts to the psql invocation
used for the executor_registrations count, ensuring a wedged Postgres check
returns promptly within the health timeout.

---

Outside diff comments:
In `@docs/manual/en/06-operations.md`:
- Around line 114-119: Update the corresponding deployment operations section in
docs/manual/zh-CN/06-operations.md to reflect the same Compose deployment,
rebuild, locking, image-retention, commit-reachability, rollback,
database-migration, backup, and readiness behavior documented in the English
operations manual, keeping both manuals synchronized.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: effdda43-f303-4b19-b570-e023e9728d98

📥 Commits

Reviewing files that changed from the base of the PR and between 4467017 and 54e8f85.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • docs/design/08-deployment.md
  • docs/manual/en/06-operations.md
  • docs/manual/zh-CN/06-operations.md
  • infra/deploy.sh
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG.md
  • docs/design/08-deployment.md

Comment thread docs/manual/en/06-operations.md Resolved
Comment thread infra/deploy.sh Resolved
Comment thread infra/deploy.sh Resolved
hutusi added 2 commits July 30, 2026 07:03
…check

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 `< <dump>` placeholder, which
does not run if pasted. It now assigns the dump path to a variable and quotes
the redirect, in both locales.
…test it

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.
@hutusi

hutusi commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
infra/deploy.sh (1)

278-319: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Ensure pruning preserves the rollback image’s latest tag.

The prune loop preserves only sha and previous; if previous is latest, the current rollback image tag is preserved, but if an earlier deploy left latest on an older image that is no longer previous, it can be pruned before it might become a rollback target. Include latest in the keep list or prevent stale latest tags from persisting as rollback targets.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infra/deploy.sh` around lines 278 - 319, Update the image filtering in the
prune loop for agrippa-api and agrippa-worker to always preserve the latest tag
alongside sha and previous. Keep the existing pruning behavior for all other
tags so an image tagged latest remains available as a rollback target.
🧹 Nitpick comments (1)
infra/deploy.test.ts (1)

181-187: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a test for the 5-dump retention cap.

This test verifies a single dump's permissions but not that old dumps beyond the documented 5-dump retention are pruned. Seeding a few stale pgdump-*.dump files in stateDir before run() and asserting the count stays at 5 afterward would close this coverage gap cheaply.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infra/deploy.test.ts` around lines 181 - 187, Extend the “keeps the dump
private to root” test around run() to seed more than five stale pgdump-*.dump
files in stateDir before execution, then assert that only five matching dumps
remain afterward. Preserve the existing permission assertions for the retained
dump and state directory.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@infra/deploy.sh`:
- Around line 256-276: Update the retry loop in stack_ok so the sleep after a
failed api_ok/worker_ok probe is capped by the remaining time before deadline.
Recompute the remaining budget and sleep for no longer than 5 seconds, avoiding
any trailing sleep once the deadline has been reached; preserve the existing
deadline check and failure diagnostics.

---

Outside diff comments:
In `@infra/deploy.sh`:
- Around line 278-319: Update the image filtering in the prune loop for
agrippa-api and agrippa-worker to always preserve the latest tag alongside sha
and previous. Keep the existing pruning behavior for all other tags so an image
tagged latest remains available as a rollback target.

---

Nitpick comments:
In `@infra/deploy.test.ts`:
- Around line 181-187: Extend the “keeps the dump private to root” test around
run() to seed more than five stale pgdump-*.dump files in stateDir before
execution, then assert that only five matching dumps remain afterward. Preserve
the existing permission assertions for the retained dump and state directory.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b605275f-9840-436d-b04c-86ff5f2a569f

📥 Commits

Reviewing files that changed from the base of the PR and between 54e8f85 and 146c4e0.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • docs/manual/en/06-operations.md
  • docs/manual/zh-CN/06-operations.md
  • infra/deploy.sh
  • infra/deploy.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • docs/manual/zh-CN/06-operations.md
  • docs/manual/en/06-operations.md
  • CHANGELOG.md

Comment thread infra/deploy.sh Resolved
…adline

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`.
@hutusi

hutusi commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
infra/deploy.sh (1)

193-197: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Remove orphaned services during rollback.

infra/deploy.sh resets the working tree to the last good commit and then starts AGRIPPA_VERSION="$previous", but compose() does not include --remove-orphans. If the failed commit added a compose service, compose up -d will leave that container running instead of restoring the known-good stack.

Suggested fix
-  compose up -d || {
+  compose up -d --remove-orphans || {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infra/deploy.sh` around lines 193 - 197, Update the rollback compose
invocation in deploy.sh to remove orphaned services while restoring the previous
version. Ensure the compose() call used after setting
AGRIPPA_VERSION="$previous" includes the --remove-orphans option, while
preserving the existing restore_hint and rollback failure handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@infra/deploy.test.ts`:
- Around line 215-220: Update the assertions around the remaining files in the
deployment cleanup test to verify exactly two are seeded dumps and exactly one
is the deployment-created dump. Use the existing dump filename conventions or
setup symbols to distinguish the run’s dump, while preserving checks that
seed0006 and seed0005 remain and seed0001 is removed.

---

Outside diff comments:
In `@infra/deploy.sh`:
- Around line 193-197: Update the rollback compose invocation in deploy.sh to
remove orphaned services while restoring the previous version. Ensure the
compose() call used after setting AGRIPPA_VERSION="$previous" includes the
--remove-orphans option, while preserving the existing restore_hint and rollback
failure handling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e31345fd-d036-490b-8c65-c79bfb055832

📥 Commits

Reviewing files that changed from the base of the PR and between 146c4e0 and dca53d7.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • infra/deploy.sh
  • infra/deploy.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

Comment thread infra/deploy.test.ts
Comment on lines +215 to +220
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that the deployment-created dump is retained.

The current assertions can pass with three seeded dumps and no dump from the deployment itself. Explicitly assert that exactly two remaining files are seeded dumps and that one remaining file is the run’s dump.

Suggested test adjustment
 const left = [...new Bun.Glob("pgdump-*.dump").scanSync(stateDir)].sort();
+const seedDumps = left.filter((f) => f.includes("-seed"));
 expect(left.length).toBe(3);
+expect(seedDumps).toHaveLength(2);
+expect(left.some((f) => !f.includes("-seed"))).toBe(true);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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);
const left = [...new Bun.Glob("pgdump-*.dump").scanSync(stateDir)].sort();
const seedDumps = left.filter((f) => f.includes("-seed"));
expect(left.length).toBe(3);
expect(seedDumps).toHaveLength(2);
expect(left.some((f) => !f.includes("-seed"))).toBe(true);
// 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);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infra/deploy.test.ts` around lines 215 - 220, Update the assertions around
the remaining files in the deployment cleanup test to verify exactly two are
seeded dumps and exactly one is the deployment-created dump. Use the existing
dump filename conventions or setup symbols to distinguish the run’s dump, while
preserving checks that seed0006 and seed0005 remain and seed0001 is removed.

@hutusi
hutusi merged commit e22591a into main Jul 30, 2026
5 checks passed
@hutusi
hutusi deleted the infra/janus-deploy branch August 5, 2026 08:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant