Skip to content

Do not read the PostgreSQL connection from the thread that cancels the read - #123693

Merged
evillique merged 4 commits into
ClickHouse:masterfrom
groeneai:postgresql-cancel-handle-on-reader-thread
Oct 8, 2026
Merged

evillique merged 4 commits into
ClickHouse:masterfrom
groeneai:postgresql-cancel-handle-on-reader-thread

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Related: #118995, #113150

TSan data race on master, Integration tests (amd_tsan, 1/6): report. The server aborted and took four tests of test_postgresql_kill_query down with it.

PostgreSQLSource::onCancel runs on the KILL / timeout thread and called conn().is_open() and conn().cancel_query(), i.e. PQstatus and PQgetCancel on the PGconn, while the pipeline thread was inside libpq on the same connection. When that read fails, pqDropConnection writes conn->sock. libpq allows one thread per PGconn; only PQcancel on a PGcancel built beforehand may run on another thread.

The PGcancel is now built by the reading thread in onStart (before the COPY starts) and published under tx_mutex with the socket duplicate. onCancel and the destructor only call PQcancel on it, so cancel_mutex is gone. The request sent to the server is the same one cancel_query sent. pqxx exposes the raw connection only through largeobject::raw_connection (protected static, also in libpqxx 8.0.2); if a public accessor in the libpqxx fork is preferred, I can do that instead.

New test test_kill_query_when_the_connection_resets_during_the_cancel: a proxy resets the data connection when the cancel request arrives, so the reader drops the connection while the cancel is in flight. On a TSan build it failed 12/15 without the fix with the CI stack pair, and passed 10/10 with it; the whole module passed 3/3 on TSan and 5/5 on debug.


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

Version info

  • Merged into: 26.10.1.1861-master (included in 26.10 and later)
  • Backported to: 26.8.43.13

groeneai and others added 2 commits October 3, 2026 12:50
…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]>
`CancelResettingProxy` decided whether a connection carries the cancel
request from the first `recv` alone, which TCP may cut short of the
8-byte packet, and the test never checked that the reset happened, so a
plain cancel without the reset also passed. Buffer the client's first 8
bytes before deciding, and assert `connection_was_reset()`.

Reword the `onCancel` comment that said the cancel is sent first "while
the connection can still address it": the cancel handle is now built in
`onStart`, so that no longer holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds: 1 finding, then 0 on the fixed head) plus my own review (5 nits over 2 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test could pass without the proxy ever resetting the connection: a split first recv or a timed-out wait would forward a plain cancel, which every assertion accepts (test.py CancelResettingProxy._pump) AGREE, fixed @ 3f57103 The proxy buffers the first 8 bytes before matching the cancel request, and the test asserts that the reset happened. Mutating the cancel code makes the test fail on that assertion.
2 💡 onCancel no longer checks is_open(), so it sends the cancel even after the reader dropped the connection AGREE, noted That check is PQstatus on the connection from the cancelling thread, i.e. the race itself. The server ignores a cancel for a backend that is gone.
3 💡 The raw connection is reached through the protected static pqxx::largeobject::raw_connection AGREE, noted Present in libpqxx 7.10.0 and 8.0.2, no largeobject is constructed, the build has no deprecation warning. A public accessor in the libpqxx fork is offered in the description.
4 💡 The onCancel comment gave "while the connection can still address it" as the reason to cancel before shutdown, which the pre-built handle removes AGREE, fixed @ 3f57103 Comment reworded; the order is unchanged.
5 💡 A NULL PQgetCancel after BEGIN throws without marking the connection broken AGREE, noted Same as the existing socket-duplication failure next to it. PQgetCancel returns NULL only for an invalid socket or OOM, and a dead pooled connection is replaced on its next use.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261003-133500

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_kill_query_when_the_connection_resets_during_the_cancel on a TSan build without the fix: 12/15 runs report the CI race (pqDropConnection fe-connect.c:535 vs PQgetCancel fe-cancel.c:377 from PostgreSQLSource::onCancel). The test asserts that the proxy reset the connection, so a green run is never a run without the reset.
b Root cause explained? onCancel read the PGconn (PQstatus, PQgetCancel) on the cancelling thread while the reading thread was inside libpq on it; a failed read makes libpq write conn->sock. libpq allows that only for PQcancel on a PGcancel built beforehand.
c Fix matches root cause? Yes. The PGcancel is built on the reading thread before the COPY and onCancel only calls PQcancel on it; no lock, suppression or annotation.
d Test intent preserved / new tests added? New integration test; existing tests unchanged and green (module 3/3 on TSan, 5/5 on debug).
e Both directions demonstrated? Yes. TSan without the fix: 12/15 fail. TSan with the fix: 10/10 pass, 0 reports.
f Fix is general across code paths? Yes. Both branches of onCancel (own and borrowed transaction), all its callers (KILL, max_execution_time, partial result) and the destructor use the same handle; PostgreSQLSource is the only cross-thread cancel of a PostgreSQL connection in src/.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for data types. Own-connection readers (postgresql(), PostgreSQL engine, dictionary) and the MaterializedPostgreSQL snapshot load were run: all pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the server gets the same cancel request.
i Invariants and contracts preserved? No thread but the reader touches the PGconn during the read. The handle is published with the transaction under tx_mutex and lives until the destructor, which cannot overlap onCancel. A missing handle fails the read start, like the existing socket-duplication failure.

Session id: cron:clickhouse-impl-slot-5:20261003-132100

@groeneai
groeneai requested review from evillique and kssenii October 3, 2026 14:00
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8ba928]

Summary: ✅


AI Review

Summary

This PR fixes the PostgreSQL cancellation race by creating the PGcancel handle on the reader thread before COPY starts, publishing only that handle and the duplicated socket to onCancel, and avoiding further reads from the shared PGconn on the cancelling thread. It also adds a targeted integration test that forces the data connection to reset while the cancel request is in flight and now positively asserts that the reset really happened. I reviewed the current diff, the prior PR discussion, and the current all-green CI state, and I did not find a remaining correctness, lifetime, or regression-testing issue on the current head.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit a8ba928.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 40/43 (93.02%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-postgresql PostgreSQL-specific integration (table engine/function, logical replication bridge). labels Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a8ba928cb7eed66bfb15a83631e8a6f3f1ccdc3e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

Picks up ClickHouse#123679, which fixes the 04896_orfill_merge_group_by_overflow_any
failure in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel).
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3f57103

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on master and on 97 PRs in 24h; the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04896_orfill_merge_group_by_overflow_any not from this PR: the overflow any two keys arm counts 2000 rows instead of 1000 because each parallel replica applies max_rows_to_group_by to its own hash table; 16 PRs in 24h #123679 (mine, merged after this run was built), merged master @ cfee6b1
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04819_dynamic_aggregate_function_state_version not from this PR: the fetch with output_format_native_encode_types_in_binary_format = 1 fails because the replica writes binary type names that the initiator reads as text (Unknown codec family code: 0); 21 PRs in 24h #123649 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04103_user_network_bandwidth_throttler not from this PR: when a remote replica reads the part it runs as user default, whose bandwidth throttler is not the test user's, so the initiator sees no throttling; 5 PRs in 24h #123734 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 03100_lwu_41_bytes_limits timeout under one randomized-settings draw: the runner's rerun with the same settings timed out again, while 56 of 56 reruns without randomization passed; first failure in 30 days a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 109 PRs in 24h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521, #123679, #123649, #123734 and the fix tasks above (a fix task is created)

None of these touches the PostgreSQL source this PR changes, and test_postgresql_kill_query passed. All 160 checks completed; CIDB has no other FAIL or ERROR on this head. CI restarts on the master merge.

Session id: cron:our-pr-ci-monitor:20261003-183140

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 03100_lwu_41_bytes_limits (arm_binary, ParallelReplicas timeout) created: #123765

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cfee6b1

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails on every master commit of the last 12 hours and on 150 PRs in 24h #123738 (external, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04316_reader_executor_basic not from this PR: when the coordinator hands every mark to the remote replicas, the initiator's query id logs no using ReaderExecutor line, so the activation check prints 0; 7 PRs in 24h #123709 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05213_timeseries_metric_families_target not from this PR: a TimeSeries table function run on a parallel replica looks up its unqualified table argument in default; 67 PRs in 24h #123763 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant not from this PR: under a Replicated database the view reads the same-named table instead of the alias declared inside its WITH expression; 161 PRs in 24h #123774 (mine, open)
Mergeable Check, PR rollups, red only because of the rows above #123738, #123709, #123763, #123774

None of these touches the PostgreSQL source this PR changes, and Integration tests (amd_tsan, targeted) passed. All 160 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-233424

@evillique

Copy link
Copy Markdown
Member

@groeneai could you merge the fresh master to resolve the CI issues?

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged the current master in a8ba928. The diff against master is unchanged (the same three files), and PostgreSQLSource.cpp compiles against the new postgres REL_18_6 pin from master.

@evillique
evillique added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit 56ffbc1 Oct 8, 2026
152 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 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 #123693 to 26.8: Do not read the PostgreSQL connection from the thread that cancels the read
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-postgresql PostgreSQL-specific integration (table engine/function, logical replication bridge). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants