Skip to content

fix(migrations): drop the constraint drops that CASCADE already handled - #700

Merged
sydevs-bot merged 1 commit into
mainfrom
claude/fix-user-messages-down-fk
Sep 5, 2026
Merged

sydevs-bot merged 1 commit into
mainfrom
claude/fix-user-messages-down-fk

Conversation

@sydevs-bot

Copy link
Copy Markdown
Contributor

Summary

  • pnpm payload migrate:down could not roll back past 20260826_214829_add_user_messages.
  • fix(migrations): the user_messages down drops a constraint by a name that was never created #682's diagnosis was wrong, and the real cause is the line above. The constraint name matches. DROP TABLE … CASCADE had already dropped it.
  • Two more migrations carry the same shape, and a batch rollback walks all three, so the ticket's acceptance criterion needs all three.
  • A unit spec now guards the class, since migrate:create emits this pair itself.

Changes

  • src/migrations/20260826_214829_add_user_messages.ts — one redundant DROP CONSTRAINT removed
  • src/migrations/20260812_032435_add_event_submissions.ts — same, one
  • src/migrations/20260608_174939.ts — same, four (regions, events, registrations, users)
  • tests/unit/migration-down-cascade.spec.ts — new, reads the whole chain

What was actually wrong

#682 read the failure as a down naming a constraint its up never created. That is not what happens.

The up creates it, at 20260826_214829_add_user_messages.ts:35, and \d payload_locked_documents_rels on a migrated database names it exactly as written:

"payload_locked_documents_rels_user_messages_fk" FOREIGN KEY (user_messages_id)
    REFERENCES user_messages(id) ON DELETE CASCADE

The line above the failure is what does it. DROP TABLE "user_messages" CASCADE drops every foreign key referencing that table, so the named drop one line later has nothing left to drop:

DROP TABLE "user_messages" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_user_messages_fk";  -- gone already

So the fix is deletion, not correction — which also answers the ticket's third criterion. No IF EXISTS: it would have hidden this failure and the next one.

Why three migrations and not one. migrate:down rolls back a batch, and on a database migrated from empty the whole chain is one batch. Fixing only the migration named in the ticket moves the abort to 20260812_032435_add_event_submissions, then to 20260608_174939. The ticket asks that migrate:down complete on such a database, so all three are in scope. Every removed line is redundant for the same reason.

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (121 files, 1566 tests)
  • New spec: tests/unit/migration-down-cascade.spec.ts, 2 cases
  • Targeted integration specs: none — no spec reads these files, and the real gate is the round trip below
  • Build: N/A — Railway builds the preview

Verified against a real Postgres 18, not inferred. On a fresh database:

Step Before After
pnpm payload migrate Done. — 140 tables Done. — 140 tables
pnpm payload migrate:down aborts on the DROP CONSTRAINT quoted above Rolling back batch 1 consisting of 54 migration(s). → Done., 0 tables
pnpm payload migrate again not reachable Done. — 140 tables

The new spec was confirmed to fail before it passed: reinstating the one line in 20260826_214829 turns it red, naming that line.

Manual verification

Optional — the table above is reproducible:

createdb migtest && DATABASE_URL=postgresql://…/migtest pnpm payload migrate
DATABASE_URL=postgresql://…/migtest pnpm payload migrate:down

Notes for reviewer

  • Editing an applied migration is the thing to check here. src/migrations/AGENTS.md warns that "unmerged does not mean unapplied" — Railway applies these on every preview boot. That warning is about changing what a migration does to a schema. These six lines only ever ran during a rollback that has never succeeded, so no deployed database took a different path because of them, and up is untouched. The .json snapshots are untouched too, since the schema is unchanged.
  • Production is unaffected either way. It rolls forward — prodMigrations applies on boot and nothing calls migrate:down there. What this restores is the local escape hatch, which is also the check that found the bug.
  • The spec reads the chain rather than one file because a single bad down fails the whole batch, whichever migration holds it. Its first case asserts the glob matched something, so a future rename cannot make the second case vacuously green.
Detail

How the spec decides. It parses every up for ADD CONSTRAINT "c" FOREIGN KEY (…) REFERENCES "public"."t", building constraint → referenced table. Then it walks each down in order, tracking tables dropped with CASCADE, and flags a DROP CONSTRAINT whose referenced table is already in that set. Order matters: a constraint dropped before its table is correct and stays unflagged. Reading the referenced table from the up rather than guessing it from the constraint name is what keeps the check honest — the names are conventional, not load-bearing.

This is a generator shape, not a typo. All three came out of migrate:create the same way, which is why the guard is worth more than the six deletions. A fourth collection added tomorrow arrives with the same pair.

Pipeline notes. /pr-review-toolkit:review-pr all is not installed in this environment. /security-review was gated off: securityReview.triggerPattern in .claude/workflow.json does not match src/migrations/ or tests/. Flagged so the substitutions are visible rather than assumed.

Closes #682

🤖 Written by the sydevs autonomous loop — see what this is

🤖 Generated with Claude Code

https://claude.ai/code/session_01A6p13bPyPaiysoorzsPDcK


Generated by Claude Code

`pnpm payload migrate:down` could not roll back past
`20260826_214829_add_user_messages`. Its `down` aborted on

    constraint "payload_locked_documents_rels_user_messages_fk" of relation
    "payload_locked_documents_rels" does not exist

**The ticket's diagnosis was wrong, and the real cause is next door.** #682
read this as a name the `up` never created. The name matches: the `up`
creates it at line 35, and `\d payload_locked_documents_rels` on a migrated
database names it exactly so. The line above the failure is what does it —
`DROP TABLE "user_messages" CASCADE` drops every foreign key referencing
that table, so the named drop that follows has nothing left to drop.

So the fix is deletion, not correction. No `IF EXISTS`, which would have
hidden this and the next one.

**Two more migrations carry the same shape**, and a batch rollback walks all
of them, so fixing one alone still fails at the next: `20260608_174939`
(regions, events, registrations, users) and
`20260812_032435_add_event_submissions`. The ticket asks that `migrate:down`
complete on a database migrated from empty, and that needs all three.

Verified against a real Postgres 18, not inferred: 54 migrations applied to
an empty database (140 tables), rolled back to 0 tables, re-applied to 140.
Before the change the same rollback aborts on the query quoted above.

`tests/unit/migration-down-cascade.spec.ts` guards the class. It reads each
`up` for what a constraint references, then flags any `down` that names one
after dropping its table with CASCADE. Confirmed it fails first —
reinstating the one line turns it red naming that line.

Closes #682

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01A6p13bPyPaiysoorzsPDcK
@railway-app

railway-app Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-700 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 5, 2026 at 3:31 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-700 September 5, 2026 15:29 Destroyed
@sydevs-bot
sydevs-bot merged commit fe7a353 into main Sep 5, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in SYDevelopers Technical Roadmap Sep 5, 2026
sydevs-bot pushed a commit that referenced this pull request Sep 5, 2026
Review of #703 found the `reads === 0` exit too blunt. It fired on any
cause, including a transient statuses-API incident that outlasted the
12-minute deadline — turning every open PR red, clearable only by a full
re-run — and it spent the whole budget before saying so. #661 resolved
that the fail-open is correct for a PR with genuinely no preview, and
scoped exactly one new hard failure.

`fetchStatuses` collapsed every non-ok response into one opaque Error, so
the loop could not tell a permanent 401/403 from a retryable 502. It now
throws StatusFetchError carrying `res.status`, and discovery returns a
`forbidden` outcome on the first 401/403 — terminal, like `unpublished`,
because GitHub will not relent inside one run. That keeps the property
worth keeping (never having looked is not evidence of absence) and drops
both the transient trigger and the 12-minute cost.

A budget spent entirely on transient errors now warns and skips instead
of failing. The remaining causes are the ones that clear on their own.

Also from review: the OTHER fixture used `mailpit - Mailpit`, a context
Railway never posts. Railway's shape is `<project> - <service>`, so a
sibling service is `sahajcloud - Mailpit`. The old fixture asserted
against an impossible string; the new one covers the case that can occur,
and records that the discrimination rests on `includes` being
case-sensitive.

And the `unpublished`-is-terminal docstring now records its evidence:
settled-state only (#699, #700), bounded by discovery starting about six
minutes into the job, so the status it reads is already minutes old.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY
sydevs-bot added a commit that referenced this pull request Sep 5, 2026
…#703)

* fix(ci): fail closed when a Railway deploy publishes no preview URL

Railway can report `success` on a PR deploy while the service has no
domain, so the commit-status description reads a bare `Success` with no
host after it. Discovery treated that as "not ready yet": neither the
success break nor the failure return fired, so it re-read the identical
immutable status every 15s for the full 12-minute budget, then exported an
empty `preview_url` and exited 0. `ci.yml` gates the smoke step on that
value, so the step skipped and the job stayed green.

The cost was silent and large. `Lint, Test & Smoke: pass` has meant "unit +
integration passed" on every PR for weeks, and three specs — `cors-preflight`,
`error-disclosure`, `images` — have never run in CI at all.

**A deploy that succeeds without a host is broken configuration, not an
absent preview.** PR services inherit a domain only from a base-environment
service that has one, so this is terminal on the first poll and re-running
changes nothing. Discovery now exits 1 with an `::error` naming the cause
and the fix. The genuine skips are untouched and still exit 0: no status
within the timeout, a failed or cancelled deploy, or missing env.

Returning on the first terminal status also ends the 12-minute wait. A
healthy PR now resolves in one poll.

`scripts/railway-preview-status.ts` splits the decision out as a pure
module — `classifyStatuses` plus `discoverPreview` over injected clock,
sleep and fetch — so the unit lane can cover it without network or a
direct-run guard on the CI entrypoint. The runner keeps env parsing, the
GitHub fetch, the health check and the exit codes.

Fixture note: the specs assume Railway posts context `sahajcloud -
SahajCloud` with either `Success - <host>.up.railway.app` or a bare
`Success`. Verified against the live statuses on #700 (host present) and
#699 (bare), not inferred.

The new specs were confirmed to fail before they passed: classifying
success-with-no-host as `pending` again — the original behaviour, at the
line that caused it — turns three of them red.

Every exit path was also exercised end to end through `main()` with a
stubbed fetch, since a passing unit spec is not evidence that its caller
reaches the branch: unpublished exits 1 in ~1s, ready exits 0 with the URL
exported, a failed deploy and missing env both exit 0 empty.

Docs corrected in the same pass. `playwright.config.ts` and
`tests/AGENTS.md` said the URL is "discovered via the Railway API"; it
comes from the GitHub commit-status API. `RAILWAY_RUNBOOK.md` claimed PR
previews need "no manual per-PR configuration" — the false premise behind
this outage — and now states the coupling to production's domain, with the
three quiet symptoms. `scripts/AGENTS.md` had no row for either script.

Infra step 1 of the ticket was already applied on 2026-09-05: production's
`SahajCloud` service has `sahajcloud-production.up.railway.app` on port
8080 beside the custom domain.

Closes #661

Claude-Session: https://claude.ai/code/session_01QkaVUYxFsjHJd1aN8hYhVP

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(ci): apply the simplify and review passes to preview discovery

Quality pass over the branch, plus two review findings worth fixing.

- Never sleep past the deadline. The sleep after the last useful poll
  gated nothing, and an unclamped one overran the advertised budget by up
  to a full interval — 15s of dead CI clock on every timing-out run. The
  new assertion fails without the clamp: a 40s budget reported 45s.
- Log the classification (`unpublished`, `pending`) rather than GitHub's
  raw state. Telling `unpublished` from `success` is the whole point of
  the change, so the log should say which. Drops the `statusState` helper
  and its type subtraction, and `state` off `unpublished`, where it is
  always `success` and so derivable from `kind`.
- Make `last` and `elapsedMs` load-bearing instead of test-only: the
  timeout message now says whether a status ever appeared, or which state
  it never left. That was the diagnostic the docstring already promised
  and never delivered.
- Trim the duplicated remediation from the `::error` string and its
  comment. RAILWAY_RUNBOOK.md owns the fix; a copy in a string literal is
  the one that goes stale while the runbook gets corrected.

**A run where every statuses read failed now exits 1 too.** Review found
the same silent green as #661 through another door: a revoked
`statuses: read` scope makes every poll throw, `last` stays `absent`, and
after 12 minutes the run reports "no preview" and exits 0 — indistinguishable
from a PR that genuinely has none. `reads`/`errors` on the timeout outcome
separate the two, and never having looked is not evidence of absence. A
genuinely absent, failed, or still-building preview is untouched and still
exits 0.

Verified through `main()` with a stubbed fetch and a virtual clock, not
just through the unit lane — a passing spec is no evidence that its caller
reaches the branch. All reads failing: 48 requests over the full 720s
budget, then exit 1.

**Not taken.** Review argued that acting on the first `unpublished` is
unsound, since a context can post a later status. The premise is right and
the docstring overclaimed, so the rationale is corrected in place — but
immediate failure is a resolved decision on #661, which named one grace
re-poll as the alternative and chose immediate. Also left alone: sharing a
`pollUntil` between this loop and `waitHealthy` (pre-existing, unchanged
here), and shortening the budget for a never-seen status (#661 keeps the
genuine skip paths as they are).

Claude-Session: https://claude.ai/code/session_01QkaVUYxFsjHJd1aN8hYhVP

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ci): correct what the preview-discovery step can do to a CI run

The workflow comment is the first contract description a CI reader sees,
and it still said the step "skips gracefully" with no mention that it can
now fail the job — so someone debugging a red `Discover Railway preview
URL` would read an adjacent comment telling them that step does not fail.

`RAILWAY_RUNBOOK.md`'s CI section asserted the superseded rule five lines
above the new section correcting it. Folded the correction into the
paragraph it supersedes, rather than leaving a reader to hit the old
contract first and the amendment second.

The skip warning claimed "This PR has no preview environment", which is
only one of the three cases that reach it — a failed deploy and one still
building at the deadline also skip. It now points at the discovery step's
own log instead of guessing.

`scripts/AGENTS.md` records both non-zero exits.

Claude-Session: https://claude.ai/code/session_01QkaVUYxFsjHJd1aN8hYhVP

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ci): fail fast on a refused statuses read, not on every failed one

Review of #703 found the `reads === 0` exit too blunt. It fired on any
cause, including a transient statuses-API incident that outlasted the
12-minute deadline — turning every open PR red, clearable only by a full
re-run — and it spent the whole budget before saying so. #661 resolved
that the fail-open is correct for a PR with genuinely no preview, and
scoped exactly one new hard failure.

`fetchStatuses` collapsed every non-ok response into one opaque Error, so
the loop could not tell a permanent 401/403 from a retryable 502. It now
throws StatusFetchError carrying `res.status`, and discovery returns a
`forbidden` outcome on the first 401/403 — terminal, like `unpublished`,
because GitHub will not relent inside one run. That keeps the property
worth keeping (never having looked is not evidence of absence) and drops
both the transient trigger and the 12-minute cost.

A budget spent entirely on transient errors now warns and skips instead
of failing. The remaining causes are the ones that clear on their own.

Also from review: the OTHER fixture used `mailpit - Mailpit`, a context
Railway never posts. Railway's shape is `<project> - <service>`, so a
sibling service is `sahajcloud - Mailpit`. The old fixture asserted
against an impossible string; the new one covers the case that can occur,
and records that the discrimination rests on `includes` being
case-sensitive.

And the `unpublished`-is-terminal docstring now records its evidence:
settled-state only (#699, #700), bounded by discovery starting about six
minutes into the job, so the status it reads is already minutes old.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

* docs(ci): correct what discovery does when a statuses read fails

The scripts guide still described the blanket `reads === 0` failure.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

---------

Co-authored-by: Claude <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
Railway can report `success` on a PR deploy while the service has no
domain, so the commit-status description reads a bare `Success` with no
host after it. Discovery treated that as "not ready yet": neither the
success break nor the failure return fired, so it re-read the identical
immutable status every 15s for the full 12-minute budget, then exported an
empty `preview_url` and exited 0. `ci.yml` gates the smoke step on that
value, so the step skipped and the job stayed green.

The cost was silent and large. `Lint, Test & Smoke: pass` has meant "unit +
integration passed" on every PR for weeks, and three specs — `cors-preflight`,
`error-disclosure`, `images` — have never run in CI at all.

**A deploy that succeeds without a host is broken configuration, not an
absent preview.** PR services inherit a domain only from a base-environment
service that has one, so this is terminal on the first poll and re-running
changes nothing. Discovery now exits 1 with an `::error` naming the cause
and the fix. The genuine skips are untouched and still exit 0: no status
within the timeout, a failed or cancelled deploy, or missing env.

Returning on the first terminal status also ends the 12-minute wait. A
healthy PR now resolves in one poll.

`scripts/railway-preview-status.ts` splits the decision out as a pure
module — `classifyStatuses` plus `discoverPreview` over injected clock,
sleep and fetch — so the unit lane can cover it without network or a
direct-run guard on the CI entrypoint. The runner keeps env parsing, the
GitHub fetch, the health check and the exit codes.

Fixture note: the specs assume Railway posts context `sahajcloud -
SahajCloud` with either `Success - <host>.up.railway.app` or a bare
`Success`. Verified against the live statuses on #700 (host present) and
#699 (bare), not inferred.

The new specs were confirmed to fail before they passed: classifying
success-with-no-host as `pending` again — the original behaviour, at the
line that caused it — turns three of them red.

Every exit path was also exercised end to end through `main()` with a
stubbed fetch, since a passing unit spec is not evidence that its caller
reaches the branch: unpublished exits 1 in ~1s, ready exits 0 with the URL
exported, a failed deploy and missing env both exit 0 empty.

Docs corrected in the same pass. `playwright.config.ts` and
`tests/AGENTS.md` said the URL is "discovered via the Railway API"; it
comes from the GitHub commit-status API. `RAILWAY_RUNBOOK.md` claimed PR
previews need "no manual per-PR configuration" — the false premise behind
this outage — and now states the coupling to production's domain, with the
three quiet symptoms. `scripts/AGENTS.md` had no row for either script.

Infra step 1 of the ticket was already applied on 2026-09-05: production's
`SahajCloud` service has `sahajcloud-production.up.railway.app` on port
8080 beside the custom domain.

Closes #661

Claude-Session: https://claude.ai/code/session_01QkaVUYxFsjHJd1aN8hYhVP

Co-Authored-By: Claude Opus 5 <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
Review of #703 found the `reads === 0` exit too blunt. It fired on any
cause, including a transient statuses-API incident that outlasted the
12-minute deadline — turning every open PR red, clearable only by a full
re-run — and it spent the whole budget before saying so. #661 resolved
that the fail-open is correct for a PR with genuinely no preview, and
scoped exactly one new hard failure.

`fetchStatuses` collapsed every non-ok response into one opaque Error, so
the loop could not tell a permanent 401/403 from a retryable 502. It now
throws StatusFetchError carrying `res.status`, and discovery returns a
`forbidden` outcome on the first 401/403 — terminal, like `unpublished`,
because GitHub will not relent inside one run. That keeps the property
worth keeping (never having looked is not evidence of absence) and drops
both the transient trigger and the 12-minute cost.

A budget spent entirely on transient errors now warns and skips instead
of failing. The remaining causes are the ones that clear on their own.

Also from review: the OTHER fixture used `mailpit - Mailpit`, a context
Railway never posts. Railway's shape is `<project> - <service>`, so a
sibling service is `sahajcloud - Mailpit`. The old fixture asserted
against an impossible string; the new one covers the case that can occur,
and records that the discrimination rests on `includes` being
case-sensitive.

And the `unpublished`-is-terminal docstring now records its evidence:
settled-state only (#699, #700), bounded by discovery starting about six
minutes into the job, so the status it reads is already minutes old.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-700 — 18fac05c Deployed Sep 5, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(migrations): the user_messages down drops a constraint by a name that was never created

3 participants