Skip to content

Fix crash on deeply nested expressions with raised max_parser_depth - #108493

Merged
Algunenano merged 9 commits into
ClickHouse:masterfrom
Algunenano:fix-deep-nested-field-to-type-stack-overflow
Jun 29, 2026
Merged

Algunenano merged 9 commits into
ClickHouse:masterfrom
Algunenano:fix-deep-nested-field-to-type-stack-overflow

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

A deeply nested expression combined with a large max_parser_depth could crash the server with an uncatchable stack overflow (SIGSEGV). max_parser_depth is a client-settable session setting, so any user can trigger it.

Raising max_parser_depth lets the parser build an arbitrarily deep expression. Several recursive routines that subsequently walk the resulting Field/DataType/AST had no stack guard and overflowed the native stack:

  • convertFieldToType: deeply nested Array/Tuple/Map literals such as [[[ ... ]]].
  • FieldToDataType for Array/Tuple/Map.
  • getLeastSupertype.
  • IAST::childrenHaveSecretParts: secret-argument masking of deeply nested function calls such as array(array( ... )).

Each now calls checkStackSize at its recursive entry point, so the queries report TOO_DEEP_RECURSION instead of crashing the server. Added a stateless regression test covering both the literal and the nested-function paths.

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 server crash (stack overflow) caused by deeply nested expressions such as [[[ ... ]]] or array(array( ... )) when max_parser_depth is set to a large value.

Version info

  • Merged into: 26.7.1.251 (included in 26.7 and later)
  • Backported to: 26.6.2.16, 26.5.5.10, 26.4.5.88, 26.3.17.7, 25.8.26.7

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4ab1f07]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Received signal 6 (STID: 5852-425e) FAIL cidb

AI Review

Summary

This PR adds checkStackSize guards to the recursive Field, DataType, and AST walks that can be reached after a user raises max_parser_depth, and it adds focused stateless regressions for nested literals, AST formatting, and SET param_* parsing. The prior bot findings have been addressed in the current code; I resolved the remaining fixed thread and found no new blockers or majors.

Missing context / blind spots
  • ⚠️ I could not run the new stateless tests locally because this checkout has no build directory. The direct Praktika PR report URL for head 4ab1f0727810f3ca885d822716362ef9d4ae1227 currently exposes no per-test failed entries; a green stateless run would close this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jun 25, 2026
Algunenano and others added 2 commits June 25, 2026 16:38
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]>
Comment thread src/Parsers/IAST.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

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.

A little bit worried about performance. Is checkStackSize fast?

@alexey-milovidov alexey-milovidov self-assigned this Jun 25, 2026
@alexey-milovidov alexey-milovidov added the pr-performance Pull request with some performance improvements label Jun 25, 2026
@Algunenano

Copy link
Copy Markdown
Member Author

A little bit worried about performance. Is checkStackSize fast?

It is relatively cheap after the fist call. It caches the stack bounds in thread local variables, so it's a check for fibers (loading a thread local variable), a call to __builtin_frame_address (usually a single register read or stack memory load), reading the 2 thread local variables (stack address and size) and the comparison. Not cheap but not horrible. The main concern might be the function call itself and that it might prevent some optimizations/unrolling. OTOH, it prevents crashes :D

In any case, I'll have a look and try to optimize the common path

Algunenano and others added 2 commits June 26, 2026 11:45
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]>
Comment thread src/Common/FieldVisitorToString.cpp Resolved
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]>
Comment thread src/Common/FieldVisitorToString.cpp Resolved
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]>
Comment thread src/Parsers/IAST.cpp Resolved
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR adds stack-overflow guards to recursive Field visitors and AST traversal (format, hash, clone, type inference) plus a micro-optimization of the stack-size check. Those paths run during parsing, AST formatting, and literal type inference, not during the per-row scan, join, or aggregation work these benchmarks exercise. The two flagged ClickBench improvements (Q4 -16%, Q28 -6%) and the borderline TPC-H Q4 regression (+10%) all sit off the changed code, so they are treated as run-to-run variance rather than real effects of this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 262 220 -16.0% <0.0001 PR only adds parser/AST/type-inference stack guards; Q4's scan+aggregate path is untouched, so -16% is run-to-run varian
⚠️ 28 not_sure 6980 6556 -6.1% <0.0001 Same off-path change; nested Field visitors/AST formatting don't run during Q28 execution, so -6% is noise

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 2362 2608 +10.4% 0.0364 Borderline +10% on a noisy query; stack-guard edits don't touch join/aggregate execution, treat as variance

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 3912e507-7a24-4090-bb32-5b8228966728
  • MIRAI run: 5c352fdb-be0b-491f-9397-4861d803480b
  • PR check IDs:
    • clickbench_148816_1782484064
    • clickbench_148830_1782484064
    • clickbench_148836_1782484064
    • tpch_adapted_1_official_148843_1782484064
    • tpch_adapted_1_official_148853_1782484064
    • tpch_adapted_1_official_148865_1782484064

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 109/149 (73.15%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code

Full report · Diff report

@Algunenano

Copy link
Copy Markdown
Member Author

Fuzzer -> #108821

@Algunenano
Algunenano added this pull request to the merge queue Jun 29, 2026
Merged via the queue into ClickHouse:master with commit 7c45c76 Jun 29, 2026
165 of 167 checks passed
@Algunenano
Algunenano deleted the fix-deep-nested-field-to-type-stack-overflow branch June 29, 2026 16:51
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 29, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Resolve cherry-pick conflicts of #108493 (stack-overflow guards for deeply
nested expressions) onto 25.8:

- src/Common/FieldVisitorToCastedLiteral.cpp: absent in 25.8, so the guard
  added there on master is dropped (the file does not exist on this branch).
- src/Common/checkStackSize.cpp: take the PR's refactored form
  (`stack_bounds.max_size / STACK_SIZE_FREE_RATIO`); the rest of the
  per-call-overhead refactor auto-merged cleanly. Final behavior is identical
  to master (half the stack, 5% under TSan).
- src/Parsers/ASTLiteral.cpp: add only `#include <Common/checkStackSize.h>`;
  the master-only `#include <Common/FieldVisitorDump.h>` is not used in 25.8.
- src/Parsers/IAST.cpp: 25.8 has no `decideParensEmission`/out-of-line
  `IAST::format` block (master-only), so that whole region is dropped; the
  guards on `checkSize`/`updateTreeHash`/`childrenHaveSecretParts`/
  `cloneChildren`/`dumpTree` and the include auto-merged.
- src/Parsers/IAST.h: in 25.8 `IAST::format` overloads are inline in the
  header (not in IAST.cpp), so the PR's format-path `checkStackSize()` guards
  are applied here instead, with the matching include.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
Cherry pick #108493 to 25.8: Fix crash on deeply nested expressions with raised max_parser_depth
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
Cherry pick #108493 to 26.3: Fix crash on deeply nested expressions with raised max_parser_depth
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
Cherry pick #108493 to 26.4: Fix crash on deeply nested expressions with raised max_parser_depth
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
Cherry pick #108493 to 26.5: Fix crash on deeply nested expressions with raised max_parser_depth
robot-clickhouse added a commit that referenced this pull request Jun 30, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 30, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jun 30, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jun 30, 2026
Backport #108493 to 26.6: Fix crash on deeply nested expressions with raised max_parser_depth
Algunenano added a commit that referenced this pull request Jun 30, 2026
Backport #108493 to 26.3: Fix crash on deeply nested expressions with raised max_parser_depth
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #108493 to 26.5: Fix crash on deeply nested expressions with raised max_parser_depth
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #108493 to 26.4: Fix crash on deeply nested expressions with raised max_parser_depth
Algunenano added a commit that referenced this pull request Jul 1, 2026
Backport #108493 to 25.8: Fix crash on deeply nested expressions with raised max_parser_depth
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…field-to-type-stack-overflow

Fix crash on deeply nested expressions with raised max_parser_depth
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
OTHER: deeply nested literal with a large max_parser_depth -> crash.
Effect in the production build a394e92: its upstream test(s) 04411_deep_nested_field_to_type, 04412_deep_nested_literal_format, 04413_set_param_deep_collection fail on it (the server process died in 04411_deep_nested_field_to_type) and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04411_deep_nested_field_to_type,04412_deep_nested_literal_format,04413_set_param_deep_collection.

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

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-performance Pull request with some performance improvements 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.

5 participants