Skip to content

feat(scripts): work locally on a safe copy of production data - #879

Closed
sydevs-bot wants to merge 10 commits into
mainfrom
claude/feat-876-db-refresh-from-prod
Closed

sydevs-bot wants to merge 10 commits into
mainfrom
claude/feat-876-db-refresh-from-prod

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The immediate screening kick bypassed JOBS_AUTORUN_ENABLED, so a pending submission on a prod copy still delivered to a real mailing list within two seconds. Both triggers now read one predicate.
  • pnpm db:refresh-from-prod --force refuses to copy production until the flag resolves to off, before production is read. The dry run reports the resolved value.
  • Three docs claimed a guard that a local prod copy breaks, and the README now names the paths the flag cannot reach at all.

Test results

  • Lean gate: ✓ .claude/skills/pr-prep/check.sh — lint, typecheck, typecheck:tests, 172 unit files / 2285 tests
  • Targeted specs: ✓ screen-submissions.int.spec.ts + user-submissions-create.int.spec.ts (49), and lib-boundary / client-bundle-safety / public-env-substitution for the new src/lib/jobs/ module
  • Script: ✓ verified end to end against a stand-in production database — see Detail
  • Build: N/A (Railway builds the preview)

Preview

The preview sets no flag, so it runs with autoRun on — it shows the unchanged path, not the gated one.

  • User submissions — the intake whose post-commit kick is now gated; creating a pending row here still screens and delivers as on main
  • Clients — the mailing-list key whose validation the README now names as outside the flag's reach

Manual verification

Needs a machine with railway login and Postgres client tools — the routine has neither.

  1. With JOBS_AUTORUN_ENABLED=true in the shell, pnpm db:refresh-from-prod --force exits non-zero naming the flag, and psql "$DATABASE_URL" -c 'select 1' still connects to the unchanged database.
  2. With nothing set, pnpm db:refresh-from-prod prints the production host, the target database and JOBS_AUTORUN_ENABLED resolves to on, then exits 0.
  3. On a dev server with JOBS_AUTORUN_ENABLED=false, create a user-submissions row with status: pending in the admin, wait 5 s, then select count(*) from payload_jobs_log where created_at > now() - interval '1 minute' returns 0.

Notes for reviewer

The ticket's open question is now answerable with numbers. It chose the flag over scrubbing secrets from the copy, and kept that choice here. The review enumerated what the flag cannot reach, which is the evidence that was missing: magicLinks.ts:152/:166 mails a real manager a sign-in link, invitations.ts:288 mails on a manager save, and validateMailingList.ts:79 GETs the real provider with the production key — all request paths, none of them a job. Scrubbing is one statement at a seam the script already has (UPDATE clients SET mailing_list_api_key = NULL beside the existing TRUNCATE), and it would travel with the database rather than with a process env. I did not do it: the ticket decided against it explicitly and marked it for you.

Adopted from the adversarial review, in 48cb0b6: ServerEnvSchema's docblock had drifted onto the shared pauseFlag declaration, leaving the schema undocumented.

Dismissed findings, with reasons:

  • Share the two-token flag parse between server.ts and the bash script via a dependency-free .mjs both import. A shim in the env graph costs more than the duplication, and the script's comment names the original.
  • Revert server-env.spec.ts to a flat it.each now that one pauseFlag schema is under test. Kept the describe.each: it pins each field's semantics, so giving one flag its own transform later cannot pass silently.
  • Consolidate the three copies of the minimal-required-env test fixture into tests/utils/. Two predate this branch; consolidating means editing two specs this ticket does not touch.
  • Replace the predicate module with a direct serverEnv read at both sites, and rename src/lib/jobs/ so it does not read as a job's. Kept both: server.ts:97 instructs readers to take the flag only through jobsMayAutoRun(), so two raw reads reopen the split feat(scripts): work locally on a safe copy of production data #876 was filed for, and src/lib/<domain>/ mirroring an owner folder is the established shape (src/lib/clients/, src/lib/submissions/).
Detail

Why the kick was the gap. shouldAutoRun is checked per cron tick, but runScreeningQueueAfterCommit called payload.jobs.run({ queue: 'screening' }) directly with only a NODE_ENV === 'test' guard. It fires from enqueueSubmissionScreening on any pending create — the default status — and again from ScreenSubmissions to deliver. The NODE_ENV=test suppression stayed where it is: it is about racing a spec's assertions, not jobs policy.

The spec was proven non-vacuous in both directions. With the gate removed, the three "off" rows failed; with the predicate forced to false, the two "on" rows failed. The table is deliberately two rows now — the flag's vocabulary (0, FALSE, padding) is the schema's and is pinned in server-env.spec.ts. NODE_ENV is development in the fixture, or the other guard would mask the flag entirely and both rows would pass for the wrong reason.

Script verification. railway is absent in the routine environment, so a stub stood in for it and a throwaway database stood in for production, seeded with payload_jobs, payload_jobs_log and a content table. Confirmed: content copied, both job tables truncated, no leftover _incoming database, --force refused with the flag on and with it unset, the gate passed with it off, and the target untouched in every refusal. A staging database held open by another session now reports is being accessed by other users and stops, where before 2>/dev/null || true swallowed it and createdb failed with a worse message.

Flag resolution duplicates the schema's two-token test in bash, because the script cannot import TypeScript and reading server.ts would validate every unrelated variable as a side effect. It comes out of the existing DATABASE_URL parse, so the value reported and the value enforced cannot differ.

No migration. The change adds no field and no collection.

Fixture pre-mortem. tests/unit/screening-queue-kick.spec.ts's baseEnv assumes ServerEnvSchema's required set is PAYLOAD_SECRET, DATABASE_URL, WEMEDITATE_WEB_URL, SAHAJATLAS_URL. Verified against src/lib/env/server.ts and against tests/unit/server-env.spec.ts's own requiredEnv, which matches.

Security review ran (the diff touches src/payload.config.ts, which matches securityReview.triggerPattern) and returned no finding above the confidence threshold. It traced the ALTER DATABASE identifier interpolation, the production URI on pg_dump's argv, the dump file's umask 077 + mktemp -d + EXIT trap, and the local-target case guard, and dropped each with a stated reason.

Review lenses: /simplify (reuse, simplification, efficiency, altitude) plus /security-review. pr-review-toolkit is not installed in a routine. comment-lint clean over 6 changed files.

Worth a follow-up, not done here: the repo guards storage at the delete boundary and derives the condition from the deployment (isStorageIsolationActive()), rather than asking anyone to set anything. Email has no equivalent, and a flag on job autorun cannot reach the three request paths above even in principle. The general change is a third reason in the existing transport branch at payload.config.ts:258-264, covering all 14 sendEmail callers at one point. Out of scope here, and SMTP_URL unset already disables those sends loudly.

Closes #876

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

🤖 Generated with Claude Code

https://claude.ai/code/session_01FVSr4kigMtwDmRn1yh4YWR

antontcymbal and others added 6 commits October 2, 2026 15:37
…o pause jobs on the copy

Replace the local dev database with a read-only pg_dump of production. Dry run
by default, --force to replace. Refuses a non-local target, restores beside the
old database and swaps only on success, empties the copied job queue, and
deletes the dump on exit.

JOBS_AUTORUN_ENABLED gates jobs.autoRun through shouldAutoRun, so a local
server on a prod copy does not run the scheduled queues against real people.
On by default, parsed like EVENT_VERIFICATION_ENABLED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shouldAutoRun gated the cron ticks only. runScreeningQueueAfterCommit called
payload.jobs.run directly, guarded by nothing but NODE_ENV, so a `pending`
submission created on a copy of production still screened and delivered within
two seconds — real Mailchimp, Brevo or Klaviyo calls with the plain-text key
copied from prod, plus registrant and manager mail.

Both sites now read one predicate, jobsMayAutoRun, so the flag cannot stop one
and miss the other. The NODE_ENV=test suppression stays where it is: it is
about racing a spec's assertions, not about jobs policy.

With the flag off there is no safety net either, which is the intended
behaviour and not a regression — the rows wait for the flag to come back on.

Refs #876

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

The script copied production without ever checking the one flag that keeps the
copy's jobs away from real people's mailing lists. Its default is on, so the
safe configuration was the one nobody was holding.

--force now exits non-zero before production is read, naming the flag and
where to set it. The dry run reports the resolved value, so checking first is
worth something. Resolution shares the existing DATABASE_URL parse, so the
value reported and the value enforced cannot differ.

The two-token test duplicates the transform in src/lib/env/server.ts because
the script cannot import TypeScript, and reading that module would validate
every unrelated variable as a side effect. The comment names the original.

Refs #876

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

pnpm db:refresh-from-prod makes both claims false locally, and each was the
only statement of the reason something was safe.

docs/rules/email.md said Mailpit holds only fixtures and preview traffic. A
local SMTP_URL pointing at the shared Railway Mailpit now puts real people's
mail behind a login several people hold, for 7 days. The claim about previews
and production stays, since both are still true; the third sender is named,
and so is the configuration that is the only guard.

docs/rules/storage.md's preview paragraph is cited elsewhere as the reason a
delete is safe. For a local prod copy it is not the reason:
isStorageIsolationActive() is !isProductionDeployment(), true off Railway, so
the delete guard is what holds. Said next to the original rather than inside
it, so the preview claim keeps its one home.

The README section now carries the three things that reach production from a
developer's machine with nothing in code to stop them — SMTP_URL,
purgeCloudflareCache's two variables, and railway run — plus the backlog that
waits for the flag to come back on.

Refs #876

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
Review pass over the branch. No behaviour change except where noted.

The two pause flags had the same zod transform written out twice, with a
comment asserting the sameness instead of the code. They share a `pauseFlag`
schema now, so the bash mirror in the refresh script has one definition to
mirror rather than two that could drift.

The script derived the `_incoming` suffix in node and again in bash, which was
the only real drift risk in the five-field handoff. Node emits the name.

dropdb's inline `2>/dev/null || true` hid every failure, not just the missing
database `--if-exists` already handles, and moved the complaint to createdb
where it reads worse. Behaviour change: a dropdb failure now stops the script
and says why. Notices are quietened via client_min_messages rather than
redirected, so an error keeps its message. The trap's copy is untouched —
a trap must not mask the real exit code.

Verified against a stand-in production database: the swap copies content,
empties the job queue, leaves no staging database, refuses --force with the
flag on, and reports a held-open staging database instead of swallowing it.

Comment and spec trims: the predicate's docblock said in thirteen lines what
the name plus #876 carries, and the kick spec's table re-tested flag
vocabulary that server-env.spec.ts owns.

Refs #876

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
The flag was documented as though it were the whole guard. It is not, and a
developer following a job docblock on a copy of production would find out the
hard way.

The README's prod-copy section now lists the paths it cannot reach: a run the
operator asks for (pnpm payload jobs:run, /api/payload-jobs/run — four job
docblocks suggest that exact command), and saving a clients document, which
validates its mailing-list key against the real provider. SMTP_URL's bullet
keeps the rule and hands the detail to docs/rules/email.md, which owns it.

Two surfaces the flag belonged on and was missing from: DEPLOYMENT.md's
environment table, beside EVENT_VERIFICATION_ENABLED, and the Scheduled Jobs
section of docs/architecture.md, where the runs-not-scheduling distinction is
what explains the backlog.

The storage.md paragraph is cut back to the one sentence the neighbouring rule
does not already carry — that rule says to cite it rather than restate it.

Refs #876

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

railway-app Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated
SahajCloud ❌ Build Failed (View Logs) Web Oct 10, 2026 at 1:59 am UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 2, 2026
@sydevs-bot

sydevs-bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 2

recent dispatches
  • 05:16Z fix-ci · attempt 1 · session · done
  • 05:16Z fix-ci · attempt 1 · session
  • 22:57Z resolve-conflicts · attempt 1 · session · done
  • 22:57Z resolve-conflicts · attempt 1 · session
  • 23:31Z fix-ci · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

Scope matches the ticket — four items remained, four done.

The parked decision is still the one that matters. This guard is a process env var, so it protects the process while the copy stays faithful. The body counts three request paths it cannot reach (magicLinks.ts:152, invitations.ts:288, validateMailingList.ts:79). The scrub the ticket asked about is one statement beside the existing TRUNCATE, and travels with the database rather than a shell. Yours to settle.

The gate is complete for runs this process starts. payload.jobs.run has one call site, and shouldAutoRun covers every autoRun entry, the cron loginPlugin appends included.

Findings

  • consider — src/lib/jobs/autoRun.ts:11: does the module need to exist?
  • consider — src/lib/env/server.ts:34: the schema's docblock now documents pauseFlag.

What was checked

Read: screeningQueue.ts, autoRun.ts, server.ts, the script. Grepped every jobs.run / autoRun site on the branch. No contract surface in the diff.

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


Generated by Claude Code

Comment thread src/lib/jobs/autoRun.ts
* mailing list on a copy of production (#876). A run the operator asked for —
* `GET /api/payload-jobs/run`, admin-only — is unaffected.
*/
export const jobsMayAutoRun = (): boolean => serverEnv.JOBS_AUTORUN_ENABLED

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Does this module need to exist? It is one read of one serverEnv field, and that field is already the single predicate the ticket asked for — shouldAutoRun: () => serverEnv.JOBS_AUTORUN_ENABLED in the config and the same read in the kick is the same gate, one file fewer.

The name is the other half. src/CLAUDE.md reserves src/jobs/ for one folder per job, so src/lib/jobs/ reads as shared code for those jobs — and this is runner policy, not a job's.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping both, with reasons.

The module. server.ts:97 tells readers to take the flag through jobsMayAutoRun(), never directly, so the cron and the kick cannot be gated separately. Two raw reads reopen the split #876 was filed for.

The name. src/lib/<domain>/ mirroring an owner folder is this repo's pattern: src/lib/clients/ beside src/collections/Clients/, src/lib/submissions/ beside UserSubmissions.

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


Generated by Claude Code

Comment thread src/lib/env/server.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 2, 2026
The shared `pauseFlag` schema landed between `ServerEnvSchema`'s docblock and
its declaration, so the block documenting the schema attached to the flag
transform instead, and the schema was left with none. Declaring `pauseFlag`
above the block restores both.

Comment placement only.

Refs #876

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FVSr4kigMtwDmRn1yh4YWR
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-879 October 2, 2026 15:05 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

One adopted, one rebutted. Pushed 48cb0b6.

  • Adopted — the schema's docblock. pauseFlag is declared above it now, so the block documents ServerEnvSchema again. Placement only; thread resolved.
  • Rebutted — the src/lib/jobs/autoRun.ts module. server.ts:97 instructs readers to take the flag only through jobsMayAutoRun(), and src/lib/<domain>/ beside an owner folder is this repo's shape. Left open for you to settle.

Nothing asked. Lean gate green: lint, both typechecks, 172 unit files / 2285 tests.

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 2, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review October 2, 2026 15:18
@sydevs-bot
sydevs-bot requested a review from Ardnived October 2, 2026 15:18
@sydevs-bot
sydevs-bot enabled auto-merge October 2, 2026 15:18
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-879 October 7, 2026 23:21 Destroyed
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Oct 7, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The red check is the Railway preview build, and it is not this PR's. Nothing pushed.

f929af3 is clean here: pnpm build emitted the standalone server, lint, both typechecks, and 173 unit files / 2288 tests all passed.

The diff changes no build input — no dependency, no next.config.mjs, no railway.toml. JOBS_AUTORUN_ENABLED is optional and defaults to on, so build-time env validation cannot fail on it. pnpm install --frozen-lockfile succeeds, so your main merge left no lockfile drift.

Six previews rebuilt at once when main moved. The three earliest failed, the three later ones succeeded:

Failed 23:23–23:24 Succeeded 23:24–23:27
this PR, #880, #885 #890, #892, #882

I cannot read the Railway build log — no Railway CLI and no token in a routine environment — and I cannot re-run a Railway build. Redeploy this preview from Railway; its log is the only evidence left if it fails again.

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


Generated by Claude Code

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Still the Railway preview, and CI has now confirmed it. Nothing pushed.

Three facts my last comment could not yet state:

Redeploy this preview from Railway. Its log stays the only evidence left, and a routine has neither the CLI nor a token.

Filed sydevs/claude-workflow#164: a deploy commit status bypasses ci.ignoreCheckNames, so this failure spent two of three fix-ci passes on a green commit.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting labels Oct 7, 2026
…fresh-from-prod

Two conflicts, both where #878 rewrote what this branch extends.

`src/payload.config.ts`: #878 moved the `autoRun` array into
`src/jobs/queues.ts` as `JOB_AUTO_RUN`, adding the `monthly` entry. This
branch had added `shouldAutoRun: jobsMayAutoRun` beside the inline array.
Kept both — the flag predicate stays, and the list comes from `queues.ts`,
whose entries already include the `screening` safety net this branch's
version carried.

`docs/architecture.md`: both sides wrote into the Scheduled Jobs preamble.
Kept this branch's `JOBS_AUTORUN_ENABLED` paragraph and #878's dead-schedule
warning, plus #878's rewritten `CleanupOrphanedMedia` and new
`SyncLectureMetadata` bullets.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AaQi3J1bGMtnwrWiNgpXZD
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-879 October 9, 2026 23:04 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main in. Both conflicts sat where #878 rewrote what this branch extends, and both kept the two behaviours.

Gate green on the merge: lint, both typechecks, 177 unit files / 2313 tests — job-schedules and screening-queue-kick among them — plus screen-submissions and user-submissions-create (49).

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 9, 2026
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-879 October 10, 2026 01:58 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Not required, so not blocking: sahajcloud - SahajCloud failed. A preview link in the body may not open until it passes.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 13, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The preview build died inside Turbopack, not in this diff. Nothing pushed.

Both of this branch's failures crash at the same step, right after ✓ Compiled successfully and Running TypeScript ... — a bad read of Turbopack's memory-mapped persistent cache:

  • 3c89d1a ([log](https://railway.com/project/bdff2c72-5af2-4da3-9e2c-913f5e9d1b0f/service/1edee955-6c1f-4d8e-9cef-41737f981187?id=963aac12-f6c4-4b6e-bc9a-9feac615c336&environmentId=a35269c7-37ba-4d31-af10-711c611c2056)) — panicked at turbo-persistence/src/meta_file.rs:318: AMQF data out of bounds.
  • f929af3, Oct 7 — Bus error, exit 135.

Evidence it is not the change:

  • pnpm build on 3c89d1a exits 0 here, and emits .next/standalone.
  • These two are the only failures in the project's last 30 deployments. main deployed green at 05:16Z today.
  • The diff touches no build input.

Redeploy this preview from Railway. A routine may neither re-run a Railway build nor clear its cache.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 13, 2026
@Ardnived Ardnived closed this Oct 13, 2026
auto-merge was automatically disabled October 13, 2026 13:32

Pull request was closed

@Ardnived
Ardnived deleted the claude/feat-876-db-refresh-from-prod branch October 13, 2026 13:32
@sydevs-bot sydevs-bot moved this from Revising to Done in SYDevelopers Technical Roadmap Oct 13, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-879 — 3c89d1a4 Deployed Oct 10, 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.

feat(scripts): work locally on a safe copy of production data

4 participants