Skip to content

Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state - #118210

Merged
antonio2368 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-out-of-cycle-rejection
Sep 8, 2026
Merged

antonio2368 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-out-of-cycle-rejection

Conversation

@groeneai

@groeneai groeneai commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Flush, and any message type this handler does not implement, is answered with ErrorResponse and then sets ignore_until_sync, which is left only at Sync. While it is set every other message is discarded, so a client that sends one of those with no extended-query cycle open never receives ReadyForQuery again and its next Query is dropped unexecuted. A simple-query client never sends Sync, so its connection stays open and permanently silent.

This tracks whether a cycle is open and enters the discard state only then; outside a cycle the client is owed a ReadyForQuery at once. Errors inside a real cycle still recover at Sync, so a pipelined Execute after a rejected message is still discarded and one Sync still yields exactly one ReadyForQuery.

Making the simple Query a cycle-ending boundary exposed an older defect at the same site: unlike Sync, it did not destroy the unnamed prepared statement or the unnamed portal. Parse(""), Bind(""), Query(...), Execute("") therefore ran the stale portal instead of failing, and a Bind("") after the simple query still resolved a statement that should no longer exist. PostgreSQL destroys both (exec_simple_query calls drop_unnamed_stmt()); this now does too, leaving named statements and the SQL-level PREPARE/EXECUTE path untouched. That half is reachable on released builds (observed on 26.7.6.57 and 26.8.2.7), which is why the category is Bug Fix.

Each new or strengthened test fails on pristine master and passes here; the module's remaining failure set is unchanged.

Two things this does not change, both noted in the issue: the Flush error text still says the extended query mechanism is unsupported, and Flush is still rejected rather than implemented as an output flush.

Closes: #118202
Related: #108469

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

A simple Query in the PostgreSQL wire protocol now destroys the unnamed prepared statement and the unnamed portal, as PostgreSQL does, so a later Bind or Execute on them is rejected instead of silently reusing stale extended-query state. A Flush or unimplemented message sent outside an extended-query cycle also no longer leaves the connection unable to answer further queries; that half only affects unreleased code from #108469.


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

Version info

  • Merged into: 26.9.1.948 (included in 26.9 and later)
  • Backported to: 26.8.3.69, 26.7.7.49, 26.6.5.77, 26.3.33.17

…sage

`Flush`, and any message type the server does not implement, is answered with
`ErrorResponse` and then sets `ignore_until_sync`. That state is left only at
`Sync`, and while it is set every other message is discarded, so a client that
sends one of those messages with no extended-query cycle open never receives
`ReadyForQuery` again and its next `Query` is dropped unexecuted. A simple-query
client never sends `Sync`, so its connection stays open and permanently silent.

Track whether an extended-query cycle is open, and enter the discard state only
then. Outside a cycle the client is owed a `ReadyForQuery` right away, which is
what the server answered before the discard state reached these two branches.

The integration test covers both branches that reach it, `Flush` and an
unimplemented message type, and asserts that the connection still runs a query
afterwards.
`test_flush_error_discards_until_sync` read the pipeline reply up to the first
`ReadyForQuery` and then accepted any later `CommandComplete`. A handler that
emitted `ReadyForQuery` immediately after the `Flush` error and only then ran the
queued `Execute` satisfied both assertions, because the `Execute` reply had not
been read yet and turned up in the following read. Measured with the cycle flag
forced to false at all of its assignments: the test passed.

Read an empty simple query next, which answers with `EmptyQueryResponse` and
nothing else, and require exactly that. With the same forced flag the test now
fails with `['T', 'D', 'C', 'Z', 'I', 'Z']`, naming the late `Execute` directly.
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6359a44]

Summary: ✅


AI Review

Summary

This PR makes PostgreSQLHandler treat a simple Query as the boundary that ends the current extended-query cycle, clears the unnamed prepared statement and unnamed portal at that boundary, and only enters ignore_until_sync for rejected FLUSH or unsupported messages when an extended-query cycle is actually open. The current head is consistent with that contract: the handler now drops the unnamed state before processQuery(), and the new integration coverage exercises both out-of-cycle rejection recovery and the stale unnamed-state cases. I did not find any remaining blockers or majors in the current diff.

Missing context / blind spots
  • ⚠️ The full PR matrix was still pending on 2026-09-07 when reviewed; only Style check, Fast test, and the Build profile diff report had finished. Cross-platform build and sanitizer coverage is therefore not confirmed yet.
Final Verdict

✅ No remaining review findings in the current head. The prior bot thread about stale unnamed extended-query state is fixed and was resolved.

LLVM Coverage Report

Measured on commit 6359a44.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

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

Full report · Diff report

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6359a441f with master 58f74d473 (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

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

Job report

@antonio2368

Copy link
Copy Markdown
Member

@groeneai merge master

@antonio2368 antonio2368 self-assigned this Sep 7, 2026
…of-cycle-rejection

ClickHouse#118097 moved the `ignore_until_sync` reset out of the `Sync` case in `run()` and
into `processSyncQuery()`, which conflicted with the `in_extended_query_cycle`
reset that sits beside it. Resolution keeps master's removal and the cycle reset,
so every cycle-flag assignment stays in `run()`'s switch and clearing
`ignore_until_sync` stays where master put it.
No test reddened if the `Sync` case stopped clearing `in_extended_query_cycle`:
the out-of-cycle test opens fresh connections whose flag was never set, and the
`FLUSH` test runs a simple query before any further rejection, which clears the
flag on its own. With the reset removed, a `Flush` sent after a completed
extended-query cycle waits again for a `Sync` that the client has no reason to
send.

Send that second `Flush` right after the cycle's `Sync` and require exactly
`ErrorResponse` and `ReadyForQuery`. Measured with the reset removed: the new
assertion fails with `['<no ReadyForQuery, client left waiting>']`, while the
pre-existing assertions and the out-of-cycle test still pass.
The out-of-cycle test ran its control `Query` on a connection whose cycle flag
was still false from the handshake, so removing the reset in the `QUERY` case
left the test green. A client that runs `Parse`, then a simple query, then a
standalone `Flush` would go deaf again.

Open a cycle with `Parse` before the control query, and require `ParseComplete`
so the arm cannot pass without one. Measured with that reset removed: the test
fails with `['<no ReadyForQuery, client left waiting>']`, while the FLUSH test,
which does not depend on this reset, still passes.

The flag's declaration named `Sync` as the only closing transition, which the
`QUERY` case has always contradicted; say so where the flag is declared.
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master at 7152cbb, so the PR is mergeable again. The one conflict was the SYNC case in run(): #118097 moved the ignore_until_sync reset into processSyncQuery(), so I kept that removal and left only the in_extended_query_cycle reset there.

Two test commits ride along, because re-checking the merged tree showed that neither cycle reset was pinned by an assertion: with the reset in SYNC deleted, or with the one in QUERY deleted, every test still passed. Each now has one arm that fails without it, a second Flush immediately after the cycle's Sync and a Parse before the control query. test_postgresql_protocol passes on the merged tree.

Comment thread src/Server/PostgreSQLHandler.cpp Resolved
`Sync` and a simple `Query` both end an extended-query cycle, and this handler
now treats them as equivalent boundaries, but only `Sync` cleared the cycle's
objects. After `Parse("")`, `Bind("")`, `Query(...)`, a bare `Execute("")` still
ran the portal bound before the simple query, and a `Bind("")` after it still
resolved the unnamed prepared statement. PostgreSQL rejects both cases
(`exec_simple_query` calls `drop_unnamed_stmt()` and recreates the unnamed
portal), so stale extended-query state stayed executable across a boundary that
should have destroyed it.

Measured on 7152cbb: `Execute("")` after the simple query returned the stale
portal's row instead of an error; it now answers `Execute without prior Bind`,
and a later `Bind("")` answers `Unknown statement`. Named statements are
unaffected, as is the SQL-level `PREPARE`/`EXECUTE` path.

The defect predates ClickHouse#108469: `resetBindQuery()` is called only from
`processSyncQuery` and `Close('P')` on master and at that PR's base alike. It is
fixed here because this PR is what makes the simple `Query` a cycle-ending
boundary.

Reported by the AI reviewer on ClickHouse#118210.

The `Parse` comment claiming a cycle ends only at `Sync` contradicted that, so it
now names both boundaries.

`test_out_of_cycle_rejection_keeps_connection_usable` also now sends the rejected
message as the connection's first message. Every other case opens and ends a cycle
first, so a handler that started out believing a cycle was in progress kept the
whole suite green while a fresh simple-query connection went deaf on its first
`Flush`.
@groeneai groeneai changed the title Keep a PostgreSQL connection usable after a rejected out-of-cycle message Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

The finding is real, and it is older than this PR: resetBindQuery() is called only from processSyncQuery and Close('P'), on master and at #108469's base alike, so a simple Query never destroyed the unnamed prepared statement or the unnamed portal.

It also reproduces on released builds, not just master. On 26.7.6.57 and 26.8.2.7, Parse(""), Bind(""), Query("SELECT 222"), Execute("") answers RowDescription/DataRow for the stale portal's SELECT 111, and a Bind("") sent after the simple query still resolves the statement that should be gone. Both now answer ErrorResponse. Named statements and the SQL-level PREPARE/EXECUTE path are unaffected.

Since that half is user-visible in a stable release, I moved the changelog category from Not for changelog to Bug Fix and rewrote the entry to cover both behaviours. I kept the cleanup in this PR because it lands on the same case QUERY: this PR already changes, but if you would rather have it split out and this one back at Not for changelog, I will do that.

Separately, test_out_of_cycle_rejection_keeps_connection_usable now also sends the rejected message as the connection's first message. Every case opened and ended a cycle first, so initialising in_extended_query_cycle to true left the whole suite green while a fresh connection's first Flush went deaf, which is exactly the bug this PR fixes.

New head: 6359a441f30dab9.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 7, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 8, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 8, 2026
Cherry pick #118210 to 26.3: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
robot-clickhouse added a commit that referenced this pull request Sep 8, 2026
…y and stale unnamed extended-query state
robot-ch-test-poll2 added a commit that referenced this pull request Sep 8, 2026
Cherry pick #118210 to 26.8: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
robot-clickhouse added a commit that referenced this pull request Sep 8, 2026
…y and stale unnamed extended-query state
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 8, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 8, 2026
…y and stale unnamed extended-query state
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #118210 to 26.6: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #118210 to 26.7: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
antonio2368 added a commit that referenced this pull request Sep 8, 2026
Backport #118210 to 26.3: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
antonio2368 added a commit that referenced this pull request Sep 9, 2026
Backport #118210 to 26.8: Fix PostgreSQL out-of-cycle message recovery and stale unnamed extended-query state
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
…ge recovery and stale unnamed extended-query state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

Flush/unsupported message sets ignore_until_sync: simple-query connection goes deaf

5 participants