Repository navigation
Description
Issue Description
In replication-pool mode, when a Postgres socket error fires on a connection between when _connect() resolves and when the pool's create callback assigns connection.queryType, the pool's destroy(connection) wrapper crashes with TypeError: Cannot read properties of undefined (reading 'destroy') in 6.37.x, or Error: Unable to determine to which pool the connection belongs in main. The throw surfaces from a Connection.emit('error', ...) listener, so it becomes a process.uncaughtException (v6) or unhandled rejection (v7).
The race is rare — we have only had one production incident in the last 30 days across a moderately-busy app.
This may be a concrete root-cause for #9242, which has been open since 2018 against v4 with the same surface message. PR #18218 appears to fix it on main by introducing an afterConnect hook so the connection is registered in owningPools before any error-prone post-connect work runs.
I have applied a fix (see below) by patching v6.37.8 during yarn install, but it would still be useful for us if this could be fixed upstream. I can make a PR if that helps - I see the contribution guidelines ask for maintainer approval before creating PRs against branches though.
Reproducible example
This is a race condition between socket error delivery and pool registration, so there is no straightforward SSCCE that triggers it deterministically against unmodified Sequelize. The race could be forced by stubbing the dialect's connect() to schedule a connection.emit('error', ...) on the same tick that the connection resolves, before the pool's create callback executes its next synchronous step.
Root cause
v6.37.8
lib/dialects/abstract/connection-manager.js:
// lib/dialects/abstract/connection-manager.js
this.pool = {
// ...
destroy: connection => {
this.pool[connection.queryType].destroy(connection); // line 118
debug('connection destroy');
},
// ...
read: new Pool({
name: 'sequelize:read',
create: async () => {
const nextRead = reads++ % config.replication.read.length;
const connection = await this._connect(config.replication.read[nextRead]);
// Errors thrown during _connect are reported to the event
// handler below, which calls this.pool.destroy(connection),
// which fails because the following line hasn't run yet.
connection.queryType = 'read'; // line 137
return connection;
},
// ...
}),
write: new Pool({ /* connection.queryType = 'write' assigned on line 153 */ })
};lib/dialects/postgres/connection-manager.js:
// inside connect(config) — the function that becomes `this._connect`:
const connection = await new Promise((resolve, reject) => {
// ... new this.lib.Client(config), parameter handlers, etc.
connection2.connect(err => {
if (err) { /* reject */ }
else { resolve(connection2); }
});
});
connection.on('error', error => { // line 158
connection._invalid = true;
debug(`connection error ${error.code || error.message}`);
this.pool.destroy(connection); // line 161
});
let query = '';
// ... SET standard_conforming_strings, SET client_min_messages,
// SET TIME ZONE — multiple awaits ...
if (query) { await connection.query(query); }
if (Object.keys(this.nameOidMap).length === 0 /* ... */) {
await this._refreshDynamicOIDs(connection);
}
return connection;The on('error') handler is registered before any post-connect SET queries run. Each await after line 158 (and each post-connect SET / OID refresh) is a tick boundary on which an ECONNRESET delivered by the socket emits 'error' on the connection. If that happens before the abstract pool's create callback reaches connection.queryType = 'read', the handler routes through this.pool.destroy(connection), which dereferences this.pool[undefined] and crashes.
main (v7)
The structural race is the same. v7 replaced the per-connection queryType property with a WeakMap<object, 'read' | 'write'> and an explicit throw, but the timing of registration is unchanged:
packages/core/src/abstract-dialect/replication-pool.ts:
this.read = new Pool({
create: async () => {
const nextRead = reads++ % readConfig.length;
const connection = await connect(readConfig[nextRead]);
owningPools.set(connection, 'read'); // line 117
return connection;
},
// ...
});
// ...
async destroy(client: Connection): Promise<void> {
const connectionType = owningPools.get(client);
if (!connectionType) {
throw new Error('Unable to determine to which pool the connection belongs');
}
await this.getPool(connectionType).destroy(client);
}packages/postgres/src/connection-manager.ts:
// Don't let a Postgres restart (or error) to take down the whole app
connection.on('error', (error: any) => { // line 201
connection._invalid = true;
debug(`connection error ${error.code || error.message}`);
void this.sequelize.pool.destroy(connection); // line 204
});
// post-connect SET queries, refreshOidMap, ...PR #18218 looks like the correct fix — register the connection in owningPools first, then run the error-prone post-connect setup.
Observed stack (v6.37.1, dialect=postgres, replication enabled)
TypeError: Cannot read properties of undefined (reading 'destroy')
at Object.destroy (/picnic/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:118:41)
at Client.<anonymous> (/picnic/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:161:17)
at Client.emit (node:events:519:28)
at Client._handleErrorEvent (/picnic/node_modules/pg/lib/client.js:340:10)
at Connection.<anonymous> (/picnic/node_modules/pg/lib/client.js:149:16)
at Connection.emit (node:events:519:28)
at Socket.<anonymous> (/picnic/node_modules/pg/lib/connection.js:62:12)
at Socket.emit (node:events:519:28)
at TCP.<anonymous> (node:net:346:12)
The triggering socket error was write ECONNRESET mid-COMMIT (the COMMIT failure rejected that transaction normally; the crash came from the same connection's on('error') handler firing asynchronously).
Expected behavior
pool.destroy(connection) should not crash when called on a connection whose ownership hasn't been registered yet. Either:
- Register ownership before the connection becomes externally addressable (the approach in PR fix: register new pool connections before they can be destroyed #18218), or
- Make
destroydefensive — on unknown ownership, fall back to destroying from both sub-pools.sequelize-pool7.1.0'sPool.destroyfilters by identity and short-circuits with_ensureMinimum()when the resource isn't owned, so the non-owning sub-pool no-ops.
We've implemented the second approach as a patch for 6.37.8 that we're applying during yarn install.
Environment
- Sequelize: observed on 6.37.1.
- Node.js: 22.x
- Database: PostgreSQL 15 (AlloyDB), replication enabled (
replication: { read: [...], write: ... }) - Connector:
pg8.13.1 - TypeScript: 5.9
Related
- Cannot read property 'destroy' of undefined #9242 — open since 2018, same symptom against v4. We believe this issue describes the same race.
- fix: register new pool connections before they can be destroyed #18218 — open PR proposing the fix on
main(but does not cover v6). - Pooling Race Condition with Replication v4 #11139 — historical "Pooling Race Condition with Replication v4" (closed).
Activity