Skip to content

Fix server abort on PostgreSQL value type mismatch - #110264

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-query-type-mismatch-abort
Jul 14, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-postgresql-query-type-mismatch-abort

Conversation

@groeneai

@groeneai groeneai commented Jul 13, 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 a server abort (in debug and sanitizer builds) when a value from a mysql/postgresql/sqlite-family PostgreSQL source is read into a declared type it cannot be parsed into (for example a text column declared as Int32). Such a type mismatch is now reported as a query error instead of aborting the server.

Description

Follow-up to #107740 (which added passing a query to the postgresql table function and engine). While extending the integration coverage that PR asked about, the type-mismatch edge path was found to abort the server.

Reading a PostgreSQL text value into a numeric declared type makes pqxx::from_string throw pqxx::conversion_error. That is a foreign std::exception (not a DB::Exception), so it escaped insertPostgreSQLValue and hit abortOnFailedAssertion (signal 6 / LOGICAL_ERROR) in debug and sanitizer builds instead of failing the query.

The fix wraps insertPostgreSQLValue in a function-try-block that converts pqxx::conversion_error (which also covers the conversion_overrun overflow subclass) into a BAD_ARGUMENTS error. The fix is in the value layer shared by the query-passing and the plain table-name PostgreSQL read paths, so it covers both.

Repro (aborts the server before the fix):

-- PostgreSQL: CREATE TABLE t (a integer, b text); INSERT ... ('name_0');
CREATE TABLE m (a Int32, b Int32)
ENGINE = PostgreSQL('host:5432', 'db', query('SELECT a, b FROM t'), 'user', 'pass');
SELECT * FROM m;  -- b is text 'name_0' read into Int32

Also adds integration coverage for the query-passing feature edge paths @PedroTadim asked about on #107740: missing permissions, empty result sets, and type mismatches (tests/integration/test_storage_postgresql/test.py::test_postgres_query_passing_edge_cases).

Version info

  • Merged into: 26.7.1.905 (included in 26.7 and later)

Reading a PostgreSQL text value into a numeric declared type (e.g. a column
declared Int32 over a text result) made pqxx::from_string throw
pqxx::conversion_error, a foreign std::exception that escaped
insertPostgreSQLValue and aborted the server (signal 6 / LOGICAL_ERROR in
debug and sanitizer builds) instead of failing the query.

Convert pqxx::conversion_error (covering the conversion_overrun overflow
subclass) into a BAD_ARGUMENTS query error. Applies to both the query-passing
and the plain table-name PostgreSQL paths.

Add integration coverage for the query-passing feature edge paths: missing
permissions, empty result sets, and type mismatches.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT * FROM PostgreSQL(..., query('SELECT a, b FROM t'), ...) with declared (a Int32, b Int32) over a text column aborts the server every time (debug/sanitizer).
b Root cause explained? pqxx::from_string<int32_t>("name_0") throws pqxx::conversion_error, a foreign std::exception. It escapes insertPostgreSQLValue (which had no catch) up to abortOnFailedAssertion -> signal 6 / LOGICAL_ERROR in debug/sanitizer builds.
c Fix matches root cause? Yes. A function-try-block on insertPostgreSQLValue converts pqxx::conversion_error into a BAD_ARGUMENTS DB::Exception at the value-parsing boundary where the foreign exception originates.
d Test intent preserved / new tests added? New test test_postgres_query_passing_edge_cases added (missing perms, empty result set, type mismatch). No existing test weakened.
e Demonstrated in both directions? Yes. Baseline build: test crashes (Received signal 6, pqxx::conversion_error). With fix: test passes and the query returns Cannot parse PostgreSQL value ....
f Fix is general, not a narrow patch? Yes. Fix is in the shared value layer insertPostgreSQLValue, covering both the query-passing and plain table-name PostgreSQL read paths and every scalar type parsed via pqxx::from_string.
g Generalizes across inputs/types? pqxx::conversion_error is the base of conversion_overrun (overflow) and unexpected_null, so malformed and out-of-range text values for all numeric types are caught, not just the reproduced Int32 case.
h Backward compatible? Yes. No setting/format/behavior change for valid data; only a previously-crashing case now returns a clean error.
i Invariants and contracts preserved? Yes. Column insertion is all-or-nothing per value: the throw happens before insertValue, so no partial/torn column state; block-structure invariants are unchanged.

Session id: cron:clickhouse-worker-slot-6:20260713-121100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @scanhex12 — could you review this? A PostgreSQL text value read into a numeric declared type made pqxx::from_string throw pqxx::conversion_error (a foreign std::exception), which escaped insertPostgreSQLValue and aborted the server in debug/sanitizer builds; this converts it into a BAD_ARGUMENTS query error at the value-parsing boundary. Also adds the missing-perms / empty-result / type-mismatch integration coverage for the #107740 query-passing feature.

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [10829d5]

Summary: ✅


AI Review

Summary

This PR normalizes PostgreSQL value-conversion failures to BAD_ARGUMENTS, keeps MaterializedPostgreSQL advancing on bad source values, and adds regression coverage for query-passing and replication edge cases. The current head appears to close the previously discussed duplicate-on-retry and Decimal partial-insert problems, but one blocker remains: the new catch-all std::exception translation still converts allocator failures into bad-input errors, which can silently default data in the replication path.

PR Metadata

The chosen Bug Fix category is defensible, but the changelog entry does not accurately describe the scope of the code change: the implementation changes are PostgreSQL-only, while the MySQL and SQLite diffs are test coverage.
Suggested replacement: Reading a value from PostgreSQL into an incompatible declared type now returns a clean query error instead of an internal exception. MaterializedPostgreSQL also keeps replicating by inserting the column default for the bad source value.

Findings

❌ Blockers

[src/Core/PostgreSQL/insertPostgreSQLValue.cpp:206] The new translation layer promises to turn bad PostgreSQL text into BAD_ARGUMENTS, but catch (const std::exception &) also catches allocator failures from std::string(value) / String(value) and the global operator new. Those failures are rethrown as BAD_ARGUMENTS at line 213, and MaterializedPostgreSQLConsumer::insertValue then treats them as a malformed source value and inserts a default (src/Storages/PostgreSQL/MaterializedPostgreSQLConsumer.cpp:256-269) instead of surfacing OOM. Under memory pressure this turns a resource failure into silent data loss in replication and a misleading user error on the query path.
Suggested fix: add a catch (const std::bad_alloc &) that rethrows before the generic translation, and narrow the remaining std::exception catch to the specific foreign parse exceptions this helper actually expects.

Final Verdict

Changes requested: the remaining std::exception catch still masks allocator failure as bad input.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
…-parse errors

insertPostgreSQLValue now translates a foreign pqxx::conversion_error into a
DB::Exception(BAD_ARGUMENTS). MaterializedPostgreSQLConsumer::insertValue only
caught the raw pqxx::conversion_error, so the translated exception escaped to
readTupleData, which inserts a default and rethrows. consume() then returns
false without advancing the replication slot, and the buffered row is
re-inserted on every retry, duplicating replicated rows indefinitely.

Broaden the caller's catch to also handle the translated BAD_ARGUMENTS the same
way as the raw conversion error (log and insert a default), so replication keeps
advancing. Other DB::Exceptions still propagate unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch, addressed in 1092dad. Broadening the raw-pqxx::conversion_error catch would drop the translation for the MaterializedPostgreSQL path, so instead MaterializedPostgreSQLConsumer::insertValue now also catches the translated DB::Exception and handles BAD_ARGUMENTS exactly like the raw conversion error (log + insert default), preserving the pre-PR behavior where replication keeps advancing. Other DB::Exceptions still propagate. This removes the escape to readTupleData that would have left the slot unadvanced and duplicated the buffered row on retry.

@@ -1186,6 +1186,63 @@ def test_postgres_query_passing(started_cluster):
cursor.execute(f"DROP TABLE {dim_name}")


def test_postgres_query_passing_edge_cases(started_cluster):
cursor = started_cluster.postgres_conn.cursor()

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.

@groeneai add the same test for MySQL and SQLite. Test a number of query projections that mismatch with the number of columns in the table.

insertPostgreSQLValue previously only caught pqxx::conversion_error. Text
values read into declared UUID/Date/DateTime/DateTime64/Decimal types throw
DB::Exception (CANNOT_PARSE_*) or, for Date/Date32, a foreign std::runtime_error
from LocalDate::init. The latter escaped the catch entirely and aborted the
server (STD_EXCEPTION), and the former reached readTupleData in the
MaterializedPostgreSQL consumer as a non-BAD_ARGUMENTS code, bypassing the
consumer catch that keeps replication advancing.

Broaden the value-layer catch: parse errors (isParseError) and BAD_ARGUMENTS
become a single BAD_ARGUMENTS query error; foreign std::exception is likewise
translated; genuine failures (LOGICAL_ERROR, memory limit) still propagate.

Add regression coverage for declared-type and projection-count mismatches
across the postgresql, mysql and sqlite query-passing paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed fc3efeb.

@clickhouse-gh The value-layer catch is broadened. insertPostgreSQLValue now translates every parse failure to BAD_ARGUMENTS, not just pqxx::conversion_error:

  • catch (const Exception &): parse errors (isParseError: UUID/DateTime/DateTime64/Decimal via CANNOT_PARSE_*, UNEXPECTED_DATA_AFTER_PARSED_VALUE, DECIMAL_OVERFLOW, ...) and existing BAD_ARGUMENTS are re-thrown as BAD_ARGUMENTS; non-parse codes (LOGICAL_ERROR, memory limit) still propagate.
  • catch (const std::exception &): covers foreign throws, notably Date/Date32 where LocalDate::init throws std::runtime_error. On base this escaped the pqxx-only catch and aborted the server (STD_EXCEPTION); it now surfaces as BAD_ARGUMENTS.

So all declared-type mismatches reach the consumer as BAD_ARGUMENTS, which the catch added earlier handles (log + default, replication keeps advancing). Verified locally against a live PostgreSQL for Int32/UUID/Date/DateTime/DateTime64/Decimal: base leaks STD_EXCEPTION on the Date path, fixed build reports BAD_ARGUMENTS for all.

@PedroTadim Added MySQL and SQLite coverage for projection-count and type mismatch:

  • postgresql: declared-type mismatch across Int32/UUID/Date/DateTime/DateTime64/Decimal, plus count mismatch (TOO_MANY_COLUMNS).
  • mysql (test_query_passing_projection_mismatch): count mismatch (NUMBER_OF_COLUMNS_DOESNT_MATCH) and type mismatch (typed accessor error).
  • sqlite (04341): count mismatch (extra declared column pads defaults) and type mismatch (CANNOT_PARSE_DATE).

Session id: cron:clickhouse-worker-slot-3:20260713-142300

"Cannot parse PostgreSQL value '{}' as {}: {}", value, data_type->getName(), e.message());
throw;
}
catch (const std::exception & e)

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.

catch (const std::exception &) is broader than the foreign parse failures this helper needs to normalize. This function does ordinary heap allocations itself (std::string(value) for Date/Date32, String(value) in the Int256 overflow branch), and ClickHouse's global operator new can throw std::bad_alloc (src/Common/AllocationInterceptors.cpp:50-100).

After this translation, the query path reports that as BAD_ARGUMENTS, and MaterializedPostgreSQLConsumer::insertValue treats it as a bad source value and inserts a default. That turns memory pressure into silent data loss instead of propagating the real failure. Can we rethrow std::bad_alloc here, and ideally narrow this catch to the specific foreign parse exceptions we actually expect?

@PedroTadim PedroTadim self-assigned this Jul 13, 2026
groeneai and others added 2 commits July 13, 2026 17:24
Fewer declared columns than the passed query returns is not an error: the
PostgreSQL and MySQL engines take the first N result columns positionally and
drop the rest. The TOO_MANY_COLUMNS / NUMBER_OF_COLUMNS_DOESNT_MATCH assertions
were wrong and failed deterministically (the query succeeds). Keep the empty-
result, missing-permission and type-mismatch coverage, which is the point.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A PostgreSQL numeric that parses but does not fit the declared ClickHouse
Decimal is rejected by the Decimal text reader with ARGUMENT_OUT_OF_BOUND
(already in isParseError), which the shared value layer normalizes to
BAD_ARGUMENTS. It therefore surfaces as a query error and reaches the
MaterializedPostgreSQL catch, never a foreign exception or server abort.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified against source and a live PostgreSQL 16: DECIMAL_OVERFLOW is not reachable through this path, so the numeric-overflow case is already covered.

The Decimal text reader guards precision before the scale multiply. readDecimalText (src/IO/readDecimalText.h:160) throws ARGUMENT_OUT_OF_BOUND when digits + exponent > precision - scale, so a parsed value always satisfies |x| < 10^(precision - unread_scale) and thus x * 10^unread_scale < 10^precision. For every Decimal, 10^precision is below the native max (Decimal128: 1e38 < ~1.7e38; Decimal256: 1e76 < ~5.78e76), so the mulOverflow at SerializationDecimal.cpp:51 cannot fire for a valid Decimal(P,S). The code that does fire, ARGUMENT_OUT_OF_BOUND, is already in isParseError (src/Formats/ParseError.cpp:44, "For Decimals"), so it was already translated to BAD_ARGUMENTS in the prior commit.

Empirical check confirms this. An exhaustive sweep over P in {9,18,38,76} and S in {0, P/2, P-1, P} with boundary/e-notation values produced zero DECIMAL_OVERFLOW, and the real numeric path:

CREATE TABLE pt (a Int32, v Decimal(10,2)) ENGINE = PostgreSQL(..., 'ovf', ...);  -- ovf.v = 99999999999999999999999999999999999999
SELECT * FROM pt;
-- Code: 36. Cannot parse PostgreSQL value '99999...' as Decimal(10, 2): Too many digits (11 > 10) ... (BAD_ARGUMENTS)

That reaches the BAD_ARGUMENTS catch in MaterializedPostgreSQLConsumer::insertValue, so no duplicate-on-retry and no abort.

Since there is no reproducible DECIMAL_OVERFLOW here, I did not add a code change for it (per the "no speculative changes for a case that cannot be reproduced" guidance). I added a numeric-overflow regression to test_postgres_query_passing_edge_cases (5f2f0b7) that asserts an overflowing PostgreSQL numeric read into a narrow Decimal surfaces as a query error.

A prefix-valid PostgreSQL text value like '1abc' read into a declared
Decimal does not break MaterializedPostgreSQL replication:
SerializationDecimal::deserializeText push_back's the parsed prefix and
throwUnexpectedDataAfterParsedValue popBack(1)'s it before throwing, so
the destination column stays consistent. The consumer inserts a default
and replication keeps advancing. Test-only change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified against source: this path does not break replication.

SerializationDecimal::deserializeText does push_back(x) and then calls ISerialization::throwUnexpectedDataAfterParsedValue (src/DataTypes/Serializations/ISerialization.cpp:765), which does column.popBack(1) ("Restore correct column size.") before throwing UNEXPECTED_DATA_AFTER_PARSED_VALUE. So the parsed prefix is rolled back by the serializer itself; the destination column keeps a consistent size and insertValue then inserts a default on top of it. No stray value survives for the WAL tuple, so the next syncTables does not trip Chunk::checkNumRowsIsConsistent.

Confirmed end to end with an integration test: a PostgreSQL text column mapped to Decimal(10, 2) via TABLE OVERRIDE, sending 1abc. On HEAD the consumer logs Conversion failed while inserting PostgreSQL value 1abc, will insert default value and replication advances (Table sync end for 1 tables); the row gets the column default and a following valid row arrives, count reaches 3 with no row-count inconsistency.

No source change is warranted here. Added the regression test (test_prefix_valid_value_keeps_replicating in test_postgresql_replica_database_engine/test_3.py) so this stays covered.

…ng edge test

Inserting 99999999999999999999999999999999999999 through ClickHouse typed the
literal as Float64 and failed the INSERT with DECIMAL_OVERFLOW before the read
path under test was reached. Seed the value via a PostgreSQL-side INSERT so it
stays an exact numeric and the declared-Decimal read surfaces BAD_ARGUMENTS as
intended.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI update: the Stateless/Integration red on test_postgres_query_passing_edge_cases was the test's own setup, not the source. Line 1255 did INSERT INTO postgresql(...) SELECT 1, 99999999999999999999999999999999999999; ClickHouse types that literal as Float64 (1e38), so the INSERT failed with DECIMAL_OVERFLOW at the CAST layer before the read path under test ran. Fixed by seeding the value with a PostgreSQL-side INSERT so it stays an exact numeric (pushed 10829d5).

With the value seeded PG-side, the declared-Decimal(10,2) read now goes through insertPostgreSQLValue -> deserializeWholeText and surfaces Code 36 BAD_ARGUMENTS "Cannot parse PostgreSQL value ... Too many digits", which the MaterializedPostgreSQL consumer catch handles (log + default), so replication keeps advancing. Verified both test_postgres_query_passing_edge_cases and test_query_passing_type_mismatch PASS on the praktika integration runner.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 10/18 (55.56%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 10829d5

All CI checks are green, including all four Bugfix validation checks (SUCCESS). The test_postgresql_replica_database_engine/test_3.py rows shown as FAIL are the EXPECTED master-binary side of the bugfix-validation harness (the new regression test and the fix-dependent behaviors must fail on master HEAD and pass on the PR) — the Bugfix validation checks themselves are green, so they are not failures. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (integration, amd64/aarch64) / test_3.py rows expected master-side behavior (bugfix-validation harness; check conclusion = SUCCESS) N/A — not a failure
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-093000

@PedroTadim
PedroTadim enabled auto-merge July 14, 2026 12:35
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 14, 2026
Merged via the queue into ClickHouse:master with commit 5d2993a Jul 14, 2026
176 of 177 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix server abort on PostgreSQL value type mismatch

ClickGap verified: reproduced it with the script below on 26.6; tested 7 version(s) — 6 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

Reproduction

-- On the PostgreSQL side:
CREATE TABLE t (a integer, b text);
INSERT INTO t VALUES (1, 'name_0');

-- On ClickHouse: declare the text column b as Int32 (type mismatch).
CREATE TABLE m (a Int32, b Int32)
ENGINE = PostgreSQL('host:5432', 'db', 't', 'user', 'pass');
SELECT * FROM m;

-- Pre-fix: pqxx::conversion_error (a foreign std::exception) escapes
--   insertPostgreSQLValue -> server abort (signal 6) on debug/sanitizer
--   builds; Code: 1001 (STD_EXCEPTION) on release/RelWithDebInfo builds.
-- Post-fix: Code: 36 (BAD_ARGUMENTS) "Cannot parse PostgreSQL value 'name_0' as Int32".

▶ Run on ClickHouse Fiddle

Bisect

  • Reproduces on every release line tested down to v22.3.20.29 (the oldest with a downloadable binary for this repro). The introducing change predates v22.3.20.29, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-postgresql
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @PedroTadim


ClickGap · Finding: phase_d_pr110264

Triage metadata

  • Primary component: comp-postgresql
  • Secondary components: comp-testing
  • Component owners (comp-postgresql): @alexey-milovidov @kssenii

@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ry-type-mismatch-abort

Fix server abort on PostgreSQL value type mismatch
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