Skip to content

Reapply "Make postgresql and PostgreSQL engine work against a ClickHouse instance", with a fix for the cancel-request logical error - #112940

Merged
alexey-milovidov merged 123 commits into
masterfrom
reapply-pg-self-connect
Oct 11, 2026
Merged

alexey-milovidov merged 123 commits into
masterfrom
reapply-pg-self-connect

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Reapply #110760, reverted in #112935, together with a fix for the bug that motivated the revert.

Related: #110760
Related: #112935
Related: #84085

Why it was reverted, and why the bug is not in the reverted change

Every Stress test job on master started failing with

Logical error: 'Query context must be created after authentication'
  DB::Session::makeQueryContextImpl @ src/Interpreters/Session.cpp:690
  DB::PostgreSQLHandler::cancelRequest @ src/Server/PostgreSQLHandler.cpp:867
  DB::PostgreSQLHandler::startup @ src/Server/PostgreSQLHandler.cpp:737

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=cd6fd72e2b29fa607cffe0595e347452f8dcba9b&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

A PostgreSQL client cancels a running statement by opening a second connection and sending a
CancelRequest on it, carrying the (process id, secret key) pair the server handed out in
BackendKeyData. By the protocol that connection never authenticates - the secret key is the
credential - so PostgreSQLHandler::cancelRequest has no authenticated session, and the
session->makeQueryContext() it called throws LOGICAL_ERROR. That has been true since sessions
were introduced (51ffc334573), and it is reachable by any PostgreSQL client that cancels a
statement: psql on Ctrl-C, or the pgx driver in issue #84085, which reports this very error.

#110760 did not introduce it, it only made CI reach it: with ClickHouse acting as a libpq/pqxx
client against itself, PostgreSQLSource cancels the remote statement through PQcancel, so a
stress run that cancels a query now sends a cancel request to the server's own PostgreSQL port.

The fix (second commit)

  • cancelRequest cancels the query through the process list directly, which needs no session, via
    a new ProcessList::sendCancelToQueryOfAnyUser. Only queries whose id has the
    postgres:<connection id>:<secret key> shape the server itself assigns can be named this way, and
    the secret key is what makes such an id unguessable - the same credential PostgreSQL relies on.
  • The raw KILL QUERY result the old code wrote straight into the client socket is gone with it.
    The protocol expects no answer at all to a cancel request, so that was protocol garbage.
  • The secret key never matched anything either: BackendKeyData was sent while secret_key was
    still zero, and every statement then re-randomized it, so the query id a cancel request resolved
    to was never the id of a running query - cancellation over the PostgreSQL protocol has never
    worked. The key now belongs to the connection, as in PostgreSQL, where it identifies the backend
    rather than one statement, and every statement of the connection runs under
    postgres:<connection id>:<secret key>. Statements of one connection run one after another, so
    reusing the id is safe.
  • New test 04669_postgresql_protocol_cancel_request, which drives a real psql and cancels it
    with SIGINT - that is what makes psql send a CancelRequest.

The -- ping half of issue #84085 (a comment-only statement is not recognized as an empty query) is
not addressed here.

Privileges

A self-connect needs nothing beyond access to the table being read. system.databases,
system.tables and system.columns, which the emulated pg_namespace, pg_class and
pg_attribute are views over, are readable by every user even with
access_control_improvements.select_from_system_db_requires_grant enabled, and their rows are
filtered by the reader's own grants - so the catalog shows a user exactly the relations that user
may read, as pg_catalog does in PostgreSQL.

Changelog category (leave one):

  • New Feature

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

The postgresql table function and PostgreSQL table engine can now be used to connect to another ClickHouse server over the PostgreSQL protocol (inferring the structure of the query(...) variant is not supported yet, so it needs an explicit column list). Added the PostgreSQL-compatibility functions format_type and current_setting. Fixed cancellation over the PostgreSQL protocol: a cancel request used to log a logical error and never cancelled anything.


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

Version info

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

…ckHouse instance"

This reverts commit ea54b3c.

The reason for the revert was a `Query context must be created after authentication`
logical error in the `Stress test` jobs on master. It is not introduced by this change:
`PostgreSQLHandler::cancelRequest` has needed an authenticated session that a
PostgreSQL cancel request never has since sessions were introduced. This change only
made the path reachable in CI, because it makes ClickHouse a libpq client against
itself and `PostgreSQLSource` cancels the remote statement through `PQcancel`. The
next commit fixes that bug.
A PostgreSQL client cancels a running statement by opening a second connection and
sending a `CancelRequest` on it, carrying the `(process id, secret key)` pair the
server handed out in `BackendKeyData`. By the protocol that connection never
authenticates - the secret key is the credential - so `PostgreSQLHandler::cancelRequest`
had no authenticated session, and `Session::makeQueryContext` threw
`Query context must be created after authentication` (`LOGICAL_ERROR`). Cancel the
query through the process list directly instead, which needs no session; the raw
`KILL QUERY` output the old code wrote straight into the client socket, where the
protocol expects no answer at all, is gone with it.

The secret key never matched anything either: `BackendKeyData` was sent while
`secret_key` was still zero, and every statement then re-randomized it, so the query
id a cancel request resolved to was never the id of a running query. The key now
belongs to the connection, as in PostgreSQL, where it identifies the backend rather
than one statement, and every statement of the connection runs under
`postgres:<connection id>:<secret key>`. Statements of one connection run one after
another, so reusing the id is safe.

Reachable by any PostgreSQL client that cancels a statement - `psql` on Ctrl-C, or the
`pgx` driver in the issue below.
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b3d39c]

Summary: ✅


AI Review

Summary

This PR adds a lot of PostgreSQL-compatibility surface area — self-connect for the postgresql table function / PostgreSQL table engine, catalog emulation, COPY, compatibility functions, and cancel-request fixes — and most of the earlier review history looks addressed. I found one remaining correctness gap: CSV COPY still inherits ClickHouse's bare-Tuple flattening settings, so a single PostgreSQL-visible column can turn into multiple CSV fields on the wire.

Findings

⚠️ Majors

  • [src/Server/PostgreSQLHandler.cpp:1374] pinCopyFormatSettings does not pin the tuple-related CSV settings, so COPY ... WITH (FORMAT csv) can serialize a bare Tuple column as multiple CSV fields even though the PostgreSQL surface advertises it as one text column and CopyOutResponse reports one column. COPY FROM STDIN has the symmetric problem on input. Pin output_format_csv_serialize_tuple_into_separate_columns, output_format_csv_header_serialize_tuple_into_separate_columns, and input_format_csv_deserialize_separate_columns_into_tuple to false, or force tuple values through one text field before handing them to the CSV format.
Final Verdict

⚠️ Needs changes before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 1, 2026
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 1116/1285 (86.85%) · Uncovered code

Full report · Diff report

`fetchPostgreSQLTableStructureImpl` looks the physical columns up in
`current_schema()` when no schema is given, but the `with_replica_identity_index`
query at the end of the same helper still fell back to a hardcoded `public`, so a
caller asking for `replica_identity_columns` described the columns of one relation
and the replica identity of another whenever the connected schema is not `public` -
which, against a ClickHouse server, is every database other than one named `public`.
On real PostgreSQL with the default search path `current_schema()` is `public`, so
nothing changes there.
…s enough

The flaky check failed `04665_postgresql_self_connect` with "Test runs too long
(> 180s)": every self-connect opens a second connection and runs a handful of
catalog queries on it, and the test spent eleven `clickhouse-client` invocations
and six self-connects doing that, which is slow enough under a sanitizer on a
loaded server to cross the limit (196 runs of that job passed, averaging 99s).

The test now runs as a single client invocation, drops the `count()` read that the
row-by-row read already covers, and the `PostgreSQL` engine, the explicit schema and
the search path move to `04692_postgresql_self_connect_engine`. Both take about a
second here.

The blanket `GRANT SELECT ON system.*` is gone with it: `system.databases`,
`system.tables` and `system.columns`, which the emulated `pg_namespace`, `pg_class`
and `pg_attribute` are views over, are readable by every user - their rows are
filtered by the user's own grants - so a grant on the table to read is all a
self-connect needs. The one remaining `GRANT SELECT ON system.one` is for the table
the first query reads, not for the catalog.
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

12 object files changed (+698.88 KiB total), 2 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/postgresCatalog.cpp.o new 361.03 KiB +361.03 KiB
src/CMakeFiles/dbms.dir/Server/PostgreSQLHandler.cpp.o 628.89 KiB 841.02 KiB +212.12 KiB (+33.73%)
src/CMakeFiles/dbms.dir/Processors/Formats/PostgreSQLArrayText.cpp.o new 89.39 KiB +89.39 KiB
src/CMakeFiles/dbms.dir/Core/PostgreSQLProtocol.cpp.o 9.53 KiB 35.22 KiB +25.69 KiB (+269.51%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

29 translation units recompiled, 146 s compile time in total, 27 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. This failure is not caused by this PR: the PR does not touch ReplicatedMergeTreeQueue or the replication queue, and this is the only occurrence of in the memory queue in CIDB over the last 120 days (0 on master). No fix is in progress yet. I'm investigating the removeProcessedEntry path for the finished MUTATE_PART entry and will post the fixing PR here.

Comment thread src/Parsers/ParserCopyQuery.cpp Resolved
Comment thread src/Parsers/ParserCopyQuery.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Functions/postgresCatalog.cpp Resolved
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR: #119264 (mine, open). My "no fix is in progress" above was wrong: this is the release-build form of the race that PR fixes. On the attach path, a ZSESSIONEXPIRED in queueUpdatingTask woke the restarting thread's pool task while the inline activation was still running, and its second tryStartup reinitialized the queue under the running MUTATE_PART for all_1_1_0_5, so removeProcessedEntry no longer found the original entry. Server log timeline: #119264 (comment)

alexey-milovidov and others added 5 commits October 9, 2026 20:26
…nect

The conflict in `ParserCopyQuery.cpp` is resolved by keeping this branch's
non-throwing `COPY` option parser and applying master's acceptance of the
terminating `;` (`isEndOfStatement`) to its option loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `COPY (query)`

The option scan of `ParserCopyQuery::parseOptions` treated `WITH`, `AS`,
standalone booleans and stray punctuation as inert, so e.g.
`COPY t TO STDOUT WITH (FORMAT csv, false)` ran as `WITH (FORMAT csv)`. A
boolean is now accepted only as the value of `HEADER`, `AS` only after
`DELIMITER` / `NULL` / `QUOTE`, `WITH` only at the start of the options, and
punctuation other than balanced parentheses and commas is rejected; the
command is answered with "malformed option syntax".

`COPY (SELECT 1) AS junk TO STDOUT` dropped the alias of the subquery and ran
as `COPY (SELECT 1) TO STDOUT`; an alias is now a syntax error.

The endpoint after `TO` / `FROM` is now required: the handler splits the
statements on `;` before parsing, so `COPY t TO;` reached the parser as
`COPY t TO` and ran as `COPY t TO STDOUT`, which the test
`05331_postgresql_copy_trailing_semicolon` from master rejects. Its reference
also loses the empty line after each `COPY ... TO STDOUT`: that came from the
`CopyCompletionResponse` sent on master, while this branch ends the copy with
`CopyDone` and `CommandComplete`, after which `psql` prints nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`rewritePgTableIsVisible` rewrote any `pg_table_is_visible(...)`, so
`SELECT other.pg_table_is_visible(oid)` became `other.((oid) IN (...))`. The
`pg_catalog.` qualifier is already removed by `removePgCatalogQualifier`, so a
call that is still qualified belongs to another schema and is left alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In PostgreSQL `format_type` is not strict, and a `NULL` type modifier means
that no modifier is known, so introspection queries use
`format_type(t.oid, NULL)`. The function now takes a `NULL` or `Nullable`
type modifier and treats `NULL` as `-1`; only a `NULL` type OID gives `NULL`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le` and `format_type` with `NULL`

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 I merged master and resolved the conflict in ParserCopyQuery.cpp (654fd901908). The resolution keeps this branch's non-throwing option parser and adds master's handling of the terminating ;. The COPY endpoint is now required (8ecc3c13326). The handler splits statements on ; before parsing, so without that change COPY t TO; would run as COPY t TO STDOUT, and master's new test 05331_postgresql_copy_trailing_semicolon rejects it. Its reference also loses the empty lines that came from master's CopyCompletionResponse. The four review threads are addressed and resolved. The previous arm_tidy failure (FifoQueue in gtest_throttler_constraint.cpp) came from master, and its fix be9cfb18407 is part of this merge. @groeneai, thanks for linking #119264 for the stress-test failure.

Comment thread src/Core/PostgreSQLProtocol.h Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
Comment thread src/Server/PostgreSQLHandler.cpp Resolved
…py-out, limits of the catalog refresh

- `normalizeDecimal` checked the precision after padding the digits with the display-only leading zero,
  so a valid `Decimal256(76)` value like `0.0...01` (76 fractional digits) was rejected as a `numeric`
  or `numeric[]` prepared-statement parameter. Check the precision before padding.
- A `COPY ... TO STDOUT` cancelled by `CancelRequest` / `KILL QUERY` is reported with SQLSTATE `57014`
  (as `COPY FROM STDIN` already is), not with the generic `2F000`.
- `refreshCatalogOids` runs before any statement that mentions `pg_` and inherited the scan and
  complexity limits of the session, so e.g. `max_rows_in_set` could make an unrelated statement fail.
  Reset those limits in the internal context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// to move them: a session that did `SET format_csv_delimiter = ';'` would otherwise get its
/// `COPY ... WITH (FORMAT csv, DELIMITER ',')` accepted and then served with `;`, which is the silent
/// shape mismatch the option list is there to prevent. The NULL marker of the CSV format is set
/// afterwards from `ASTCopyQuery::csv_null_marker`.
void pinCopyFormatSettings(const ContextMutablePtr & query_context)
{
query_context->setSetting("format_csv_delimiter", String(","));

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.

Because pinCopyFormatSettings leaves the CSV tuple settings at their defaults, COPY ... WITH (FORMAT csv) still inherits ClickHouse's bare-Tuple flattening on the PostgreSQL path. A column like Tuple(UInt8, UInt8) is advertised as one text column (convertDataTypeToPostgresColumnTypeSpec falls back to VARCHAR), but CSV / CSVWithNames will emit two CSV fields by default, and COPY FROM STDIN will symmetrically accept two fields into one column.

That breaks the PostgreSQL COPY contract for every bare Tuple column: CopyOutResponse still reports one column, while the payload/header carry two fields (x.1,x.2 / 1,2). Please pin output_format_csv_serialize_tuple_into_separate_columns, output_format_csv_header_serialize_tuple_into_separate_columns, and input_format_csv_deserialize_separate_columns_into_tuple to false here (or otherwise force tuple values through a single text field, the way arrays are handled).

@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026

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

Looks good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into master with commit 6c579f3 Oct 11, 2026
163 checks passed
@alexey-milovidov
alexey-milovidov deleted the reapply-pg-self-connect branch October 11, 2026 02:39
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is there a check if the number of columns returned by the function doesn't match the alias? I think I found an issue like this before in a similar place.

@groeneai

Copy link
Copy Markdown
Collaborator

No. The alias list is checked only after a subquery: (SELECT * FROM t) AS x(p, q, r) fails with Number of aliases does not match number of projection columns. Expected 2, got 3 (QueryNode.cpp:68). After a table function or a table it is neither checked nor applied, because QueryTreeBuilder::buildJoinTree reads column_aliases only in its subquery branch. On master 371b23a4, with t (a UInt32, b String):

SELECT * FROM postgresql('127.0.0.1:21550', 'default', 't', 'u', 'p') AS x(p, q, r); -- columns a, b, no error
SELECT * FROM numbers(2) AS x(a, b, c); -- column number, no error
SELECT a FROM t AS x(b, a);             -- t.a (1, 2); (SELECT * FROM t) AS x(b, a) gives t.b ('x', 'y')

The last one is a silent wrong result. It is not specific to this PR and is already reported as #124803 (open, no fixing PR yet). It also shows up through this PR's self-connect: a PostgreSQL-valid query('SELECT * FROM t AS x(p, q)') fails against a ClickHouse server with Unknown expression identifier p.

The lists the postgresql engine sends itself match by construction: in doQueryResultStructure, unnest(...) WITH ORDINALITY AS t(type_oid, type_mod, ord) and (query) AS __subquery(c0, ...) are built from the column count of the LIMIT 0 sample, and PostgreSQLSource rejects a row with more fields than the header (TOO_MANY_COLUMNS).

I can send the fix for #124803 if nobody else is on it.

qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Oct 22, 2026
In a simple-query message holding several statements, every statement must
report its own row count in `CommandComplete`. On releases 26.3 to 26.9
statement N reported N times its count, because `processQuery` reused one query
context for every statement and `executeQueryWithTracking` chained a progress
callback onto the previous statement's callback, writing into counters of a
returned stack frame. Master is fixed by ClickHouse#112940 (per-statement query context,
callback-owned counters restored on exit), but nothing asserted the counts: the
same fix first landed with ClickHouse#110760 and was reverted along with it (ClickHouse#112935)
without any test noticing.

The test speaks the PostgreSQL wire protocol over a raw socket and prints every
`CommandComplete` tag of two multi-statement queries (SELECT and INSERT, which
use the `result_rows` and `written_rows` counters). It prints
`SELECT 9, SELECT 18, SELECT 12` / `INSERT 0 7, INSERT 0 4` on v26.3.57.12-lts,
v26.8.32.14-lts and v26.9.23.15, and matches the reference on master.

Closes ClickHouse#117805

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-feature Pull request with new product feature 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