Skip to content

Fix a crash and a LOGICAL_ERROR when trim(BOTH '' FROM x) is used where a function is expected - #119317

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-trim-empty-chars-parser-fold
Sep 13, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-trim-empty-chars-parser-fold

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #67792
Related: #69922

Changelog category (leave one):

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

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

Fixed a crash and a LOGICAL_ERROR for statements that write trim(BOTH '' FROM x) (or the LEADING/TRAILING spelling) where a function is expected: a column's STATISTICS(...) or CODEC(...) list, INDEX ... TYPE, ALTER TABLE ... ADD STATISTICS, auto_statistics_types, a table function, a named collection and SETTINGS. The parser folded it into its operand instead of building a trimBoth call, and those places cast or dereference the result as a function. The fold also bypassed the function's own checks, so trim(BOTH '' FROM <non-string>) now raises ILLEGAL_TYPE_OF_ARGUMENT and a FixedString argument now yields String, as every other trim spelling does.

Description

TrimLayer short-circuited an empty trim character: getResultImpl returned the operand instead of a trimBoth call, so ParserFunction published a non-ASTFunction while its callers read one - ParserIdentifierWithOptionalParameters writes setNoEmptyArgs through the failed downcast (SIGSEGV), ParserSetQuery reads ->name off it, and the statistics, index and table-function consumers use a throwing as<ASTFunction &>().

One line reproduces it:

CREATE TABLE t (c Int64 STATISTICS(trim(BOTH '' FROM 'x'))) ENGINE = MergeTree ORDER BY c

The official master release build segfaults on it: the server dies parsing the statement, and clickhouse-client faults first, parsing it locally. 26.3 LTS returns Code: 49 ... Bad cast from type DB::ASTLiteral to DB::ASTFunction.

The shortcut came from #67792, when trim was a replaceRegexpOne rewrite that could not express an empty character class. #69922 asked for a native trim taking the character; that landed in 4a14b0e, so the parser half is leftover.

The fold was also an accidental optimisation: a predicate over trim(BOTH '' FROM col) was a predicate over col, usable for primary-key analysis; a trimBoth call is not. It never covered trimBoth(col, '') anyway.

Found by BuzzHouse (amd_msan) on an unrelated PR (report) - provenance only: how that job reached StatisticsDescription.cpp:205 is unestablished, so nothing is closed.

Also noticed, not raised: QueryFuzzer::fuzzColumnDeclaration casts statistics_desc to a type that slot never holds, so that mutation is dead code.

Measured before / after, debug and official builds
input before (debug) before (official release) after
EXPLAIN AST SELECT trim(BOTH '' FROM 'x') Literal 'x' - Function trimBoth('x', '')
column STATISTICS(trim(BOTH '' FROM 'x')) SIGSEGV SIGSEGV (26.9); Code: 49 bad cast (26.3 LTS) Code: 80 unknown statistics type
column CODEC(trim(BOTH '' FROM 'x')) SIGSEGV SIGSEGV (26.9); Code: 223 (26.3 LTS) Code: 432 unknown codec
ALTER TABLE t ADD STATISTICS c TYPE trim(BOTH '' FROM 'x') abort, Inconsistent AST formatting Code: 49 bad cast Code: 80
INDEX i c TYPE trim(BOTH '' FROM 'x') abort, Index declaration type must be a function Code: 49, same text Code: 80
SETTINGS auto_statistics_types = 'trim(BOTH '''' FROM ''x'')' SIGSEGV Code: 36 Code: 80
SELECT 1 SETTINGS max_threads = trim(BOTH '' FROM 'x') SIGSEGV Code: 62 Code: 62
CREATE NAMED COLLECTION nc AS k = trim(BOTH '' FROM 'x') SIGSEGV Code: 62 Code: 62
SELECT * FROM trim(BOTH '' FROM 'x') abort Code: 49 bad cast Code: 46 unknown table function
SELECT trim(BOTH '' FROM 123) 123 123 Code: 43 illegal type
toTypeName(trim(BOTH '' FROM CAST('x' AS FixedString(5)))) FixedString(5) FixedString(5) String

Unchanged: trim(BOTH '' FROM 'x') = x, trim(BOTH 'a' FROM 'aXa') = X, trimBoth(' x ', '') = x , the LEADING/TRAILING results, SHOW CREATE for ordinary STATISTICS/CODEC/INDEX/auto_statistics_types, a dictionary source with HOST trim(BOTH '' FROM 'localhost') (still HOST 'localhost'), and the cases of #67792 and #69922. The debug-only symptoms of some rows are the AST format/re-parse consistency check, which is #ifndef NDEBUG; the null write in the parser is undefined behaviour, so whether it faults depends on the build.


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

Version info

  • Merged into: 26.9.1.1427 (included in 26.9 and later)
  • Backported to: 26.8.4.6, 26.7.8.15, 26.6.6.16, 26.3.33.74

groeneai and others added 3 commits September 10, 2026 15:41
TrimLayer short-circuited an empty trim character: getResultImpl returned
elements.at(1), the operand, instead of building a trimBoth call. ParserFunction
then published a node that is not an ASTFunction while its callers read one.
ParserIdentifierWithOptionalParameters calls setNoEmptyArgs through the failed
downcast, which is a write through nullptr; ParserSetQuery reads ->name off it;
the statistics, index and table-function consumers use throwing
as<ASTFunction &>() casts. From ordinary SQL that is a segfault for a column's
STATISTICS(...) or CODEC(...) list and for a named collection, a LOGICAL_ERROR
for ALTER TABLE ... ADD STATISTICS, for INDEX ... TYPE and for a table function,
and a syntax error for SETTINGS max_threads = ... . Two guards written for
exactly this shape, "Expected a function for statistic type" in Statistics.cpp
and "Index declaration type must be a function" in ASTIndexDeclaration::getType,
were unreachable or asserting instead of reporting.

The fold also bypassed the function itself, so trim(BOTH '' FROM 123) returned
123 instead of raising ILLEGAL_TYPE_OF_ARGUMENT, and a FixedString operand kept
its type instead of becoming String.

The shortcut was added for ClickHouse#67792, when trim was implemented by rewriting to
replaceRegexpOne and an empty character class could not be expressed as a regexp.
ClickHouse#69922 asked for a native trim taking the trim character instead; 4a14b0e
did that, and FunctionTrim has since built its membership table from the second
argument, so an empty character set matches nothing natively. Deleting the
shortcut leaves every input accepted, with the node shape and the semantics the
rest of the system already assumes.

Related: ClickHouse#67792
Related: ClickHouse#69922

Co-Authored-By: Claude Opus 5 <[email protected]>
…e arms

ParserSetQuery has two independent unchecked downcasts of a ParserFunction
result, in two functions where neither calls the other.
parseNameValuePairWithParameterOrDefault, at the ->name read, is reached only
from ParserSetQuery::parseImpl, so the SELECT ... SETTINGS max_threads = ...
case already in this test covers that one alone. parseNameValuePair has the
same read and five callers of its own: CREATE NAMED COLLECTION, ALTER NAMED
COLLECTION, a dictionary SETTINGS(...) clause, BACKUP and CREATE FUNCTION.
None of them was covered, and the changelog entry names a named collection
among the fixed slots, so add the CREATE NAMED COLLECTION case. A dictionary
SOURCE pair does not reach it; that goes through ParserKeyValuePair.

The assertion is clientError because the client parses locally and the server
never receives the statement, which system.query_log confirms. The statement
fails, so nothing is created and a server-global named collection cannot leak
between parallel runs.

The three ILLEGAL_TYPE_OF_ARGUMENT arms all failed the same
isStringOrFixedString check on argument 0 in FunctionTrim::getReturnTypeImpl
and all returned the same code, so keep one and drop the UInt8 array and Date
repetitions. LEADING and TRAILING stay covered by the string result cases.

Co-Authored-By: Claude Opus 5 <[email protected]>
The changelog entry names all three spellings, but only BOTH was actually
pinned by an assertion that can fail. Every discriminating case in this test
used BOTH: the EXPLAIN AST oracle, the two formatQuery cases, the slots that
require a function, the type check and the FixedString result. LEADING and
TRAILING with an empty trim character appeared only in result comparisons,
and that is the one place a result cannot discriminate: trimming an empty
character set is the identity, so ' x ' and 'foo' come out byte-identical
whether the parser folds the call away or builds it. Restoring the fold gated
on the BOTH keyword alone would have left every assertion in the file passing.

Add one EXPLAIN AST oracle per keyword, asserting the function the parser
actually produces, so each of trimBoth, trimLeft and trimRight is pinned by
its own case. Measured against both binaries: each of the three returns 1 on
the fix and 0 on unmodified master, which is what makes them oracles rather
than decoration. Unmodified master answers 0 here rather than crashing,
because the fold leaves a literal in the SELECT list and that slot accepts
one; the crashing slots are the ones that require a function.

The assertions use the count()-over-subquery form with an ILIKE probe, like
the BOTH oracle beside them, rather than a full EXPLAIN AST reference diff,
so they survive formatter and indentation changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review: my own cold pass over the resulting code, then an independent model
(engine: codex). Three review rounds, six findings adjudicated; the third round found none.

# Sev Finding Verdict Evidence / action
1 ⚠️ The changelog promises the named-collection slot, but no test covers it: ParserSetQuery has two independent unchecked downcasts, parseNameValuePair:222 and parseNameValuePairWithParameterOrDefault:295, and the SETTINGS case only reaches the second AGREE, fixed Added a CREATE NAMED COLLECTION case. :222 has five callers (named collection, ALTER NAMED COLLECTION, dictionary SETTINGS, BACKUP, CREATE FUNCTION); :295 has one
2 ⚠️ Only the BOTH spelling was actually pinned: every discriminating assertion used BOTH, while LEADING and TRAILING with an empty character appeared only in result-only checks whose output is identical with the fold in place AGREE, fixed Added per-keyword EXPLAIN AST oracles for trimLeft and trimRight. Each was measured on its own, run alone against both binaries: 1 on the fix, 0 on unmodified master. Unfixed code answers 0 there rather than crashing, which is exactly why a result comparison could not have caught these two spellings
3 💡 Deleting the fold also removes an accidental optimisation, undisclosed AGREE, fixed Disclosed in the description: the folded form was a predicate over the bare column and could drive primary-key analysis, while trimBoth(col, '') written out never folded
4 💡 Three ILLEGAL_TYPE_OF_ARGUMENT cases for one predicate AGREE, fixed Kept the 123 case; Array and Date fail the same isStringOrFixedString check on argument 0
5 ⚠️ The description understated the defect as a client-reachable SIGSEGV AGREE, fixed The server itself dies parsing the statement (measured: process exit 139, port refusing afterwards), and the HTTP interface hands the raw text to the parser with no client-side parse. The description and the category question now say so
6 💡 Use Critical Bug Fix because the statement crashes the server DISAGREE I do not assign that category to my own PR. The question is in the description instead, and I will move it if a maintainer says so

Also checked and deliberately not changed: this spelling now formats as a two-argument
trimBoth, which a Distributed initiator sends to its shards; native two-argument trim
landed in 4a14b0e8f9ea0 and is present in both 26.3 and 26.8, so every supported shard
accepts it.

Round 3 closed the invariant on a different axis than the earlier rounds, which had enumerated
the layers getFunctionLayer returns and then every getResultImpl in the file. Dispatch is
the part that can hide a path: ExpressionLayer is the only class that overrides the
getResult wrapper, and it is never constructed by getFunctionLayer, while
ParserExpressionImpl::parse publishes the start layer's result. So the carrier set is exactly
those 14 layers, ViewLayer and EvalLayer override the base reducer precisely so they emit a
function, and TrimLayer was the only violator.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260910-174800

@clickhouse-gh clickhouse-gh Bot closed this Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, one line, no settings and no fuzzer: clickhouse local -q "CREATE TABLE t (c Int64 STATISTICS(trim(BOTH '' FROM 'x'))) ENGINE = MergeTree ORDER BY c" segfaults 100% of the time on a debug build and on the official master release build. Ten more one-liners (CODEC(...), INDEX ... TYPE, ALTER ... ADD STATISTICS, auto_statistics_types, SETTINGS max_threads = ..., a table function, a named collection) fail on demand too.
b Root cause explained? Yes. getFunctionLayer maps trim/ltrim/rtrim to TrimLayer; for an empty string literal as the trim character it set noop and getResultImpl returned the operand instead of building a trimBoth call. ParserFunction therefore published a node that is not an ASTFunction, while its callers read one: ParserIdentifierWithOptionalParameters calls setNoEmptyArgs through a failed downcast (null write, SIGSEGV), ParserSetQuery reads ->name off it, and the statistics, index and table-function consumers use throwing as<ASTFunction &>() casts. The same fold also skipped FunctionTrim's own argument validation and result type.
c Fix matches root cause? Yes, and it is a net deletion (+4 / -20 in one file): the parser stops manufacturing a shape its own contract forbids. No guard at any crash site, no null check added at a consumer, no flag, no widened bound. Hardening the consumers instead would have meant tolerating a LOGICAL_ERROR that correctly caught a real bug.
d Test intent preserved / new tests added? Yes. New stateless test 05175_trim_empty_chars_is_a_function_call (no tags, parallel-safe) plus one case in 02864_statistics_ddl. 03224_trim_empty_string, the test written for #67792, keeps its .reference byte-for-byte and still passes. Each of the three EXPLAIN AST oracles was checked for liveness on its own rather than trusted because the file as a whole fails on unfixed code: run alone, each returns 1 on the fix and 0 on unmodified master.
e Both directions demonstrated? Yes. On unmodified master the new test fails either way round, because every affected downcast is in the parser and the client parses locally: with a client and server both built from unmodified master the client segfaults (Reason: return code: 139), and with a fixed client driving an unmodified server the server dies instead (Reason: server died 32, process exits 139). Against the fixed binary it is [ OK ], 5/5 and 10/10 on repeat, 310/310 across 50 randomized plus 50 non-randomized runs together with the three neighbouring trim/statistics tests, and 110/110 on a re-run after the test's last edit. A negative control that restores only the deleted fold brings back all six symptoms.
f Fix is general across code paths? Yes, by construction: fixing the single producer covers all of its callers at once (the two wrapper parsers, ParserSetQuery, the four table-function call sites, ParserKeyValuePair, ParserDataType, and the two hand-written guards in Statistics.cpp and ASTIndexDeclaration::getType that were unreachable or asserting). TrimLayer was the only layer getFunctionLayer can return that could yield a non-function; every other layer builds one.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the test asserts the matrix: all three keywords (BOTH/LEADING/TRAILING, the only spellings that reach the deleted branch), each pinned by its own EXPLAIN AST oracle on the produced function name (trimBoth/trimLeft/trimRight) rather than by a result comparison, because with an empty trim character the result is byte-identical before and after the fix; all six function spellings including the two-argument forms, const and materialized columns, Nullable, LowCardinality, LowCardinality(Nullable), FixedString (now String), NULL, the empty string, a non-string operand (now ILLEGAL_TYPE_OF_ARGUMENT), and a computed empty trim character (#69922). The non-string rejection is asserted once rather than per type: UInt8, Array and Date all fail the same isStringOrFixedString check on argument 0 in FunctionTrim::getReturnTypeImpl and all return the same code, so the test keeps one arm.
h Backward compatible? No setting, default or serialization change, so no SettingsChangesHistory.cpp entry. Two user-visible behaviour changes are the point of the fix and are stated in the changelog entry: trim(BOTH '' FROM <non-string>) now raises ILLEGAL_TYPE_OF_ARGUMENT instead of returning its argument, and a FixedString operand yields String. Both make the empty-character spelling agree with every other trim spelling. formatQuery now renders the expression as trimBoth(x, ''), and re-parsing that is idempotent.
i Invariants and contracts preserved? The invariant restored is "ParserFunction yields an ASTFunction", which its callers already relied on and which ASTJSONReadHelpers.h states in writing for the same argument lists. TrimLayer's state machine is otherwise untouched (char_override, to_remove and the trimBoth/trimLeft/trimRight selection are unchanged), and trimBoth(x, '') is the identity for string input because FunctionTrim builds an all-false membership table from an empty character set. Nothing here touches storage, serialization or concurrency: the invariant is resolved at parse time, before any storage exists.

Session id: cron:clickhouse-impl-slot-6:20260910-130800

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e4d15c]

Summary: ✅


AI Review

Summary

This PR removes the parser shortcut that folded trim(BOTH|LEADING|TRAILING '' FROM x) into its operand, so ParserFunction again returns an ASTFunction and the downstream consumers that expect one no longer dereference or cast the wrong AST shape. After checking the current diff, the touched parser paths, the existing review thread, and the PR discussion, I did not find a remaining correctness issue in the current code.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because this checkout does not contain a build directory or ready binary; this review is based on code inspection, the added regression tests, and the PR discussion/CI summary.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 7e4d15c.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 12/14 (85.71%) · 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 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @Ergus, could you review this? The trim parser layer folded trim(BOTH '' FROM x) into its bare operand, so ParserFunction published a non-function node that its callers downcast unchecked and a column STATISTICS(...) list segfaults the server on it; the same fold also bypassed FunctionTrim's own argument checks, which is the second behaviour change named in the entry.

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e4d15c15 with master abcadc3ce (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 3345498c8; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1a37e57

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05141_time_series_select_join_settings trunk regression from merged #117356, first failure on master 2026-09-10 17:40:24Z (189 true-master rows, 45 unrelated pull requests) #119334 (external, merged 19:22:08Z) reverted the cause on master and is NOT in the tree this run built (ledger rule 3c, not 3d)
Stateless tests (arm_binary, parallel) / 05141_time_series_select_join_settings same trunk regression #119334 (external, merged)
Stateless tests (arm_asan_ubsan, targeted) / 05141_time_series_select_join_settings (5 repeats), Too many test failures same trunk regression; all 5 failures are repeats of that one test and the abort row is this job's own --max-failures early stop #119334 (external, merged)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) / Timeout ERROR: session-timeout occurred during test execution: this 6-way ASan shard runs out of its session, no individual test failed #118933 (external, open) splits these ASan jobs into eight batches
Finish Workflow / Post Hooks rollup: new_tests_check.py reports the stateless jobs above #119334 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

Not caused by this pull request. The boundary is measurable: 05141_time_series_select_join_settings
first failed on master at 17:40:24Z, #119334 (the automatic Revert CI regressions revert of #117356)
merged at 19:22:08Z, and praktika pins the merge ref when Config Workflow starts. This workflow was
dispatched at 18:12:35Z, before that merge. Every one of my open pull requests dispatched after it passes
these same jobs (11 heads checked), and every one dispatched before it fails them.

A master merge is therefore owed here to re-run CI on a tree that contains the revert; nothing else
re-dispatches these jobs. PR and Mergeable Check are praktika rollups of the rows above, not
separate failures. Note that #119335 re-lands #117356 and carries the same test file, so the merge is
stable in both worlds.

Session id: cron:our-pr-ci-monitor:20260911-010040

@PedroTadim PedroTadim self-assigned this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e721960

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) / 03100_lwu_deletes_4_index (3 rows) trunk regression, not this PR: the second lightweight DELETE reports read_rows = 0 instead of 8 (.reference line 2) #119400 (mine, open)
Stateless tests (amd_debug, parallel) / 03100_lwu_deletes_4_index same signature; the runner's own diagnosis reproduces it 110/110 under the randomized MergeTree pair min_bytes_for_wide_part=0 + patch_parts_version=v1 and 0/114 without randomization #119400 (mine, open)
Mergeable Check, PR rollup of the two checks above #119400 (mine, open)

03100_lwu_deletes_4_index began failing with this signature at ~00:32Z today across true master (3 shas) and ~30 unrelated pull requests, and this branch only changes ExpressionListParsers.cpp plus two test files, so it cannot reach lightweight updates. #119400 fixes read_rows being reported as zero when a read step materializes no column from the part, which is exactly the 8 -> 0 delta above.

Session id: cron:our-pr-ci-monitor:20260911-083121

-- String results are unchanged, for every keyword and every spelling.
SELECT trim(BOTH '' FROM ' x '), trim(LEADING '' FROM ' x '), trim(TRAILING '' FROM ' x ');
SELECT trim(BOTH 'a' FROM 'aXa'), trim(LEADING 'a' FROM 'aXa'), trim(TRAILING 'a' FROM 'aXa');
SELECT trim(' x '), ltrim(' x '), rtrim(' x '), trimBoth(' x ', ''), trimLeft(' x ', ''), trimRight(' x ', '');

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 can you add more test cases such as the verbatim mode, hex notation x'', unicode strings and non UTF-8 ones?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in c36b3c7, five statements in 05175_trim_empty_chars_is_a_function_call.

ParserStringLiteral::parseImpl reaches an ASTLiteral through five spellings, and makeHexOrBinStringLiteral returns an empty String for both x'' and b'', so all five could reach the fold this PR removes while only the plain quoted one was pinned. Every new assertion is measured against a pristine-master build, which still folds:

  • formatQuery over x'', b'', ‘’ and $$$$ gives SELECT trimBoth('x', ''), trimLeft, trimRight, trimBoth. On master all four print SELECT 'x'.
  • (c Int64 STATISTICS(trim(BOTH x'' FROM 'x'))) gives INCORRECT_QUERY. Master exits 139 on it.
  • trim(BOTH x'' FROM 123) gives ILLEGAL_TYPE_OF_ARGUMENT. Master answers 123.
  • toTypeName(trim(BOTH b'' FROM CAST('ä' AS FixedString(4)))) gives String, master FixedString(4). The bytes are C3A40000 either way, padding included.

I read "verbatim" as the two spellings that do no escaping, the heredoc and the fancy quotes. Tell me if you meant something else and I will add it.

The Unicode and non-UTF-8 cases cannot change value here, because a non-empty character was never folded: trim(BOTH 'ä' FROM 'äxä') is x and hex(trim(BOTH x'FF' FROM x'FF41FF')) is 41 both before and after, the character being a byte set rather than a code point. That line therefore stands as the argument-order assertion: it is what fails if the character and the operand are ever built the wrong way round. Non-UTF-8 results go through hex() so the reference file stays ASCII.

The description no longer asks about the changelog category, since you moved it yourself.

@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 11, 2026
@ PedroTadim asked for the verbatim, hex, Unicode and non-UTF-8 cases.
ParserStringLiteral::parseImpl reaches an ASTLiteral through five spellings: a
quoted string, a hex literal, a binary literal, a heredoc and fancy quotes.
makeHexOrBinStringLiteral returns an empty String for both x'' and b'', so all
five could reach the removed fold, and only the quoted one was pinned.

Each new assertion was measured against the pristine-master baseline binary,
which still folds: the four formatQuery columns print SELECT 'x' there instead
of a trimBoth/trimLeft/trimRight call, a STATISTICS(trim(BOTH x'' FROM 'x'))
column exits 139 instead of raising INCORRECT_QUERY, trim(BOTH x'' FROM 123)
answers 123 instead of ILLEGAL_TYPE_OF_ARGUMENT, and a FixedString argument
keeps FixedString(4) instead of becoming String.

The parser never folded a non-empty character, so the Unicode and non-UTF-8
byte sequences cannot change value with this fix. Their line asserts that: it
is what fails if the two arguments are ever built in the wrong order.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c36b3c7

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Logical error: Virtual row has different type for A. Expected B, got C (STID 1637-309b) trunk regression, not PR-caused: setVirtualRow aborts because the planned type of a sorting-key expression, CAST(__table1.json.b, 'String'), is Nullable(String) while the delivered virtual row carries String #119385 (mine, open)
Mergeable Check praktika aggregator, reports the single leg above #119385 (mine, open)
PR top-level praktika aggregator #119385 (mine, open)

Attribution, measured rather than assumed:

  • Breadth over 30 days for STID 1637-309b: 38 rows across 37 pull requests, 37 distinct commits and 1 true-master tree, first seen 2026-09-10 16:22Z, spread over Upgrade check (amd_release) and six Stress test flavours. A single-day trunk-wide onset, not a property of this branch.
  • This branch cannot reach it: the diff is src/Parsers/ExpressionListParsers.cpp plus 02864_statistics_ddl.sql and the new 05175_trim_empty_chars_is_a_function_call test. A parser change cannot influence read-in-order virtual rows.
  • Fix wrong results when a sorting key expression's type depends on a session setting #119385 is the fix for exactly this abort: it corrects the read-in-order path when a sorting-key expression's type depends on a session setting (ReadInOrderOptimizer.cpp, actionsDAGUtils.{cpp,h}). It is open and unmerged, so no master merge is owed here.
  • CH Inc sync was green at this head, so no row is owed for it.

Session id: cron:our-pr-ci-monitor:20260911-183208

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 0c3b387 Sep 13, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 13, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119317 to 26.8: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119317 to 26.6: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 14, 2026
…BOTH '' FROM x)` is used where a function is expected
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119317 to 26.7: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
PedroTadim added a commit that referenced this pull request Sep 14, 2026
Backport #119317 to 26.3: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 14, 2026
…hen `trim(BOTH '' FROM x)` is used where a function is expected
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…hen `trim(BOTH '' FROM x)` is used where a function is expected
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…hen `trim(BOTH '' FROM x)` is used where a function is expected
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-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

6 participants