Skip to content

Do not write ErrorResponse into a canceled PostgreSQL socket buffer - #118369

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix/postgresql-error-response-on-canceled-socket
Oct 3, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix/postgresql-error-response-on-canceled-socket

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Related: #111327

When a PostgreSQL protocol client goes away while the server is still streaming the result, the next write to the socket fails with NETWORK_ERROR (Broken pipe) and WriteBuffer::next cancels the socket buffer. The error handlers in PostgreSQLHandler then tried to send ErrorResponse through the same buffer, which is a logical error:

Logical error: 'Cannot write to canceled buffer'.
DB::WriteBuffer::write(char) @ src/IO/WriteBuffer.cpp:67
DB::PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::serialize @ src/Core/PostgreSQLProtocol.h:393
DB::PostgreSQLHandler::processQuery() @ src/Server/PostgreSQLHandler.cpp:1055

Now the handler tears the connection down instead when the output buffer is already canceled: there is nobody left to deliver the error to. The check lives in a single helper, sendErrorResponseOrRethrow, which is used by every place that reports a failed statement to the client - processQuery, processParseQuery, processBindQuery, processDescribeQuery, processExecuteQuery, processCloseQuery and processSyncQuery - so the invariant "once out is canceled, no handler recovers by sending another message" holds for the extended-query protocol as well.

Tests: 05099_postgresql_protocol_client_disconnect_mid_result kills psql with SIGKILL in the middle of a streamed simple query, and 05100_postgresql_protocol_extended_client_disconnect_mid_result does the same for the extended-query protocol with a minimal Parse/Bind/Execute/Sync client that aborts the connection with RST. Both check that the statement disappears and that no such message reaches system.text_log.

Seen in Stress test (arm_debug) of a PR that does not touch this code: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111327&sha=ff11b640e3ff97e92863685fdba4882a09597508&name_0=PR&name_1=Stress%20test%20%28arm_debug%29, and on master on 2026-09-05 (the test 05056_postgresql_protocol_cancel_request exits psql while the result is still streaming, so under load the server hits the broken pipe before the cancellation is processed).

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

Fix a logical error Cannot write to canceled buffer in the PostgreSQL wire protocol handler when a client disconnects while the server is still sending the result of a query.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1452-master (included in 26.10 and later)

When a PostgreSQL protocol client goes away while the server is still streaming the result, the next write to the socket fails with `NETWORK_ERROR` (`Broken pipe`), and `WriteBuffer::next` cancels the socket buffer. The error handlers of `processQuery` and `processExecuteQuery` in `PostgreSQLHandler` then tried to send `ErrorResponse` through the same buffer, which is a logical error: `Cannot write to canceled buffer`.

Tear the connection down instead when the output buffer is already canceled: there is nobody left to deliver the error to.

Seen in the stress test of a PR that does not touch this code: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111327&sha=ff11b640e3ff97e92863685fdba4882a09597508&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 (#111327), and on master on 2026-09-05.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f001115]

Summary: ✅


AI Review

Summary

This PR fixes the PostgreSQL-wire disconnect path by routing statement-level error reporting through sendErrorResponseOrRethrow, so a failed socket write no longer leads to a second write into an already canceled buffer. The change is applied consistently across the simple-query and extended-query statement handlers, and the new stateless regressions cover both the psql simple-query path and an extended Parse/Bind/Execute/Sync client that disconnects mid-result. I do not see a remaining correctness issue in the changed surface.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f001115.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

The same unguarded ErrorResponse send remains in five sibling catch blocks: processParseQuery, processBindQuery, processDescribeQuery, processCloseQuery, and processSyncQuery (the 2F000 sends around lines 1192, 1213, 1233, 1349, 1374). In the extended-query flow a client that disappears mid-result cancels out during processExecuteQuery, and the already-buffered pipeline messages (Sync, Close, another Bind) are still processed afterwards, so any of those catch blocks can hit the same Cannot write to canceled buffer this PR fixes for the simple-query and Execute paths. The identical two-line guard would cover them.

@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0011155b with master b1f44e396 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

8 translation units recompiled, 17 s compile time in total, 8 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits September 11, 2026 04:59
Address review from `clickhouse-gh` and @zlareb1: the guard was only in
`processQuery` and `processExecuteQuery`, while `processParseQuery`,
`processBindQuery`, `processDescribeQuery`, `processCloseQuery` and
`processSyncQuery` still sent `ErrorResponse` unconditionally from their
`catch` blocks. Factor the send into `sendErrorResponseOrRethrow`, which
rethrows the exception being handled when `out` is already canceled, and use
it in every place that reports a failed statement to the client.

Also stop `05099_postgresql_protocol_client_disconnect_mid_result` from
failing with `having stderror`: `bash` reports the death of the background
`psql` job as `Killed` on the stderr of the shell itself, not on the stderr of
`wait`, so the shell's stderr has to be redirected around the `kill`/`wait`
pair.

Add `05100_postgresql_protocol_extended_client_disconnect_mid_result`, which
covers the same disconnect on the extended-query path with a minimal
`Parse`/`Bind`/`Execute`/`Sync` client that aborts the connection in the
middle of the result.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…r-response-on-canceled-socket

Conflict in `src/Server/PostgreSQLHandler.h`: master added
`recoverFromRejectedMessage` next to where this branch added
`sendErrorResponseOrRethrow`. Kept both declarations.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Merging master brought in other tests with the `05100` prefix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you — you were right, and the list of call sites was exactly what was needed. Fixed in 409d62d: the ErrorResponse send is now factored into sendErrorResponseOrRethrow, which rethrows the exception being handled when out is already canceled, and it is used by processQuery, processParseQuery, processBindQuery, processDescribeQuery, processExecuteQuery, processCloseQuery and processSyncQuery.

Also added 05182_postgresql_protocol_extended_client_disconnect_mid_result for the extended-query path (a minimal Parse/Bind/Execute/Sync client that aborts the connection with RST mid-result), and fixed 05099 failing with having stderror: bash reports the death of the background psql job as Killed on the stderr of the shell itself, which is not silenced by a redirection on wait. Both tests were checked against a control binary with the guard removed — they report the Cannot write to canceled buffer message there and none with the fix.

alexey-milovidov and others added 2 commits September 18, 2026 10:57
…2` as `no-fasttest`

The `Cannot write to canceled buffer` count in `05099` and `05182` was global over the whole
retained `system.text_log`, so a row left by an earlier PostgreSQL test on the same server would
have failed it. Both checks now use a `RUN_START` anchor on `event_time_microseconds` and set
`max_rows_to_read = 0`.

`05182` opens `CLICKHOUSE_PORT_POSTGRESQL`, which fasttest does not enable, so it gets the same
`no-fasttest` tag as the other PostgreSQL wire-protocol tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118369&sha=409d62d37d6526ec76d3f0fa442b895144fbf738&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (Logical error: Got read request from replica A for unknown stream B, tracked in #110518, unrelated to the PostgreSQL handler) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other two reds on that run were the fleet-wide 03100_lwu_deletes_4_index burst of 2026-09-11 (already fixed on master and pulled in by the merge) and a job-level error in the coverage stateless lane.

@groeneai

Copy link
Copy Markdown
Collaborator

Not the PostgreSQL handler, agreed. On this run the abort is the parallel-replicas symptom of #112891, and my fix for that is already open: #114955.

The failing statement is SELECT id, department FROM t_mt_index_rp ORDER BY id in 04891_mergetree_index_respects_row_policy.sql. The table is ORDER BY (department, id) and the policy is USING department = 'engineering', so on the initiator the policy filter fixes department, ORDER BY id then matches the second key position, the read is planned in order, and the coordinator is created for ...t_mt_index_rp#split_0 with mode WithOrder. The followers receive the serialized query plan without the row-level filter, so they get Key condition: unknown, plan a default (not in-order) read, and announce the bare ...t_mt_index_rp. The coordinator ignores that announcement as an unknown stream, the default pool discards the announcement response by design and so never learns the stream is unknown, and it then sends a read request for it, which is the LOGICAL_ERROR. The full server log trace for the same failure is in my reply on #119381. #114955 replans the read on the executing server with that server's own policies, so both sides derive the same coordination mode and the same stream id.

Two notes on where this is visible. The abort is on the previous release (No Error messages after server upgrade is green on this job, and the upgrade check's only test load runs before the upgrade), so no change to master can clear that lane. That is why my merged #119406 stopped the upgrade check from drawing serialize_query_plan; it landed at 10:25 UTC on 2026-09-11, about two hours after this run started, and since CI tests this branch merged with master, a rerun picks it up and this row should not come back. What is still live on master is the stress lanes, most recently Stress test (amd_debug) on 2026-09-17 with the same table, and that is what #114955 fixes.

One thing to expect in this check regardless: the same STID also reaches it by the join route, 04649_pr_plan_based_join_distributed.sql / jd_r, last seen on 2026-09-17. That route is fixed on master by my merged #118084, but because the load runs against the previous release, it stays visible in the upgrade check until a release carries the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118369&sha=0db9b39955866061975e2881f884582961c915de&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 (Hung check failed, possible deadlock found, the stuck thread is in DatabaseReplicatedDDLWorker → InterpreterCreateQuery::createTable → getDependenciesFromCreateQuery → SelectQueryDescription::getSelectQueryFromASTForMatView; this PR only changes PostgreSQLHandler) and provide a fix in a separate PR. If the fix is already in progress, link it here. The Build profile diff red is the CI logs cluster query failure (infra). I merged master (1f7ab90) for a fresh run; the two PostgreSQL tests pass 3x locally on the merged build.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Not caused by this PR, and the frame quoted above is not the stuck thread.

getSelectQueryFromASTForMatView reaches the report through the hung check's Top messages without format string table (row 19), as the stack of a thrown Code: 397. MATERIALIZED VIEW cannot have PREWHERE, SAMPLE or FINAL, count 2: a fuzzer-mutated CREATE MATERIALIZED VIEW that was correctly rejected. It sits in the log-statistics tables that hung_check.log appends after the stack dumps (line 720 of 818, the dumps end at 254), and CIDB keeps only the last 32 KiB of the failure text, so those tables are the only part that survives there.

The single entry under Found hung queries in processlist: is:

query_id 5380c7d4-9139-4880-8f8d-04445e93470d, is_internal=1, elapsed 907.03 s, is_cancelled=1
log_comment 05109_json_empty_streams_marks_not_loaded.sh-test_7, max_execution_time=10
INSERT INTO test_7.t_json_empty_streams_sync
SELECT number, CAST(concat('{"a":', toString(number), ...), 'JSON') FROM numbers(2147483648)

Two of its 14 threads hold the wedge, both inside the per-granule loop of MergeTreeDataPartWriterWide::writeColumn:

  • 19162: getCurrentMarksForColumn -> SerializationObject::enumerateStreams -> ISerialization::SubstreamData::~SubstreamData
  • 19306: getCurrentMarksForColumn -> SerializationObject/SerializationDynamic/SerializationVariant::enumerateStreams -> ISerialization::getFileNameForStream

with __msan::PoisonMemory / StackDepotBase::Put innermost, which is why this shape surfaces on the msan flavours. Thread 10015 waits in CompletedPipelineExecutor::execute under executeASTFuzzerQueries. So this is not a deadlock: that loop has no cancellation point, so is_cancelled=1 from max_execution_time=10 left the query running 907 s.

A fix is already in progress and it is not mine: #108357. Its MergeTreeDataPartWriterWide.cpp hunk inserts checkWriteCancellation() as the first statement of exactly that for (const auto & granule : granules) loop, and checkWriteCancellation() calls throwIfKilled(), which covers a throw-mode max_execution_time.

Fix-presence probe: checkWriteCancellation has 0 occurrences in MergeTreeDataPartWriterWide.cpp and MergeTreeDataPartWriterOnDisk.cpp both on the tested build f3e839b1f062 (the merge commit for 0db9b399) and on master today. Master's only per-granule check of this kind is the checkTimeLimit() in calculateAndSerializeSkipIndices, which does not cover column writes.

So there is no separate PR from me here; I am tracking #108357 and will report if it stops being the owner.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, that makes sense: the stress hang is the uncancellable per-granule write loop tracked in #108357, not this PR.

The only red on the last run (1f7ab900551) was Performance Comparison (arm_release, master_head, 2/6): order_by_read_in_order #1 (14.8 ms -> 20.9 ms). This PR only changes PostgreSQLHandler. That query is a known false positive, tracked in #121456 with a fix in progress in #122459.

I merged the latest master (f0011155b21, clean merge, clickhouse builds) to get a fresh run.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into master with commit d3cc829 Oct 3, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/postgresql-error-response-on-canceled-socket branch October 3, 2026 22:22
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... 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