Skip to content

payload run <script> intermittently exits 0 without ever evaluating the target module — no error, no output, ~15-20% of invocations under back-to-back CLI use #17757

Closed

Description

@holdeeno

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 (or
payload 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"
done

Trigger conditions, as measured:

  • Invocations must be back-to-back with effectively no delay (a for loop with no
    sleep). 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 !== production and typescript.autoGenerate not 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 to
dist/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:

  1. Every getPayload() call in a dev-mode script silently launches a second, full CLI
    bootstrap (its own bin.js → tsImport() → dist/bin/index.js → generateTypes()
    sequence) as a detached side effect, with no log line indicating it happened (log: false).
  2. Because it's unawaited, a script that calls process.exit() itself right after
    getPayload() finishes its own work (a documented, intentional pattern for scripts
    that hold a DB pool open — see payloadcms/payload#13744 / #13564 for the
    generate:types analogue of the same pool-holds-loop-open problem) does not
    wait for this child. It becomes an orphan.
  3. We measured 3–5 such orphans alive concurrently during a 40-iteration back-to-back
    payload run loop.
  4. Separately, payloadcms/payload#15553 documents that generate:types itself can hang
    indefinitely (never calling process.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's tsImport()/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:types fails with ERR_MODULE_NOT_FOUND on extensionless collection imports — tsx tsImport() scoped-registration gap #16734 independently documents that tsImport()'s "scoped"
    registration (exactly what bin.js uses, 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-orphaned
    await 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 (loading dist/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 .ts file
    requiring tsx's transform — ever fails to settle.
  • Not concurrency-only: our primary reproduction recipe is strictly sequential
    back-to-back invocations (a for loop with no &/parallelism), not concurrent
    processes. (A related but distinct symptom — concurrent payload migrate invocations
    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:

  1. Any insight into what could cause a module.register()-based ESM loader hook
    (installed via tsx/esm/api's tsImport(), as bin.js does) to leave a dynamic
    import() promise permanently unsettled with no error surfaced anywhere.
  2. Confirmation of / more context on whether payload generate:types fails with ERR_MODULE_NOT_FOUND on extensionless collection imports — tsx tsImport() scoped-registration gap #16734's "scoped
    registration gap" for tsImport() could plausibly manifest this way for a second,
    nested import() call issued from inside the already-tsImport()-loaded module,
    rather than from a config-file-relative extensionless import as in that report.
  3. Whether the unawaited generate:types child spawned from getPayload()'s init()
    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

  1. AlessioGr commented on Aug 11, 2026

    @AlessioGr
    Member

    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. Having prismjs in 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

    • a newer Node.js version. Maybe node fixed this in a newer version
    • removing stuff from the code you're trying to run, until you're able to narrow down the dependency that's causing this

    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:

  2. HyadeNN commented on Aug 31, 2026

    @HyadeNN

    Independent reproduction, plus a measurement that rules out the prismjs hypothesis 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 migrate

    This report is mostly about payload run; we see the identical signature on payload migrate as well. Captured 2026-08-30 in CI (from-zero migrate against a fresh Postgres service):

    • healthy run: Reading migration files from … followed by 42 Migrating: / Migrated: lines, ~23s
    • silent run: zero lines, exit 0, ~5s — not even the WARN: No email adapter provided that every healthy run prints before anything else

    That WARN is emitted during config load, so its absence puts the stall upstream of the config module finishing evaluation. NODE_OPTIONS=--trace-exit printed nothing, matching your finding that process.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.

    prismjs is in our graph but is never loaded — and we still reproduce

    Re: the suggestion that prismjs in 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:

    @payloadcms/richtext-lexical 3.84.1
    └─ @lexical/react 0.41.0
       └─ @lexical/markdown 0.41.0
          └─ @lexical/code 0.41.0
             └─ prismjs 1.30.0
    

    richtext-lexical no longer depends on @lexical/markdown directly (so #9382 holds on that edge), but @lexical/react pulls it back in transitively.

    However — being in the graph is not the same as being loaded. We instrumented an ESM resolve hook (module.register) and imported our full Payload config (44 collections, 25 globals, resolved successfully):

    specifier times resolved
    @lexical/react 4
    @lexical/markdown 18
    @lexical/code 0
    prismjs 0

    Neither @lexical/code nor prismjs is ever resolved in the config import chain, yet we still hit the silent exit. So for our case the prismjs mechanism 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 payload bin and onto the tsx CLI directly — pnpm exec tsx <file> — including a small migrate.ts that calls the exported migrateCLI so the migration logic itself is unchanged and only the module loader differs. Motivation was #16734: bin.js uses tsImport()'s scoped registration, while the tsx CLI registers globally.

    One caveat for anyone else trying this: bin()'s unconditional process.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. Explicit process.exit() at each entry point fixed it.

    Related note: that same unconditional exit(0) also overrides a process.exitCode set by the user script, so a script that signals failure via process.exitCode = 1 is observed as exit 0 by CI. We had worked around it with an explicit process.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.

  3. rjohnsonbade-corrivium commented on Sep 17, 2026

    @rjohnsonbade-corrivium

    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:

    • Running migrate
    • Running a db seed script which uses the payload local api to seed a bunch of data

    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?

  4. davidbalzan commented on Sep 24, 2026

    @davidbalzan

    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

    • payload: 3.88.0
    • tsx (nested dep of payload): 4.23.13
    • Node.js: v22.22.2
    • macOS, 14 cores

    Same signature, but on generate:types, and at the CONFIG import

    This report covers payload run and payload migrate. We see the identical signature on
    payload generate:types — exit 0, no output file, no error.

    The divergence point is a different await import() from the one traced above. In
    dist/bin/index.js:

    const configPath = findConfig();
    const configPromise = await import(pathToFileURL(configPath).toString());  // <- never settles
    let config = await configPromise;

    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.log at
    module scope) prints on every silent run, and then the import promise still never settles.

    So on a failing run we observe, in order:

    1. the config module's top-level side effect runs (proves evaluation started and reached module scope)
    2. nothing else — the first statement of the next stage never logs, so the awaited value never arrived
    3. beforeExit fires (see below)
    4. exit 0

    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: beforeExit

    Rather than file-based tracing, beforeExit alone discriminates cleanly, because it fires only
    when the loop empties with no explicit process.exit:

    let stage = 'start'
    process.on('beforeExit', (code) => console.log(`BEFOREEXIT stage=${stage} code=${code}`))
    process.on('exit',       (code) => console.log(`EXIT stage=${stage} code=${code}`))
    process.on('unhandledRejection', (e) => console.log(`UNHANDLED stage=${stage} err=${e?.message}`))
    
    const start = async () => {
      stage = 'pre-tsx'
      const tsImport = (await import('tsx/esm/api')).tsImport
      const { bin } = await tsImport('./dist/bin/index.js', url)   // resolves fine, always
      stage = 'bin-module-loaded'
      await bin()
      stage = 'bin-resolved'
    }
    void start()
    • healthy run: EXIT stage=bin-module-loaded, no BEFOREEXIT (the CLI's own process.exit(0)
      skips the hook)
    • silent run: BEFOREEXIT stage=bin-module-loaded code=0

    Across 191 healthy runs beforeExit fired zero times, so it is a clean discriminator rather
    than a heuristic. No unhandledRejection ever fired.

    --use-swc does not fix it

    Worth recording as a measurement, since it supports the comment above that this is not
    tsx-specific. Same harness, same width, same box:

    loader runs silent
    default (tsx) 192 0
    --use-swc 192 1

    register('@swc-node/register/esm', ...) succeeded in all 192 swc runs (no fallback message). So
    swapping 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 prismjs hypothesis

    [email protected] is in our graph, and the whole chain is inside Payload's own packages:

    @payloadcms/[email protected] -> @lexical/react -> @lexical/markdown -> @lexical/code -> [email protected]
    

    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 prismjs is the trigger, that
    seems 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 N
    concurrent cold CLI invocations with N > cores.

  5. Firzus commented on Sep 25, 2026

    @Firzus

    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 migrate command 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:

    • Exit diagnostics only: 6/100 silent exits.
    • Async resolve/load tracing: 3/50 silent exits. All three ended after 8,222 trace records, with final resolutions of lexical/@lexical packages. Every observed load-start had a load-end. This does not rule out evaluation waiting on unresolved top-level awaits.
    • Replacing the tsx branch's void start() in payload/bin.js with await 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.
    • Node 24.21.0, unmodified bin.js: 2/100 failures with exit diagnostics, then 3/100 without them in a separate batch.
    • Node 24.21.0, removing the assignment that disables module.registerHooks: 7/100 code-0 failures. We verified the patch, not which hook implementation was actually used at runtime; this is not proof that synchronous hooks were exercised.
    • --use-swc was not an interpretable comparison in our project: it failed to resolve the extensionless next/cache import before migration. We exclude it from failure-rate comparisons.

    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:

    1. A first dependency logs "graph evaluation started".
    2. The wrapper imports the normal config, then logs "graph evaluated".
    3. It awaits the exported buildConfig promise, then logs "config resolved".

    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.

  6. added a commit that references this issue on Sep 30, 2026
    1fcb220
  7. added a commit that references this issue on Oct 1, 2026
    96725e3
  8. github-actions commented on Oct 7, 2026

    @github-actions
    Contributor

    🚀 This is included in version v4.0.0-canary.38

  9. github-actions commented on Oct 15, 2026

    @github-actions
    Contributor

    🚀 This is included in version v3.91.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions