Skip to content

Make a PostgreSQL read cancellable while it is streaming - #118995

Merged
evillique merged 11 commits into
ClickHouse:masterfrom
evillique:postgres-cancel-streaming-read
Sep 28, 2026
Merged

evillique merged 11 commits into
ClickHouse:masterfrom
evillique:postgres-cancel-streaming-read

Conversation

@evillique

@evillique evillique commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Closes: #114080
Related: #83626

PostgreSQLSource::onCancel only cancelled a read that had not started yet: once the COPY was streaming it just set a flag that generate checks between rows, so a query parked in libpq's untimed socket wait never saw the cancel. It now asks the server to cancel and then shuts the connection down, so the read wakes whether or not the server obliges.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed KILL QUERY and max_execution_time having no effect on a query reading from PostgreSQL when the remote host stops sending data, and DROP of a refreshable materialized view whose refresh reads from PostgreSQL hanging for the same reason.


Workflow [PR]
Sync PR [sync-upstream/pr/118995]

Version info

  • Merged into: 26.10.1.926-master (included in 26.10 and later)
  • Backported to: 26.8.43.10

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8abf445]

Summary: ✅


AI Review

Summary

This PR makes PostgreSQLSource wake a stalled PostgreSQL COPY read by duplicating the socket and tearing the transport down on cancellation, and it adds integration coverage for KILL QUERY, max_execution_time, and refreshable-view DROP. The direction is right, but the current implementation still leaves one blocker in the owned-connection cancel path and one remaining completeness gap for the transaction-backed snapshot path, so I would not merge it yet.

Findings

❌ Blockers

  • [src/Processors/Sources/PostgreSQLSource.cpp:311] The promised local interrupt is now gated on cancel_query(): onCancel() calls finalize(tx_snapshot, nullptr) before shutdown(fd). If that separate cancel connection blackholes instead of failing fast, the blocked read_row() never gets its guaranteed local wakeup and KILL QUERY / max_execution_time can still hang on network I/O. Suggested fix: make the socket shutdown unconditional and immediate, and run the server-side cancel only as a bounded or non-blocking best-effort step.

⚠️ Majors

  • [src/Processors/Sources/PostgreSQLSource.cpp:119, src/Processors/Sources/PostgreSQLSource.cpp:321, src/Storages/PostgreSQL/PostgreSQLReplicationHandler.cpp:763] The new "streaming reads are cancellable" invariant still only holds for sources that create their own transaction. PostgreSQLTransactionSource in loadFromSnapshot() enters the same read_row() loop with no duplicated socket, and once started is true onCancel() only flips stop_requested; any executor-side cancellation of that snapshot read still leaves libpq parked on a silent peer. Suggested fix: initialize an interrupt fd for the transaction-backed constructor too, or explicitly reject/contain cancellation for that mode instead of reusing the generic source implementation.
Tests
  • ⚠️ Add one focused regression where the separate cancel connection blackholes rather than returning connect() failure immediately, so the test proves onCancel() reaches the local socket interrupt without waiting for the cancel round-trip.

LLVM Coverage Report

Measured on commit 8abf445.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 45/50 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-postgresql PostgreSQL-specific integration (table engine/function, logical replication bridge). label Sep 9, 2026

/// The connection is ours to discard, so a read parked in the client library with no deadline is
/// woken by taking the transport away. `shutdown` keeps the descriptor valid for that thread.
if (connection_holder && fd >= 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onCancel() only reaches the new shutdown() path when connection_holder is set, but PostgreSQLTransactionSource is instantiated with a pre-existing tx and connection_holder == nullptr in PostgreSQLReplicationHandler::loadFromSnapshot(). Once that snapshot COPY is already streaming, cancellation therefore still falls back to the old behavior: stop_requested flips, but read_row() stays blocked in libpq if PostgreSQL stops sending data.

Can we make the duplicate-fd interrupt work for the tx-backed constructor as well, or otherwise prove that the snapshot-load path is intentionally non-cancellable?

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8abf44508 with master a61a24c6a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

11 object files changed (+27.62 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Sources/PostgreSQLSource.cpp.o 138.27 KiB 158.04 KiB +19.76 KiB (+14.29%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

10 translation units recompiled, 30 s compile time in total, 10 of them have a recent master baseline.

Job report

@evillique
evillique force-pushed the postgres-cancel-streaming-read branch from 64a421b to 291e5de Compare September 10, 2026 15:04
return;

if (tx_snapshot->conn().is_open())
finalize(tx_snapshot, nullptr);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shutdown(fd) is the only guaranteed local wakeup for the blocked read_row(), but this path now waits for cancel_query() first. That call is still a blocking network round-trip in libpqxx/libpq, so if the separate cancel connection blackholes instead of failing fast we never reach the socket shutdown and KILL QUERY / max_execution_time are back to waiting on the network instead of interrupting the stalled read locally.

Can we make the transport interrupt unconditional and immediate, and keep the server-side cancel as a bounded/non-blocking best-effort step instead?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional: after shutdown libpq drops the socket and PQgetCancel returns NULL, so the cancel must go first. Worst case is the SYN-retry window (~2 min) on an unreachable host, same as the pre-PR destructor.

@thevar1able thevar1able self-assigned this Sep 25, 2026
@evillique
evillique added this pull request to the merge queue Sep 28, 2026
Merged via the queue into ClickHouse:master with commit 614ee95 Sep 28, 2026
174 checks passed
@evillique
evillique deleted the postgres-cancel-streaming-read branch September 28, 2026 16:21
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
alexey-milovidov added a commit that referenced this pull request Oct 2, 2026
…nect

Conflicts resolved:
- `ParserCopyQuery.cpp` / `ASTCopyQuery.h`: master (#119376) reworked the `COPY` option parsing
  with a parser that throws; this branch has its own non-throwing parser that records the reason in
  `unsupported_option` (so the handler answers with an `ErrorResponse` and keeps the connection). Kept
  the branch's parser and ported master's features into it: `HEADER` (now honoured through the
  `*WithNames` formats via `getFormatName`) and `QUOTE` (accepted when it is the CSV default).
- `PostgreSQLHandler.cpp`: kept the branch's staged, cancellable `COPY FROM` reader instead of master's
  `ReadBufferFromCopyData`, and ported master's `pinCopyFormatSettings` (the CSV NULL marker is still
  applied afterwards from `csv_null_marker`) and the header settings. Master's handshake-timeout and
  startup-size changes merged cleanly.
- `PostgreSQLSource.cpp`: took master's (#118995) cancellation, which interrupts a streaming read via a
  duplicated socket and arbitrates the clean finish and the interrupt through `teardown_started`; it
  supersedes the branch's narrower change to the same code.
- Tests: master's `COPY` option tests now expect this branch's error messages (and the rejection of
  the PostgreSQL binary format), and the branch's test that `HEADER` is rejected now checks its output.
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 8, 2026
…e read

`PostgreSQLSource::onCancel` runs on the KILL / timeout / partial-result
thread. It called `conn().is_open()` (`PQstatus`) and `cancel_query()`,
which builds its request with `PQgetCancel(m_conn)` and so reads
`conn->sock`, `raddr`, the backend pid and the cancel key, while the
pipeline thread was inside libpq on the same `PGconn` (`PQexec` of the
COPY in `stream_from`, or `PQgetCopyData` in `read_row`). When that read
fails, `pqReadData` drops the connection and writes `conn->sock`.

libpq allows one thread per `PGconn`. Only `PQcancel` on a `PGcancel`
built beforehand may run on another thread: it reads only that copy.
Since ClickHouse#118995 shuts the socket down right after the cancel, a failed
read is the normal outcome of a cancel. TSan saw the pair on master
(`Integration tests (amd_tsan, 1/6)`, ea9f598) when the reader's
`recv` returned ECONNRESET, which is not an acquire, so nothing ordered
it after the cancelling thread's read.

Build the `PGcancel` on the reading thread in `onStart`, after the
transaction exists and before the COPY starts, and publish it under
`tx_mutex` with the socket duplicate. `onCancel` and the destructor only
call `PQcancel` on it. This is `cancel_query` split in two, so the
request and the transport do not change. `cancel_mutex` is removed:
`PQcancel` does not write the `PGcancel`, and `onCancel` cannot overlap
the destructor. pqxx hands out the raw `PGconn` only through the
protected static `largeobject::raw_connection` (also present in libpqxx
8.0.2), reached through a derived struct. A NULL from `PQgetCancel`
(invalid socket or OOM) refuses the read before it starts, like a failed
socket duplication.

The new test puts a proxy between the source and PostgreSQL that resets
the data connection when the cancel request arrives, before forwarding
it. On a TSan build it reported the CI race in 8 of 10 runs without this
change and in none with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 20, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #118995 to 26.8: Make a PostgreSQL read cancellable while it is streaming
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-postgresql PostgreSQL-specific integration (table engine/function, logical replication bridge). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cancellation of a PostgreSQL read is lost if the cancel reaches the backend before the COPY starts executing

5 participants