Repository navigation
Description
Versions
- payload: 3.87.1
- @payloadcms/db-postgres: 3.87.1
- tsx (nested dependency of
payload): 4.22.4 - Node.js: v22.23.2
- OS: Linux (Ubuntu 24.04-based), x86_64, 8 cores
Summary
payload run <path-to-ts-file> sometimes exits with code 0 having never evaluated the
target file at all — not even its first top-level statement. No error is printed on
stdout or stderr. This happens intermittently (measured 12/70 ≈ 17% locally, matches
independent reports of 15–20% and 2/10 on GitHub Actions) when payload run (orpayload migrate) is invoked repeatedly, back to back, with no delay between
invocations.
We instrumented the CLI itself (not the target script) with file-based tracing
(fs.appendFileSync, chosen specifically so the trace can't be lost to whatever might
be swallowing stdout/stderr) and captured the exact divergence point across 5 silent
occurrences. All 5 show the identical shape:
bin.js: tsImport('./dist/bin/index.js', url) -> resolves fine, always
dist/bin/index.js runBinScript(), script==='run' branch:
scriptPath resolved -> logged, always
absoluteScriptPath resolved -> logged, always
await import(pathToFileURL(absoluteScriptPath).toString())
-> called (logged immediately before)
-> NEVER settles: no success continuation,
no catch block, no finally block
[1.8s – 17.1s of nothing]
process exits, code 0
No uncaughtException, no unhandledRejection, no thrown error anywhere in the
process (verified with global handlers wired at the very top of bin.js, before
anything else runs). The promise from that single import() call simply never settles,
and the process exits cleanly once nothing else is keeping the event loop alive.
Minimal repro
We do not yet have a repro reduced to a bare Payload project (that's the natural next
step for whoever picks this up upstream — our repro is on a ~30-collection production
config). What we have, reduced as far as time allowed:
# any Payload 3.87.1 project with a postgres/mongo adapter
set -a; source .env.local; set +a
for i in $(seq 1 40); do
npm run <a script that runs `payload run some-file.ts`> > /tmp/o 2>/tmp/e
c=$?
# some-file.ts's first top-level statement should write a marker to stderr,
# flushed, before anything else — including before any guard/throw logic
grep -q 'MARKER' /tmp/e || echo "run $i: SILENT, exit=$c, stdout=$(wc -c </tmp/o)B stderr=$(wc -c </tmp/e)B"
doneTrigger conditions, as measured:
- Invocations must be back-to-back with effectively no delay (a
forloop with nosleep). We have not tested whether a small delay between invocations
suppresses it (an earlier, less careful local harness that inserted schema-teardown
time between runs saw 0/27 — see caveats below on why we don't treat that as
conclusive). NODE_ENV !== productionandtypescript.autoGeneratenot explicitly disabled (see
next section for why this matters) — though we have not isolated whether autoGenerate
itself is required to reproduce, only that it is present and firing in every run we
captured.
A concerning side effect we found while instrumenting, possibly related
Not filed as the main bug, but found investigating this one and worth flagging in the
same report because it may be a contributing factor:
getPayload()'s init() (packages/payload/src/index.ts, compiled todist/index.js around line 359 in 3.87.1) does this on every non-production init
unless config.typescript.autoGenerate === false:
if (process.env.NODE_ENV !== 'production' && this.config.typescript.autoGenerate !== false) {
void this.bin({ args: ['generate:types'], log: false });
}this.bin() spawns node <path-to-payload>/bin.js generate:types as a **real,****
**unawaited child process (spawn(..., { stdio: 'ignore' }), wrapped in void). This
means:
- Every
getPayload()call in a dev-mode script silently launches a second, full CLI
bootstrap (its ownbin.js→tsImport()→dist/bin/index.js→generateTypes()
sequence) as a detached side effect, with no log line indicating it happened (log: false). - Because it's unawaited, a script that calls
process.exit()itself right aftergetPayload()finishes its own work (a documented, intentional pattern for scripts
that hold a DB pool open — see payloadcms/payload#13744 / #13564 for thegenerate:typesanalogue of the same pool-holds-loop-open problem) does not
wait for this child. It becomes an orphan. - We measured 3–5 such orphans alive concurrently during a 40-iteration back-to-back
payload runloop. - Separately, payloadcms/payload#15553 documents that
generate:typesitself can hang
indefinitely (never callingprocess.exit()) under certain plugin/config
combinations, which would make these orphans long-lived rather than self-clearing.
We did not confirm #15553's specific hang in our own environment (our orphans did
eventually exit), but the mechanism — this exact fire-and-forget child — is the same
one.
We are not claiming this side effect is the direct cause of the silent import().
We could not prove causation in the time available — see FINDINGS.md's explicit
measured-vs-inferred breakdown, in particular the note that the "3 vs 4 orphans"
correlation we observed alongside every silent run is fully explained by simple
bookkeeping (a run that never reaches getPayload() never spawns its own orphan) and
is not independent evidence of resource contention. We flag it because:
- it's a second, independently-surprising behavior discovered on the same call path
(bin.js'stsImport()/loader-hook machinery) that this bug lives on, - it multiplies the number of concurrent tsx-loader-hook-using processes on the machine
in exactly the scenario (back-to-back CLI invocations) that triggers the main bug,
and payload generate:typesfails with ERR_MODULE_NOT_FOUND on extensionless collection imports — tsxtsImport()scoped-registration gap #16734 independently documents thattsImport()'s "scoped"
registration (exactly whatbin.jsuses, at the exact two call sites instrumented
here) has a known gap vs. tsx's normal global registration for propagating resolution
to nested/dynamic imports — which is the same shape as our second, silently-orphanedawait import()call.
If maintainers confirm no connection, this half of the report can be split off as its
own issue: "getPayload() silently spawns an unawaited generate:types child on every
dev-mode init; should be logged and/or awaited (or at minimum, made unref()-safe and
loud)."
What we ruled out
- Not a crash: zero uncaught exceptions, zero unhandled rejections, across 40 traced
invocations (parent processes and orphan children). - Not stdout/stderr buffering hiding a later crash: the gap begins at the
import()
call itself, before the target module can have produced any output on any stream. - Not specific to our seed script's logic or guards: the target module's very first
top-level statement — placed above all guard/throw logic specifically to test this —
never runs. The bug is upstream of anything in the target file. - Not unique to loading any module through the tsx-hooked realm: the CLI's own first
tsImport()call (loadingdist/bin/index.js, plain compiled JS, no transform
needed) always eventually resolves in every run we captured, healthy or silent, even
under multi-second delays from machine load. Only the second import — of a.tsfile
requiring tsx's transform — ever fails to settle. - Not concurrency-only: our primary reproduction recipe is strictly sequential
back-to-back invocations (aforloop with no&/parallelism), not concurrent
processes. (A related but distinct symptom — concurrentpayload migrateinvocations
also silently no-oping — is reported separately on our internal tracker; we have not
established whether it shares this same mechanism.)
Caveat on our own earlier (non-)reproduction
We previously ran ~27 clean local iterations across three configurations before finally
reproducing this. What changed was inserting schema teardown (or not) between
iterations — teardown-between-runs iterations were clean; back-to-back, no-teardown
iterations reproduce at the stated rate. We have not established that teardown
itself is causal (as opposed to simply adding a delay, or changing what work happens
before the next payload run), and flag this explicitly so nobody over-reads it: at a
15–20% true rate, 12 clean serial runs individually has ~14% probability of happening by
chance alone.
Request
We'd appreciate:
- Any insight into what could cause a
module.register()-based ESM loader hook
(installed viatsx/esm/api'stsImport(), asbin.jsdoes) to leave a dynamicimport()promise permanently unsettled with no error surfaced anywhere. - Confirmation of / more context on whether
payload generate:typesfails with ERR_MODULE_NOT_FOUND on extensionless collection imports — tsxtsImport()scoped-registration gap #16734's "scoped
registration gap" fortsImport()could plausibly manifest this way for a second,
nestedimport()call issued from inside the already-tsImport()-loaded module,
rather than from a config-file-relative extensionless import as in that report. - Whether the unawaited
generate:typeschild spawned fromgetPayload()'sinit()
is intentional, and whether it should be logged, awaited, or otherwise made safe for
back-to-back invocation.
Happy to provide the full instrumented node_modules/payload diff and the raw trace
log (1395 lines, 40 runs) on request.
Activity
AlessioGr commentedon Aug 11, 2026
There may be something in the code you're trying to run that causes node to sometimes fail to import it. We've had this issue in the past because lexical shipped with
prismjs. Havingprismjsin your dependency graph will sometimes cause node to stop evaluating dynamic imports and exit without warning. This will happen with plain node, and has nothing to do with tsx or swc - they just cause a slowdown that makes this issue appear more often.This is also why it's very difficult to reproduce. The less code you're trying to run, the faster it gets, the lower the chance of reproducing it.
Try
If it's something in your code that's causing this, there may be nothing we can do from our side. If it's something within payload, we can remove the problematic dependency.
See:
HyadeNN commentedon Aug 31, 2026
Independent reproduction, plus a measurement that rules out the
prismjshypothesis for our case.Environment: payload 3.84.1, @payloadcms/db-postgres 3.84.1, tsx 4.21.0 (nested dep of payload), Node 22.18, Linux. Both CI (GitHub-hosted runners) and production (Docker,
node:22-alpine).Same shape, and it also hits
payload migrateThis report is mostly about
payload run; we see the identical signature onpayload migrateas well. Captured 2026-08-30 in CI (from-zero migrate against a fresh Postgres service):Reading migration files from …followed by 42Migrating:/Migrated:lines, ~23sWARN: No email adapter providedthat every healthy run prints before anything elseThat
WARNis emitted during config load, so its absence puts the stall upstream of the config module finishing evaluation.NODE_OPTIONS=--trace-exitprinted nothing, matching your finding thatprocess.exit()is never called.Frequency in our environment is lower than yours: 1 in 40 consecutive CI runs (2.5%) measured over one sample, vs. the 15–20% reported here. Our invocations are not back-to-back — they're separated by other CI steps — which is consistent with your "back-to-back with no delay" trigger condition being an amplifier rather than a requirement.
prismjsis in our graph but is never loaded — and we still reproduceRe: the suggestion that
prismjsin the dependency graph causes Node to stop evaluating dynamic imports.[email protected]is in our graph, and the path is worth flagging because it routes around the fix in #9382:richtext-lexicalno longer depends on@lexical/markdowndirectly (so #9382 holds on that edge), but@lexical/reactpulls it back in transitively.However — being in the graph is not the same as being loaded. We instrumented an ESM
resolvehook (module.register) and imported our full Payload config (44 collections, 25 globals, resolved successfully):@lexical/react@lexical/markdown@lexical/codeprismjsNeither
@lexical/codenorprismjsis ever resolved in the config import chain, yet we still hit the silent exit. So for our case theprismjsmechanism appears ruled out — which may help narrow the search, since it leaves the loader-hook path as the remaining shape.(Caveat on our own numbers, in the spirit of your caveat section: this is one 40-run sample at a ~2.5% rate, so it is not strong evidence about frequency changes over time — only about the failure existing and about what is not loaded.)
What we did
We moved every Payload CLI invocation off the
payloadbin and onto the tsx CLI directly —pnpm exec tsx <file>— including a smallmigrate.tsthat calls the exportedmigrateCLIso the migration logic itself is unchanged and only the module loader differs. Motivation was #16734:bin.jsusestsImport()'s scoped registration, while the tsx CLI registers globally.One caveat for anyone else trying this:
bin()'s unconditionalprocess.exit(0)is not only the thing that masks the failure — it is also what terminates scripts holding a Payload DB pool open. After the switch our seed completed all steps, printed its final line, then hung for 23.5 minutes until the job was cancelled;payload.destroy()on its own was not enough. Explicitprocess.exit()at each entry point fixed it.Related note: that same unconditional
exit(0)also overrides aprocess.exitCodeset by the user script, so a script that signals failure viaprocess.exitCode = 1is observed as exit 0 by CI. We had worked around it with an explicitprocess.exit(1); after moving off the wrapper the exit code propagates normally.Happy to run any instrumentation on our side if it would help isolate this further.
rjohnsonbade-corrivium commentedon Sep 17, 2026
We have also experienced this issue, with a high level of intermittent failures during our db setup phased running in ci, prior to running tests. This consists of:
Either of these can fail silently, and then cause the resulting tests to fail.
These failures appear to be happening more often now than previously.
This is eating up a lot of time an resources.
@HyadeNN , was your team able to reliable avoid the issue?
davidbalzan commentedon Sep 24, 2026
Another independent reproduction, on newer versions, with three things that may narrow it: a
different call site, a different sub-shape, and a measurement that rules out the
transpiler.
Versions
Same signature, but on
generate:types, and at the CONFIG importThis report covers
payload runandpayload migrate. We see the identical signature onpayload generate:types— exit 0, no output file, no error.The divergence point is a different
await import()from the one traced above. Indist/bin/index.js:That is the import of the Payload config itself, not of a user script. It matters because the
advice above ("there may be something in the code you're trying to run") does not apply here —
there is no user script in this path. The module that fails to settle is the config.
The sub-shape differs, and this may be the useful part
The trace above reports the target file was never evaluated — "not even its first top-level
statement". Ours evaluates. A top-level side effect in the config graph (a
console.logatmodule scope) prints on every silent run, and then the import promise still never settles.
So on a failing run we observe, in order:
beforeExitfires (see below)That is evaluation-happened-but-promise-lost, which is not the same as never-evaluated. Both may be
one bug, but they are distinguishable observations and I have not seen the first one reported.
A lighter instrument:
beforeExitRather than file-based tracing,
beforeExitalone discriminates cleanly, because it fires onlywhen the loop empties with no explicit
process.exit:EXIT stage=bin-module-loaded, noBEFOREEXIT(the CLI's ownprocess.exit(0)skips the hook)
BEFOREEXIT stage=bin-module-loaded code=0Across 191 healthy runs
beforeExitfired zero times, so it is a clean discriminator ratherthan a heuristic. No
unhandledRejectionever fired.--use-swcdoes not fix itWorth recording as a measurement, since it supports the comment above that this is not
tsx-specific. Same harness, same width, same box:
--use-swcregister('@swc-node/register/esm', ...)succeeded in all 192 swc runs (no fallback message). Soswapping the transpiler did not remove it — consistent with the loader only changing the
timing, not the cause.
Trigger: CPU contention rather than back-to-back invocation
Our trigger is parallelism, not sequence: N concurrent cold invocations where N exceeds core
count. Strictly sequential runs have never reproduced it here (12/12 and 192/192 clean). Rate at
width 16 on 14 cores: ~1/256 (2 in 448) — and unstable: 1-in-64, then 0-in-192, at the same
width on the same box. On constrained CI runners we observe ≥3.3%, which fits contention being
the driver.
⚠ One caution for anyone sizing a validation run: at ~1/256 an arm of 192 runs comes back clean
47% of the time even unfixed, which is enough to make a before/after look like a fix. ~750 runs
per arm gets P(zero | unfixed) ≈ 0.05.
On the
prismjshypothesis[email protected]is in our graph, and the whole chain is inside Payload's own packages:So it is consistent with the hypothesis, but it is not something a user can remove — it arrives
with the official lexical richtext package on current 3.88.0. If
prismjsis the trigger, thatseems worth addressing in the dependency chain rather than in user code.
What we do not have
A repro reduced to a bare Payload project. Ours is a large config, same as the original report. If
it would help, say so and I can try to reduce it — the useful variables to hold seem to be: lexical
richtext present (for
prismjs), a TS config loaded through the transpiling loader, and Nconcurrent cold CLI invocations with N > cores.
Firzus commentedon Sep 25, 2026
Independent reproduction of the config-import failure on GitHub Actions: Payload 3.90.2, tsx 4.22.4, Node 22.23.2, ubuntu-latest, PostgreSQL 17.
Two separate batches of the unchanged
pnpm payload migratecommand each produced 8/100 exits with code 0 without reaching "Reading migration files". Each batch used 10 runners, each running 10 sequential attempts. Only the first attempt on each runner had an empty database; later attempts used the same database. One failure in the first batch was the first invocation on an empty database. The package script sets NODE_OPTIONS="--no-deprecation --conditions=react-server".Additional experiments:
void start()in payload/bin.js withawait start(): 5/100 failures, now code 13, printing "Detected unsettled top-level await" at bin.js:44. The concurrent unmodified control had 8/100 code-0 failures. This makes the failure visible but does not fix the underlying import.For the three traced failures, beforeExit fired with code 0 and getActiveResourcesInfo() returned ["PipeWrap"]. Unlike a normal explicit process.exit(), this shows natural event-loop exhaustion. The diagnostics preload is inherited by child processes, so successful attempts can contain multiple exit records; these should not be attributed to one PID.
A further 100-attempt batch used a wrapper config with three synchronous file markers:
All four failing attempts logged only marker 1. This narrows our case to config dependency-graph evaluation, before the wrapper body, not merely an unresolved buildConfig result. Several Lexical *.node.mjs modules in the loaded graph use top-level await to dynamically import their dev/prod implementation. That is an investigation lead only, not an established cause.
The repository and Actions artifacts are private, so these are aggregate observations, not a public minimal reproduction. No corrective change has been established. In particular, we cannot conclude that tsx worker liveness is the cause, or that different rates across these small batches represent an improvement.
fix: prevent silent CLI exits (#18398)
fix(richtext-lexical)!: upgrade lexical to 0.52.0 and tsx to 4.23.15 (p…
fix(throughline-payload): fail a Payload CLI run that exits 0 without…
github-actions commentedon Oct 7, 2026
🚀 This is included in version v4.0.0-canary.38
github-actions commentedon Oct 15, 2026
🚀 This is included in version v3.91.0