Skip to content

COPY API: problems after an error, a cancellation or the end of the operation #6705

Open

Description

@Brar

While looking at how the COPY exporters handle a server error, reviews turned up the problems below. Items 1–5 are on main, item 6 only on the 8.0, 9.0 and 10.0 branches; line numbers refer to main at 75a8b40. Read in the code, items 1–5 are on the 10.0 branch too, and on the 9.0 and 8.0 branches except for item 1's failed BeginBinaryImport (its catch there doesn't dispose the importer, so nothing is logged), item 1's activity (no COPY tracing there) and item 5's text reader and writer (no Timeout there). Each
item ends with what was verified (run, or read in the code) and what is only inferred.

  1. Imports count an import that an error ended as finished. When NpgsqlBinaryImporter.Complete() throws the
    server's error, e.g. a unique violation, its catch runs the cleanup (NpgsqlBinaryImporter.cs:444-447), which logs
    "Binary COPY operation completed (2 rows transferred)" at Information level (:551), although the server rolled
    the COPY back. Later StartRow and Complete calls throw ObjectDisposedException "The COPY operation has already
    ended." (:586) without the error. Raw and text imports (BeginRawBinaryCopy with FROM STDIN,
    BeginTextImport) behave the same way. The connection itself stays usable. Possible fix: no "completed" log after
    an error, and later calls throw an InvalidOperationException with the error as the inner exception.

    Verified on PostgreSQL 18.6: a unique violation at Complete, sync and async, and for the raw and text imports an
    immediate foreign key violation after the client's CopyDone and a unique violation at the 2nd of 20000 rows.

    Two more cases of the same kind. A BeginBinaryImport that fails at the COPY response, e.g. COPY missing_table FROM STDIN (FORMAT BINARY) with 42P01, also logs "Binary COPY operation completed (0 rows transferred)": its
    catch disposes the importer (NpgsqlConnection.cs:1130-1139), CloseAsync runs the cleanup for an uninitialized
    importer (NpgsqlBinaryImporter.cs:532-541), and the cleanup logs unconditionally (:551). And a cancelled raw or
    text import (Cancel() on BeginRawBinaryCopy with FROM STDIN or on BeginTextImport) logs "COPY operation completed", although the server rolled the COPY back: the cancel's catch for the server's 57014 runs the cleanup, which logs "completed" (NpgsqlRawCopyStream.cs:357-371, :449-452).

    Verified on PostgreSQL 18.6, sync and async.

  2. A binary importer disposed without Complete after a server error stays in the Copy state. The server can end
    an import with an error while the client still writes, e.g. on a unique violation at a row. If the caller then
    disposes the importer without calling Complete(), the dispose calls Cancel, which reads the server's error and
    rethrows it because it isn't 57014 (NpgsqlBinaryImporter.cs:478-498, the check at :495). So CloseAsync never
    reaches its cleanup (:541): the connector stays in the Copy state with the importer as its current COPY
    operation, and the connection can't run another command until the importer is disposed a second time.
    NpgsqlRawCopyStream's cancel cleans up in that case (NpgsqlRawCopyStream.cs:340-375; its comment at :359 notes
    that the importer doesn't). In a using block whose body threw, the server's error from the dispose replaces the
    body's exception, and the connection stays blocked until it's closed (inferred).

    Verified by mock tests; the mechanism read in the code.

  3. NpgsqlCopyTextWriter's Dispose after Cancel throws. With using var writer = conn.BeginTextImport(...) and
    writer.Cancel(), the end of the using block throws ObjectDisposedException: StreamWriter's dispose flushes the
    raw stream, whose Flush finds the operation already ended by the cancel (NpgsqlRawCopyStream.cs:206-220,
    CheckDisposed at :462). The same after a cancel that threw the server's earlier error. The raw stream and the
    binary importer don't throw there.

    Verified by a mock test.

  4. Cancelling a raw or text export reports a timeout. For an export, NpgsqlRawCopyStream.Cancel calls
    PerformPostgresCancellation (NpgsqlRawCopyStream.cs:375), which marks the cancellation as performed but not as
    requested by the user. The read that then gets the server's 57014 turns it into NpgsqlException "Exception while
    reading from stream" with an inner TimeoutException "Timeout during reading attempt"
    (NpgsqlConnector.cs:1612-1620). So the caller can't tell its own cancellation from a timeout. The binary exporter's cancel uses
    PerformImmediateUserCancellation (NpgsqlBinaryExporter.cs:460), which should give an OperationCanceledException
    (inferred, not run).

    Verified by a mock test, and live on PostgreSQL 18.6.

  5. Some COPY members throw NullReferenceException after the operation ended.

    • NpgsqlBinaryExporter.Cancel(), CancelAsync() and the Timeout setter (NpgsqlBinaryExporter.cs:460, 465,
      48-51) after the exporter was disposed, by the caller or because the connection broke: the dispose clears
      _connector and _buf (:540, 543). NpgsqlRawCopyStream.Cancel throws ObjectDisposedException instead.
    • NpgsqlRawCopyStream.ReadTimeout and WriteTimeout (NpgsqlRawCopyStream.cs:43-52), and through them NpgsqlCopyTextWriter.Timeout and NpgsqlCopyTextReader.Timeout (:568-576, 608-616), after the stream's cleanup, which runs at its dispose, at an import's cancel and when reading the next message fails, and clears the buffers (:456-457).

    A cancellation callback on a token that fires after the export ended, e.g. token.Register(exporter.Cancel), then
    throws NullReferenceException (inferred scenario). Possible fix: ObjectDisposedException after the end, or no-op
    for Cancel.

    Verified by mock probes.

  6. 8.0, 9.0 and 10.0 with Multiplexing=true: Cancel() after a finished export makes the next command fail. After
    a binary export was read to its end (StartRow returned -1), exporter.Cancel() only cancels the read buffer's
    CancellationTokenSource, because outside StartRow no PostgreSQL cancellation is attempted
    (NpgsqlConnector.cs:2182-2183 on hotfix/10.0.4). In multiplexing mode nothing resets it, so the next multiplexed
    command fails with OperationCanceledException "Query was cancelled". Without multiplexing, or without the
    Cancel(), the next command works. main has no multiplexing any more.

    Verified on hotfix/10.0.4 with a mock test, in Debug and Release; inferred for 9.0 and 8.0 from the same code.

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