Repository navigation
Fix a crash and a LOGICAL_ERROR when trim(BOTH '' FROM x) is used where a function is expected - #119317
Conversation
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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review: my own cold pass over the resulting code, then an independent model
Also checked and deliberately not changed: this spelling now formats as a two-argument Round 3 closed the invariant on a different axis than the earlier rounds, which had enumerated Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260910-174800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260910-130800 |
|
Workflow [PR], commit [7e4d15c] Summary: ✅
AI ReviewSummaryThis PR removes the parser shortcut that folded Missing context / blind spots
Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 7e4d15c.
Changed lines: Changed C/C++ lines covered: 12/14 (85.71%) · Uncovered code |
|
cc @evillique @Ergus, could you review this? The trim parser layer folded |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 1a37e57Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this pull request. The boundary is measurable: A master merge is therefore owed here to re-run CI on a tree that contains the revert; nothing else Session id: cron:our-pr-ci-monitor:20260911-010040 |
CI finish ledger - e721960Every 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
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 ', ''); |
There was a problem hiding this comment.
@groeneai can you add more test cases such as the verbatim mode, hex notation x'', unicode strings and non UTF-8 ones?
There was a problem hiding this comment.
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:
formatQueryoverx'',b'',‘’and$$$$givesSELECT trimBoth('x', ''),trimLeft,trimRight,trimBoth. On master all four printSELECT 'x'.(c Int64 STATISTICS(trim(BOTH x'' FROM 'x')))givesINCORRECT_QUERY. Master exits 139 on it.trim(BOTH x'' FROM 123)givesILLEGAL_TYPE_OF_ARGUMENT. Master answers123.toTypeName(trim(BOTH b'' FROM CAST('ä' AS FixedString(4))))givesString, masterFixedString(4). The bytes areC3A40000either 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 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.
CI finish ledger - c36b3c7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Attribution, measured rather than assumed:
Session id: cron:our-pr-ci-monitor:20260911-183208 |
Backport #119317 to 26.8: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
Backport #119317 to 26.6: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
…BOTH '' FROM x)` is used where a function is expected
Backport #119317 to 26.7: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
Backport #119317 to 26.3: Fix a crash and a LOGICAL_ERROR when `trim(BOTH '' FROM x)` is used where a function is expected
…hen `trim(BOTH '' FROM x)` is used where a function is expected
…hen `trim(BOTH '' FROM x)` is used where a function is expected
…hen `trim(BOTH '' FROM x)` is used where a function is expected
Related: #67792
Related: #69922
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash and a
LOGICAL_ERRORfor statements that writetrim(BOTH '' FROM x)(or theLEADING/TRAILINGspelling) where a function is expected: a column'sSTATISTICS(...)orCODEC(...)list,INDEX ... TYPE,ALTER TABLE ... ADD STATISTICS,auto_statistics_types, a table function, a named collection andSETTINGS. The parser folded it into its operand instead of building atrimBothcall, and those places cast or dereference the result as a function. The fold also bypassed the function's own checks, sotrim(BOTH '' FROM <non-string>)now raisesILLEGAL_TYPE_OF_ARGUMENTand aFixedStringargument now yieldsString, as every othertrimspelling does.Description
TrimLayershort-circuited an empty trim character:getResultImplreturned the operand instead of atrimBothcall, soParserFunctionpublished a non-ASTFunctionwhile its callers read one -ParserIdentifierWithOptionalParameterswritessetNoEmptyArgsthrough the failed downcast (SIGSEGV),ParserSetQueryreads->nameoff it, and the statistics, index and table-function consumers use a throwingas<ASTFunction &>().One line reproduces it:
The official master release build segfaults on it: the server dies parsing the statement, and
clickhouse-clientfaults first, parsing it locally. 26.3 LTS returnsCode: 49 ... Bad cast from type DB::ASTLiteral to DB::ASTFunction.The shortcut came from #67792, when
trimwas areplaceRegexpOnerewrite that could not express an empty character class. #69922 asked for a nativetrimtaking 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 overcol, usable for primary-key analysis; atrimBothcall is not. It never coveredtrimBoth(col, '')anyway.Found by BuzzHouse (amd_msan) on an unrelated PR (report) - provenance only: how that job reached
StatisticsDescription.cpp:205is unestablished, so nothing is closed.Also noticed, not raised:
QueryFuzzer::fuzzColumnDeclarationcastsstatistics_descto a type that slot never holds, so that mutation is dead code.Measured before / after, debug and official builds
EXPLAIN AST SELECT trim(BOTH '' FROM 'x')Literal 'x'Function trimBoth('x', '')STATISTICS(trim(BOTH '' FROM 'x'))Code: 49bad cast (26.3 LTS)Code: 80unknown statistics typeCODEC(trim(BOTH '' FROM 'x'))Code: 223(26.3 LTS)Code: 432unknown codecALTER TABLE t ADD STATISTICS c TYPE trim(BOTH '' FROM 'x')Inconsistent AST formattingCode: 49bad castCode: 80INDEX i c TYPE trim(BOTH '' FROM 'x')Index declaration type must be a functionCode: 49, same textCode: 80SETTINGS auto_statistics_types = 'trim(BOTH '''' FROM ''x'')'Code: 36Code: 80SELECT 1 SETTINGS max_threads = trim(BOTH '' FROM 'x')Code: 62Code: 62CREATE NAMED COLLECTION nc AS k = trim(BOTH '' FROM 'x')Code: 62Code: 62SELECT * FROM trim(BOTH '' FROM 'x')Code: 49bad castCode: 46unknown table functionSELECT trim(BOTH '' FROM 123)123123Code: 43illegal typetoTypeName(trim(BOTH '' FROM CAST('x' AS FixedString(5))))FixedString(5)FixedString(5)StringUnchanged:
trim(BOTH '' FROM 'x')=x,trim(BOTH 'a' FROM 'aXa')=X,trimBoth(' x ', '')=x, theLEADING/TRAILINGresults,SHOW CREATEfor ordinarySTATISTICS/CODEC/INDEX/auto_statistics_types, a dictionary source withHOST trim(BOTH '' FROM 'localhost')(stillHOST '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
26.9.1.1427(included in26.9and later)26.8.4.6,26.7.8.15,26.6.6.16,26.3.33.74