Skip to content

Make Field copy and destroy iterative to survive deeply nested literals - #110393

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
Algunenano:fix-deep-nested-literal-stack-overflow
Jul 20, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
Algunenano:fix-deep-nested-literal-stack-overflow

Conversation

@Algunenano

@Algunenano Algunenano commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

A deeply nested collection literal such as SELECT [[[ ... ]]] is parsed into a single ASTLiteral whose Field nests one Array/Tuple/Map per level. Since the collection-of-literals parser is iterative, that Field can be built to an arbitrary depth (bounded only by the client-settable max_parser_depth) without tripping the parser's periodic checkStackSize guard, which relies on native recursion to fire.

The recursive Field copy constructor (reached via ASTLiteral::clone when the analyzer clones the AST) and the Field destructor then recurse once per nesting level with no stack guard and overflow the native stack, crashing the server. A checkStackSize guard cannot cover the destructor, because throwing from a destructor calls std::terminate.

This makes the copy and destroy of Array/Tuple/Map/Object fields (and the copy- and move-assignment paths that route through them) iterative, using an explicit worklist so the native stack depth stays bounded regardless of the nesting depth. The stack-guarded type-inference and formatting walks still reject genuinely too-deep structures cleanly with TOO_DEEP_RECURSION.

Related: #108892

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 crash (native stack overflow) when a deeply nested Array/Tuple/Map/Object literal is copied or destroyed, for example a query with a very deeply nested literal at a raised max_parser_depth.

Version info

  • Backported to: 26.6.2.87, 26.5.6.59, 26.4.5.147, 26.3.17.60, 25.8.29.27

A deeply nested collection literal (e.g. `[[[ ... ]]]`) is parsed into a
single `Field` nested one `Array`/`Tuple`/`Map` per level. Since the collection
parser became iterative, that `Field` can be built to an arbitrary depth
(bounded only by the client-settable `max_parser_depth`) without tripping the
parser's periodic `checkStackSize` guard, which relies on native recursion to
fire.

The recursive `Field` copy constructor (reached via `ASTLiteral::clone` when the
analyzer clones the AST) and the `Field` destructor then recurse once per
nesting level with no stack guard and overflow the native stack, crashing the
server. A `checkStackSize` guard cannot fix the destructor because throwing from
a destructor calls `std::terminate`.

Make the copy and destroy of `Array`/`Tuple`/`Map`/`Object` fields (plus the
copy- and move-assignment paths that route through them) iterative, using an
explicit worklist so the native stack depth stays bounded regardless of the
nesting depth. Guarded type-inference/formatting walks still reject genuinely
too-deep structures cleanly with `TOO_DEEP_RECURSION`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f7d034]

Summary: ✅


AI Review

Summary

This PR makes Field copy and destroy iterative so deeply nested literals no longer overflow the native stack during AST cloning or teardown. The implementation itself looks consistent after the latest updates, but the new regression test still does not exercise the same-type templated container-assignment branch it claims to cover, so the evidence for that part of the contract is incomplete.

Tests

⚠️ [src/Core/tests/gtest_field.cpp:101] assigned = a starts from a Null Field, so it only covers the destroy(); createConcrete(a) path in Field::operator=(T &&). It does not hit the same-type assignConcrete(a) branch that reassigns an existing Array/Object field. A focused regression case should initialize assigned with a deep container first and then assign into it once.

Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
Comment thread src/Core/Field.cpp Resolved
The iterative destroy runs from `~Field` (noexcept), but its worklist can
allocate, and the global `operator new` throws `MEMORY_LIMIT_EXCEEDED` on the
soft memory limit like any other allocation. The old recursive destructor never
allocated, so this would be a new way for teardown to `std::terminate` under
memory pressure.

Wrap the worklist in `LockMemoryExceptionInThread`, which suppresses the
memory-limit exception while still tracking memory, so the memory freed during
teardown is still credited (no tracker drift) and only a genuine out-of-memory
`bad_alloc` remains. Also use an inline worklist buffer so the common (deep and
therefore narrow) case does not allocate at all.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Core/Field.h Resolved
…alues

Guards the iterative Field copy/destroy against regressions and covers the
container-lvalue entry points (the templated Field(T&&) constructor and
assignment, e.g. Field(object) in the analyzer): they forward to the underlying
container copy, whose elements are copied via the now-iterative Field copy, so a
deeply nested container lvalue must not overflow the native stack either.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Core/tests/gtest_field.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.30% 78.20% -0.10%

Changed lines: Changed C/C++ lines covered: 120/126 (95.24%) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue Jul 20, 2026
Merged via the queue into ClickHouse:master with commit e1af523 Jul 20, 2026
178 checks passed
@Algunenano
Algunenano deleted the fix-deep-nested-literal-stack-overflow branch July 20, 2026 17:27
@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 Jul 20, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 20, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 20, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jul 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 20, 2026
Backport #110393 to 26.6: Make Field copy and destroy iterative to survive deeply nested literals
Algunenano added a commit that referenced this pull request Jul 21, 2026
Backport #110393 to 26.5: Make Field copy and destroy iterative to survive deeply nested literals
Algunenano added a commit that referenced this pull request Jul 21, 2026
Backport #110393 to 26.4: Make Field copy and destroy iterative to survive deeply nested literals
Algunenano added a commit that referenced this pull request Jul 21, 2026
Backport #110393 to 26.3: Make Field copy and destroy iterative to survive deeply nested literals
Algunenano added a commit that referenced this pull request Jul 21, 2026
The backport of #110393 changed the Array/Tuple/Map/Object cases of
Field::destroy to call destroyContainerIteratively(old_which), but kept
the pre-existing 25.8 structure that switched on which and set
which = Types::Null at the end, so old_which was never declared.

Match master: capture old_which = which and reset which = Types::Null
before the switch, then switch on old_which. This also satisfies the
destroyContainerIteratively contract that which is already Null on entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano added a commit that referenced this pull request Jul 22, 2026
Backport #110393 to 25.8: Make Field copy and destroy iterative to survive deeply nested literals
joelynch pushed a commit to aiven/ClickHouse that referenced this pull request Aug 17, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…literal-stack-overflow

Make Field copy and destroy iterative to survive deeply nested literals
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
OTHER: deeply nested literal copy/destroy -> crash.
Effect in the production build a394e92: its upstream test(s) 04538_deep_nested_literal_clone_no_crash fail on it 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): 04538_deep_nested_literal_clone_no_crash.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 22, 2026
`AsyncLoader::worker`, `remove` and `schedule` run their bookkeeping under
`DENY_ALLOCATIONS_IN_SCOPE`, and `LoadJob::finish` resets `func` and
`dependency_failure` inside it, destroying whatever the job captured. A
table-load job from `DatabaseOrdinary::loadTableFromMetadataAsync` holds the
last reference to the CREATE query AST. Since ClickHouse#110393, destroying a `Field`
with more than 16 non-empty nested containers allocates (the inline worklist
of `Field::destroyContainerIteratively`), so a debug server aborts with
`Memory tracker: allocations not allowed` at startup when a table whose
definition holds such a literal (e.g. `DEFAULT [[1], [2], ..., [17]]`)
finishes loading. Seen in `La Casa Del Dolor (amd_debug)` (STID 4176-5176).

Destroy the two callbacks under `ALLOW_ALLOCATIONS_IN_SCOPE`, as
`ThreadPool` does for its jobs (ClickHouse#63829). `LoadJob::finish` is the only place
where the loader destroys job callbacks, so the worker, `remove()` and the
cancel in `schedule()` are all covered, and the callbacks are still destroyed
before `finished.notify_all()`. Both macros are no-ops with `NDEBUG`.

The new gtests cover the three paths; each aborts without the fix.

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-bugfix Pull request with bugfix, not backported by default 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.

4 participants