Skip to content

COPY TO STDOUT through BeginRawBinaryCopy or BeginTextExport: an error after the last row makes the dispose wait until Command Timeout and break the connection #6704

Description

@Brar

After CopyDone, the server can still end a COPY ... TO STDOUT with an error instead of CommandComplete: an AFTER trigger such as the immediate foreign key check of COPY (INSERT ... RETURNING ...) TO STDOUT, a deferred constraint at commit, or a statement_timeout or a cancellation while those triggers run (postgres copyto.c:1282, execMain.c:452-454, postgres.c:1308-1321). An error in a second statement of the command comes after the COPY's CommandComplete, instead of ReadyForQuery.

NpgsqlRawCopyStream, which BeginTextExport reads through, cleans up when the read of the next message fails (NpgsqlRawCopyStream.cs:278-292), but it reads CommandComplete and ReadyForQuery after CopyDone outside that block (:299-302). That read throws the error, but the stream stays Ready, so:

  • its dispose waits for another ReadyForQuery (:419-425) until Command Timeout, swallows the timeout and leaves the connection broken; with Command Timeout=0 it waits forever (shown with a mock);
  • a later read waits for another message the same way, and so does closing the connection without disposing the stream (NpgsqlConnector.cs:2163-2206), which then throws "Connection is not open";
  • because that timeout breaks the connection without a cancellation, the data source's pool is cleared too, unless Cancellation Timeout is -1 (NpgsqlConnector.cs:2307-2313).
CREATE TEMP TABLE parent (id int PRIMARY KEY);
CREATE TEMP TABLE child (id int REFERENCES parent);
BEGIN;
COPY (INSERT INTO child VALUES (1) RETURNING id) TO STDOUT;  -- BeginTextExport; for BeginRawBinaryCopy add (FORMAT BINARY)

On PostgreSQL 18.6 with Command Timeout=5, the read threw 23503 at once; the dispose then waited 5 s, the connection was broken, and the pool's idle connection was gone. The same with a deferred constraint, a plain AFTER ROW trigger and a failing second statement, for BeginRawBinaryCopy and BeginTextExport alike. The binary exporter mishandles the same errors too, with different results (#6703). The same code is on the 8.0, 9.0 and 10.0 hotfix branches (read, not run).

Activity

  1. added this to the 11.0.0 milestone on Oct 25, 2026
  2. self-assigned this
    on Oct 25, 2026
  3. added theissue type on Oct 25, 2026
  4. modified the milestones: 11.0.0, 12.0.0 on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions