Skip to content

Fix server abort when cancelling postgresql table function queries - #105949

Merged
tiandiwonder merged 4 commits into
ClickHouse:masterfrom
rorylshanks:fix-postgresql-cancel-exception-master
Jun 5, 2026
Merged

tiandiwonder merged 4 commits into
ClickHouse:masterfrom
rorylshanks:fix-postgresql-cancel-exception-master

Conversation

@rorylshanks

@rorylshanks rorylshanks commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Closes #105998

Our CH clusters are crashing when the postgresql() function is cancelled with the below crash_log

PostgreSQLSource::onCancel is noexcept, but it called pqxx::connection::cancel_query directly. libpqxx can throw pqxx::sql_error when cancelling the PostgreSQL query fails, which then escapes the noexcept cancellation path and causes std::terminate.

This wraps the cancellation call, logs the failure, and still marks the PostgreSQL connection as broken. Query cleanup can now continue without aborting the server.

Row 1:
──────
hostname:                     REDACTED
event_date:                   2026-05-27
event_time:                   2026-05-27 13:15:03
timestamp_ns:                 1779887703517965358
signal:                       6
signal_code:                  -6
thread_id:                    2153535 -- 2.15 million
query_id:                     2_cache_2_53205b2741a4611faa0ac84ca84c251a6ac7746b5ccad14b90019a82926af91a_W6xI8sH6
query:                        SELECT system__integration_repository_cache.full_name AS full_name FROM postgresql('REDACTED', 'REDACTED', 'REDACTED', 'REDACTED', '[HIDDEN]') AS system__integration_repository_cache WHERE and(equals(system__integration_repository_cache.team_id, 2), equals(system__integration_repository_cache.tree_truncated, 1)) LIMIT 50 SETTINGS readonly = 2, max_execution_time = 600, allow_experimental_object_type = 1, max_ast_elements = 4000000, max_expanded_ast_elements = 4000000, max_bytes_before_external_group_by = 0, transform_null_in = 1, optimize_min_equality_disjunction_chain_length = 4294967295, allow_experimental_join_condition = 1, use_hive_partitioning = 0
trace:                        [268111290594825,268111290288956,268111290203648,340413864,543451784,543451708,235297756,234721776,398717864,443245888,443359752,526622808,526624356,526341048,526333424,268111290587484,268111291005772]
trace_full:                   ['2. ? @ 0x0000000000087609','3. raise @ 0x000000000003cb3c','4. conjf128 @ 0x0000000000027e00','5. terminate_handler() @ 0x00000000144a4da8','6. std::__terminate(void (*)()) @ 0x0000000020646a88','7. std::terminate() @ 0x0000000020646a3c','8. ? @ 0x000000000e065bdc','9. ? @ 0x000000000dfd91f0','10. DB::BlockIO::onException(bool) @ 0x0000000017c3f3a8','11. DB::TCPHandler::runImpl() @ 0x000000001a6b6540','12. DB::TCPHandler::run() @ 0x000000001a6d2208','13. Poco::Net::TCPServerConnection::start() @ 0x000000001f63a058','14. Poco::Net::TCPServerDispatcher::run() @ 0x000000001f63a664','15. Poco::PooledThread::run() @ 0x000000001f5f53b8','16. Poco::ThreadImpl::runnableEntry(void*) @ 0x000000001f5f35f0','17. ? @ 0x000000000008595c','18. ? @ 0x00000000000ebb4c']
fault_address:                ᴺᵁᴸᴸ
fault_access_type:
signal_description:           Sent by tkill.
current_exception_trace_full: ['0. pqxx::sql_error::sql_error(String const&, String, char const*) @ 0x000000001e727e64','1. pqxx::connection::cancel_query() @ 0x000000001e7249b4','2. DB::PostgreSQLSource<pqxx::transaction<(pqxx::isolation_level)0, (pqxx::write_policy)0>>::onCancel() @ 0x000000000dfd91d0','3. DB::BlockIO::onException(bool) @ 0x0000000017c3f3a8','4. DB::TCPHandler::runImpl() @ 0x000000001a6b6540','5. DB::TCPHandler::run() @ 0x000000001a6d2208','6. Poco::Net::TCPServerConnection::start() @ 0x000000001f63a058','7. Poco::Net::TCPServerDispatcher::run() @ 0x000000001f63a664','8. Poco::PooledThread::run() @ 0x000000001f5f53b8','9. Poco::ThreadImpl::runnableEntry(void*) @ 0x000000001f5f35f0','10. ? @ 0x000000000008595c','11. ? @ 0x00000000000ebb4c']
version:                      ClickHouse 26.3.10.60
revision:                     54517
build_id:                     0D13C8995FEFC6E19CDC8D81BC58BC16952CEB9F
git_hash:                     6a6d2d137dfc14972ab1f77412a9e2ada5e0698f
architecture:                 aarch64

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

Fixed a server crash that could occur when a query reading from PostgreSQL — via the postgresql table function, the PostgreSQL table engine, or a dictionary with a PostgreSQL source — was cancelled (for example with KILL QUERY) and cancelling the remote PostgreSQL query failed.

Version info

  • Merged into: 26.6.1.416 (included in 26.6 and later)
  • Backported to: 26.5.2.37, 26.4.4.35, 26.3.17.33

@rorylshanks rorylshanks changed the title Fix panic when cancelling postgres connections Fix server abort when cancelling postgresql table function queries May 27, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Hello! Could you create an issue with a reproducible if possible, so we can investigate further?

@rorylshanks

Copy link
Copy Markdown
Contributor Author

@PedroTadim

PedroTadim commented May 28, 2026 •

Copy link
Copy Markdown
Member

The fix seems correct so far. Can you import the test? We have a few .sh tests, and it should be easy to add one for this case.

@rorylshanks

Copy link
Copy Markdown
Contributor Author

Hey i added a test in the existing postgres test suite

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label May 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [47fb31d]

Summary: ✅


AI Review

Summary

This PR catches exceptions from pqxx::connection::cancel_query inside PostgreSQLSource::onCancel, logs the failure, and marks the PostgreSQL connection holder broken so it will not be reused. The added integration test forces the separate PostgreSQL cancel connection to fail while a postgresql query is killed. I did not find any correctness or safety issue requiring an inline review comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels May 28, 2026
@tiandiwonder tiandiwonder self-assigned this May 29, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

Better to update change log entry:
Fixed a server crash that could occur when a query reading from PostgreSQL — via the postgresql table function, the PostgreSQL table engine, or a dictionary with a PostgreSQL source — was cancelled (for example with KILL QUERY) and cancelling the remote PostgreSQL query failed.

@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 7/7 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR only wraps the PostgreSQL source's query-cancellation call in a try/catch and adds an integration test — it does not touch any code path the ClickBench SELECT queries execute. The three flagged improvements (Q4 -15.49%, Q15 -13.6%, Q32 -5.96%) are therefore off-path and cannot plausibly be caused by this change, so all three are downgraded to not-sure as run-to-run variance. No real performance impact is expected from these queries.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 268 226 -15.5% <0.0001 PR only adds try/catch to PostgreSQL cancel path; ClickBench SELECT hot path untouched, so this delta is variance
⚠️ 15 not_sure 250 216 -13.6% <0.0001 PostgreSQL cancel error-handling change cannot speed up a local SELECT; off-path improvement is run-to-run variance
⚠️ 32 not_sure 1502 1413 -6.0% 0.0010 No code touched in this query's execution path; the smaller 5.96% gain is noise, not a PR effect

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2e39ff38-963e-487e-82c0-5ed1055ce943
  • MIRAI run: c2b0d5c5-7e2d-4361-96e0-076404e8e061
  • PR check IDs:
    • clickbench_426847_1780621144
    • clickbench_426861_1780621144
    • clickbench_426863_1780621144
    • tpch_adapted_1_official_426874_1780621144
    • tpch_adapted_1_official_426877_1780621144
    • tpch_adapted_1_official_426945_1780621144

@tiandiwonder
tiandiwonder added this pull request to the merge queue Jun 5, 2026
Merged via the queue into ClickHouse:master with commit a17422e Jun 5, 2026
166 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @rorylshanks @tiandiwonder — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body conveys the fix at a high level but omits the root cause: onCancel is noexcept, so an exception from cancel_query() escaping it calls std::terminate (SIGABRT). It also does not note that this mirrors the existing try/catch guard already present in the destructor.

  • Suggested addition:

    Root cause: PostgreSQLSource::onCancel is noexcept and is called directly from the noexcept ISource::cancel. On the early-cancel path it called tx->conn().cancel_query() unguarded; pqxx can throw (e.g. when the separate cancel connection cannot be opened, 'PQcancel() -- connect() failed'), and an exception escaping a noexcept function calls std::terminate, aborting the server. The fix wraps the call in try/catch + tryLogCurrentException, matching the guard already present in ~PostgreSQLSource.

Ignore this if the current title/body is intentional.

robot-clickhouse added a commit that referenced this pull request Jun 5, 2026
robot-clickhouse added a commit that referenced this pull request Jun 5, 2026
Cherry pick #105949 to 26.5: Fix server abort when cancelling postgresql table function queries
robot-clickhouse added a commit that referenced this pull request Jun 5, 2026
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 5, 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 Jun 5, 2026
alexey-milovidov added a commit that referenced this pull request Jun 5, 2026
Backport #105949 to 26.5: Fix server abort when cancelling postgresql table function queries
alexey-milovidov added a commit that referenced this pull request Jun 5, 2026
Backport #105949 to 26.4: Fix server abort when cancelling postgresql table function queries
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 12, 2026
Cherry pick #105949 to 25.8: Fix server abort when cancelling postgresql table function queries
robot-clickhouse added a commit that referenced this pull request Jun 12, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 12, 2026
tiandiwonder added a commit that referenced this pull request Jul 8, 2026
Backport #105949 to 26.3: Fix server abort when cancelling postgresql table function queries
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 9, 2026
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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…5949

Backport ClickHouse#105949 to 26.4: Fix server abort when cancelling postgresql table function queries
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

server abort when cancelling postgresql table function queries

8 participants