diff --git a/.env.example b/.env.example index 030a0700..8c423878 100644 --- a/.env.example +++ b/.env.example @@ -163,24 +163,27 @@ HEALTH_PORT=3005 # Health check port — read by FIVE services (wor # (discord 3001, slack 3002, teams 3003, worker 3005). # Running several locally needs a per-process override. -# OUTPOST_ALLOW_SCHEMA_DRIFT=1 # Incident release valve for apps/worker/start.sh. - # The worker refuses to boot when the live database does - # not match schema.prisma, or when that check cannot run - # at all. Setting this (1/true/yes/on) starts it anyway, - # with warnings. Use it for transient skew while a sibling - # service is mid-rollout, or to get the worker up during +# OUTPOST_ALLOW_SCHEMA_DRIFT=1 # Incident release valve for the schema-drift guard + # that apps/web/start.sh and apps/worker/start.sh share + # (packages/outpost/db/schema-drift-guard.sh). Both + # refuse to boot when the live database does not match + # schema.prisma, or when that check cannot run at all. + # Setting this (1/true/yes/on) starts them anyway, with + # warnings. Use it for transient skew while a sibling + # service is mid-rollout, or to get a service up during # an incident; unset it once the schema is repaired. - # TRACKER_SYNC may write wrong statuses to Linear while - # this is set. - -# OUTPOST_STARTUP_STEP_TIMEOUT=180 # Seconds the worker's schema-drift check may run - # before it is abandoned (apps/worker/start.sh). Bounds - # only the read-only check; `migrate deploy` is left - # unbounded on purpose, since killing it mid-migration - # creates the P3009 failed-migration state the guard - # exists to report. Keep it below the platform's - # healthcheck timeout, or a slow check is killed as an - # unexplained deploy failure instead of logging a reason. + # TRACKER_SYNC may write wrong statuses to Linear, and + # the web app keeps serving pages, while this is set. + +# OUTPOST_STARTUP_STEP_TIMEOUT=180 # Seconds a schema-drift check may run before it + # is abandoned (apps/web/start.sh, apps/worker/start.sh). + # Bounds only the read-only check; `migrate deploy` is + # left unbounded on purpose, since killing it + # mid-migration creates the P3009 failed-migration state + # the guard exists to report. Keep it below the + # platform's healthcheck timeout, or a slow check is + # killed as an unexplained deploy failure instead of + # logging a reason. # ─── Railway ───────────────────────────────────────────────────────────────── # Railway auto-deploys from GitHub; no deploy hook needed. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ae31b16..fcb4f6f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,75 +225,110 @@ jobs: $PRISMA migrate deploy --schema packages/outpost/db/prisma/schema.prisma echo "CI database restored." - - name: Verify the worker startup guard + - name: Verify the startup guard run: | set -e # Execute start.sh itself against a stub CLI. Nothing previously ran # this script -- CI re-implemented its prisma calls in bash -- which is # why a busybox-vs-GNU timeout exit-code difference sat in it unnoticed. - # Every branch that decides whether the worker may boot is asserted here. + # Every branch that decides whether a service may boot is asserted here. + # + # Both services are asserted, because they migrate the SAME database + # and share one guard (packages/outpost/db/schema-drift-guard.sh). A + # guard that only the worker ran would leave web free to serve + # traffic against a schema the worker refuses to run against. stub=$(mktemp); chmod +x "$stub" printf '#!/bin/sh\nif [ "$1" = migrate ] && [ "$2" = diff ]; then exit "${DIFF_RC:-0}"; fi\nexit "${DEPLOY_RC:-0}"\n' > "$stub" - script=$(mktemp) - sed 's|^exec node apps/worker/dist/index.js|echo STARTED|' apps/worker/start.sh > "$script" - - check() { # label expect_exit expect_started env... - label=$1 want_rc=$2 want_started=$3; shift 3 - # set +e around the call: half these cases are SUPPOSED to exit - # non-zero, and this step runs under `bash -e`, so the assignment - # would abort the whole step on the first expected failure. + guard="$PWD/packages/outpost/db/schema-drift-guard.sh" + + for target in worker web; do + echo "== $target ==" + script=$(mktemp) + # The last line of each start.sh execs the service; replace it so + # the script can run to completion without a built server. + sed 's|^exec node .*|echo STARTED|' "apps/$target/start.sh" > "$script" + + check() { # label expect_exit expect_started env... + label=$1 want_rc=$2 want_started=$3; shift 3 + # set +e around the call: half these cases are SUPPOSED to exit + # non-zero, and this step runs under `bash -e`, so the assignment + # would abort the whole step on the first expected failure. + set +e + out=$(env OUTPOST_PRISMA_CMD="$stub" OUTPOST_SCHEMA_GUARD_SCRIPT="$guard" "$@" sh "$script" 2>&1) + rc=$? + set -e + case "$out" in *STARTED*) got=yes ;; *) got=no ;; esac + if [ "$rc" != "$want_rc" ] || [ "$got" != "$want_started" ]; then + echo "FATAL: $target: $label -> exit=$rc started=$got (wanted exit=$want_rc started=$want_started)" + echo "$out" + exit 1 + fi + echo " ok: $label" + } + + check "clean schema boots" 0 yes DIFF_RC=0 + check "drift blocks the boot" 1 no DIFF_RC=2 + check "drift + override boots" 0 yes DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=1 + check "drift + override=on boots" 0 yes DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=on + check "drift + unknown override blocks" 1 no DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=banana + check "drift + override=0 blocks" 1 no DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=0 + # A check that could not RUN must be overridable too, or a CLI-level + # breakage is an unbreakable crash loop under restartPolicyType=ALWAYS. + check "tool failure blocks" 1 no DIFF_RC=1 + check "tool failure + override boots" 0 yes DIFF_RC=1 OUTPOST_ALLOW_SCHEMA_DRIFT=1 + check "migrate deploy failure blocks" 1 no DEPLOY_RC=1 + # A bad timeout value must not fail the step closed. + check "non-numeric timeout still boots" 0 yes DIFF_RC=0 OUTPOST_STARTUP_STEP_TIMEOUT=abc + check "timeout=0 means unbounded" 0 yes DIFF_RC=0 OUTPOST_STARTUP_STEP_TIMEOUT=0 + + # Diagnostics must reach stderr, and an overridden boot must not page. set +e - out=$(env OUTPOST_PRISMA_CMD="$stub" "$@" sh "$script" 2>&1) - rc=$? + env OUTPOST_PRISMA_CMD="$stub" OUTPOST_SCHEMA_GUARD_SCRIPT="$guard" DIFF_RC=2 sh "$script" 2>/dev/null | grep -q FATAL + leaked=$? + env OUTPOST_PRISMA_CMD="$stub" OUTPOST_SCHEMA_GUARD_SCRIPT="$guard" DIFF_RC=1 OUTPOST_ALLOW_SCHEMA_DRIFT=1 sh "$script" 2>&1 >/dev/null | grep -q FATAL + paged=$? set -e - case "$out" in *STARTED*) got=yes ;; *) got=no ;; esac - if [ "$rc" != "$want_rc" ] || [ "$got" != "$want_started" ]; then - echo "FATAL: $label -> exit=$rc started=$got (wanted exit=$want_rc started=$want_started)" - echo "$out" + if [ "$leaked" -eq 0 ]; then + echo "FATAL: $target: diagnostics leaked to stdout." exit 1 fi - echo " ok: $label" - } - - check "clean schema boots" 0 yes DIFF_RC=0 - check "drift blocks the boot" 1 no DIFF_RC=2 - check "drift + override boots" 0 yes DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=1 - check "drift + override=on boots" 0 yes DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=on - check "drift + unknown override blocks" 1 no DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=banana - check "drift + override=0 blocks" 1 no DIFF_RC=2 OUTPOST_ALLOW_SCHEMA_DRIFT=0 - # A check that could not RUN must be overridable too, or a CLI-level - # breakage is an unbreakable crash loop under restartPolicyType=ALWAYS. - check "tool failure blocks" 1 no DIFF_RC=1 - check "tool failure + override boots" 0 yes DIFF_RC=1 OUTPOST_ALLOW_SCHEMA_DRIFT=1 - check "migrate deploy failure blocks" 1 no DEPLOY_RC=1 - # A bad timeout value must not fail the step closed. - check "non-numeric timeout still boots" 0 yes DIFF_RC=0 OUTPOST_STARTUP_STEP_TIMEOUT=abc - check "timeout=0 means unbounded" 0 yes DIFF_RC=0 OUTPOST_STARTUP_STEP_TIMEOUT=0 - - # Diagnostics must reach stderr, and an overridden boot must not page. - set +e - env OUTPOST_PRISMA_CMD="$stub" DIFF_RC=2 sh "$script" 2>/dev/null | grep -q FATAL - leaked=$? - env OUTPOST_PRISMA_CMD="$stub" DIFF_RC=1 OUTPOST_ALLOW_SCHEMA_DRIFT=1 sh "$script" 2>&1 >/dev/null | grep -q FATAL - paged=$? - set -e - if [ "$leaked" -eq 0 ]; then - echo "FATAL: diagnostics leaked to stdout." - exit 1 - fi - if [ "$paged" -eq 0 ]; then - echo "FATAL: an overridden boot emitted FATAL and would page." - exit 1 - fi + if [ "$paged" -eq 0 ]; then + echo "FATAL: $target: an overridden boot emitted FATAL and would page." + exit 1 + fi + done + + # A sourced library must not change its caller's errexit setting. + OUTPOST_PRISMA_CMD="$stub" sh -c ' + set +e + . "$1" + outpost_migrate_and_verify + case $- in *e*) exit 1 ;; esac + ' sh "$guard" + + # Exercise the actual BusyBox timeout used in the images. Its TERM + # timeout can return 0 if the child catches TERM and exits cleanly. + docker run --rm -v "$PWD:/src:ro" node:24-alpine sh -c ' + printf "#!/bin/sh\nif [ \"\$2\" = diff ]; then trap '\''exit 0'\'' TERM; while :; do :; done; fi\n" > /tmp/prisma-stub + chmod +x /tmp/prisma-stub + for target in web worker; do + if OUTPOST_PRISMA_CMD=/tmp/prisma-stub OUTPOST_STARTUP_STEP_TIMEOUT=1 sh "/src/apps/$target/start.sh" > /tmp/guard-out 2>&1; then + printf "FATAL: %s accepted a timed-out check\n" "$target" + exit 1 + fi + grep -q "timed out" /tmp/guard-out || { cat /tmp/guard-out; exit 1; } + done + ' echo "Startup guard behaves correctly across all branches." - name: Verify the pinned Prisma CLI matches the lockfile run: | set -e - # apps/worker/start.sh gates the worker's boot on this CLI's `migrate - # diff` exit code, so a CLI that has drifted from @prisma/client can - # report false drift and block every deploy with a message pointing at - # the database. Keep the Dockerfile pin and the lockfile in lockstep. + # apps/web/start.sh and apps/worker/start.sh gate their boot on this + # CLI's `migrate diff` exit code, so a CLI that has drifted from + # @prisma/client can report false drift and block every deploy with + # a message pointing at the database. Keep the Dockerfile pin and the + # lockfile in lockstep. set -o pipefail resolved=$(node "$(cd packages/outpost && node -p "require.resolve('prisma/build/index.js')")" --version | sed -n 's/^prisma *: *\([0-9][^ ]*\).*/\1/p' | head -1) if [ -z "$resolved" ]; then diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 06da9526..00ebb8f7 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -70,9 +70,14 @@ COPY --from=installer --chown=outpost:outpost /app/node_modules/.pnpm/@prisma+cl COPY --from=installer --chown=outpost:outpost /app/node_modules/.pnpm/@prisma+client*/node_modules/.prisma/client/schema.prisma ./apps/web/.next/server/ # Prisma schema and migrations for migrate deploy on startup COPY --from=installer --chown=outpost:outpost /app/packages/outpost/db/prisma ./packages/outpost/db/prisma +# The schema-drift guard, shared with apps/worker/start.sh. start.sh sources it +# and refuses to serve traffic against a database that does not match +# schema.prisma. The worker's image already copies the whole packages/ tree, so +# it needs no equivalent line here. +COPY --from=installer --chown=outpost:outpost /app/packages/outpost/db/schema-drift-guard.sh ./packages/outpost/db/schema-drift-guard.sh # Prisma CLI for running migrations at startup (installed with all transitive deps) # Pinned in lockstep with apps/worker/Dockerfile. web and worker run migrate deploy -# against the SAME database, and the worker's start.sh now fails its deploy on any +# against the SAME database, and both start.sh files now fail their deploy on any # schema difference -- so if web applies migrations with a different 6.x CLI than the # worker verifies with, an unrelated web-side bump can hard-fail worker deploys with a # drift message describing drift that does not exist. A CI step asserts both literals @@ -86,7 +91,14 @@ EXPOSE 3000 # Use 127.0.0.1, not localhost: the standalone server binds IPv4 (0.0.0.0) and # `localhost` can resolve to IPv6 ::1 inside the container, which is refused. -HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ +# +# start-period covers the whole pre-listen window, which is now two full prisma +# CLI invocations (migrate deploy, then the schema-drift check) before anything +# binds the port. At the old 10s an orchestrator honouring this status could +# restart the container mid-check — and killing it mid-migration manufactures +# the failed-migration (P3009) state the guard exists to diagnose. The value +# matches apps/worker/Dockerfile, which guards the same way. +HEALTHCHECK --interval=30s --timeout=5s --start-period=120s --retries=3 \ CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1 COPY --from=installer --chown=outpost:outpost /app/apps/web/start.sh ./apps/web/start.sh diff --git a/apps/web/start.sh b/apps/web/start.sh index ace1b895..efdf8c20 100755 --- a/apps/web/start.sh +++ b/apps/web/start.sh @@ -1,8 +1,32 @@ #!/bin/sh set -e -# Run pending database migrations before starting -node /opt/prisma/node_modules/prisma/build/index.js migrate deploy --schema packages/outpost/db/prisma/schema.prisma +# The schema-drift guard is shared with apps/worker/start.sh. web and worker +# migrate the SAME database, so they have to agree about what that database looks +# like: a guard only one of them applies leaves the other free to serve traffic +# against a schema the guarded service refuses to run against. +# +# The path is resolved relative to this script, so the image can place the guard +# wherever it likes. OUTPOST_SCHEMA_GUARD_SCRIPT overrides it, which is how CI +# runs a copy of this script from a temporary directory. +OUTPOST_SERVICE=web +OUTPOST_DRIFT_WARNING="the web app keeps serving traffic against a schema it does not match until this is repaired" +OUTPOST_SCHEMA_GUARD_SCRIPT="${OUTPOST_SCHEMA_GUARD_SCRIPT:-$(dirname "$0")/../../packages/outpost/db/schema-drift-guard.sh}" +if [ ! -f "$OUTPOST_SCHEMA_GUARD_SCRIPT" ]; then + echo "[web] FATAL: the schema-drift guard is missing at ${OUTPOST_SCHEMA_GUARD_SCRIPT}." >&2 + exit 1 +fi +# shellcheck source=packages/outpost/db/schema-drift-guard.sh +. "$OUTPOST_SCHEMA_GUARD_SCRIPT" + +# Apply the pending migrations, then check that the database really matches +# schema.prisma. `migrate deploy` alone only compares the migrations directory +# against the _prisma_migrations bookkeeping table and never looks at the actual +# schema, so a migration recorded as applied but never executed is invisible to +# it — and web would then serve every page against a schema it does not match. +# The guard's own comments explain the rest; the CI step "Verify the startup +# guard" asserts every branch of it against a stub CLI. +outpost_migrate_and_verify # Start Next.js # Bind all interfaces. Docker sets HOSTNAME to the container id, which Next's diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 17efcddc..a6e21971 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -488,7 +488,7 @@ try { `[Worker] /health on ${port} reports 503 ("${boot.error}") for ${BOOT_FAILURE_LINGER_MS}ms, ` + `then this process exits 1 so Railway's restart policy retries. ` + `A missing table or column here means the database does not match schema.prisma — ` + - `check the schema-drift guard in apps/worker/start.sh.`, + `check the schema-drift guard in packages/outpost/db/schema-drift-guard.sh.`, ); setTimeout(() => { console.error( diff --git a/apps/worker/start.sh b/apps/worker/start.sh index fc7c9e32..838620fd 100644 --- a/apps/worker/start.sh +++ b/apps/worker/start.sh @@ -12,202 +12,31 @@ set -eu trap 'echo "[worker] SIGTERM received between startup steps, aborting" >&2; exit 143' TERM trap 'echo "[worker] SIGINT received between startup steps, aborting" >&2; exit 130' INT -# Overridable so CI can execute this script against a stub that returns canned exit -# codes. Nothing previously ran start.sh at all — CI re-implemented the prisma calls -# in bash on ubuntu, which is exactly why a busybox-vs-GNU exit-code difference in -# the timeout handling went unnoticed. -PRISMA="${OUTPOST_PRISMA_CMD:-node /opt/prisma/node_modules/prisma/build/index.js}" -SCHEMA="packages/outpost/db/prisma/schema.prisma" - -# The drift check is bounded. Against a black-holing endpoint (a dropped packet -# rather than a refusal) the CLI can hang far past any TCP timeout, and a hang -# produces NO log line at all — indistinguishable from a slow migration and from a -# healthy-but-slow boot, which defeats the point of putting the reason in the log. +# The schema-drift guard is shared with apps/web/start.sh. web and worker migrate +# the SAME database, so they have to agree about what that database looks like: a +# guard only one of them applies leaves the other free to serve traffic against a +# schema the guarded service refuses to run against. # -# `migrate deploy` is deliberately NOT bounded. Killing it mid-migration leaves -# _prisma_migrations holding a row with finished_at = NULL, which is the P3009 -# failed-migration state this script exists to diagnose — a bound there would -# manufacture the very condition it reports. Same reasoning as the signal traps -# above: a slow migration is survivable, a half-applied one is not. -STEP_TIMEOUT="${OUTPOST_STARTUP_STEP_TIMEOUT:-120}" -UNBOUNDED=no -case "$STEP_TIMEOUT" in - '' | *[!0-9]*) - echo "[worker] NOTE: OUTPOST_STARTUP_STEP_TIMEOUT='${STEP_TIMEOUT}' is not a whole number of seconds; using 120." >&2 - STEP_TIMEOUT=120 - ;; - 0) - # GNU timeout reads 0 as "no limit"; busybox reads it as "kill immediately", - # which would SIGKILL the drift check at t=0 and report it as a database - # failure. Honour the GNU reading, since that is what an operator means. - echo "[worker] NOTE: OUTPOST_STARTUP_STEP_TIMEOUT=0 — the drift check will run unbounded." >&2 - UNBOUNDED=yes - ;; -esac - -if [ "$UNBOUNDED" = no ] && command -v timeout >/dev/null 2>&1; then - # -k so a child that traps SIGTERM (the prisma CLI does, for engine cleanup) is - # still killed: busybox otherwise signals and then waits for it anyway, which - # means no bound at all. And busybox reports a timeout as 128+SIGTERM = 143, - # not GNU coreutils' 124 — normalise here so callers can test one value. - run_step() { - timeout -k 10 "$STEP_TIMEOUT" "$@" - _st=$? - if [ "$_st" -eq 143 ] || [ "$_st" -eq 137 ]; then - return 124 - fi - return "$_st" - } -else - # Not the deployed path (busybox provides timeout in node:*-alpine), but a - # missing applet must not fail every startup step closed. - [ "$UNBOUNDED" = no ] && echo "[worker] NOTE: timeout(1) is unavailable; the drift check will run unbounded." >&2 - run_step() { "$@"; } -fi - -# Progress goes to stdout; everything else (NOTE, WARNING, FATAL) to stderr. web -# and worker migrate into the same database and their Railway logs interleave, so -# "something needs attention" has to be machine-distinguishable and not merely -# prefixed. Note this is a two-way split, not three severity levels — an alert rule -# keyed on stderr alone will also catch NOTE lines. -fatal() { - echo "" >&2 - while [ "$#" -gt 0 ]; do - echo "[worker] $1" >&2 - shift - done -} - -# Recognised spellings of the incident override. Anything else fails closed, but -# says so — an operator who sets OUTPOST_ALLOW_SCHEMA_DRIFT=on under pressure must -# not get output byte-identical to having never set it at all. -drift_override_set() { - _drift_value=$(printf '%s' "${OUTPOST_ALLOW_SCHEMA_DRIFT:-0}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]"') - case "$_drift_value" in - 1 | true | yes | y | on | enabled) return 0 ;; - '' | 0 | false | no | n | off) return 1 ;; - *) - echo "[worker] NOTE: OUTPOST_ALLOW_SCHEMA_DRIFT is set to '${OUTPOST_ALLOW_SCHEMA_DRIFT:-}', which is not recognised." >&2 - echo "[worker] NOTE: use 1, true, yes, or on. Treating it as NOT set." >&2 - return 1 - ;; - esac -} - -echo "[worker] Running database migrations..." -# A migrate deploy failure is far more common than drift and, left to bare `set -e`, -# dies with Prisma's output and no framing — in a script whose whole purpose is -# naming the real cause. -set +e -$PRISMA migrate deploy --schema "$SCHEMA" -DEPLOY_STATUS=$? -set -e - -if [ "$DEPLOY_STATUS" -ne 0 ]; then - fatal "FATAL: prisma migrate deploy failed (see the error above)." \ - "Common causes: a migration recorded as failed in _prisma_migrations (P3009)," \ - "a migration file edited after it was applied (P3006), or an unreachable database." \ - "The worker will not start against a database whose migrations did not apply." +# The path is resolved relative to this script, so the image can place the guard +# wherever it likes. OUTPOST_SCHEMA_GUARD_SCRIPT overrides it, which is how CI +# runs a copy of this script from a temporary directory. +OUTPOST_SERVICE=worker +OUTPOST_DRIFT_WARNING="TRACKER_SYNC may write wrong statuses to Linear until this is repaired" +OUTPOST_SCHEMA_GUARD_SCRIPT="${OUTPOST_SCHEMA_GUARD_SCRIPT:-$(dirname "$0")/../../packages/outpost/db/schema-drift-guard.sh}" +if [ ! -f "$OUTPOST_SCHEMA_GUARD_SCRIPT" ]; then + echo "[worker] FATAL: the schema-drift guard is missing at ${OUTPOST_SCHEMA_GUARD_SCRIPT}." >&2 exit 1 fi - -# Schema-drift guard. -# -# `migrate deploy` only compares the migrations directory against the -# _prisma_migrations bookkeeping table. It never inspects the actual schema, so a -# migration recorded as applied but never executed is invisible to it — it -# cheerfully reports "No pending migrations to apply" against a database missing -# the tables that migration declares. -# -# That is exactly what happened: production had 0001_init recorded as applied -# while the SystemConfig table it declares did not exist. Every deploy from -# 2026-08-07 failed with nothing but "1/1 replicas never became healthy" — nine -# days of a five-minute healthcheck timeout that looked like a broken image. -# CI now runs this same comparison against a real database on every PR, so the -# repo-side version of that gap fails there rather than here. -# -# `migrate diff --exit-code`: 0 = identical, 2 = they differ, anything else = the -# CLI itself failed. Those last two are different problems and must not share a -# message — a script whose purpose is naming the real cause should not send the -# on-call hunting for drift that was never detected. -# -# ANY difference is fatal, deliberately. An earlier revision classified the diff -# and failed only on missing objects, so a sibling service mid-rollout would not -# block the worker. That classifier silently passed real drift — missing enum -# values and wrong column types both escaped it — and printed "schema matches" -# against a drifted database, which is the exact failure mode of the `migrate -# deploy` bookkeeping this guard compensates for. A guard that can be wrong in the -# reassuring direction is worse than no guard, so the crude check stands and -# OUTPOST_ALLOW_SCHEMA_DRIFT is the release valve for the skew case. -# -# Fatal because the worker's sync mappings come from the database, and one running -# against a schema it does not match would write wrong statuses to Linear. Failing -# the deploy leaves the previously-deployed replica running — note that replica is -# already serving against this same database and was never re-checked, so this -# buys "no NEW bad worker", not "the database is fine". -# -# NOTE: every exit below happens before `exec node`, so nothing binds /health and -# the platform sees only a healthcheck timeout. The deploy log is the sole channel. -SCHEMA_VERIFIED=yes -echo "[worker] Checking for schema drift..." -set +e -run_step $PRISMA migrate diff \ - --from-schema-datasource "$SCHEMA" \ - --to-schema-datamodel "$SCHEMA" \ - --exit-code -DRIFT_STATUS=$? -set -e - -if [ "$DRIFT_STATUS" -eq 2 ]; then - if drift_override_set; then - echo "[worker] WARNING: schema drift detected, but OUTPOST_ALLOW_SCHEMA_DRIFT is set — starting anyway." >&2 - echo "[worker] WARNING: TRACKER_SYNC may write wrong statuses to Linear until this is repaired." >&2 - echo "[worker] WARNING: unset this variable as soon as the schema is fixed." >&2 - SCHEMA_VERIFIED=no - else - fatal "FATAL: the database does not match schema.prisma (migrate diff printed the differences on stdout, above)." \ - "A migration may be recorded as applied without having run." \ - "Compare models in schema.prisma against the live tables before redeploying." \ - "If this is transient skew from a sibling service mid-rollout, or you need the" \ - "worker up during an incident, set OUTPOST_ALLOW_SCHEMA_DRIFT=1." - exit 1 - fi -elif [ "$DRIFT_STATUS" -ne 0 ]; then - # The override covers this branch too. A check that could not RUN is a strictly - # weaker guarantee than one that ran and found drift, so an operator who accepts - # drift necessarily accepts this. Without it, any CLI-level breakage — a schema - # the pinned CLI rejects, a missing engine binary, an unreadable /opt/prisma — - # is an unbreakable crash loop under restartPolicyType="ALWAYS", with no recourse - # short of a code change and a rebuild. A guard added to unblock deploys must not - # become the thing that blocks them. - if [ "$DRIFT_STATUS" -eq 124 ]; then - reason="the schema-drift check timed out after ${STEP_TIMEOUT}s; the database accepted the connection but never answered" - else - reason="prisma migrate diff exited $DRIFT_STATUS without comparing the database" - fi - # The override is consulted BEFORE emitting FATAL. Calling fatal() first would - # page on every successfully-overridden boot, which is exactly what the - # stdout/stderr split above exists to avoid. - if drift_override_set; then - echo "[worker] WARNING: $reason." >&2 - echo "[worker] WARNING: this is NOT confirmed drift — OUTPOST_ALLOW_SCHEMA_DRIFT is set, starting unverified." >&2 - SCHEMA_VERIFIED=no - else - fatal "FATAL: $reason." \ - "The database was NEVER COMPARED. This is NOT confirmed drift." \ - "Causes, roughly by likelihood: DATABASE_URL unset or wrong; database unreachable" \ - "from this container; the pinned prisma CLI (apps/worker/Dockerfile) rejecting" \ - "schema.prisma; a missing or unloadable schema engine binary." \ - "To boot without the guard, set OUTPOST_ALLOW_SCHEMA_DRIFT=1." - exit 1 - fi -fi - -# The success line must not claim verification on either override path — one starts -# against known drift, the other against a database that was never compared. -if [ "$SCHEMA_VERIFIED" = yes ]; then - echo "[worker] Migrations complete and schema verified. Starting worker..." -else - echo "[worker] Migrations complete; schema NOT verified (override in effect). Starting worker..." -fi +# shellcheck source=packages/outpost/db/schema-drift-guard.sh +. "$OUTPOST_SCHEMA_GUARD_SCRIPT" + +# Applies the pending migrations, then checks that the database really matches +# schema.prisma. `migrate deploy` alone only compares the migrations directory +# against the _prisma_migrations bookkeeping table and never looks at the actual +# schema, so a migration recorded as applied but never executed is invisible to +# it. The guard's own comments explain the rest; the CI step "Verify the startup +# guard" asserts every branch of it against a stub CLI. +outpost_migrate_and_verify + +echo "[worker] Starting worker..." exec node apps/worker/dist/index.js diff --git a/docs/deployment.md b/docs/deployment.md index 4dedd2d5..0b4f330e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -337,6 +337,21 @@ outlasts the lock timeout — a restart clears it. Worth knowing before adding a migrating service, and worth consolidating onto a single migrate step (or a release-phase job) if migrations grow long. +Both services then check that the database they ended up with really matches +`schema.prisma`, using the shared guard in `packages/outpost/db/schema-drift-guard.sh`. +`migrate deploy` only compares the migrations directory against the `_prisma_migrations` +bookkeeping table and never inspects the schema itself, so a migration recorded as applied +but never executed is invisible to it. Production ran in exactly that state for nine days in +August 2026 — every deploy failed with nothing but "1/1 replicas never became healthy". + +Any difference is fatal, in **both** services: a guard only one of them applied would leave +the other serving traffic against a schema the guarded service refuses to run against. +`OUTPOST_ALLOW_SCHEMA_DRIFT=1` is the incident release valve — it starts the service +anyway, with warnings — and `OUTPOST_STARTUP_STEP_TIMEOUT` bounds the check so a +black-holing database cannot hang the boot without saying why. CI runs the same comparison +against a real database on every PR, and exercises every branch of the guard against a stub +CLI. + To apply migrations by hand (e.g. against a fresh local database): ```bash diff --git a/packages/outpost/db/schema-drift-guard.sh b/packages/outpost/db/schema-drift-guard.sh new file mode 100644 index 00000000..427c9205 --- /dev/null +++ b/packages/outpost/db/schema-drift-guard.sh @@ -0,0 +1,264 @@ +# Schema-drift guard for the services that migrate the outpost database. +# +# SOURCED, not executed. The functions below run in the caller's shell, so a +# fatal failure exits the caller with its own exit status, its own traps and its +# own log prefix. Both apps/web/start.sh and apps/worker/start.sh use it. +# +# Why it exists +# ------------- +# web and worker migrate the SAME database, and `prisma migrate deploy` only +# compares the migrations directory against the _prisma_migrations bookkeeping +# table. It never inspects the actual schema, so a migration recorded as +# applied but never executed is invisible to it — it cheerfully reports "No +# pending migrations to apply" against a database missing the tables that +# migration declares. +# +# That is exactly what happened in production: 0001_init was recorded as +# applied while the SystemConfig table it declares did not exist. Every deploy +# from 2026-08-07 failed with nothing but "1/1 replicas never became healthy" — +# nine days of a five-minute healthcheck timeout that looked like a broken +# image. CI now runs this same comparison against a real database on every PR, +# so the repo-side version of that gap fails there rather than here. +# +# Why both services run it +# ------------------------ +# A guard that only one of the two services applies leaves the other one free +# to serve traffic against a schema the guarded service refuses to run against. +# The two migrate the same database, so they have to agree about what that +# database looks like — otherwise a drifted deploy half-succeeds: the worker +# stays down while web keeps answering. +# +# `migrate diff --exit-code`: 0 = identical, 2 = they differ, anything else = +# the CLI itself failed. Those last two are different problems and must not +# share a message — a script whose purpose is naming the real cause should not +# send the on-call hunting for drift that was never detected. +# +# ANY difference is fatal, deliberately. An earlier revision classified the diff +# and failed only on missing objects, so a sibling service mid-rollout would +# not block the worker. That classifier silently passed real drift — missing +# enum values and wrong column types both escaped it — and printed "schema +# matches" against a drifted database, which is the exact failure mode of the +# `migrate deploy` bookkeeping this guard compensates for. A guard that can be +# wrong in the reassuring direction is worse than no guard, so the crude check +# stands and OUTPOST_ALLOW_SCHEMA_DRIFT is the release valve for the skew case. +# +# Usage +# ----- +# OUTPOST_SERVICE=worker . packages/outpost/db/schema-drift-guard.sh +# outpost_migrate_and_verify +# +# The caller sets OUTPOST_SERVICE (the label every line is prefixed with) and +# may set OUTPOST_DRIFT_WARNING (what this service gets wrong while the drift +# is unrepaired). + +# ─── Configuration ────────────────────────────────────────────────────────── + +# The label every line is prefixed with. Each service sets its own so the +# messages name the service that failed. +OUTPOST_SERVICE="${OUTPOST_SERVICE:-service}" + +# The prisma CLI to invoke. Overridable so CI can execute the calling script +# against a stub that returns canned exit codes. Nothing previously ran +# start.sh at all — CI re-implemented the prisma calls in bash — which is +# exactly why a busybox-vs-GNU exit-code difference in the timeout handling went +# unnoticed. +OUTPOST_PRISMA_CMD="${OUTPOST_PRISMA_CMD:-node /opt/prisma/node_modules/prisma/build/index.js}" + +# The schema the live database is compared against. +OUTPOST_SCHEMA_PATH="${OUTPOST_SCHEMA_PATH:-packages/outpost/db/prisma/schema.prisma}" + +# What this service gets wrong while it runs against a schema it does not +# match. Named per service because the consequence differs: the worker writes +# statuses to Linear from the database, web serves every page from it. +OUTPOST_DRIFT_WARNING="${OUTPOST_DRIFT_WARNING:-this service keeps running against a schema it does not match until this is repaired}" + +# ─── Output ───────────────────────────────────────────────────────────────── + +# Progress goes to stdout; everything else (NOTE, WARNING, FATAL) to stderr. web +# and worker migrate into the same database and their Railway logs interleave, so +# "something needs attention" has to be machine-distinguishable and not merely +# prefixed. Note this is a two-way split, not three severity levels — an alert rule +# keyed on stderr alone will also catch NOTE lines. +outpost_fatal() { + echo "" >&2 + while [ "$#" -gt 0 ]; do + echo "[$OUTPOST_SERVICE] $1" >&2 + shift + done +} + +# ─── Timeout ──────────────────────────────────────────────────────────────── + +# The drift check is bounded. Against a black-holing endpoint (a dropped packet +# rather than a refusal) the CLI can hang far past any TCP timeout, and a hang +# produces NO log line at all — indistinguishable from a slow migration and from +# a healthy-but-slow boot, which defeats the point of putting the reason in the +# log. +# +# `migrate deploy` is deliberately NOT bounded. Killing it mid-migration leaves +# _prisma_migrations holding a row with finished_at = NULL, which is the P3009 +# failed-migration state this guard exists to diagnose — a bound there would +# manufacture the very condition it reports. Same reasoning as the signal traps +# in the worker's start.sh: a slow migration is survivable, a half-applied one +# is not. +outpost_resolve_step_timeout() { + OUTPOST_STEP_TIMEOUT="${OUTPOST_STARTUP_STEP_TIMEOUT:-120}" + OUTPOST_UNBOUNDED=no + case "$OUTPOST_STEP_TIMEOUT" in + '' | *[!0-9]*) + echo "[$OUTPOST_SERVICE] NOTE: OUTPOST_STARTUP_STEP_TIMEOUT='${OUTPOST_STARTUP_STEP_TIMEOUT:-}' is not a whole number of seconds; using 120." >&2 + OUTPOST_STEP_TIMEOUT=120 + ;; + 0) + # GNU timeout reads 0 as "no limit"; busybox reads it as "kill immediately", + # which would SIGKILL the drift check at t=0 and report it as a database + # failure. Honour the GNU reading, since that is what an operator means. + echo "[$OUTPOST_SERVICE] NOTE: OUTPOST_STARTUP_STEP_TIMEOUT=0 — the drift check will run unbounded." >&2 + OUTPOST_UNBOUNDED=yes + ;; + esac + + if [ "$OUTPOST_UNBOUNDED" = no ] && command -v timeout >/dev/null 2>&1; then + # BusyBox returns the child's exit status even after a timeout. A child + # that catches TERM and exits 0 could therefore falsely pass verification. + # KILL cannot be caught; normalize its status alongside GNU's timeout status. + outpost_run_step() { + if timeout -s KILL "$OUTPOST_STEP_TIMEOUT" "$@"; then + return 0 + else + _st=$? + if [ "$_st" -eq 137 ]; then + return 124 + fi + return "$_st" + fi + } + else + # Not the deployed path (busybox provides timeout in node:*-alpine), but a + # missing applet must not fail every startup step closed. + if [ "$OUTPOST_UNBOUNDED" = no ]; then + echo "[$OUTPOST_SERVICE] NOTE: timeout(1) is unavailable; the drift check will run unbounded." >&2 + fi + outpost_run_step() { "$@"; } + fi +} + +# ─── The incident override ────────────────────────────────────────────────── + +# Recognised spellings of the incident override. Anything else fails closed, but +# says so — an operator who sets OUTPOST_ALLOW_SCHEMA_DRIFT=on under pressure must +# not get output byte-identical to having never set it at all. +outpost_drift_override_set() { + _drift_value=$(printf '%s' "${OUTPOST_ALLOW_SCHEMA_DRIFT:-0}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]"') + case "$_drift_value" in + 1 | true | yes | y | on | enabled) return 0 ;; + '' | 0 | false | no | n | off) return 1 ;; + *) + echo "[$OUTPOST_SERVICE] NOTE: OUTPOST_ALLOW_SCHEMA_DRIFT is set to '${OUTPOST_ALLOW_SCHEMA_DRIFT:-}', which is not recognised." >&2 + echo "[$OUTPOST_SERVICE] NOTE: use 1, true, yes, or on. Treating it as NOT set." >&2 + return 1 + ;; + esac +} + +# ─── The check ────────────────────────────────────────────────────────────── + +# Apply the pending migrations, then verify that the database that results +# actually matches schema.prisma. Exits the calling shell when the database does +# not match and no override is in effect. +outpost_migrate_and_verify() { + outpost_resolve_step_timeout + + echo "[$OUTPOST_SERVICE] Running database migrations..." + if $OUTPOST_PRISMA_CMD migrate deploy --schema "$OUTPOST_SCHEMA_PATH"; then + DEPLOY_STATUS=0 + else + DEPLOY_STATUS=$? + fi + + if [ "$DEPLOY_STATUS" -ne 0 ]; then + # A migrate deploy failure is far more common than drift and, left to bare + # `set -e`, dies with Prisma's output and no framing — in a script whose + # whole purpose is naming the real cause. + outpost_fatal "FATAL: prisma migrate deploy failed (see the error above)." \ + "Common causes: a migration recorded as failed in _prisma_migrations (P3009)," \ + "a migration file edited after it was applied (P3006), or an unreachable database." \ + "The service will not start against a database whose migrations did not apply." + exit 1 + fi + + # Fatal because the sync mappings and the pages both come from the database, + # and one running against a schema it does not match reads and writes the + # wrong columns. Failing the deploy leaves the previously-deployed replica + # running — note that replica is already serving against this same database + # and was never re-checked, so this buys "no NEW bad service", not "the + # database is fine". + # + # NOTE: every exit below happens before the caller execs its server, so + # nothing binds its health endpoint and the platform sees only a healthcheck + # timeout. The deploy log is the sole channel. + OUTPOST_SCHEMA_VERIFIED=yes + echo "[$OUTPOST_SERVICE] Checking for schema drift..." + if outpost_run_step $OUTPOST_PRISMA_CMD migrate diff \ + --from-schema-datasource "$OUTPOST_SCHEMA_PATH" \ + --to-schema-datamodel "$OUTPOST_SCHEMA_PATH" \ + --exit-code; then + DRIFT_STATUS=0 + else + DRIFT_STATUS=$? + fi + + if [ "$DRIFT_STATUS" -eq 2 ]; then + if outpost_drift_override_set; then + echo "[$OUTPOST_SERVICE] WARNING: schema drift detected, but OUTPOST_ALLOW_SCHEMA_DRIFT is set — starting anyway." >&2 + echo "[$OUTPOST_SERVICE] WARNING: $OUTPOST_DRIFT_WARNING." >&2 + echo "[$OUTPOST_SERVICE] WARNING: unset this variable as soon as the schema is fixed." >&2 + OUTPOST_SCHEMA_VERIFIED=no + else + outpost_fatal "FATAL: the database does not match schema.prisma (migrate diff printed the differences on stdout, above)." \ + "A migration may be recorded as applied without having run." \ + "Compare models in schema.prisma against the live tables before redeploying." \ + "If this is transient skew from a sibling service mid-rollout, or you need the" \ + "$OUTPOST_SERVICE up during an incident, set OUTPOST_ALLOW_SCHEMA_DRIFT=1." + exit 1 + fi + elif [ "$DRIFT_STATUS" -ne 0 ]; then + # The override covers this branch too. A check that could not RUN is a + # strictly weaker guarantee than one that ran and found drift, so an + # operator who accepts drift necessarily accepts this. Without it, any + # CLI-level breakage — a schema the pinned CLI rejects, a missing engine + # binary, an unreadable /opt/prisma — is an unbreakable crash loop under + # restartPolicyType="ALWAYS", with no recourse short of a code change and + # a rebuild. A guard added to unblock deploys must not become the thing + # that blocks them. + if [ "$DRIFT_STATUS" -eq 124 ]; then + reason="the schema-drift check timed out after ${OUTPOST_STEP_TIMEOUT}s; the database accepted the connection but never answered" + else + reason="prisma migrate diff exited $DRIFT_STATUS without comparing the database" + fi + # The override is consulted BEFORE emitting FATAL. Calling fatal() first would + # page on every successfully-overridden boot, which is exactly what the + # stdout/stderr split above exists to avoid. + if outpost_drift_override_set; then + echo "[$OUTPOST_SERVICE] WARNING: $reason." >&2 + echo "[$OUTPOST_SERVICE] WARNING: this is NOT confirmed drift — OUTPOST_ALLOW_SCHEMA_DRIFT is set, starting unverified." >&2 + OUTPOST_SCHEMA_VERIFIED=no + else + outpost_fatal "FATAL: $reason." \ + "The database was NEVER COMPARED. This is NOT confirmed drift." \ + "Causes, roughly by likelihood: DATABASE_URL unset or wrong; database unreachable" \ + "from this container; the pinned prisma CLI in this image rejecting" \ + "schema.prisma; a missing or unloadable schema engine binary." \ + "To boot without the guard, set OUTPOST_ALLOW_SCHEMA_DRIFT=1." + exit 1 + fi + fi + + # The success line must not claim verification on either override path — one starts + # against known drift, the other against a database that was never compared. + if [ "$OUTPOST_SCHEMA_VERIFIED" = yes ]; then + echo "[$OUTPOST_SERVICE] Migrations complete and schema verified." + else + echo "[$OUTPOST_SERVICE] Migrations complete; schema NOT verified (override in effect)." + fi +}