Files
PaperClipAI/patches/postgres@3.4.9.patch
T
627e1be76d fix(db): give each database address time for a retransmitted SYN (#23784)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server reads and writes all state through one postgres.js pool
in `packages/db`.
> - Sentry recorded a production query failure. Every address of the
database host failed to connect: `connect ETIMEDOUT` on three IPv4
addresses and `ENETUNREACH` on three IPv6 addresses.
> - Node tries the addresses of a host name in turn ("happy eyeballs").
It gives each address except the last only 250 ms. The last address was
IPv6 and this host has no IPv6 route, so it failed at once.
> - Thus the connection failed after about 750 ms. One dropped SYN was
sufficient, because Linux sends the first SYN again only after 1 s. The
30 s `connect_timeout` of postgres.js did not apply.
> - This pull request gives each address 2 s by default, so a
retransmitted SYN can get an answer.
> - The benefit is that a short network stall to the database no longer
fails queries.

## Linked Issues or Issue Description

No public GitHub issue exists. This is a bug report.

**What happened?**

A server query failed with `Failed query: select ... from "companies"
...`. The cause was an `AggregateError` with code `ETIMEDOUT`. Its
errors were `ETIMEDOUT`, `ENETUNREACH`, `ETIMEDOUT`, `ENETUNREACH`,
`ETIMEDOUT`, `ENETUNREACH`. Each `ETIMEDOUT` came from Node's
per-address attempt timer (`internalConnectMultipleTimeout`), not from
postgres.js.

**Steps to reproduce**

1. Use a database host name that resolves to IPv4 addresses and IPv6
addresses, on a machine without an IPv6 route.
2. Make the IPv4 addresses drop SYN packets for less than one second.
3. Run a query that opens a new pooled connection.

**Expected behavior**

The connection waits for a retransmitted SYN. It fails only after
`connect_timeout`.

**Actual behavior**

The connection fails after about 750 ms with `AggregateError`
`ETIMEDOUT`.

## What Changed

- `patches/postgres@3.4.9.patch`: postgres.js now calls
`socket.connect({ port, host, autoSelectFamilyAttemptTimeout })` when
the new `auto_select_family_attempt_timeout` option is set. Without the
option, the call is the same as before. The change is in both the ESM
and CJS builds.
- `packages/db/src/client.ts`: new `connectAttemptTimeoutMs` client
option and `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` variable.
`resolveDatabaseClientOptions` sets a default of 2000 ms, so all pools
from `createDb` use it. `client.ts` was already longer than 1,000 lines.
This change adds the option next to the other driver options in that
file, because they share one parser and one mapping.
- `packages/db/src/postgres-connect-attempt-timeout.test.ts`: new
regression test. It examines the arguments that the patched driver gives
to `net.Socket.prototype.connect`.
- `packages/db/src/client-options.test.ts`: tests for the new variable,
its validation, the mapping and the default.
- `docs/deploy/database.md` and `doc/DATABASE.md`: document the new
variable.
- I did not commit `pnpm-lock.yaml`. The patch hash changes, and the
lockfile policy in `doc/ci-workflows.md` lets CI and the refresh
workflow update it.

## Verification

- Red, then green: `cd packages/db && npx vitest run
src/postgres-connect-attempt-timeout.test.ts`. Before the fix, both
tests failed. The driver called `connect(1, "127.0.0.1")` with no
options. After the fix, both tests pass.
- Focused: `npx vitest run src/postgres-connect-attempt-timeout.test.ts
src/client-options.test.ts src/postgres-connection-recovery.test.ts
src/client-disconnect-replay.test.ts src/client.test.ts
src/postgres-receive-buffer.test.ts`. Result: 6 files, 48 tests pass.
Some of these tests open real connections through the patched driver.
- `pnpm exec tsc --noEmit -p packages/db` passes.
- `pnpm verify` exits 2, because the postgres patch is a global CI
input. Required CI supplies the broad coverage.
- Manual reproduction on Node v24.23.0. A script overrides `dns.lookup`
to give the production address shape: three loopback IPv4 listeners with
full accept queues, which drop SYNs, and three unroutable IPv6
addresses. The listeners start to accept after 600 ms.
- Before: `AggregateError code=ETIMEDOUT after 764ms
inner=ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH,ETIMEDOUT,ENETUNREACH`.
This is the same as the production error.
- After, with the 2000 ms default: the listener accepted the client's
retransmitted SYN at 1.035 s, and the TCP connection opened. The stub
was not a Postgres server, so the query then stopped at the test's 3 s
`connect_timeout`.

## Risks

- Low risk. The option changes only how long Node waits for one address
before it tries the next one. `connect_timeout` still bounds the whole
attempt.
- If an IPv6 address comes first and drops packets without an error,
each new connection can wait up to 2 s before it tries IPv4, not 250 ms.
Operators can set `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` lower.
- Unix-socket connections (`path`) and custom `socket` factories do not
change.
- The patch hash of `postgres@3.4.9` changes. CI resolves the lockfile
for this run, and the refresh workflow commits the new lockfile after
merge.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit and test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:08:46 -08:00

311 lines
11 KiB
Diff

diff --git a/cjs/src/connection.js b/cjs/src/connection.js
index 07f6716702ac888215c86ad6e0071aaf55ae519c..3ecac096b4d757364d4a9b33add6ded4eecbd80f 100644
--- a/cjs/src/connection.js
+++ b/cjs/src/connection.js
@@ -173,8 +173,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return write(toBuffer(q))
&& !q.describeFirst
&& !q.cursorFn
- && sent.length < max_pipeline
&& (!q.options.onexecute || q.options.onexecute(connection))
+ && sent.length < max_pipeline
} catch (error) {
sent.length === 0 && write(Sync)
errored(error)
@@ -330,6 +330,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
}
+
+ incoming.length === 0 && (incoming = Buffer.alloc(0))
}
async function connect() {
@@ -351,7 +353,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return socket.connect(options.path)
socket.ssl = ssl
- socket.connect(port[hostIndex], host[hostIndex])
+ socket.connect({
+ port: port[hostIndex],
+ host: host[hostIndex],
+ ...(options.auto_select_family_attempt_timeout
+ ? { autoSelectFamilyAttemptTimeout: options.auto_select_family_attempt_timeout }
+ : {})
+ })
socket.host = host[hostIndex]
socket.port = port[hostIndex]
@@ -438,6 +446,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
clearImmediate(nextWriteTimer)
+ chunk = nextWriteTimer = null
socket.removeListener('data', data)
socket.removeListener('connect', connected)
idleTimer.cancel()
@@ -451,6 +460,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return reconnect()
!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+ query = results = errorResponse = null
+ result = new Result()
+ rows = 0
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
diff --git a/cjs/src/index.js b/cjs/src/index.js
index f09c61c7e998f411560b95c9a8e1ed6a97972c11..5ae05848b627d4e7b849eb093a3d9ceb7f922b6d 100644
--- a/cjs/src/index.js
+++ b/cjs/src/index.js
@@ -216,8 +216,19 @@ function Postgres(a, b) {
: move(c, reserved)
c.reserved.release = true
+ let closedError
+ c.onclose = error => {
+ closedError = error
+ while (queue.length)
+ queue.shift().reject(error)
+ }
+
const sql = Sql(handler)
sql.release = () => {
+ if (closedError)
+ return
+ closedError = Errors.connection('CONNECTION_RELEASED', options)
+ c.onclose = null
c.reserved = null
onopen(c)
}
@@ -225,6 +236,8 @@ function Postgres(a, b) {
return sql
function handler(q) {
+ if (closedError)
+ return q.reject(closedError)
c.queue === full
? queue.push(q)
: c.execute(q) || move(c, full)
@@ -236,13 +249,19 @@ function Postgres(a, b) {
const queries = Queue()
let savepoints = 0
, connection
+ , closedError
, prepare = null
try {
await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
return await Promise.race([
scope(connection, fn),
- new Promise((_, reject) => connection.onclose = reject)
+ new Promise((_, reject) => connection.onclose = error => {
+ closedError = error
+ while (queries.length)
+ queries.shift().reject(error)
+ reject(error)
+ })
])
} catch (error) {
throw error
@@ -290,6 +309,8 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
+ if (closedError)
+ return q.reject(closedError)
c.queue === full
? queries.push(q)
: c.execute(q) || move(c, full)
@@ -493,6 +514,7 @@ function parseOptions(a, b) {
onclose : o.onclose,
onparameter : o.onparameter,
socket : o.socket,
+ auto_select_family_attempt_timeout: o.auto_select_family_attempt_timeout,
transform : parseTransform(o.transform || { undefined: undefined }),
parameters : {},
shared : { retries: 0, typeArrayMap: {} },
diff --git a/cjs/src/queue.js b/cjs/src/queue.js
index 8438f5da92cf7637d98a33491d75c75b1c817c25..1c9a330fa173ecae84219055368cf630feadbda2 100644
--- a/cjs/src/queue.js
+++ b/cjs/src/queue.js
@@ -9,10 +9,10 @@ function Queue(initial = []) {
return xs.length - index
},
remove: (x) => {
- const index = xs.indexOf(x)
- return index === -1
+ const at = xs.indexOf(x, index)
+ return at === -1
? null
- : (xs.splice(index, 1), x)
+ : (xs.splice(at, 1), x)
},
push: (x) => (xs.push(x), x),
shift: () => {
@@ -21,6 +21,9 @@ function Queue(initial = []) {
if (index === xs.length) {
index = 0
xs = []
+ } else if (index > 1024 && index * 2 > xs.length) {
+ xs = xs.slice(index)
+ index = 0
} else {
xs[index - 1] = undefined
}
diff --git a/src/connection.js b/src/connection.js
index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..a5057f0d1b03898b4c22b8711498871f200cce69 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -173,8 +173,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return write(toBuffer(q))
&& !q.describeFirst
&& !q.cursorFn
- && sent.length < max_pipeline
&& (!q.options.onexecute || q.options.onexecute(connection))
+ && sent.length < max_pipeline
} catch (error) {
sent.length === 0 && write(Sync)
errored(error)
@@ -330,6 +330,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
}
+
+ incoming.length === 0 && (incoming = Buffer.alloc(0))
}
async function connect() {
@@ -351,7 +353,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return socket.connect(options.path)
socket.ssl = ssl
- socket.connect(port[hostIndex], host[hostIndex])
+ socket.connect({
+ port: port[hostIndex],
+ host: host[hostIndex],
+ ...(options.auto_select_family_attempt_timeout
+ ? { autoSelectFamilyAttemptTimeout: options.auto_select_family_attempt_timeout }
+ : {})
+ })
socket.host = host[hostIndex]
socket.port = port[hostIndex]
@@ -438,6 +446,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
clearImmediate(nextWriteTimer)
+ chunk = nextWriteTimer = null
socket.removeListener('data', data)
socket.removeListener('connect', connected)
idleTimer.cancel()
@@ -451,6 +460,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return reconnect()
!hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+ query = results = errorResponse = null
+ result = new Result()
+ rows = 0
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
diff --git a/src/index.js b/src/index.js
index c7fba3dace20173f4cb13f3f138bb6d213b43683..59fcbc0d44e709e86abdf34e47ad6bc98a9e6974 100644
--- a/src/index.js
+++ b/src/index.js
@@ -216,8 +216,19 @@ function Postgres(a, b) {
: move(c, reserved)
c.reserved.release = true
+ let closedError
+ c.onclose = error => {
+ closedError = error
+ while (queue.length)
+ queue.shift().reject(error)
+ }
+
const sql = Sql(handler)
sql.release = () => {
+ if (closedError)
+ return
+ closedError = Errors.connection('CONNECTION_RELEASED', options)
+ c.onclose = null
c.reserved = null
onopen(c)
}
@@ -225,6 +236,8 @@ function Postgres(a, b) {
return sql
function handler(q) {
+ if (closedError)
+ return q.reject(closedError)
c.queue === full
? queue.push(q)
: c.execute(q) || move(c, full)
@@ -236,13 +249,19 @@ function Postgres(a, b) {
const queries = Queue()
let savepoints = 0
, connection
+ , closedError
, prepare = null
try {
await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
return await Promise.race([
scope(connection, fn),
- new Promise((_, reject) => connection.onclose = reject)
+ new Promise((_, reject) => connection.onclose = error => {
+ closedError = error
+ while (queries.length)
+ queries.shift().reject(error)
+ reject(error)
+ })
])
} catch (error) {
throw error
@@ -290,6 +309,8 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
+ if (closedError)
+ return q.reject(closedError)
c.queue === full
? queries.push(q)
: c.execute(q) || move(c, full)
@@ -493,6 +514,7 @@ function parseOptions(a, b) {
onclose : o.onclose,
onparameter : o.onparameter,
socket : o.socket,
+ auto_select_family_attempt_timeout: o.auto_select_family_attempt_timeout,
transform : parseTransform(o.transform || { undefined: undefined }),
parameters : {},
shared : { retries: 0, typeArrayMap: {} },
diff --git a/src/queue.js b/src/queue.js
index c4ef97164f057db99dce1b9af3401dbb1af37e31..46e7ade55c0a3250137a21117c03ce9166b40bc2 100644
--- a/src/queue.js
+++ b/src/queue.js
@@ -9,10 +9,10 @@ function Queue(initial = []) {
return xs.length - index
},
remove: (x) => {
- const index = xs.indexOf(x)
- return index === -1
+ const at = xs.indexOf(x, index)
+ return at === -1
? null
- : (xs.splice(index, 1), x)
+ : (xs.splice(at, 1), x)
},
push: (x) => (xs.push(x), x),
shift: () => {
@@ -21,6 +21,9 @@ function Queue(initial = []) {
if (index === xs.length) {
index = 0
xs = []
+ } else if (index > 1024 && index * 2 > xs.length) {
+ xs = xs.slice(index)
+ index = 0
} else {
xs[index - 1] = undefined
}