porsager / porsager/postgres

Calling sql.end() or sql.close() after a server disconnection causes a permanent hang

Open
#1,097 3 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
8.7k
Forks
374
Avg merge
11d 16h
Merged PRs (30d)
1

Description

I've found that if I experience a disconnection from the server, then attempting to clean up by calling sql.end() or sql.close() before exiting returns a promise that will never resolve. Below is a small reproduction which causes node to exit with exit status 13, which indicates that the process exited because an awaited top-level promise would never resolve:

import postgres from "postgres";

async function test() {
  const sql = postgres();

  try {
    // Run a slow query to give time to kill the DB process while the query is still running
    const result = await sql`select pg_sleep(10)`;

    console.log({ success: true, result: result });
  } catch (e) {
    console.error("Caught error: " + e);
  }

  try {
    await sql.end();
  } catch (err) {
    console.error("Caught error shutting down sql: " + err);
  }

  console.log("All done!");
}

await test();

If I then run this and kill the postgres database while the pg_sleep(10) query is running, then the script outputs:

$ node postgres.mjs
Caught error: Error: write CONNECTION_CLOSED 127.0.0.1:5243
$ echo $?
13

There's something important here about needing the disconnection to happen after we've connected to the server; if I just don't have a running postgres instance in the first place or if I leave the postgres instance running the entire time without disturbing it, then the script will happily run to completion, printing All done! before exiting cleanly with exit status 0.

This may be the same underlying problem as #861, I'm not sure. But having a simpler repro seemed valuable.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the connection lifecycle behind sql.end() and sql.close(), using the provided script and its pg_sleep(10) query as the reproduction. Kill PostgreSQL while the query is running, then verify cleanup resolves, prints “All done!”, and exits with status 0 instead of hanging with status 13.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js, postgresql
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.