Skip to content

Fix data race on the transaction pointer in PostgreSQLSource - #113150

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-postgresqlsource-tx-data-race
Aug 9, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-postgresqlsource-tx-data-race

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

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 cancellation of postgresql table 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 the COPY statement 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, onCancel against the onStart store; the neighbouring guard loads a different object, so it orders nothing. Fixed by publishing tx under a new std::mutex tx_mutex, snapshotted in onCancel and used with the lock released. Holding it across stream_from would deadlock cancellation against the call it must interrupt.

2. Cancellation lost while the transaction is starting. A cancel arriving before tx is published saw it null, so onCancel consumed the one-shot is_completed flag and skipped cancel_query and setBroken; onStart entered the blocking COPY anyway, so the read ran on and the connection went back to the pool with the transaction open. onStart now rechecks after publishing and does not open the COPY; the destructor does that teardown. ConnectionHolder::is_broken becomes atomic, the one site the flag does not serialize.

3. Cancellation lost while the COPY is starting. One step later tx is published, so onCancel does call cancel_query(), but the backend holds no statement yet, so nothing is interrupted. onStart opened the COPY regardless, 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_requested is now a pure stop signal, finalized is the teardown claim, and the destructor owns the teardown on every path except an uncancelled clean finish, cancelling the COPY that exists by the time it runs.

4. Two cancels on one connection. onCancel interrupts the startup from the KILL QUERY thread while another teardown path may still reach the same connection, which libpq forbids. Both reach PQgetCancel, which reads the cancel key and keepalive options out of the PGconn and 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, and prepare no longer commits after a cancel for the same reason.

Known remaining window (deliberate). A cancel that reaches the backend before the COPY has 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 the pqxx::stream_from constructor returns, so for query shapes that materialize their result before sending CopyOutResponse, 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 ONLY pins the source inside the transaction constructor (bug 2), withholding the COPY pins it one step later with tx published (bug 3).

Bug 3's test needs a view whose COPY starts streaming at once but keeps running, so that the constructor returns and the window is entered. A plpgsql SETOF function is not usable: PostgreSQL materialises its whole result set before the first row and never sends CopyOutResponse, so the constructor blocks and the source is pinned before the window instead of inside it.

Build IDs ef2e840a26cedb4c (without) and 67310dcb3cedaf01 (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_query 24/24 across random-order repeats, test_storage_postgresql + test_dictionaries_postgresql 39/39. A mis-scoped variant holding the lock across stream_from makes test_kill_query_when_postgresql_cancel_connection_fails fail, so that suite detects a wrong lock scope.

Report, both stacks, Stress test (arm_tsan), STID 1855-2bf1 (also on amd_tsan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106073&sha=0e95fededea7e7956d4a75cd0bf447854b702663&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Related: #114080

Version info

  • Merged into: 26.8.1.1061 (included in 26.8 and later)

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.
@groeneai

groeneai commented Aug 3, 2026

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

An independent model reviewed this diff cold, and I adjudicated its findings against the code.
Two findings, both resolved as not-blocking-here with the reasoning below. One of them is a real
pre-existing bug that now has its own owner.

# Finding Verdict
⚠️ Cancellation can be lost while the transaction constructor is blocked in BEGIN. While make_shared<T>(conn) is issuing BEGIN, the pointer is still null, so onCancel does not take its cancel branch and returns having consumed the one-shot is_completed flag; onStart does not recheck it and proceeds into the blocking COPY. Correct mechanism, but pre-existing and out of scope. Both steps the scenario needs are byte-identical at this PR's base 8c925c5bbe97: the assignment is sequenced after the constructor there too (tx = std::make_shared<T>(conn)), so the member is null for the same interval, and there is no is_completed recheck before stream_from at base either. ISource::cancel is untouched by this diff. Fixing it needs a new behavioral change (a post-publication recheck plus the teardown onCancel skipped, including the setBroken() that is also missed because the destructor early-returns on the consumed flag). Tracked separately at P2; I am not folding it in, because this PR's contract is the pointer race and mixing an unrelated liveness change in would make both harder to review.
⚠️ The existing tests do not distinguish the mutex publication from the unsynchronized access. They synchronize after publication, so they would pass with the old code. Premise correct, remedy unavailable. I reached the same conclusion independently before reading the implementation notes. Of the two suggested remedies, blocking BEGIN tests the other finding's defect, which this PR does not fix; and a local TSan run does not materialize: the racing branch arms on 40 of 40 cancellations under the CI stress configuration, but KILL QUERY arrives about 100 ms after the store, so TSan's shadow cell for that word is evicted before the read. CI hits it because the fuzzer cancels in process. A probe kept as a regression test would pass identically with and without this fix. What I do rely on is a negative control: a deliberately mis-scoped variant holding the lock across stream_from makes test_kill_query_when_postgresql_cancel_connection_fails fail on a 30 s timeout, so the existing suite does constrain the one property a later edit could break, and the correct scope passes 30/30.

Also checked and found sound: conn() and is_open() are noexcept, so the snapshot adds no
throw site beyond the lock, which is inside the try; cancel_query can throw and is called with
the lock released; tx_mutex is a leaf lock, so no ordering risk; and tx/stream are still
destroyed before connection_holder, since the new member is declared ahead of it.

I also re-derived the carrier list independently rather than taking it from the change: among the
sources with an onCancel, SQLiteSource never reassigns its handle, MySQLWithFailoverSource
reads only atomics, RemoteSource's executor is fixed after construction, and
ReadFromDistributedPlanSource is already mutex-guarded. PostgreSQLSource is the only carrier, so
this fix creates no asymmetry.

Session id: cron:clickhouse-review-slot-48:20260803-152100

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Partial, and bounded honestly. The racing branch reproduces deterministically: with an instrumented TSan build I measured onCancel entering with started=false, tx != null and taking the racing branch on 40 of 40 cancellations. The TSan report does not reproduce locally, because KILL QUERY arrives over a docker round trip about 100 ms after the tx store, so the shadow cell for that word is evicted before the read. CI hits it because the fuzzer cancels in process, microseconds after the write.
b Root cause explained? Yes. tx is a plain std::shared_ptr while the started/is_completed flags beside it are atomic. !started.load() at PostgreSQLSource.cpp:201 loads a different object, so it creates no happens-before edge with the tx = std::make_shared<T>(...) store at :88/:93. The cancelling thread's read and the executor thread's write are therefore unordered, which is the reported race (the two stacks hold different mutexes, M0 vs M1).
c Fix matches root cause? Yes. It establishes the missing happens-before edge on the pointer itself via a dedicated std::mutex tx_mutex. No suppression, no widened bound, and the load-bearing tx read is kept: the transaction is how the cancelling thread reaches the connection to call cancel_query.
d Test intent preserved / new tests added? Preserved: no existing test is weakened, removed or retagged. No new test is added, deliberately. A probe kept as a regression test would pass identically with and without the fix, i.e. a vacuous oracle. The 5 existing test_postgresql_kill_query tests already cover this cancel path under Integration tests (amd_tsan).
e Both directions demonstrated? For the behavioral risk, yes, via a negative control: a deliberately mis-scoped variant holding tx_mutex across the blocking stream_from makes test_kill_query_when_postgresql_cancel_connection_fails FAIL (PQcancel() -- connect() failed never logged, 30 s timeout), and the correct scope PASSES 30/30. For the race itself the "fails without fix" side is the CI TSan report with both stacks rather than a local run, for the reason in (a).
f Fix is general across code paths? Yes. Every access to tx was enumerated. Fixed: the onStart write (both the initial and the broken_connection retry site) and the onCancel read. Left unguarded with reasons: onStart:98 is same thread sequenced after the write; prepare:116-117 is ordered through ExecutingGraph's per node serialization; the destructor runs only after pool->wait() joins the executing threads. Sibling sweep of src/Processors/Sources/: SQLiteSource (pointer set at construction, never reassigned), MySQLWithFailoverSource (atomics only), RemoteSource (const after construction), ReadFromDistributedPlanSource (already mutex guarded, the prior art this mirrors), MongoDBSource (no onCancel). PostgreSQLSource is the only carrier, so no asymmetry is created.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrapper matrix is not applicable, there is no type dispatch here. Both template instantiations (pqxx::ReadTransaction, pqxx::ReplicationTransaction) share this code. The only subclass, PostgreSQLTransactionSource, passes tx in through the protected constructor, so tx is non-null before the pipeline starts and onStart's if (!tx) never writes it; it pays one uncontended acquire.
h Backward compatible? Yes. No setting, no default change, no wire or serialization format change, no public API change. Purely internal synchronization, so no SettingsChangesHistory.cpp entry is needed.
i Invariants and contracts preserved? Yes. onCancel stays effectively noexcept: the lock is taken inside a try/catch, so a throwing lock_guard cannot reach std::terminate. Cancellation still never blocks: the lock covers only a pointer move and a pointer copy, never a pqxx call, which the negative control in (e) demonstrates is the load-bearing property. setBroken() still runs whenever the branch is taken, including when cancel_query throws, which is what ..._cancel_connection_fails asserts. Member declaration order is unchanged relative to connection_holder, so the documented "tx and stream must be destroyed before connection_holder" ordering holds. tx_mutex is a leaf lock: nothing else is acquired while it is held, so no lock ordering risk is introduced.

Session id: cron:clickhouse-impl-slot-7:20260803-120600

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @kssenii, could you review this? PostgreSQLSource<T>::tx is a plain shared_ptr published by onStart on the executor thread and read by onCancel on the cancelling thread, and the !started.load() guard beside it loads a different object so it orders nothing; this publishes the pointer under a small dedicated mutex and has onCancel use a snapshot taken under it, never holding the lock across a pqxx call.

@kssenii kssenii self-assigned this Aug 3, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b3c76ce]

Summary: ✅


AI Review

Summary

This PR substantially improves PostgreSQLSource cancellation by separating the stop signal from teardown ownership, serializing concurrent cancel_query() calls, and adding focused startup-window tests. One major gap remains: cancellation is still lossy for COPY queries whose pqxx::stream_from constructor does not return promptly, so the branch does not yet fully satisfy its own "startup cancellation is fixed" contract.

Findings

⚠️ Majors

  • [src/Processors/Sources/PostgreSQLSource.cpp:145] The new destructor-owned teardown still cannot rescue the case where the first cancel_query() ran before PostgreSQL had the COPY, and pqxx::stream_from then blocks until the backend starts producing output. In that path stop_requested is set, but the destructor cannot issue the second cancel until onStart() returns, so materializing COPY queries can still ignore KILL QUERY and run until PostgreSQL finishes by itself.
    Suggested fix: add a deferred second cancel once the backend has actually started the COPY, or hand interruption off to a path that can break stream_from() without waiting for it to return.
Tests
  • ⚠️ test_kill_query_while_copy_is_starting intentionally uses a promptly-streaming view, so it does not prove the non-streaming startup case above. Add the smallest focused case where PostgreSQL accepts COPY but stream_from() does not return promptly, or narrow the PR description/changelog if that case is intentionally left for follow-up.
Final Verdict

Changes requested: the non-streaming COPY startup case still loses cancellation.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 53/58 (91.38%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 86804b1

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
Stress test (arm_msan) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-3663) trunk bug, not this diff #111997 (mine, open)
Build (arm_release) / Post Hooks CI telemetry infra (build_profile_hook.py -> LogCluster query failed with code 500 on the build_time_trace INSERT) a fix task is pending (investigating at full effort - fixing-PR link to follow here)

150 of the 175 check-runs are success, 24 skipped, Config Workflow and Finish Workflow both success.

Why the ColumnBLOB abort is not caused by this PR. This diff touches only src/Processors/Sources/PostgreSQLSource.{cpp,h}. The aborting query, from the server log, is SELECT __table1.number AS number FROM merge('test_2', '^t_hash_table_sizes_stats_1569312143') AS __table1 GROUP BY __table1.number LIMIT ... (02151_hash_table_sizes_stats_distributed.sh), and the stack is ExpressionTransform -> columnMatchesType -> ColumnBLOB::throwInapplicable - no PostgreSQL frame anywhere. STID 3059-3663 over 30 days is 42 rows across 32 distinct PRs including 5 master runs, first seen 2026-07-22, so it is carrier-independent. It is the exact shape of issue #111945 (merge() spanning a table that produces marshalled blocks), which #111997 closes; #111997 is still open, so the failing build does not contain the fix.

Post Hooks. The row reports test_status = FAIL while its enclosing Build (arm_release) job is check_status = success - the telemetry INSERT in the job hook fails, no build artifact or test result is affected. This occurrence is the bare 500 form (no Code: token in the context).

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.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 464a074

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
Stress test (arm_msan) / Hung check failed, possible deadlock found one cancelled SELECT ... FROM merge(REGEXP('.*'), '^') ARRAY JOIN ... sits 891s single-threaded with is_cancelled: 1; ReadFromMerge plan-time analysis has no cancellation point, so the KILL never takes effect #113140 (external, open) for the planning cost; the interruptibility half is owned by a fix task (fixing PR link to follow here)
Stress test (arm_release) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-3663) trunk block-marshalling unwrap gap, 197 rows / 121 unrelated PRs in 14d #111997 (mine, open)
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace gets HTTP 500 from LogCluster; check_status is success and the check is non-gating a fix task is moved to pending (investigating at full effort - fixing PR link to follow here)

The Bugfix validation (integration tests, {aarch64,amd64}) rows for
test_postgresql_kill_query are the MASTER-binary side of the bugfix-validation contract: the new
test must fail on master HEAD to prove it catches the bug. Both jobs report success, so these are
not failures and need no owner.

Not caused by this PR. The diff is the transaction-pointer race in PostgreSQLSource
(src/Processors/Sources/PostgreSQLSource.*, src/Core/PostgreSQL/ConnectionHolder.h); neither the
merge() planning hang nor the ColumnBLOB abort touches the PostgreSQL source.

Session id: cron:our-pr-ci-monitor:20260804-173000

@kssenii
kssenii added this pull request to the merge queue Aug 6, 2026
@kssenii
kssenii removed this pull request from the merge queue due to a manual request Aug 6, 2026
@kssenii

kssenii commented Aug 6, 2026

Copy link
Copy Markdown
Member

@groeneai
Fix this:

[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.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in d387217.

You are right on both counts. onStart now rechecks the flag once the stream exists and cancels the COPY that by then does exist, instead of trying to prevent entry: preventing entry means 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 test was the harder half, and your second sentence was correct: the existing one stalls BEGIN, so it pins the source before publication and structurally cannot reach this window. The proxy now stalls any chosen client statement, and the new test stalls the COPY request instead. A wire-level trace confirms it lands where you describe: the cancel request arrives 180 ms before the COPY reaches the server.

One thing worth flagging. Stalling the COPY splits into two sub-cases, and only one is fixable from onStart:

  • PostgreSQL starts producing output, so the constructor returns. The dropped cancel then costs the teardown, because the consumed flag makes the destructor return before its own cancel_query(), leaving the rollback waiting for the read. This is what the fix and the new test cover.
  • PostgreSQL produces nothing, so the constructor blocks inside the COPY and onStart never regains control. No post-construction recheck can run. Measured: 45.7 s from forwarding the COPY to EOF with zero server bytes, ending only when the connection died. Interrupting that 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. I have not done it here.

That distinction also decided the fixture. My first attempt reused the existing plpgsql SETOF view and failed on both binaries, correctly: such a function materialises its whole result set before the first row and never sends CopyOutResponse, so it produces the second sub-case. The new view sends CopyOutResponse at once and keeps running.

Verification: build IDs ef2e840a26cedb4c without the fix and 67310dcb3cedaf01 with it. The new test fails on the first with the cancelled query still running, passes on the second, and the suite is 7/7. The mis-scoped-lock negative control still fails test_kill_query_when_postgresql_cancel_connection_fails, so the suite still detects a wrong lock scope. PR body and changelog updated to cover all three windows.

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

Comment on lines +60 to +67
/// 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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

remove comments

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in ecf9ef0.

if (connection_holder)
connection_holder->setBroken();
if (connection_holder)
connection_holder->setBroken();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's make a single method which will finalize the state of the source (cancel query, set connection broken)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ecf9ef0

Every failure below has an owner: a fixing PR (ours 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.

CI fully finished on this head: 175 check-runs, none queued or in progress, Finish Workflow
success at 2026-08-08T03:37:05Z. One failing check-run, Stress test (arm_asan_ubsan).

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Sanitizer (STID: 2064-2dbf) Not PR-caused. LeakSanitizer: detected memory leaks, 30120 bytes in 49 allocations, every entry indirect and zero direct. All roots are the Replicated-database DDL path: Context::createCopy <- DDLTaskBase::makeQueryContext <- DDLWorker::tryExecuteQuery <- DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry, plus ZooKeeper request objects. This PR changes only PostgreSQLSource, ConnectionHolder and one integration test: the leak report contains zero occurrences of PostgreSQL, pqxx, libpq or ConnectionHolder (control: DDLWorker appears 164 times), and the diff contains zero occurrences of DatabaseReplicated, DDLTask, DDLWorker, ZooKeeper or makeQueryContext (control: PostgreSQLSource appears 15 times). a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Build (arm_release) / Post Hooks Not PR-caused, and non-gating: the Build (arm_release) check-run itself is success, so this row exists only in the results database. The build_profile_hook.py build-time-trace telemetry INSERT into the shared CI logs cluster is rejected with HTTP 500 after exhausting every retry. Environmental rather than branch-specific: 3061 rows across 847 distinct pull requests in the last 7 days, 1256 of them on master. a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Not failures, recorded so a later pass does not re-flag them. The six
Bugfix validation (integration tests, amd64/aarch64) / test_postgresql_kill_query FAIL rows
are the master-binary side of bugfix validation, which is inverted by design: both jobs'
conclusions are success.

Why merged #113409 is deliberately not linked as the owner of the Post Hooks row. That PR
("Retry the build-profile telemetry INSERT through the CI logs cluster memory-pressure spikes",
merged 2026-08-06T00:05:00Z) is present in the tree this job actually built, so per the ledger
rules it must not be listed as the owner of a failure that happened with it applied. Presence was
established per build rather than from the merge date, and the two probes initially disagreed:

  • Reading ci/jobs/scripts/log_cluster.py at the head ref returns the pre-fix file
    (11916 bytes, retries=8 once, no data.seek(0)), which suggests the fix is absent.
  • Reading it at refs/pull/113150/merge returns the post-fix file (12698 bytes, retries=8
    four times, data.seek(0) present), and compare/de947727b2ba...5c1dfb7f126b reports
    status=ahead, behind_by=0.

The merge ref is the tree CI builds, so the fix is present. The retry count in the failure text is
the independent discriminator and agrees with that reading: pre-fix code calls
do_query(..., retries=1) and can emit at most one WARNING: LogCluster query failed line,
while the merged fix passes retries=8. This row carries exactly 8 such lines, so it provably
ran post-fix code and exhausted every retry. The 5*(retry+1) backoff totals at most ~140 s,
which does not outlast the cluster's memory-pressure spike.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not pass new_tx here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the DDL-path LeakSanitizer leak (STID 2064-2dbf): #113953. It breaks a Context retain cycle in the DatabaseReplicated digest finalizer, which captured its own owning Context by strong pointer, so a multi() throw left the finalizer uncleared and retained the whole graph.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (*_asan_ubsan) LeakSanitizer failure (STID 2064-22d0) on this PR: #113397 (not mine, open, AI-review approved).

It breaks a MaterializedCTE <-> QueryPlan reference cycle: MaterializedCTE::plan is a strong unique_ptr<QueryPlan> and the MaterializingCTEStep appended into that same plan held a strong handle back to the CTE, so a query that builds a materialized-CTE plan and then abandons it leaks the whole graph, including the Context::createCopy from QueryTreeBuilder::buildSelectExpression at the root of the reported stacks. @ alexey-milovidov attached this exact CI signature to that PR in #113397 (comment).

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});

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the scoping, and #114080 matches what I measured: the materializing shape stays pinned until PostgreSQL finishes it, so there is nothing for a test to assert while the window is open.

Nothing further from me on this PR. CI is green on b3c76ce (155 success, 21 skipped, 0 failures).

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b3c76ce

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks build-profile telemetry INSERT to the CI logs cluster; NON-GATING, the check itself concluded success #113409 (ours, merged)

No failing check on this head: all 155 executed check-runs concluded success, 20 skipped, 0 running, Finish Workflow success.

For the record, since it reads like a failure in CIDB but is not one: the three test_postgresql_kill_query rows marked FAIL under Bugfix validation (integration tests, amd64/aarch64) are the master-binary arm, which MUST fail for the validation to pass. Both of those checks concluded success, and the same three tests report OK on all six real integration jobs on this head (amd_tsan 3/6, amd_msan 5/8, amd_asan_ubsan db disk old analyzer 3/6, amd_asan_ubsan flaky, amd_llvm_coverage 5/8, arm_binary distributed plan 1/4).

Session id: cron:our-pr-ci-monitor:20260809-230000

Merged via the queue into ClickHouse:master with commit 96e4554 Aug 9, 2026
181 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants