From cc4e892559535decab96b3e7b2fd5a14de1f884a Mon Sep 17 00:00:00 2001 From: G <41178744+maonakamoto@users.noreply.github.com> Date: Sat, 15 Aug 2026 13:58:29 +0200 Subject: [PATCH] perf(deploy): the pipeline was waiting, not working (#293) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merge→live measured 14–27 minutes. The irreducible work in that window is about 80 seconds: build 66s, rsync 4s, restart 4s, verify 7s. Nearly all of the rest was waiting, so nearly all of the fix is removing waits rather than making anything faster. Two waits, measured: 1. The runner drain, 480 of the ship step's 570 seconds. The deploy watched one in-flight agent, then restarted anyway at the cap. The web app had been live and verified for eight of those minutes. Two systems with opposite needs were sharing one job's wall-clock — the app wants to be live now, the runner wants to not kill anyone's work — and the runner won every time. A shorter timeout would only kill agents sooner. The wait itself is fine; the place it happened is what cost. Waiting is expensive in CI and free on the box, so it now happens on the box: the deploy schedules a detached systemd-run unit and returns as soon as the app is verified. The drain gets *longer* (1800s, not 480) and cheaper at the same time, because nothing is holding a runner open for it. 2. The CD reconciler, up to 10 minutes and 18.6 of #284's 26.8. Deploy chains off CI via workflow_run, which never fires for a CI run that GITHUB_TOKEN started — i.e. for every auto-merged PR, the only path that merges code here. The sweep covered that by reconciling on its next tick: correct, self-healing, and late. A dispatch is not a push, so it is not subject to the no-cascade rule. ci.yml now dispatches Deploy itself the moment main goes green. The sweep keeps its reconciler as the safety net, which is the right shape for "did something get missed?" and the wrong one for "did something just happen?". Also caches .next/cache across deploys — the build is the one part of this that is genuinely work, so it is the one part worth shrinking. Not done, and worth saying: I thought CI and Deploy each built the app, so the tested artifact was never the shipped one. That was wrong. ci.yml deliberately skips `next build` because App-Router pages query Postgres during pre-render; the build happens once, in Deploy. There was no discarded build and no artifact to pass. The decoupling has a test, and it asserts the property rather than the patch: the deploy must not block on a drain, the restart must be detached, the script must be shipped before it is invoked, and the drain must stay bounded. Verified the first two assertions fail against the previous version (4 blocking markers, 0 systemd-run) rather than merely passing against this one. Co-authored-by: t Co-authored-by: Claude Opus 5 --- .github/workflows/ci.yml | 35 +++++++++ .github/workflows/deploy.yml | 16 +++++ scripts/ci/auto-merge-sweep.sh | 15 ++-- scripts/deploy-hetzner.sh | 58 ++++++++------- scripts/hetzner/drain-and-restart-runner.sh | 67 +++++++++++++++++ scripts/test/deploy-runner-decoupling.ts | 80 +++++++++++++++++++++ 6 files changed, 237 insertions(+), 34 deletions(-) create mode 100644 scripts/hetzner/drain-and-restart-runner.sh create mode 100644 scripts/test/deploy-runner-decoupling.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d6e307e4..f7f4f608e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,3 +57,38 @@ jobs: # The Hetzner deploy step (scripts/deploy-hetzner.sh) builds against # the live box DB, so this CI focuses on type/lint and leaves build # verification to that deploy. + + # ── Close the CD gap where it opens, instead of polling for it ────────────── + # + # Deploy chains off CI via workflow_run. That event never fires for a CI run + # that GITHUB_TOKEN started — which is exactly how every auto-merged PR gets + # its main-CI (auto-merge.yml dispatches it, because the merge push itself + # triggers nothing either). So the chain is broken for the ONLY path that + # actually merges code here. + # + # The sweep covered that by reconciling on its next tick: correct, self- + # healing, and up to ten minutes late. Measured on #284: 18.6 minutes of the + # 26.8-minute merge→live was this wait, with nothing running. + # + # A dispatch is not a push, so it is not subject to the no-cascade rule: this + # job can start Deploy directly the moment CI proves main is green. The sweep + # keeps its reconciler as the safety net for a deploy that never fired or + # failed — a poll is the right shape for "did something get missed?", and the + # wrong shape for "did something just happen?". + # + # Deliberately only for workflow_dispatch: a real push to main still chains + # through workflow_run on its own, and dispatching here too would ship twice. + ship: + needs: check + if: github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + permissions: + actions: write + steps: + - uses: actions/checkout@v7 + - name: Dispatch Deploy now that main is green + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "main is green — dispatching Deploy without waiting for a sweep tick" + gh workflow run deploy.yml --ref main diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index aa0e2b784..3b1bcf076 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -89,6 +89,22 @@ jobs: - name: Push schema to CI Postgres (build needs it) run: npx drizzle-kit push + # Next's incremental compiler cache. Every deploy compiled the whole app + # from cold because the runner is ephemeral — the one part of the pipeline + # that is genuinely WORK rather than waiting, so it is worth making + # smaller. Keyed on the lockfile plus the sources, with a lockfile-only + # fallback so a normal source change still starts from a warm cache. + # `.next/cache` is compiler state, not output: what ships is + # `.next/standalone`, rebuilt every run either way. + - name: Cache Next.js build cache + uses: actions/cache@v4 + with: + path: .next/cache + key: ${{ runner.os }}-next-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/**/*.ts', 'src/**/*.tsx') }} + restore-keys: | + ${{ runner.os }}-next-${{ hashFiles('package-lock.json') }}- + ${{ runner.os }}-next- + - name: Build (app + bridge) run: | npm run build diff --git a/scripts/ci/auto-merge-sweep.sh b/scripts/ci/auto-merge-sweep.sh index 7804a4bbc..3a8179874 100755 --- a/scripts/ci/auto-merge-sweep.sh +++ b/scripts/ci/auto-merge-sweep.sh @@ -338,10 +338,17 @@ INNER_EOF done if [ "$merged_any" -eq 1 ]; then - # Verification only. The deploy happens in the reconciler at the top of the - # NEXT sweep, once this CI run has proved the merge on main — dispatching - # Deploy here would ship a commit whose main-CI has not finished. - echo "[auto-merge] re-arming CI on ${BASE_BRANCH} to verify the merge" + # Verification AND, now, the ship signal. Dispatching Deploy from here would + # ship a commit whose main-CI has not finished — so it still must not happen + # here. Instead ci.yml's `ship` job dispatches Deploy the moment this run goes + # green, which is the earliest correct moment. + # + # The reconciler at the top of the next sweep stays as the safety net: it now + # catches only a deploy that never fired or that failed, rather than being the + # normal path. That is the difference between polling for "did something get + # missed?" (right) and polling for "did something just happen?" (up to ten + # minutes late — 18.6 of #284's 26.8-minute merge→live). + echo "[auto-merge] re-arming CI on ${BASE_BRANCH} to verify the merge (ci.yml ships it when green)" gh workflow run ci.yml --repo "$REPO" --ref "$BASE_BRANCH" else echo "[auto-merge] nothing merged" diff --git a/scripts/deploy-hetzner.sh b/scripts/deploy-hetzner.sh index a1d5ee309..bbbf838a4 100644 --- a/scripts/deploy-hetzner.sh +++ b/scripts/deploy-hetzner.sh @@ -423,40 +423,38 @@ sync_runner "$PROJECT_DIR/scripts/box-runner.ts" \ "$PROJECT_DIR/scripts/hosted-runner.ts" \ "$PROJECT_DIR/scripts/hermes-dispatch.ts" \ "$HOST:$RUNNER_DIR/scripts/" +# The deferred-restart script must reach the box BEFORE it is invoked below. +sync_runner "$PROJECT_DIR/scripts/hetzner/drain-and-restart-runner.sh" \ + "$HOST:$RUNNER_DIR/scripts/" sync_runner "$PROJECT_DIR/tsconfig.json" "$HOST:$RUNNER_DIR/tsconfig.json" ssh "$HOST" "chown -R $RUNNER_OWNER:$RUNNER_OWNER $RUNNER_DIR/src $RUNNER_DIR/desktop $RUNNER_DIR/home $RUNNER_DIR/scripts $RUNNER_DIR/tsconfig.json" -# Wait for in-flight agent PTYs to finish before restarting the runner. Idle -# runner drains instantly (its cgroup holds only the two node processes); -# capped so a genuine runner-code fix still lands. Best-effort, never fails. -drain_box_runner_agents() { - local max="${FLEETCROWN_RUNNER_DRAIN_SECS:-480}" waited=0 n - while [ "$waited" -lt "$max" ]; do - n=$(ssh -o ConnectTimeout=10 "$HOST" ' - cg=/sys/fs/cgroup/system.slice/fleetcrown-box-runner.service/cgroup.procs - [ -r "$cg" ] || { echo 0; exit 0; } - c=0 - for p in $(cat "$cg"); do - case "$(cat /proc/$p/comm 2>/dev/null)" in - claude|hermes|codex|cursor-agent|grok) c=$((c+1));; - esac - done - echo "$c"' 2>/dev/null || echo 0) - [ "${n:-0}" -eq 0 ] 2>/dev/null && return 0 - echo " ⏳ ${n} agent(s) in-flight on the runner — waiting to drain (${waited}s/${max}s)…" - sleep 20; waited=$((waited + 20)) - done - echo " ⚠ drain timed out after ${max}s — restarting anyway so the runner code fix lands" >&2 - return 0 -} - +# The runner restart waits for in-flight agents — but it waits ON THE BOX, in a +# detached transient unit, not here. +# +# This loop used to run inside the deploy: 480 of the ship step's 570 seconds +# were spent watching one agent that never finished, after which it restarted +# anyway. The web app had been live and verified for eight minutes by then. Two +# separate systems with opposite needs were sharing one job's wall-clock: the +# app wants to be live now, the runner wants to not kill anyone's work. +# +# Decoupled, both get what they want. The deploy ends when the app is verified; +# the box waits as long as it needs (30m cap, not 8) and restarts when the +# runner is genuinely idle. `systemd-run` detaches it into its own cgroup, so it +# survives this ssh closing and cannot be killed by the restart it performs. +step "scheduling runner restart" if [ "$RUNNER_CHANGED" = 1 ]; then - echo "→ runner code changed — draining in-flight agents, then restart" - drain_box_runner_agents - ssh "$HOST" "systemctl restart fleetcrown-box-runner \ - && sleep 4 \ - && systemctl is-active fleetcrown-box-runner >/dev/null" - echo " ✓ fleetcrown-box-runner restarted (cloud builder)" + echo "→ runner code changed — scheduling a drain-then-restart on the box" + # Newest intent wins: a previous deploy's pending restart is superseded by + # this one, which is already syncing newer code. + ssh "$HOST" " + systemctl stop fleetcrown-runner-restart.service 2>/dev/null || true + systemctl reset-failed fleetcrown-runner-restart.service 2>/dev/null || true + systemd-run --unit=fleetcrown-runner-restart --collect --quiet \ + --description='FleetCrown: restart box-runner once agents drain' \ + /bin/bash $RUNNER_DIR/scripts/drain-and-restart-runner.sh + " && echo " ✓ restart scheduled — runs when the runner goes idle (journal: -t fleetcrown-drain)" \ + || echo " ⚠ could not schedule the runner restart — runner keeps old code until the next deploy" >&2 else echo " ✓ runner code unchanged — restart skipped (in-flight agents undisturbed)" fi diff --git a/scripts/hetzner/drain-and-restart-runner.sh b/scripts/hetzner/drain-and-restart-runner.sh new file mode 100644 index 000000000..3f3bed974 --- /dev/null +++ b/scripts/hetzner/drain-and-restart-runner.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Box-side: wait for in-flight agents to finish, THEN restart the box-runner. +# +# Runs ON the box as a detached transient systemd unit, not inside the deploy. +# The deploy used to do this waiting itself, in the CI job, and it was the +# single most expensive thing in the pipeline: 480 of the ship step's 570 +# seconds were this loop, which then timed out and restarted anyway. That is +# the worst of both worlds — the cost of patience with the semantics of +# impatience, paid in CI wall-clock on every runner-code change. +# +# Waiting is free HERE and expensive THERE. Moving the wait to the box lets it +# be both longer (agents genuinely finish instead of being killed at 8 minutes) +# and free (the deploy returns as soon as the app is verified live). +# +# Deliberately NOT in the runner's own cgroup: systemd-run gives this its own +# unit, so restarting fleetcrown-box-runner cannot kill the thing doing the +# restarting. + +set -uo pipefail + +UNIT="fleetcrown-box-runner" +CGROUP="/sys/fs/cgroup/system.slice/${UNIT}.service/cgroup.procs" +# Generous because it costs nothing now. Still bounded: a runner-code fix must +# eventually land even if some agent never exits. +MAX="${FLEETCROWN_RUNNER_DRAIN_SECS:-1800}" +INTERVAL=20 + +log() { logger -t fleetcrown-drain "$*" 2>/dev/null || true; echo "[drain] $*"; } + +count_agents() { + [ -r "$CGROUP" ] || { echo 0; return 0; } + local c=0 p comm + for p in $(cat "$CGROUP" 2>/dev/null); do + comm="$(cat "/proc/$p/comm" 2>/dev/null || true)" + case "$comm" in + claude|hermes|codex|cursor-agent|grok) c=$((c + 1)) ;; + esac + done + echo "$c" +} + +waited=0 +while [ "$waited" -lt "$MAX" ]; do + n="$(count_agents)" + if [ "${n:-0}" -eq 0 ] 2>/dev/null; then + log "runner idle after ${waited}s — restarting to pick up new code" + systemctl restart "$UNIT" && sleep 4 + if systemctl is-active "$UNIT" >/dev/null 2>&1; then + log "✓ ${UNIT} restarted (drained cleanly, no agent killed)" + exit 0 + fi + log "✗ ${UNIT} did not come back after restart" + exit 1 + fi + log "${n} agent(s) in-flight — deferring restart (${waited}s/${MAX}s)" + sleep "$INTERVAL" + waited=$((waited + INTERVAL)) +done + +# Cap reached. Restart anyway: stale runner code is its own outage, and at 30 +# minutes an "in-flight" agent is more likely wedged than working. +log "⚠ drain cap ${MAX}s reached — restarting anyway so the runner code lands" +systemctl restart "$UNIT" && sleep 4 +systemctl is-active "$UNIT" >/dev/null 2>&1 \ + && { log "✓ ${UNIT} restarted (forced after cap)"; exit 0; } +log "✗ ${UNIT} did not come back after forced restart" +exit 1 diff --git a/scripts/test/deploy-runner-decoupling.ts b/scripts/test/deploy-runner-decoupling.ts new file mode 100644 index 000000000..74d0e578c --- /dev/null +++ b/scripts/test/deploy-runner-decoupling.ts @@ -0,0 +1,80 @@ +/** + * A deploy must end when the APP is live — not when an unrelated system is. + * + * The web app and the box-runner have opposite needs. The app wants to be live + * immediately; the runner wants to not kill an agent mid-task. Both used to + * share one job's wall-clock, and the runner won: measured on 2026-08-15, the + * ship step spent 480 of its 570 seconds watching a single in-flight agent, + * then restarted anyway. The app had been live and verified for eight of those + * minutes. It was the most expensive thing in the whole pipeline and it bought + * nothing — the cost of patience with the semantics of impatience. + * + * The fix is not a shorter timeout, which would only kill agents sooner. It is + * moving the wait to the box, where waiting is free: the deploy schedules a + * detached drain-then-restart and returns. This suite guards that the wait + * cannot migrate back into the deploy, because it would look like a reasonable + * thing to do again. + */ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +const root = join(__dirname, "..", ".."); +const deploy = readFileSync(join(root, "scripts/deploy-hetzner.sh"), "utf8"); +const drainPath = join(root, "scripts/hetzner/drain-and-restart-runner.sh"); +let passed = 0; + +function check(name: string, fn: () => void) { + fn(); + passed++; + console.log(` ✓ ${name}`); +} + +function assert(cond: boolean, msg: string) { + if (!cond) throw new Error(msg); +} + +check("the deploy does not wait for agents to drain", () => { + // The signature of the old loop: sleeping in a loop while counting agent + // processes. Any reintroduction reads like this, whatever it is named. + const waits = /waiting to drain|drain_box_runner_agents|drain timed out/.test(deploy); + assert(!waits, "deploy-hetzner.sh must not block on draining agents — schedule it on the box instead"); +}); + +check("the runner restart is scheduled detached, not run inline", () => { + assert( + /systemd-run/.test(deploy), + "the runner restart must be detached via systemd-run so the deploy does not wait for it", + ); +}); + +check("the deferred restart script exists and is shipped before it is invoked", () => { + assert(existsSync(drainPath), "scripts/hetzner/drain-and-restart-runner.sh must exist"); + const syncIdx = deploy.indexOf("drain-and-restart-runner.sh"); + const runIdx = deploy.indexOf("systemd-run"); + assert(syncIdx !== -1, "the drain script must be rsynced to the box"); + assert( + syncIdx < runIdx, + "the drain script must be synced BEFORE systemd-run invokes it, or the first deploy invokes a missing file", + ); +}); + +check("the deferred restart cannot be killed by the restart it performs", () => { + const drain = readFileSync(drainPath, "utf8"); + // systemd-run puts it in its OWN unit; restarting fleetcrown-box-runner kills + // that unit's cgroup, which must not contain this script. + assert( + /--unit=/.test(deploy), + "the drain must run in its own systemd unit, not inside the box-runner's cgroup", + ); + assert( + /systemctl restart/.test(drain), + "the drain script is what actually restarts the runner", + ); +}); + +check("the drain still has a cap, so a wedged agent cannot freeze runner code forever", () => { + const drain = readFileSync(drainPath, "utf8"); + assert(/MAX=/.test(drain) && /cap/.test(drain), "the box-side drain must remain bounded"); +}); + +console.log(`\n${passed} passed`);