postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Calling original unlisten after reconnect leaves its callback registered

Open CheckPickerUpper opened this issue 1 month ago • 0 comments

Outcome

Calling the original unlisten() handle after an automatic LISTEN reconnect resolves successfully, but the original user callback remains registered and receives later notifications. The handle should release its subscription across reconnects while preserving other subscriptions.

Observed with postgres3.4.9, Node24.21.0, and real PostgreSQL17. Current master 411429e7bd7a3d61155ca9a70a97c111823702ea still has the same listener-identity implementation; this master statement is source inspection, not a separate runtime run.

Cause and required change

  • Written at: src/index.js:159, the listener connection's onclose callback recursively calls listen(name,l.fn,l.onlisten), constructing a replacement listener object. The original returned unsubscribe closure still captures the initial object.
  • Class: a cleanup handle owns a superseded registration rather than the currently live subscription.
  • Required change: preserve a subscription's ownership across reconnects and release that same subscription when its original handle is used. Remove the replacement-identity path. Preserve multiple listeners on the same channel and unsubscribe while reconnect is pending; closing one subscription must not remove another.

Reproduction

Run this as repro.mjs with postgres3.4.9 and the usual PGHOST, PGPORT, PGUSER, PGPASSWORD, and PGDATABASE environment for a real PostgreSQL server. The database user must be able to terminate its own listener backend. No proxy or driver internals are used.

import assert from 'node:assert/strict'
import postgres from 'postgres'

const app = 'original-unlisten-repro'
const sql = postgres({ connection: { application_name: app } })
const observer = postgres()
const reconnect = Promise.withResolvers()
const before = Promise.withResolvers()
const barrier = Promise.withResolvers()
const received = []
let registrations = 0

try {
  const original = await sql.listen('original_subscription', payload => {
    received.push(payload)
    if (payload === 'before-unlisten') before.resolve()
  }, () => {
    if (++registrations === 2) reconnect.resolve()
  })
  await sql.listen('preserved_subscription', () => barrier.resolve())
  const [{ pid }] = await observer`
    select pid from pg_stat_activity
    where application_name = ${app} and query ilike 'listen %'
  `
  await observer`select pg_terminate_backend(${pid})`
  await reconnect.promise
  await observer`select pg_notify('original_subscription','before-unlisten')`
  await before.promise
  await original.unlisten()
  await observer.begin(async tx => {
    await tx`select pg_notify('original_subscription','after-unlisten')`
    await tx`select pg_notify('preserved_subscription','barrier')`
  })
  await barrier.promise
  console.log(received)
  assert.deepEqual(received, ['before-unlisten'])
} finally {
  await sql.end()
  await observer.end()
}

PostgreSQL delivers the committed target notification before the control notification. The preserved control callback is a positive observation barrier; the result does not depend on waiting for silence. Promise.withResolvers() requires a recent Node release; the observed run used Node24.

Actual result: ['before-unlisten','after-unlisten'], assertion failure. The test's server observation also confirmed a replacement listener PID after disconnect. The original unlisten() had resolved before the unwanted notification was committed.

Done when

  • [ ] The original handle removes its callback after a real disconnect and completed reconnect.
  • [ ] Removing one listener leaves another listener on the same channel active.
  • [ ] Removing the last listener releases the server's LISTEN registration without ending the caller's shared query pool.
  • [ ] A subscription closed during reconnect is not restored afterward.

Evidence and impact

The real native run observed LISTEN backend1575 reconnect to1577, followed by successful original unlisten and the old callback receiving the post-unsubscribe payload. A separate public Foundation integration recovered its queued event after LISTEN backend453 reconnected to461, then reported clean worker stop/close while pg_stat_activity still showed backend461's LISTEN registration. The shared database query succeeded before that assertion; ending the database was not used as unsubscribe. Foundation's stopped worker blocks delivery, so the integration impact is false clean shutdown and retained subscription ownership, not delivery after stop.

Latest published release is3.4.9. Open issue/PR searches found no reconnect/unlisten identity report. The idle LISTEN connection report concerns a live pooled connection after successful unsubscribe without reconnect; this report concerns a callback and LISTEN registration that were not removed.

CheckPickerUpper avatar Oct 05 '26 04:10 CheckPickerUpper