Repository navigation
Fix data race on the transaction pointer in PostgreSQLSource - #113150
alexey-milovidov merged 8 commits into
Conversation
ThreadSanitizer reports an 8-byte read/write race on PostgreSQLSource<T>::tx:
read onCancel, PostgreSQLSource.cpp:201, cancelling thread,
via ISource::cancel <- PipelineExecutor::cancel
previous write onStart, PostgreSQLSource.cpp:88, executor pool thread,
via prepare <- PipelineExecutor::initializeExecution
The two threads hold different mutexes, so nothing orders the accesses.
tx is a plain std::shared_ptr, while the started/is_completed flags declared
beside it are atomic. The guard "if (!started.load() && tx && tx->conn().is_open())"
loads a different object, so it establishes no happens-before edge with the
"tx = std::make_shared<T>(...)" store. This is onCancel's intended operating
window rather than a rare interleaving: onCancel exists precisely for the case
where onStart is still blocked in pqxx::stream_from(..., from_query, ...). With
an instrumented build the racing branch was taken on 40 of 40 cancellations.
Publish tx under a new dedicated std::mutex tx_mutex, and have onCancel take a
shared_ptr snapshot under that lock and use the snapshot with the lock released.
The snapshot copy also removes a lifetime hazard: the cancelling thread no longer
dereferences a pointer another thread may reset underneath it.
The lock must not cover either pqxx call. The transaction constructor issues
BEGIN (contrib/libpqxx/src/transaction.cxx) and stream_from issues COPY; holding
tx_mutex across the latter would make onCancel block on the lock while onStart
waits for PostgreSQL, turning the hang onCancel is meant to interrupt into a
permanent one. A deliberately mis-scoped variant was built to confirm this is
observable: it makes test_kill_query_when_postgresql_cancel_connection_fails
fail, so that suite is a real oracle for a wrong lock scope.
The lock is acquired inside a try/catch because onCancel is noexcept and
std::lock_guard can throw std::system_error, which would otherwise reach
std::terminate.
PostgreSQLSource is the only carrier among the sources: SQLiteSource never
reassigns its pointer, MySQLWithFailoverSource::onCancel touches only atomics,
RemoteSource's executor is const after construction, ReadFromDistributedPlanSource
already guards its executor with a mutex (the pattern followed here), and
MongoDBSource has no onCancel.
The unguarded read is pre-existing: it came in with the "Use atomics" change,
which turned "if (!started)" into the current guard and added the tx read while
leaving the pointer unsynchronized. PR ClickHouse#105949 only wrapped cancel_query in
try/catch.
The report itself does not reproduce locally: the branch arms every time, but
KILL QUERY arrives over a docker round trip about 100 ms after the store, so
TSan's shadow cell for that word is evicted before the read. CI hits it because
the AST fuzzer cancels in process. Forcing it locally would need failpoint
scaffolding in product code, so the evidence is the CI report plus the analysis
above.
Validated under a TSan build: test_postgresql_kill_query 30/30 (5 tests x 6,
random order), test_storage_postgresql and test_dictionaries_postgresql 39/39.
Found by Stress test (amd_tsan) and Stress test (arm_tsan), STID 1855-2bf1.
Internal second-model review (click to expand)An independent model reviewed this diff cold, and I adjudicated its findings against the code.
Also checked and found sound: I also re-derived the carrier list independently rather than taking it from the change: among the Session id: cron:clickhouse-review-slot-48:20260803-152100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260803-120600 |
|
cc @scanhex12 @kssenii, could you review this? |
|
Workflow [PR], commit [b3c76ce] Summary: ✅
AI ReviewSummaryThis PR substantially improves Findings
Tests
Final VerdictChanges requested: the non-streaming LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 53/58 (91.38%) · Uncovered code |
CI finish ledger - 86804b1Every 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
150 of the 175 check-runs are Why the ColumnBLOB abort is not caused by this PR. This diff touches only Post Hooks. The row reports Session id: cron:our-pr-ci-monitor:20260804-010000 |
…ting A cancel landing while PostgreSQLSource::onStart is still constructing the transaction sees `tx` still null, so onCancel cannot cancel anything. It only consumes the one-shot `is_completed` flag and skips both cancel_query and setBroken. onStart then had no reason to stop, so it entered the blocking COPY and the query ran on until PostgreSQL finished it by itself. The destructor also early-returns on the consumed flag, so the connection went back to the pool with the transaction still open. Recheck the flag after publishing the transaction, and perform the teardown that onCancel skipped. No COPY is in flight at that point, only an open BEGIN READ ONLY which rolls back promptly, so marking the connection broken is what is missing. Requested by kssenii in review of ClickHouse#113150. The window predates that PR: the assignment is sequenced after the transaction constructor at its base too, and there was no recheck before stream_from either. The regression test stalls BEGIN READ ONLY at a proxy to pin the source inside the constructor, then cancels. It fails without this change, where the cancelled query keeps running against an endless view.
… failure The previous commit added a setBroken call on the path that runs precisely because the cancelling thread consumed the one-shot flag, so it can run concurrently with the setBroken in onCancel. The other two call sites were mutually exclusive through that flag, so a plain bool was sufficient before; it no longer is. Also move the new test's cleanup into an outer finally, so a failed assertion cannot leave the cancelled read, the proxy or the table behind for later tests.
The first cancel consumes the one-shot flag, so a second KILL QUERY during cleanup can be a no-op. If a failed assertion left the read inside the endless COPY, closing the connection is what ends it, so the proxy has to go down before the join rather than after it.
CI finish ledger - 464a074Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Not caused by this PR. The diff is the transaction-pointer race in Session id: cron:our-pr-ci-monitor:20260804-173000 |
|
@groeneai [src/Processors/Sources/PostgreSQLSource.cpp:105-113] Cancellation is still lossy in the final handoff from the published transaction to pqxx::stream_from. If onCancel wins after the new is_completed.load() recheck but before line 113 starts the blocking COPY, it observes started == false and calls cancel_query() before PostgreSQL is running any statement, so the cancel is dropped. onStart then still enters stream_from, and the read can keep running until PostgreSQL finishes it. The current regression test only parks the source in BEGIN, so it does not prove this last startup window closed. |
`onStart` published the transaction before opening the COPY, so a cancel landing in between passed `onCancel`'s guard and called `cancel_query()` while the backend was running no statement yet. PostgreSQL had nothing to interrupt, so the cancel was dropped, and because `onCancel` had already consumed the one-shot `is_completed` flag the destructor returned early and never reached its own `cancel_query()` either. The read then continued, and the rollback waited for the COPY to finish. Recheck the flag once the stream exists and cancel the COPY that by then does exist. Preventing entry instead would mean holding `tx_mutex` across the blocking `stream_from`, which `onCancel` needs to cancel that very COPY, and `onCancel` is `noexcept` and must not block there. The new test stalls the COPY request rather than the `BEGIN`, which is what places the cancel in this window. Its view has to start streaming promptly: with a plpgsql `SETOF` function PostgreSQL builds the whole result set before the first row and never sends `CopyOutResponse`, so `stream_from`'s constructor blocks and the source is pinned before this window instead of inside it.
|
Fixed in d387217. You are right on both counts. The test was the harder half, and your second sentence was correct: the existing one stalls One thing worth flagging. Stalling the
That distinction also decided the fixture. My first attempt reused the existing plpgsql Verification: build IDs |
The recheck added for a cancel that arrives while the COPY is starting calls cancel_query() from onStart(), on the pipeline thread. onCancel() can call cancel_query() on that same connection from the thread running KILL QUERY. The recheck only loads is_completed, so unlike onCancel() and the destructor, which claim the flag with exchange(true), it does not exclude the cancel that set it and may still be in flight. libpq requires that no two threads manipulate one PGconn at a time. Both calls reach PQgetCancel(m_conn), which reads raddr, the cancel key and the keepalive options out of the connection and can append to its error buffer, so the two cancels are a data race on that object rather than two harmless duplicates. Take a mutex around each cancel_query() so that at most one of them touches the connection at a time. It is only ever held across that one bounded call, and only with tx_mutex released, so it adds no lock ordering. The destructor needs no such lock: it claims the same one-shot flag, so it cannot run beside either. Reported by @kssenii in review.
Build profile diff (arm_release)No arm_release build profile data for commit b3c76ce - the build was skipped, reused from cache, or predates profile upload. |
| /// Serializes publication of `tx` in onStart() against the read in onCancel(), which runs on the | ||
| /// cancelling thread while onStart() is still in flight. Must not be held across pqxx calls. | ||
| std::mutex tx_mutex; | ||
|
|
||
| /// libpq forbids two threads from manipulating one connection at a time, and onStart() and | ||
| /// onCancel() can both cancel on the same one. Only ever held across cancel_query(), and only | ||
| /// ever taken with tx_mutex released. | ||
| std::mutex cancel_mutex; |
| if (connection_holder) | ||
| connection_holder->setBroken(); | ||
| if (connection_holder) | ||
| connection_holder->setBroken(); |
There was a problem hiding this comment.
Let's make a single method which will finalize the state of the source (cancel query, set connection broken)
There was a problem hiding this comment.
Done in ecf9ef0. finalize(tx_to_cancel, stream_to_close) now cancels the query, closes the COPY stream and sets the connection broken, and all four teardown paths call it: the two rechecks in onStart, onCancel, and the destructor. Each passes only what it may touch, so a null argument says how far the startup had progressed. onCancel passes no stream, because onStart is still running and owns it; the recheck before the COPY exists passes no transaction, because nothing was issued on the connection yet.
cancel_query() and setBroken() each went from four call sites to one. finalize is still only ever entered with tx_mutex released, so the lock ordering is unchanged: I checked every call site by walking the enclosing scopes rather than by eye, and all four hold no lock at that point.
Behaviour is the same on every path. The one observable difference is that a logged pqxx exception now names finalize instead of the caller. No test matches on the function name, and the message text is unchanged, so test_kill_query_when_postgresql_cancel_connection_fails, which waits for PQcancel() -- connect() failed, still matches.
test_postgresql_kill_query is 7/7. I verified the refactor is really the code under test rather than trusting the rebuild: an instrumented build logged the path, and after restoring the source the rebuild returned byte-exactly to the shipping build ID.
One thing worth saying plainly, since it is about bug 4 rather than this refactor. A second reviewer pass argued that the existing fixture cannot exercise the two cancels overlapping at all, and it is right for a reason I had not pinned down: KILL QUERY ... ASYNC still calls the executor cancellation inline, so by the time the test releases the withheld COPY, onCancel has already finished. That matches what I measured earlier in this thread, where onStart resumed 143 ms after onCancel returned. So the serialization ships on the libpq requirement and the concurrency being structural, not on a test that reddens without it. If you want that overlap actually covered I would need a proxy that stalls the first cancel while releasing the COPY, and I am happy to add it here or separately, whichever you prefer.
onStart(), onCancel() and the destructor each cancelled the query, closed the COPY stream and marked the connection broken in their own inline copy of that sequence. Collect it into one method that every teardown path calls, passing what it may safely touch: onCancel() does not touch `stream`, since onStart() is still running and owns it, and the recheck before the COPY exists has nothing to cancel yet. The cancel mutex, the exception handling and the setBroken() call now live at one site instead of three. finalize() is still only ever entered with tx_mutex released, so the lock ordering is unchanged and there is no nesting. Behaviour is the same on every path. The one observable difference is that the function name in a logged pqxx exception is now finalize() rather than the caller; no test matches on it, and the exception text is unchanged. test_postgresql_kill_query is 7/7.
CI finish ledger - ecf9ef0Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI fully finished on this head: 175 check-runs, none queued or in progress,
Not failures, recorded so a later pass does not re-flag them. The six Why merged #113409 is deliberately not linked as the owner of the
The merge ref is the tree CI builds, so the fix is present. The retry count in the failure text is Session id: cron:our-pr-ci-monitor:20260808-040000 |
| /// on it yet, so there is nothing to cancel. | ||
| if (is_completed.load()) | ||
| { | ||
| finalize(nullptr, nullptr); |
There was a problem hiding this comment.
new_tx is declared at line 115, inside the if (!tx) block that closes at line 129, so it is not in scope at line 137. There is also a path where it never exists at all: PostgreSQLTransactionSource (used at PostgreSQLReplicationHandler.cpp:760) passes a transaction to the constructor, so tx is already non-null, that block is skipped, and line 137 is still reachable.
If the intent is to pass tx instead, it would be a no-op. The only use finalize makes of that argument is cancel_query() (lines 85-90), and there is no statement to cancel at line 137. The BEGIN issued by the transaction constructor goes basic_transaction (contrib/libpqxx/src/transaction.cxx:29) -> direct_exec -> connection::exec, which is a plain PQexec (contrib/libpqxx/src/connection.cxx:732) and therefore synchronous, so it has completed before make_shared returns. The COPY is the only asynchronous statement on this connection and it starts later, at line 142, which is why the second recheck at line 147 does pass tx and stream.get(). The argument is non-null exactly where something can still be in flight.
The transaction is not left open either. finalize marks the connection broken (lines 102-103), and tx is declared after connection_holder (PostgreSQLSource.h:65 vs :72), so it is destroyed first: ~transaction() (transaction.hxx:95) -> close() -> abort() (transaction_base.cxx:364) -> ROLLBACK (transaction_base.cxx:170-174). That runs before ~ConnectionHolder resets the connection, so the pooled connection does not go back with a BEGIN outstanding.
If you would rather line 137 read finalize(tx, nullptr) for symmetry with line 148, I will change it; it costs an extra PQcancel that finds nothing to cancel.
|
Fixing PR for the DDL-path LeakSanitizer leak (STID 2064-2dbf): #113953. It breaks a |
|
Fixing PR for the It breaks a Not caused by this PR, and nothing to change here. Analysis: #113954 (comment) |
`is_completed` was three things at once: a stop signal, a one-shot teardown claim and a clean-finish marker. Because `onCancel` claimed it before deciding whether it would do anything, a cancel arriving once the source was streaming left the destructor disarmed, so the backend `COPY` was never cancelled and the `ROLLBACK` in the transaction destructor drained it instead. Split it into `stop_requested`, a pure signal, and `finalized`, claimed once by whoever tears the connection down. The destructor now owns the teardown on every path but an uncancelled finish, which lets both rechecks in `onStart` collapse - the second disappears entirely. `prepare` no longer commits after a cancel: the cancelling thread may still be inside `cancel_query` on that connection, and libpq forbids two threads from using one connection at a time. A connection that never got a transaction is left in the pool rather than marked broken, and `onStart` marks it broken if `BEGIN` itself fails, which the destructor can no longer see. Also fix a carry-buffer slice in the test proxy that degenerates to `[0:]` for a single-byte marker.
| return; | ||
|
|
||
| LOG_TEST(getLogger("PostgreSQLSource"), "Stream data from database"); | ||
| stream = std::make_unique<pqxx::stream_from>(*tx, pqxx::from_query, std::string_view{query_str}); |
There was a problem hiding this comment.
This still leaves the startup case where PostgreSQL has accepted the COPY, but pqxx::stream_from has not returned yet. If onCancel() fires before the backend has seen the statement, the first cancel_query() is a no-op; after that we only set stop_requested, and the destructor cannot send the real cancel until onStart() returns from stream_from(). For query shapes that materialize before CopyOutResponse (the non-streaming case the new test explicitly avoids), onStart() stays blocked here and the read still runs until PostgreSQL finishes on its own. We still need a deferred second cancel once the backend has actually started the COPY, or another handoff that can interrupt this constructor without waiting for it to return.
There was a problem hiding this comment.
🕵 The mechanism is right, and it is the sub-case already called out when bug 3 was folded in (#113150 (comment): the constructor that never regains control "needs an out-of-band cancel sent after the backend has the statement, so it is a deferred-cancel design rather than a local change") and documented in the code comment this thread is anchored on. It is deliberately left out of this PR, and is now tracked in #114080. In detail:
There is no event to defer the second cancel to. The only in-band signal that the backend has started executing the COPY is CopyOutResponse, which is exactly the message a materializing shape delays, so "a deferred second cancel once the backend has actually started the COPY" has nothing to hang off. What would actually close the window is one of: a re-cancelling watchdog (polling by nature, with its lifetime tied to the source's destruction — the same PGconn-sharing hazards this PR just fixed), shutdown on the fd from PQsocket (unblocks the client for every shape but forfeits the connection, and the backend still runs to completion since client_connection_check_interval defaults to 0), or moving startup onto the async libpq API. All three are designs of their own, not local changes to this bugfix; they are enumerated in the issue.
It is pre-existing and strictly narrower than at the base. At 8c925c5bbe97 a cancel in this window was dropped the same way, alongside the three windows this PR does close. The damage is also bounded: no rows are streamed, the commit is skipped, the destructor still cancels, closes the stream and marks the connection broken, and the ROLLBACK still precedes the connection reset. What is lost is the promptness of the interruption, not correctness.
On the test half: a fixture for the materializing shape exists (the plpgsql SETOF view attempt described in the PR), but it has nothing to assert while the window is open — it pins the cancelled query until PostgreSQL finishes on any binary. It belongs next to the fix, in the follow-up.
Per the review's suggested alternative, the PR description and changelog now state this remaining window explicitly and link the issue.
There was a problem hiding this comment.
CI finish ledger - b3c76ceEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
No failing check on this head: all 155 executed check-runs concluded For the record, since it reads like a failure in CIDB but is not one: the three Session id: cron:our-pr-ci-monitor:20260809-230000 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed cancellation of
postgresqltable function and PostgreSQL engine reads. Cancelling while the read was still starting up could race on the transaction pointer, and the cancellation could be lost entirely, leaving the query running until PostgreSQL finished it. A cancel that reaches PostgreSQL before theCOPYstatement has begun executing can still be dropped; that narrower, pre-existing window is tracked separately in issue #114080.Description
Four pre-existing cancellation bugs in
PostgreSQLSource. Bugs 2 to 4 were found by kssenii in review here and folded in.1. Data race on the transaction pointer. ThreadSanitizer reports an 8-byte race on
PostgreSQLSource<T>::tx,onCancelagainst theonStartstore; the neighbouring guard loads a different object, so it orders nothing. Fixed by publishingtxunder a newstd::mutex tx_mutex, snapshotted inonCanceland used with the lock released. Holding it acrossstream_fromwould deadlock cancellation against the call it must interrupt.2. Cancellation lost while the transaction is starting. A cancel arriving before
txis published saw it null, soonCancelconsumed the one-shotis_completedflag and skippedcancel_queryandsetBroken;onStartentered the blockingCOPYanyway, so the read ran on and the connection went back to the pool with the transaction open.onStartnow rechecks after publishing and does not open theCOPY; the destructor does that teardown.ConnectionHolder::is_brokenbecomes atomic, the one site the flag does not serialize.3. Cancellation lost while the COPY is starting. One step later
txis published, soonCanceldoes callcancel_query(), but the backend holds no statement yet, so nothing is interrupted.onStartopened theCOPYregardless, and the consumed flag made the destructor return before its own cancel, so the rollback waited for the read. The one-shot flag was doing three jobs at once, and kssenii reworked the ownership (b3c76ce):stop_requestedis now a pure stop signal,finalizedis the teardown claim, and the destructor owns the teardown on every path except an uncancelled clean finish, cancelling theCOPYthat exists by the time it runs.4. Two cancels on one connection.
onCancelinterrupts the startup from theKILL QUERYthread while another teardown path may still reach the same connection, which libpq forbids. Both reachPQgetCancel, which reads the cancel key and keepalive options out of thePGconnand can append to its error buffer, so it is a race on that object, not a harmless duplicate. A mutex around the cancel serializes them, held across that call only, andprepareno longer commits after a cancel for the same reason.Known remaining window (deliberate). A cancel that reaches the backend before the
COPYhas started executing is discarded: a PostgreSQL cancel request only interrupts the statement running at the moment it is processed. The destructor is then the remaining canceller, and it cannot run until thepqxx::stream_fromconstructor returns, so for query shapes that materialize their result before sendingCopyOutResponse, the read still runs until PostgreSQL finishes it. No rows are streamed and the connection is still torn down correctly; what is lost is the promptness of the interruption. Closing it needs a deferred-cancel design rather than a local change, so it is left for follow-up in issue #114080.Validation
The racing branch was taken on 40 of 40 cancellations. Both lost cancellations have regression tests, each verified to fail on the binary without its fix. A proxy withholds one client statement on the wire: withholding
BEGIN READ ONLYpins the source inside the transaction constructor (bug 2), withholding theCOPYpins it one step later withtxpublished (bug 3).Bug 3's test needs a view whose
COPYstarts streaming at once but keeps running, so that the constructor returns and the window is entered. A plpgsqlSETOFfunction is not usable: PostgreSQL materialises its whole result set before the first row and never sendsCopyOutResponse, so the constructor blocks and the source is pinned before the window instead of inside it.Build IDs
ef2e840a26cedb4c(without) and67310dcb3cedaf01(with): the new test fails on the first with the cancelled query still running, passes on the second, and the suite is 7/7. Bug 2's test was 18/18 across random-order repeats.The pointer race does not reproduce locally: the branch arms every time, but the write and read are ~100 ms apart in the harness, so TSan's shadow cell is evicted first. CI hits it because the fuzzer cancels in process, which is why that half ships on the report plus the memory-model argument.
Under a TSan build:
test_postgresql_kill_query24/24 across random-order repeats,test_storage_postgresql+test_dictionaries_postgresql39/39. A mis-scoped variant holding the lock acrossstream_frommakestest_kill_query_when_postgresql_cancel_connection_failsfail, so that suite detects a wrong lock scope.Report, both stacks,
Stress test (arm_tsan), STID1855-2bf1(also onamd_tsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106073&sha=0e95fededea7e7956d4a75cd0bf447854b702663&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29Related: #114080
Version info
26.8.1.1061(included in26.8and later)