Skip to content

[miniflare] Hyperdrive proxy crashes the Node process when the client socket errors #15768

Closed

Description

@Pduhard

What versions & operating system are you using?

  System:
    OS: Linux 7.0 Ubuntu 24.04.4 LTS 24.04.4 LTS (Noble Numbat)
    CPU: (32) x64 AMD Ryzen 9 9950X 16-Core Processor
    Memory: 16.45 GB / 30.45 GB
    Container: Yes
    Shell: 5.9 - /usr/bin/zsh
  Binaries:
    Node: 22.14.0
    npm: 10.9.2
    pnpm: 11.24.0
  npmPackages:
    miniflare: 4.20260730.0 => 4.20260730.0

Please provide a link to a minimal reproduction

https://github.com/Pduhard/miniflare-hyperdrive-crash-repro

Describe the Bug

The local Hyperdrive proxy pipes the workerd client socket to the database socket. Only the database side gets an error listener.

In packages/miniflare/src/plugins/hyperdrive/hyperdrive-proxy.ts on main:

  • createPlainTCPConnection attaches dbSocket.on("error", ...)
  • setupTLSConnection attaches tlsSocket.on("error", ...)
  • clientSocket gets nothing, at any of the four places it is piped: #handleConnection, handlePostgresTlsConnection, handleMySQLTlsConnection, setupTLSConnection. It also gets nothing before those pipes exist: on the TLS paths, #handleConnection writes to the database, reads the reply and runs a TLS handshake first, and a client that resets during that window crashes the process the same way

pipe() does not cover this. It attaches an onerror handler to the destination, but that handler removes itself and re-emits once no other listener is left. So when the client socket errors after the pipes are set up, nothing is listening, and the whole Node process exits. That takes down wrangler dev, getPlatformProxy(), or a vitest run.

Steps to reproduce

git clone https://github.com/Pduhard/miniflare-hyperdrive-crash-repro
cd miniflare-hyperdrive-crash-repro
npm install
npm run repro:half-close
npm run repro:reset

repro:half-close runs a TCP server that speaks just enough of the Postgres protocol to negotiate TLS, then streams data. A Worker connects through a Hyperdrive binding and half-closes its socket while that data is still arriving. Nothing reaches into Miniflare internals.

repro:reset covers the other window: it talks to the proxy port directly and resets the connection while the proxy is still negotiating TLS with the database, before any pipe exists.

Expected: the connection is torn down and Miniflare keeps running.
Observed: the process exits 1 on an uncaught error.

Which configurations reach this code

Since #13390 the proxy is skipped when sslmode=disable, so that mode no longer reaches it. require, prefer, verify-ca and verify-full still do, which is the ordinary setup for developing locally against a hosted Postgres that requires TLS.

version sslmode=disable sslmode=require
4.20260424.0 exits 1 exits 1
4.20260730.0 20 of 20 attempts survive exits 1

The same code is on main today.

Please provide any relevant error logs

node:events:496
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:87:19)
Emitted 'error' event on Socket instance at:
    at Socket.onerror (node:internal/streams/readable:1028:14)
    at Socket.emit (node:events:518:28)
    at emitErrorNT (node:internal/streams/destroy:170:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

Socket.onerror at readable.js:1028 is the listener pipe() installed on the destination, re-emitting because nothing else was listening. Depending on whether the write lands just before or just after the peer's FIN, the same failure also shows up as Error: This socket has been ended by the other party at Socket.writeAfterFIN.


PR: #15769. It attaches the listener as soon as the connection is accepted and at each pipe site, with a regression test for each of the two windows in packages/miniflare/test/plugins/hyperdrive/proxy.spec.ts. Both tests fail on main.

Activity

  1. workers-devprod commented on Sep 22, 2026

    @workers-devprod
    Contributor

    Automated triage

    Issue assessment

    • Actionability: ✅ Actionable.
    • Type: Bug.
    • Reproduction: Automatic attempt requested.
    • Labels:
      • package:miniflare (high)
      • product:hyperdrive (high)
    Actionability and missing information

    Miniflare's Hyperdrive proxy lacks an error listener on the client socket at its four pipe sites, so a client-side socket error becomes an unhandled error event that crashes the Node process; report includes minimal repro, versions, environment, and error logs.

    Reproduction reason: The report provides concrete steps, version comparisons, and consistent error output for a crash that still occurs in current releases, so automatic reproduction can validate it.

    Reproduction

    Evidence and attempted steps

    Steps attempted:

    1. Set up the fixture project with the exact reported dependency version
      • Command: cd project && pnpm install # pins miniflare 4.20260730.0 exactly
    2. Run the repro: streaming mock Postgres TLS server on 127.0.0.1:15432; Miniflare Hyperdrive binding with sslmode=require (proxy in-process, same wiring wrangler dev uses); dispatch a Worker fetch whose env.DB.connect() socket half-closes and closes mid-stream while the mock database keeps streaming
      • Command: node repro.mjs
    3. Verify reliability across consecutive runs
      • Command: for i in 1 2 3 4 5; do node repro.mjs > /tmp/final-$i.log 2>&1; echo "run $i: exit=$?"; done
    4. Verify the shipped artifact end-to-end from a clean state
      • Command: rm -rf node_modules && pnpm install --frozen-lockfile && pnpm reproduce

    Expected behavior: The client-side connection is torn down gracefully and the Node process running Miniflare (wrangler dev / getPlatformProxy() / a Miniflare Node-API process) keeps running; the socket error is handled rather than crashing the process.

    Observed behavior: In 5/5 consecutive runs (plus one clean-state run after a frozen reinstall), the Node process running Miniflare exited 1 during the Worker request with the exact reported signature: an uncaught 'error' event on the Hyperdrive proxy's client socket — "Error: write EPIPE" (errno: -32, syscall: 'write'), "Emitted 'error' event on Socket instance at: at Socket.onerror (node:internal/streams/readable:1028:14)" — the same re-emit site (readable.js:1028, the listener installed by pipe()) and same error as the issue's log.

    Artifact: Download reproduction archive (Cloudflare Access required).

    Treat archive contents as untrusted. Inspect them before running anything.


    This summary was generated by an LLM and may contain errors. Please verify its findings.

    Triage bot commands and options

    Repository collaborators with write or admin access can trigger actions by commenting on this issue:

    • @workers-devprod reproduce: Attempt to reproduce the issue using its description and recent comments.
  2. added
    package:miniflare
    product:hyperdrive
    on Sep 22, 2026
  3. rikbrown commented on Sep 24, 2026

    @rikbrown

    A reload in wrangler dev is another trigger for this crash, and in local development it is the common one.

    Each reload (Miniflare#setOptions()) stops the workerd process and starts a new one. The connections that a Worker holds open through a Hyperdrive binding close with the old process. If a connection still has unread data, for example a query result that arrived during the reload, the OS resets it. The proxy's client socket then emits read ECONNRESET with no listener, and wrangler dev exits 1 directly after the reload message:

    ⎔ Reloading local server...
    Error: read ECONNRESET
        at TCP.onStreamRead (node:internal/stream_base_commons:216:20) {
      errno: -54,
      code: 'ECONNRESET',
      syscall: 'read'
    }
    Error: read ECONNRESET
        at TCP.onStreamRead (node:internal/stream_base_commons:216:20) {
      errno: -54,
      code: 'ECONNRESET',
      syscall: 'read'
    }
    

    The error prints once for each open connection. With a connection pool and a TLS database, a file edit while the Worker serves requests is enough to cause it.

    The script below uses only the public API. A fake Postgres server accepts the SSLRequest, upgrades to TLS and sends data. A Worker opens two env.DB.connect() sockets and holds them, then the script calls setOptions(). Results on macOS 27.0, Node 24.12.0, workerd 1.20260921.1:

    miniflare MODE=burst (data left unread) MODE=stream (data still arriving)
    5.20260921.1-alpha 3 of 3 runs: uncaught read ECONNRESET 3 of 3 runs: uncaught write EPIPE
    5.20260921.0-alpha + the change in #15769 3 of 3 runs: no uncaught error 3 of 3 runs: no uncaught error

    The same script also shows a separate leak: each reload leaves the previous proxy servers listening, also after dispose(). That is #15843.

    repro.mjs
    // A Miniflare reload while a Worker holds Hyperdrive connections through the local TLS proxy (sslmode=require).
    // Usage: MF=<path to the miniflare package directory> MODE=burst|stream node repro.mjs
    // Needs key.pem and cert.pem beside this file:
    //   openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 1 -subj /CN=localhost
    import { readFileSync } from 'node:fs'
    import net from 'node:net'
    import tls from 'node:tls'
    import { setTimeout as sleep } from 'node:timers/promises'
    
    const { Miniflare, convertV4MiniflareOptions } = await import(`${process.env.MF}/dist/src/index.js`)
    
    let uncaught = 0
    process.on('uncaughtException', (error) => {
      uncaught += 1
      console.log(`UNCAUGHT #${uncaught}: ${error.stack} code=${error.code} syscall=${error.syscall}`)
    })
    
    // Fake Postgres: answer the SSLRequest with 'S', upgrade to TLS, then send data like a query result.
    // burst: send 256 KiB once, which the Worker leaves unread. stream: keep sending.
    const key = readFileSync(new URL('key.pem', import.meta.url))
    const cert = readFileSync(new URL('cert.pem', import.meta.url))
    let tlsReady = 0
    const db = net.createServer((raw) => {
      raw.on('error', () => {})
      raw.once('data', () => {
        raw.write('S')
        const secure = new tls.TLSSocket(raw, { isServer: true, key, cert })
        secure.on('error', () => {})
        secure.once('data', () => {
          tlsReady += 1
          const chunk = Buffer.alloc(16 * 1024, 0x41)
          if (process.env.MODE === 'burst') {
            for (let index = 0; index < 16; index += 1) secure.write(chunk)
            return
          }
          const timer = setInterval(() => secure.writable && secure.write(chunk), 2)
          secure.on('close', () => clearInterval(timer))
        })
      })
    })
    await new Promise((resolve) => db.listen(0, '127.0.0.1', resolve))
    const dbPort = db.address().port
    
    const script = `
    export default {
      async fetch(request, env) {
        const socket = env.DB.connect()
        const writer = socket.writable.getWriter()
        await writer.write(new TextEncoder().encode('startup'))
        const reader = socket.readable.getReader()
        const first = await reader.read()
        if (new URL(request.url).pathname === '/once') {
          return new Response('read ' + first.value.byteLength + ' bytes')
        }
        // Hold the connection open, as a pooled client does between queries.
        await new Promise((resolve) => setTimeout(resolve, 60_000))
        return new Response('done')
      },
    }
    `
    function options(generation) {
      return convertV4MiniflareOptions({
        workers: [
          {
            name: 'repro',
            modules: true,
            script,
            compatibilityDate: '2026-09-01',
            hyperdrives: { DB: `postgresql://user:[email protected]:${dbPort}/db?sslmode=require` },
            bindings: { GENERATION: generation },
          },
        ],
      })
    }
    function listeningServers() {
      return process.getActiveResourcesInfo().filter((resource) => resource === 'TCPServerWrap').length
    }
    
    const mf = new Miniflare(options('1'))
    await mf.ready
    console.log(`ready; listening servers=${listeningServers()}`)
    for (let index = 0; index < 2; index += 1) {
      mf.dispatchFetch('http://localhost/').catch((error) => console.log(`request ${index}: ${error.message}`))
    }
    while (tlsReady < 2) {
      await sleep(20)
    }
    await sleep(200)
    await mf.setOptions(options('2'))
    console.log(`after 1 reload; listening servers=${listeningServers()}`)
    for (let generation = 3; generation <= 6; generation += 1) {
      await mf.setOptions(options(String(generation)))
    }
    console.log(`after 5 reloads; listening servers=${listeningServers()}`)
    const after = await mf.dispatchFetch('http://localhost/once')
    console.log(`query after the reloads: ${after.status} ${await after.text()}`)
    await sleep(2000)
    await mf.dispose()
    await sleep(500)
    console.log(`after dispose(); listening servers=${listeningServers()} (1 is the fake database)`)
    console.log(`uncaught errors=${uncaught}`)
    db.close()
    process.exit(uncaught === 0 ? 0 : 1)
  4. phoorichet commented on Oct 9, 2026

    @phoorichet

    Still reproduces on the latest alpha, and through @cloudflare/vite-plugin:

    • miniflare 5.20260918.0-alpha (what @cloudflare/[email protected] installs) and 5.20261006.1-alpha (current latest): setupTLSConnection and the other pipe sites are unchanged
    • macOS, Node 25.9.0, react-router dev with @cloudflare/vite-plugin, a Hyperdrive binding with a local connection string to a hosted Postgres over sslmode=verify-full

    How we hit it without trying: the hosted Postgres ran out of connection slots (53300 remaining connection slots are reserved...), sockets got reset, and the dev server died with:

    Error: read ECONNRESET
    Emitted 'error' event on Socket instance at:
        at Socket.onerror (node:internal/streams/readable:1036:14)
    Exited with code 1
    

    Both windows from the issue reproduce through the vite plugin, by connecting to the proxy's loopback port and calling resetAndDestroy():

    Patch applied locally Reset after 3s (pipes set up) Reset after 5ms (TLS negotiation)
    none process exits (not reached)
    pipe-site listeners only survives process exits on first try
    pipe-site listeners + a listener right after accept (as in #15769) survives survives 5 of 5

    So the entry listener in #15769 is needed in practice, not just in theory. We're carrying a bun patch with both until #15769 ships.

  5. Pduhard commented on Oct 22, 2026

    @Pduhard
    ContributorAuthor

    Fixed on main by the proxy rework (#15879, #14900): a client socket error mid-stream or a reset during negotiation no longer takes down the process. Checked by running the two tests from #15769 against main.

  6. moved this from Untriaged to Done in workers-sdkon Oct 22, 2026
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

    package:miniflareproduct:hyperdrive

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions