Skip to content

"bun test" hangs up in timeout with PostgreSQL and expect->toThrow() #19130

Open

Description

@wertania

What version of Bun is running?

1.2.10

What platform is your computer?

Microsoft Windows NT 10.0.26100.0, x64

What steps can reproduce the bug?

Unit test with "Bun test" are handing up when "Test 3" is active with expect(async () => {}).toThrow();.

If I drop "Test 3" everything is running.
Also if I replace the inner function with something that is not working with the DB it will work.

But with a database function inside it will run into timeout and will never close.
It hangs up and I need to kill the process from console.

Image

I wrote a simple test to reproduce:

import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import { getDbSchema, users, type DatabaseSchema } from "../../db/db-schema";
import { BunSQLDatabase, drizzle } from "drizzle-orm/bun-sql";
import { SQL } from "bun";

/**
 * DB connection
 */
let dbClient = new SQL(
  `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`
);
let drizzleClient: BunSQLDatabase<DatabaseSchema>;

const connectToDb = async () => {
  const schema = getDbSchema();
  drizzleClient = drizzle(dbClient, { schema, logger: false });
  return drizzleClient;
};
const cleanUpAllData = async () => {
  // do something with the db
  await drizzleClient.select().from(users);
};

/**
 * Mock functions
 */
const addSomeData = async () => {
  // do something with the db
  const r = await drizzleClient.select().from(users);
  return {
    id: r[0].id,
  };
};
const doSomething = async (id: string) => {
  // do something with the db
  const r = await drizzleClient.select().from(users);
  return r[0].id === id;
};
const doSomethingElse = async () => {
  // do something with the db
  const r = await drizzleClient.select().from(users);
  throw new Error("This fails");
};

describe("getKnowledgeEntries Permissions", () => {
  let addedData: { id: string };

  beforeAll(async () => {
    await connectToDb();
    addedData = await addSomeData();
  });

  afterAll(async () => {
    await cleanUpAllData();
  });
  test("Test 1", async () => {
    const result = await doSomething(addedData.id);
    expect(result).toBe(true);
  });

  test("Test 2", async () => {
    expect(async () => {
      await doSomethingElse();
    }).toThrow();
  });

  test("Test 3", async () => {
    const result = await doSomething(addedData.id);
    expect(result).toBe(true);

    expect(async () => {
      await doSomethingElse();
    }).toThrow();
  });
});

What is the expected behavior?

Run the test and close application after that

What do you see instead?

Hanging up and tests are not resolving.

Additional information

No response

Activity

  1. changed the title [-]"bun test" hangs up with PostgreSQL and expect->toThrow()[/-] [+]"bun test" hangs up in timeout with PostgreSQL and expect->toThrow()[/+] on Apr 19, 2025
  2. added
    bun:testSomething related to the `bun test` runner
    sqlSomething to do with `sql` in the "bun" module (postgres, sqlite & mysql)
    and removed on Apr 19, 2025
  3. wertania commented on Dec 2, 2025

    @wertania
    Author

    is there some workaround?

  4. Kober-L commented on Dec 19, 2025

    @Kober-L

    are thery updates about this ? I think it is still an issue:

    • same situation as the one described above
    • same code on MacOs works just fine
    • on my windows machine it timeouts
  5. heiwen commented on Apr 8, 2026

    @heiwen

    Reproduces on macOS (arm64, Bun 1.3.11) with raw Bun.SQL — no Drizzle, no async wrapper needed:

    import { test, expect } from 'bun:test';
    import { SQL } from 'bun';
    
    const sql = new SQL('postgres://user@localhost:5432/db', { prepare: false });
    
    test('hangs forever', async () => {
      await expect(
        sql.unsafe(`SELECT * FROM table_that_does_not_exist`)
      ).rejects.toThrow();
    });

    The process never exits. Same hang with the template-literal form (sql\...``).


    Likely Root cause: Bun.SQL query objects are lazy thenables — the query isn't dispatched until JS-level .then() is called. bun:test's processPromise() (src/bun.js/test/expect.zig) extracts the internal JSC promise via asAnyPromise(), bypassing the JS-level .then() override entirely. The query is never sent, the internal promise stays permanently pending, and the test hangs.

    This is likely the same root cause as #14670 (Bun.$ shell promises). PR #27260 fixes it for Bun.$ but doesn't include a regression test for Bun.SQL — worth adding before merge.


    Workaround (until fixed):

    let threw = false;
    try {
      await sql.unsafe(`SELECT * FROM table_that_does_not_exist`);
    } catch {
      threw = true;
    }
    expect(threw).toBe(true);
  6. heiwen commented on Apr 8, 2026

    @heiwen

    @robobun what do you think?

  7. aspencreativehouse commented on May 20, 2026

    @aspencreativehouse

    Adding data — we hit this same architectural shape with bun:sqlite (sync queries exceeding bun test --timeout, runner orphans at high RSS, only external SIGTERM clears it). Two incidents on a developer Mac in the past week: four orphan processes pushed the machine into yellow memory pressure (~36GB swap), three more caught early the next day. Not driver-specific — the underlying problem is bun test --timeout can't terminate a test wedged inside any sync FFI.

    We filed #31014 asking for sqlite3_interrupt() exposure. @sroussey caught that same-thread setTimeout can't fire during a sync sqlite3_step(), so even with PR #31078 landed the test runner has no way to call interrupt() on the wedged connection. The interrupt() exposure helps iterator + cross-thread cases but doesn't close this wedge.

    Our workaround: a process-level SIGTERM wrapper (bash script that traps signals and reaps the bun child). Works because SIGTERM from outside the process doesn't care that the JS thread is blocked. But it's a tax every consumer hitting this gap pays independently.

    Question for the Bun team — what's the right architectural path here? Options from outside (no strong opinions):

    • --parallel (v1.3.13) workers per file — does the parent reap wedged workers on --timeout expiry? Couldn't find that documented either way.
    • Subprocess isolation per test (heavy)
    • Runner-level interrupt orchestration via a watchdog thread with access to open connections
    • Something we haven't thought of

    Happy to provide a minimal repro, test a patch, or run experiments. The gap affects any consumer running tests against any sync native API.

    Related tickets: #31014 (sqlite interrupt() ask, narrow), #31078 (PR for #31014), #21277 (JS infinite loop variant of same wedge), #5621 (sqlite timeout umbrella since 2023), #8913 (timeout accuracy), #2326 (broader async sqlite), #978 (async-sqlite parent).

  8. robobun commented on Aug 18, 2026

    @robobun
    Collaborator

    A smaller repro of what looks like the same hang, seen while working on #39452 with Bun 1.4.0 on Linux. expect() on a Bun.SQL query object never settles, with .resolves as well as .rejects, and the per-test timeout does not fire. The process has to be killed.

    import { SQL } from "bun";
    import { expect, test } from "bun:test";
    
    test("hangs", async () => {
      await using db = new SQL(process.env.DATABASE_URL!);
      await expect(db`SELECT 1 AS x`).resolves.toEqual([{ x: 1 }]);
    });

    The same assertion passes when the query is wrapped in a plain promise, for example when the tagged template call is moved into a Promise.resolve().then(...) callback, or with expect(query.execute()). A query object is a Promise subclass that only starts the query inside its own then() (src/js/internal/sql/query.ts). .resolves and .rejects appear to wait for the promise without calling that then(), so the query never runs and the wait never ends. expect(async () => ...).toThrow() in the original report probably hits the same wait.

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

    bugSomething isn't workingbun:testSomething related to the `bun test` runnersqlSomething to do with `sql` in the "bun" module (postgres, sqlite & mysql)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions