Skip to content

db-postgres / drizzle: commitTransaction resolves when the COMMIT fails, so a lost transaction looks like a success #18653

Open
ivan-fr/payload
#1

Description

@yousefamar

Describe the Bug

When Postgres refuses a COMMIT (a deferred constraint, a serialization failure, or the connection dropping during the commit), payload.db.commitTransaction(id) resolves normally. Nothing is thrown and nothing is logged. The rows are rolled back, but every caller continues as if they were saved: payload.create returns the document, hooks that run after the operation fire, and application code sends its mail or advances its cursor.

Why

packages/drizzle/src/transactions/beginTransaction.ts attaches a .catch() to the promise returned by this.drizzle.transaction(...):

const done = this.drizzle.transaction(async (tx) => { ... }, options).catch((err) => {
  // Connection failed before callback ran - reject instead of hanging forever
  transactionFailed(err)
})

That .catch() was added for a connection failure before the callback runs, but it also means done can never reject. resolve() returns done, and commitTransaction does:

try {
  await session.resolve()
} catch (_) {
  await session.reject()
}

so the try can never throw, and even if it could, the error would be swallowed by the empty catch. Once the callback has run, transactionFailed(err) is a no-op on an already settled promise, so the commit error goes nowhere.

Expected

commitTransaction rejects with the commit error, so payload.create and friends reject and callers can react.

Suggested fix

Keep the error when the transaction promise rejects after resolve() was called, and rethrow it:

let committing = false
let commitFailure: { error: unknown } | undefined
// ...
resolve = () => {
  committing = true
  res()
  return done.then(() => {
    if (commitFailure) throw commitFailure.error
  })
}
// ...
}, options).catch((err) => {
  transactionFailed(err)
  if (committing) commitFailure = { error: err ?? new Error('The transaction could not be committed') }
})

and in commitTransaction:

try {
  await session.resolve()
} catch (err) {
  await session.reject()
  throw err
}

We run this as a local patch with a regression test (the reproduction below, plus a successful commit and a rollback to show those are unchanged).

Possibly related: #17294 (an update that is rolled back while the request still answers 200).

Link to the code that reproduces this issue

https://github.com/yousefamar/payload-commit-failure-repro

Reproduction Steps

The linked repository is one script, with no Payload project and no collections. It opens a transaction through payload.db and commits it.

  1. Start a Postgres: docker run -d --rm --name payload-repro-pg -e POSTGRES_PASSWORD=repro -p 127.0.0.1:55432:5432 postgres:17
  2. git clone https://github.com/yousefamar/payload-commit-failure-repro && cd payload-commit-failure-repro && npm install
  3. node repro.mjs (or node repro.mjs <connection string> for another database)

The part that matters:

await payload.db.drizzle.execute(sql`create table probe (n int, constraint probe_u unique (n) deferrable initially deferred)`)
const id = await payload.db.beginTransaction()
const tx = payload.db.sessions[id].db
await tx.execute(sql`insert into probe (n) values (1)`)
await tx.execute(sql`insert into probe (n) values (1)`)
await payload.db.commitTransaction(id) // resolves; expected: rejects with 23505
// select count(*) from probe  ->  0

Actual output:

control, valid commit: resolved, rows = 1
refused COMMIT: commitTransaction RESOLVED with no error (expected: rejects with 23505)
rows in probe afterwards = 0 (0 = the transaction was rolled back)
unhandled rejections: 0

Expected: the second commitTransaction rejects with the commit error.

Which area(s) are affected?

db: postgres

Environment Info

payload: 3.90.2
@payloadcms/db-postgres: 3.90.2
@payloadcms/drizzle: 3.90.2 (latest on npm; the same code is on main today, and in 3.87.0)
drizzle-orm: 0.45.2
pg: 8.20.0
Node.js: 22.20.0
Next.js: not involved (the reproduction is a Local API script)
Postgres: 17.11 (stock postgres:17 container); also seen on Postgres 17 hosted by Neon

Activity

  1. added
    db: postgres
    on Oct 10, 2026
  2. SebastianSchuetze commented on Oct 14, 2026

    @SebastianSchuetze

    I ran into the same issue in a small public test repo:

    https://github.com/findmydoc-platform/payload-test-repo/tree/ae9d2f69a9be14914813003e59a84f37f3cce109

    It uses Payload 3.88.0 with PostgreSQL and triggers a deferred constraint error during COMMIT. commitTransaction() still resolves, even though PostgreSQL rolls the transaction back and the inserted row is not persisted. The reproduction is intentionally left unpatched.

  3. ibrahimalzubi commented on Oct 18, 2026

    @ibrahimalzubi

    Still present in 3.91.0 (latest) and 4.0.0-beta.2: packages/drizzle/src/transactions/{begin,commit,rollback}Transaction.ts have the same git blobs at v3.90.2, v3.91.0, 3.x and main, and the published dist/transactions/*.js files are byte-identical in 3.90.2, 3.91.0 and 4.0.0-beta.2.

    Some additions that may help triage:

    It happens on ordinary Local API writes, not only with payload.db. I reproduced it with a plain Node script (payload and @payloadcms/db-postgres 3.90.2, pg 8.20.0, PostgreSQL 17.4, Node 24.18): one posts collection, plus a DEFERRABLE INITIALLY DEFERRED constraint trigger that raises on every UPDATE of posts. payload.update() resolves with the new value while the row keeps the old one:

    3. payload.update({ collection: 'posts', id: 1, data: { title: 'updated' } })
         sql> begin
         [read of the current document, then the document-lock check and cleanup]
         sql> update "posts" set "title" = $1, "updated_at" = $2, "created_at" = $3 where "posts"."id" = $4 returning "id", "title", "updated_at", "created_at"  -- params: ["updated","2026-10-18T15:39:03.624Z","2026-10-18T15:39:03.586Z",1]
         sql> commit
         sql> rollback
       -> RESOLVED, returned title="updated"
       payload.findByID -> title="original"
       SELECT title FROM posts WHERE id = 1 -> "original"
    

    PostgreSQL logs ERROR: deferred check rejected posts row 1 with STATEMENT: commit on Payload's connection, then WARNING: there is no transaction in progress for drizzle's rollback. So drizzle-orm did see the failure and rethrew it. Two controls behave as expected: with disableTransaction: true the same payload.update() rejects with DrizzleQueryError (cause P0001), and a plain node-postgres BEGIN … COMMIT rejects at COMMIT. In the failing case nothing is logged and there is no unhandled rejection.

    Not a regression from #16220. The handler on done was already a plain .catch(() => {}) when #4582 (2023) made resolve() return done; #16220 only changed what the handler does. COMMIT errors have never reached the caller in the drizzle-based adapters.

    Reach, from reading the 3.91.0 source. Every operation that opens and commits its own transaction goes through this path: collection create/update/delete and their variants, global update, the auth operations, updateJobs and the migration runner. That applies on db-postgres and db-vercel-postgres by default, and on db-sqlite and db-d1-sqlite when transactionOptions is set. Some consequences once a COMMIT fails:

    • login returns a token whose session row was rolled back, so auth/strategies/jwt.ts:180-184 treats it as no user.
    • logout returns true while the session removal was rolled back, so the token keeps working.
    • migrate neither logs Error running migration … nor exits with code 1 (packages/drizzle/src/migrate.ts:110-116; on main it would rethrow, :120-127); it moves on to the next migration, although the current one and its payload-migrations row were rolled back (the Migrated: line at :100 is printed before the commit either way).
    • On main, payload's commitTransaction helper (utilities/commitTransaction.ts:15-17) also runs commitFileOperations ("Called only after the owning database transaction commits") after a failed COMMIT.

    Fixes: #17726 (into 3.x), #17727 and #18664 (into main) are open for this. One related case that none of them can catch: if an earlier SQL statement in the transaction failed and its error was caught, PostgreSQL answers COMMIT with ROLLBACK and no error (the situation in #15517).

    Reproduction script (repro.mjs, plain Node, no Next.js)

    Dependencies: [email protected], @payloadcms/[email protected] and [email protected], in a package with "type": "module". Set REPRO_DATABASE_URL to the URL of an empty database and run node repro.mjs with NODE_ENV unset, because it relies on the development schema push. The bug reproduced if the output includes a line starting with RESULT: REPRODUCED; exit code 1 alone can also mean a setup failure.

    // Reproduction: a COMMIT that fails inside Payload's own transaction is reported as success.
    //
    // Versions: payload 3.90.2, @payloadcms/db-postgres 3.90.2 (@payloadcms/drizzle 3.90.2,
    // drizzle-orm 0.45.2), pg 8.20.0, PostgreSQL 17, Node 24.
    //
    // Needs an empty scratch database. Set REPRO_DATABASE_URL or use the default below, then run:
    //   node repro.mjs
    // Exit code: 1 = bug reproduced, 0 = the failed commit was reported, 2 = unexpected error.
    import crypto from 'node:crypto'
    
    import { postgresAdapter } from '@payloadcms/db-postgres'
    import { buildConfig, getPayload } from 'payload'
    import pg from 'pg'
    
    const DATABASE_URL = process.env.REPRO_DATABASE_URL ?? 'postgres://[email protected]:54339/repro'
    
    // Plain Node script, not Next.js: when NODE_ENV !== 'production', getPayload() otherwise opens a
    // WebSocket to the Next.js dev HMR endpoint (ws://localhost:3000/_next/hmr by default).
    process.env.DISABLE_PAYLOAD_HMR = 'true'
    
    // Print the SQL that Payload sends through drizzle, only while `trace` is on.
    let trace = false
    const sqlTrace = {
      logQuery(query, params) {
        if (trace) console.log(`     sql> ${query}${params.length ? `  -- params: ${JSON.stringify(params)}` : ''}`)
      },
    }
    
    const config = buildConfig({
      secret: crypto.randomBytes(32).toString('hex'), // random per run, never printed
      telemetry: false, // no telemetry request from a repro
      typescript: { autoGenerate: false }, // otherwise init() spawns `payload generate:types`
      db: postgresAdapter({
        pool: { connectionString: DATABASE_URL },
        push: true, // development schema push (the default whenever NODE_ENV !== 'production')
        logger: sqlTrace,
      }),
      collections: [{ slug: 'posts', fields: [{ name: 'title', type: 'text' }] }],
    })
    
    // A deferred constraint trigger that rejects every UPDATE of posts when the transaction commits.
    const SETUP_SQL = `DROP FUNCTION IF EXISTS reject_at_commit() CASCADE;
    CREATE FUNCTION reject_at_commit() RETURNS trigger LANGUAGE plpgsql AS $$
    BEGIN
      RAISE EXCEPTION 'deferred check rejected posts row %', NEW.id;
    END
    $$;
    CREATE CONSTRAINT TRIGGER posts_reject_at_commit
      AFTER UPDATE ON posts
      DEFERRABLE INITIALLY DEFERRED
      FOR EACH ROW EXECUTE FUNCTION reject_at_commit();`
    
    // Indent every line after the first, so multi-line values line up under their label.
    const indent = (text, pad = '     ') => String(text).split('\n').join(`\n${pad}`)
    
    function describe(err) {
      if (!(err instanceof Error)) return String(err)
      const head = `${err.constructor.name}${err.code ? ` [${err.code}]` : ''}: ${err.message}`
      return err.cause instanceof Error ? `${head}\ncause: ${describe(err.cause)}` : head
    }
    
    process.on('unhandledRejection', (reason) => console.log(`!! unhandledRejection: ${indent(describe(reason))}`))
    
    const payload = await getPayload({ config })
    const client = new pg.Client({ connectionString: DATABASE_URL })
    await client.connect()
    const storedTitle = async (id) =>
      (await client.query('SELECT title FROM posts WHERE id = $1', [id])).rows[0]?.title
    
    let exitCode = 2
    try {
      const { server_version } = (await client.query('SHOW server_version')).rows[0]
      console.log(`\nnode ${process.version}, PostgreSQL ${server_version}`)
    
      // 1. A post created through the Local API.
      const post = await payload.create({ collection: 'posts', data: { title: 'original' } })
      console.log(`\n1. payload.create -> id=${post.id}, title=${JSON.stringify(post.title)}`)
    
      // 2. The deferred trigger, installed with a plain pg client.
      await client.query(SETUP_SQL)
      console.log(`\n2. plain pg client:\n     ${indent(SETUP_SQL)}`)
    
      // 3. The bug: payload.update runs inside Payload's transaction, and its COMMIT fails.
      console.log(`\n3. payload.update({ collection: 'posts', id: ${post.id}, data: { title: 'updated' } })`)
      let update
      trace = true
      try {
        const doc = await payload.update({ collection: 'posts', id: post.id, data: { title: 'updated' } })
        update = { resolved: true, title: doc.title }
      } catch (err) {
        update = { error: err, resolved: false }
      } finally {
        trace = false
      }
      console.log(
        update.resolved
          ? `   -> RESOLVED, returned title=${JSON.stringify(update.title)}`
          : `   -> THREW ${indent(describe(update.error))}`,
      )
      const found = await payload.findByID({ collection: 'posts', id: post.id })
      const stored = await storedTitle(post.id)
      console.log(`   payload.findByID -> title=${JSON.stringify(found.title)}`)
      console.log(`   SELECT title FROM posts WHERE id = ${post.id} -> ${JSON.stringify(stored)}`)
    
      // Control (a): the same UPDATE through a plain client transaction rejects at COMMIT.
      console.log(
        `\n4. control (a), plain pg client: BEGIN; UPDATE posts SET title = 'updated-raw' WHERE id = ${post.id}; COMMIT;`,
      )
      await client.query('BEGIN')
      const res = await client.query('UPDATE posts SET title = $1 WHERE id = $2', ['updated-raw', post.id])
      console.log(`   UPDATE -> ok, rowCount=${res.rowCount}`)
      try {
        await client.query('COMMIT')
        console.log('   COMMIT -> resolved')
      } catch (err) {
        console.log(`   COMMIT -> REJECTED ${indent(describe(err))}`)
      }
      console.log(`   SELECT title -> ${JSON.stringify(await storedTitle(post.id))}`)
    
      // Control (b): the same Local API write without Payload's transaction.
      console.log(
        `\n5. control (b): payload.update({ collection: 'posts', id: ${post.id}, data: { title: 'updated-no-tx' }, disableTransaction: true })`,
      )
      trace = true
      try {
        const doc = await payload.update({
          collection: 'posts',
          data: { title: 'updated-no-tx' },
          disableTransaction: true,
          id: post.id,
        })
        trace = false
        console.log(`   -> RESOLVED, returned title=${JSON.stringify(doc.title)}`)
      } catch (err) {
        trace = false
        console.log(`   -> THREW ${indent(describe(err))}`)
      }
      console.log(`   SELECT title -> ${JSON.stringify(await storedTitle(post.id))}`)
    
      const reproduced = update.resolved && update.title === 'updated' && stored === 'original'
      console.log(
        `\nRESULT: ${reproduced ? 'REPRODUCED' : 'not reproduced'}: payload.update ${
          update.resolved ? `resolved with title ${JSON.stringify(update.title)}` : 'threw'
        }, stored title is ${JSON.stringify(stored)}.`,
      )
      exitCode = reproduced ? 1 : 0
    } catch (err) {
      console.log(`\nUNEXPECTED: ${indent(describe(err))}`)
    } finally {
      await client.end()
      await payload.destroy()
    }
    // The adapter keeps one pooled connection checked out, so the pool never drains: exit explicitly.
    process.exit(exitCode)
  4. SamOdum commented on Oct 26, 2026

    @SamOdum

    Confirming on 3.90.1 and checked against 3.92.0's published @payloadcms/drizzle: a refused COMMIT still resolves commitTransaction, so payload.create returns a document that was never saved.

    A minimal reproduction with no mocks: a DEFERRABLE INITIALLY DEFERRED constraint, which Postgres checks only at COMMIT.

    CREATE TABLE commit_probe (value int, CONSTRAINT commit_probe_unique UNIQUE (value) DEFERRABLE INITIALLY DEFERRED);

    Insert (1), (1) inside initTransaction(req), then commitTransaction(req) resolves, and no rows exist. A constraint trigger with RAISE EXCEPTION on a collection's table shows the same through payload.create.

    We're running the change from #18664 (and #17726) as a pnpm patch in production code. With it, both cases reject and our full suite passes. A review of either PR would let us drop the patch.

  5. DanRibbens commented on Oct 29, 2026

    @DanRibbens
    Contributor

    This issue and the above linked PRs may have overlap with #19159 being worked on. I will review and coordinate what gets merged and closed.

  6. 3li7alaki commented on Nov 15, 2026

    @3li7alaki

    Confirming on @payloadcms/drizzle 3.93.0, the current release: its published dist/transactions/beginTransaction.js still has the .catch that settles done, so a refused COMMIT (deferred FK, real Postgres, no mocks) still resolves commitTransaction while the rows are rolled back.

    #19159 merged on 2026-11-12, after 3.93.0 (published 2026-11-04), so no release carries the fix yet. Is it planned for the next 3.x release? We are running a backport of #19159 as a local patch until then.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bugdb: postgresengagement: medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions