Skip to content

Destroying a copy read stream frees the connection - #1306

Merged
porsager merged 2 commits into
porsager:masterfrom
efeesrefinal:fix/copy-read-destroy
Nov 5, 2026
Merged

porsager merged 2 commits into
porsager:masterfrom
efeesrefinal:fix/copy-read-destroy

Conversation

@efeesrefinal

@efeesrefinal efeesrefinal commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Destroying the stream from copy ... to stdout hangs the connection for good. After destroy(), push() returns false and _read is never called again, so CopyData pauses the frames and the socket and nothing resumes them. The query behind it never runs, and in a pool the connection is lost. It happens with readable.destroy(), breaking out of for await, or a pipeline whose destination fails, such as a client disconnecting during an export.

The stream now has a destroy that resumes reading, so the rest of the copy is read and dropped. The query is not canceled, so the connection is free once the server has sent the rest, and in a transaction the next query and the commit still succeed.

Test: added Destroying a copy read stream frees the connection to tests/copy.js. It times out on master and passes with the fix. On PostgreSQL 15 and Node 22 all 15 tests in copy.js pass, as do the unit tests and simulate.js. I did not run the rest of the integration suite for this change.

@porsager

porsager commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Thanks Efe, great find.

cancel(item.query) doesn’t send a cancel here though. The copy query is already settled once it resolved with the stream, so cancel() takes the quiet branch and returns. What frees the connection is the resume(), which reads the rest and drops it: a destroyed 5 GB export takes 9.1 s to free the connection against 7.8 s to read it in full, and in a transaction the next query still succeeds, so it isn’t rolled back.
I think draining is actually the right behaviour, as a real cancel could land after the server finished and cancel the next query. Could you drop the cancel line and describe it as draining (in the PR and a changelog entry)?

@efeesrefinal

Copy link
Copy Markdown
Contributor Author

Thanks, you're right, it only drains. I dropped the cancel line and added a changelog entry, and the PR text now describes draining. On PostgreSQL 15, in a transaction, the next query and the commit both succeed after a destroyed copy. All 15 tests in copy.js, the unit tests and simulate.js pass.

@porsager

porsager commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Nice - thank you

@porsager
porsager merged commit 875edc3 into porsager:master Nov 5, 2026
108 of 111 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants