Skip to content

Cherry pick #108493 to 26.4: Fix crash on deeply nested expressions with raised max_parser_depth - #108830

Merged
robot-clickhouse merged 11 commits into
backport/26.4/108493from
cherrypick/26.4/108493
Jun 30, 2026
Merged

robot-clickhouse merged 11 commits into
backport/26.4/108493from
cherrypick/26.4/108493

Conversation

@robot-clickhouse-ci-2

Copy link
Copy Markdown
Contributor

Original pull-request #108493

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

Algunenano and others added 10 commits June 25, 2026 16:23
…depth

max_parser_depth is a client-settable session setting. Raising it lets the
parser build an arbitrarily deep expression, after which several recursive
routines that walk the resulting Field/DataType/AST had no stack guard and
overflowed the native stack, crashing the server with an uncatchable
SIGSEGV.

Add checkStackSize() at the recursive entry points so they report
TOO_DEEP_RECURSION instead of crashing:
- convertFieldToType (deeply nested Array/Tuple/Map literals)
- FieldToDataType for Array/Tuple/Map
- getLeastSupertype
- IAST::childrenHaveSecretParts (secret-argument masking of nested calls
  such as array(array(...)))

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Matching any "Code: N" let a server death (surfacing to the client as a
connection-reset error) or an unrelated early parser/AST limit pass as
success. Print and pin the exact code so only a catchable
TOO_DEEP_RECURSION (306) satisfies the test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
CI surfaced a stack overflow in AST formatting (IAST::format ->
ASTFunction::formatImplWithoutAlias) on a deeply nested function call such as
array(array(...)) built with a raised max_parser_depth, plus the same risk in
the other AST traversals that recurse into children unconditionally. Add
checkStackSize() to IAST::format, updateTreeHash, cloneChildren and dumpTree so
they report TOO_DEEP_RECURSION instead of crashing the server.

Make the test fast enough for sanitizer/debug builds: building a deeply nested
literal Field is quadratic, so use a single modest-depth array literal (covers
convertFieldToType / FieldToDataType) and rely on linear-to-build nested
function calls for the AST traversal paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
checkStackSize now sits on more recursive paths (Field/type building and AST
traversal), so trim the cost of the common "stack is fine" case:

- Mark getStackSize NO_INLINE and move the two throws into cold, noreturn,
  NO_INLINE helpers. The one-time detection and the error paths no longer
  inline into the body, so the hot path needs no large stack frame and no
  inline exception construction.
- Drop the weak attribute so LTO can inline the (now tiny) body into callers.
  This removes the extension point that let external ClickHouse-based products
  replace checkStackSize for custom/manual stacks; there is no such override in
  this repository.
- Mark the init / "can't check" / error branches unlikely so they are laid out
  off the hot path.
- Compute the allowed size with integer division instead of a floating-point
  multiply by a constant ratio.
- Keep the cached stack address and size in one constinit thread_local struct
  so both fields share a single TLS access instead of two (negligible on x86,
  one fewer TLS resolution on platforms where that is a real sequence).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A deeply nested Array/Tuple/Map literal is stored inside a single
ASTLiteral::value, so guarding only node-to-node AST recursion is not enough:
ASTLiteral formats and hashes that value through FieldVisitorToString /
FieldVisitorHash, which recurse into the nested Field without a stack guard. A
path that formats a literal without first running type inference, e.g.
formatQuery of a deeply nested array, could still overflow the native stack and
crash the server.

Add checkStackSize() to the Array/Tuple/Map/Object operators of every recursive
Field visitor (ToString, Hash, Dump, ToJSONElement, WriteBinary,
ToCastedLiteral) so they report TOO_DEEP_RECURSION instead of crashing. Add a
regression that formats a deeply nested array literal; it is optimized-build
only because building such a literal is quadratic, and the guard it exercises is
build-independent.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With legacy_column_name_of_tuple_literal=1 the old analyzer derives a tuple
literal's column name through FieldVisitorToColumnName, whose Tuple operator
recurses into the nested Field with no stack guard. A deeply nested tuple
literal built with a raised max_parser_depth overflowed the native stack while
deriving the column name (in TreeRewriter, before type inference), crashing the
server. Reproduced with a 40000-deep tuple literal; the fault was a pure
recursion in FieldVisitorToColumnName::operator()(const Tuple &).

Add checkStackSize() to that operator so it reports TOO_DEEP_RECURSION instead
of crashing, and add a regression with legacy_column_name_of_tuple_literal=1.
The regression is optimized-build only because building the literal is
quadratic, and the guard it exercises is build-independent.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The deeply nested literal tests build the literal Field in quadratic time, which
is too slow on the unoptimized fast-test build (it timed out there).

- 04412: tag no-fasttest and lower the depth to 20000. formatQuery formats the
  literal without analysis, so this stays a tight regression (without the guard
  it formats successfully and the expected TOO_DEEP_RECURSION is missing) while
  running in well under 20 seconds.
- 04413: removed. The legacy column-name path is shadowed by the guarded
  convertFieldToType below the depth where FieldVisitorToColumnName itself
  overflows, so a regression that actually exercises that guard needs a depth
  whose quadratic build does not fit in the time budget. The guard added in
  ASTLiteral.cpp stays; the crash was reproduced manually with a 40000-deep
  tuple literal.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two more unguarded recursive walks over deeply nested input:

- ParameterFieldVisitorToString (SET param_* stringification) recurses into
  Array/Map/Tuple with no stack guard. A statement like SET param_p = [[...]]
  with a raised max_parser_depth overflowed the native stack while the server
  parsed it (reproduced over HTTP with a 45000-deep array; the client
  interprets SET param_* locally, so it must be sent over HTTP). Add
  checkStackSize() to those operators and a regression expecting
  TOO_DEEP_RECURSION.

- IAST::checkSize recurses into children with no stack guard. In the normal
  pipeline the guarded secret-argument masking walks the same tree first and
  stops it, so this could not be triggered on its own, but the recursion is
  added as defense in depth (checkDepth is already iterative).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In normal execution a deeply nested array(array(...)) hits the secret-argument
masking walk (childrenHaveSecretParts) before IAST::format, so the existing
function-call assertions would still pass if the IAST::format guard were
removed. Add a formatQuery assertion: formatQuery parses and formats an AST
without the secret-parts walk, so it overflows in IAST::format without the
guard (verified: the 306 comes from IAST::format / formatImplWithoutAlias). It
is linear to build, so it stays fast. Also correct the comment on the
function-call assertions to say they are guarded by the masking walk.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ype-stack-overflow

Fix crash on deeply nested expressions with raised max_parser_depth
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-critical-bugfix labels Jun 29, 2026
…ypick/26.4/108493

# Conflicts:
#	src/Common/FieldVisitorToCastedLiteral.cpp
#	src/Parsers/IAST.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

Resolved the cherry-pick conflicts of #108493 (Fix crash on deeply nested expressions with raised max_parser_depth) onto 26.4 by merging the base branch backport/26.4/108493 into the cherry-pick branch. The PR is now MERGEABLE/CLEAN; net diff against the base is exactly the original PR's applicable changes (19 files, +176/-29).

Conflict resolution details (26.4 diverges from master):

  • src/Common/FieldVisitorToCastedLiteral.cpp (modify/delete): this file does not exist in 26.4 (it was introduced later on master), so the guard for it is dropped. The same checkStackSize guard was applied cleanly to the five other recursive Field visitors that do exist in 26.4 (FieldVisitorDump, FieldVisitorHash, FieldVisitorToJSONElement, FieldVisitorToString, FieldVisitorWriteBinary).
  • src/Parsers/IAST.cpp (content): the conflicting region was the master-only parenthesization refactor (decideParensEmission plus the IAST::format overloads moved out of the header), which is absent in 26.4. Took 26.4's structure and kept only the applicable guards (checkSize, updateTreeHash, childrenHaveSecretParts, cloneChildren, dumpTree).
  • src/Parsers/IAST.h: in 26.4 the recursive IAST::format overloads are still defined inline in the header, so the formatting-recursion guard was ported there — checkStackSize added to format(WriteBuffer &, const FormatSettings &, FormatState &, FormatStateStacked) and format(FormattingBuffer). Verified that 26.4 dispatches child formatting through child->format(...), so the guard fires per recursion level and the formatQuery(... array(array(...)) ...) case in 04411_deep_nested_field_to_type reports TOO_DEEP_RECURSION (code 306) instead of crashing.
  • src/Common/checkStackSize.cpp auto-merged; the resulting change is semantically identical to the original PR (including dropping the __attribute__((__weak__)) attribute). Confirmed NO_INLINE/unlikely are defined in 26.4's base/base/defines.h.

The three regression tests (04411/04412/04413) are carried over verbatim. This is the first step of the automated backport — please let the backport bot proceed (do not merge manually); CI results at this step can be ignored.

@robot-clickhouse
robot-clickhouse merged commit 68a9d46 into backport/26.4/108493 Jun 30, 2026
1 check passed
@robot-clickhouse
robot-clickhouse deleted the cherrypick/26.4/108493 branch June 30, 2026 07:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! pr-critical-bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants