Skip to content

Interactive transaction: queries batched after a failing one resolve undefined instead of rejecting #30540

Closed

Description

@lucas-gregoire

Package and version

@prisma/client, prisma and @prisma/adapter-pg 7.10.0 (the code below is unchanged in 8.1.0-dev.7).

What happened?

Inside an interactive transaction, queries issued in the same tick are grouped into one batch by the client DataLoader (batchBy → itx-<id>). When one plan of that batch fails, requestBatch stops the loop (case "multi" → catch → break) and returns a result array shorter than the request array. DataLoader.dispatchBatches then resolves every remaining request with n[i], i.e. undefined.

So a findMany sibling of the failing query neither rejects nor returns []: it resolves undefined, which then surfaces far from its cause as TypeError: Cannot read properties of undefined (reading 'map') in user code.

It happens with both failure modes we hit in production:

  • a real query error in the batch (e.g. a constraint violation, division by zero);
  • a batch sent on a transaction already rolled back (Transaction already closed: A batch query cannot be executed on a transaction that was rolled back.): only the first request gets that error, all the others resolve undefined.

Where, in @prisma/client/runtime/client.js:

  • requestBatch, case "multi": catch (H) { if (q ??= …every findUnique…, M.push(H), L = true, !q) break }
  • DataLoader.dispatchBatches: for (i < r.length) { let o = n[i]; o instanceof Error ? r[i].reject(o) : r[i].resolve(o) }, where o is undefined for every index past the failing one.

What did you expect to happen?

Every request of the batch settles with a meaningful outcome: the failing one rejects with its error, and the requests that were never executed reject too (with the same error, or a dedicated "not executed because a previous query of the batch failed" error). None of them should resolve undefined, which is not a valid value for any of these operations.

Minimal reproduction

const { PrismaClient } = require('@prisma/client');
const { PrismaPg } = require('@prisma/adapter-pg');

const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }) });

(async () => {
  await prisma
    .$transaction(async (tx) => {
      console.log(await Promise.allSettled([tx.$queryRaw`SELECT 1/0`, tx.$queryRaw`SELECT 1 AS one`]));
    })
    .catch(() => {});

  let leaked;
  await prisma.$transaction(async (tx) => { leaked = tx; throw new Error('boom'); }).catch(() => {});
  console.log(await Promise.allSettled([leaked.$queryRaw`SELECT 1 AS one`, leaked.$queryRaw`SELECT 2 AS two`]));
})();

Output:

[ { status: 'rejected', reason: ... Code: `22012`. Message: `division by zero` },
  { status: 'fulfilled', value: undefined } ]
[ { status: 'rejected', reason: ... Transaction already closed: A batch query cannot be executed on a transaction that was rolled back. },
  { status: 'fulfilled', value: undefined } ]

The same happens with model queries (findMany, createMany) instead of raw ones.

Environment

  • engineType = "client" (query compiler + driver adapter @prisma/adapter-pg)
  • PostgreSQL 18.4, Node 24.16.0, macOS (reproduced locally; seen in production on Linux)

Additional context

In our app the concurrent queries come from several event handlers running in the same interactive transaction (@nestjs-cls/transactional-adapter-prisma), which is how same-tick batching on one transaction happens.

Activity

  1. ludvig03 commented on Oct 15, 2026

    @ludvig03

    We hit this on 7.10.0 too (@prisma/adapter-pg, PostgreSQL 17, Node 26). One more consequence that is worth calling out: it defeats serialization-failure retries.

    Two Serializable interactive transactions each run Promise.all([tx.a.findMany(…), tx.$queryRaw`…`]). The loser's first query fails with 40001 / P2034, but its sibling resolves undefined, user code reads it and throws a TypeError, and that TypeError can reach Promise.all before the P2034 does. A retry wrapper keyed on P2034 then sees a non-retryable error and the operation fails instead of retrying.

    Minimal repro (no concurrency needed):

    await prisma.$transaction(async (tx) => {
      const settled = await Promise.allSettled([
        tx.item.findMany({ where: { id: "not-a-uuid" } }), // 22P02 on a @db.Uuid column
        tx.item.count(),
        tx.$queryRaw`SELECT 1 AS one`,
      ]);
      console.log(settled);
    }).catch(() => {});
    [
      { status: 'rejected', reason: PrismaClientKnownRequestError … invalid input syntax for type uuid },
      { status: 'fulfilled', value: undefined },
      { status: 'fulfilled', value: undefined }
    ]
    

    Expected: entries 2 and 3 reject, ideally with the batch's original error so retry logic on P2034 keeps working.

    Workaround we use: never start several queries at once on a transaction client. A small helper runs them sequentially when the client is a transaction client (no $connect) and in parallel on the root client, plus a lint-style test that fails on Promise.all/allSettled/any/race over a transaction client.

  2. joelbeedle commented on Nov 12, 2026

    @joelbeedle

    Same bug here on @prisma/client 7.9.1 and 7.10.1 (latest), with @prisma/adapter-pg and PostgreSQL. The adapter version does not matter: the short result array comes from the client's requestBatch (case "multi").

    One more trigger worth adding: an interactive transaction that runs past its timeout. When reads are queued on the transaction client (for example Promise.all of several findMany calls) and the transaction expires, the first queued read rejects with P2028, and every other read in that batch resolves undefined. If a caller maps one of those (rows.map(...)), the TypeError can settle first and reject the $transaction with it, so code that maps P2028 to a retryable timeout never sees the timeout. The user-facing error becomes Cannot read properties of undefined (reading 'map').

    Minimal shape that reproduces it (the P2028 must arrive later than the undefined, as it does when it settles behind a deeper call chain):

    await prisma.$transaction(
      async (tx) => {
        const slow = tx.$queryRaw`SELECT pg_sleep(0.6)`;
        const a = tx.$queryRaw`SELECT 1 AS one`.then((r) => Promise.resolve(r));
        const b = tx.$queryRaw`SELECT 2 AS two`;
        await Promise.all([slow, a.then((r) => r.map((x) => x)), b.then((r) => r.map((x) => x))]);
      },
      { timeout: 300 },
    );
    // rejects with TypeError: Cannot read properties of undefined (reading 'map'), not P2028

    Workaround we ship meanwhile: a pnpm patch of the client runtime so that, in requestBatch case "multi", every request that did not run is filled with the error that stopped the batch instead of being left out of the result array. Then DataLoader.dispatchBatches rejects them all with the real error (P2028, 22012, ...). A client extension that turns an undefined result into an error was not enough for us: it only sees the symptom, and it cannot tell a timeout from any other error that stopped the batch.

  3. prisma-asks commented on Nov 12, 2026

    @prisma-asks
  4. prisma-asks commented on Nov 17, 2026

    @prisma-asks

    This is fixed. In an interactive transaction, queries batched after a failing one now reject. They used to resolve with undefined. The fix merged to the v7 branch in #30544.

  5. added a commit that references this issue on Nov 20, 2026
    f8e30b5
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions