Repository navigation
Make a PostgreSQL read cancellable while it is streaming - #118995
Conversation
|
Workflow [PR], commit [8abf445] Summary: ✅
AI ReviewSummaryThis PR makes Findings❌ Blockers
Tests
LLVM Coverage ReportMeasured on commit 8abf445.
Changed lines: Changed C/C++ lines covered: 45/50 (90.00%) · Uncovered code |
|
|
||
| /// 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) |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+27.62 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units10 translation units recompiled, 30 s compile time in total, 10 of them have a recent master baseline. |
64a421b to
291e5de
Compare
| return; | ||
|
|
||
| if (tx_snapshot->conn().is_open()) | ||
| finalize(tx_snapshot, nullptr); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
…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.
…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]>
Backport #118995 to 26.8: Make a PostgreSQL read cancellable while it is streaming
Closes: #114080
Related: #83626
PostgreSQLSource::onCancelonly cancelled a read that had not started yet: once theCOPYwas streaming it just set a flag thatgeneratechecks 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
KILL QUERYandmax_execution_timehaving no effect on a query reading from PostgreSQL when the remote host stops sending data, andDROPof a refreshable materialized view whose refresh reads from PostgreSQL hanging for the same reason.Workflow [PR]
Sync PR [sync-upstream/pr/118995]
Version info
26.10.1.926-master(included in26.10and later)26.8.43.10