Repository navigation
Do not exhaust the stack when reading a deeply nested Dynamic or JSON value - #121441
Conversation
… value
A Dynamic value can hold a JSON object, a JSON object's dynamic path is a
Dynamic, and JSON/Object is a legal Variant member (checkAllowedInsideVariant
forbids only Nullable, LowCardinality(Nullable), a nested Variant and a direct
Dynamic). So one value can nest Object -> Dynamic -> Variant -> Object to any
depth, and that depth comes from the data: the declared type here is just
Dynamic, and each level's small type is decoded separately, so no type
complexity or parser limit bounds it.
Reading one row of such a value recurses once per level through five frames:
ColumnObject::operator[] (ColumnObject.cpp:305)
-> ColumnDynamic::operator[] (ColumnDynamic.cpp:318)
-> ColumnDynamic::get (ColumnDynamic.cpp:328)
-> ColumnVariant::get (ColumnVariant.cpp:428)
-> ColumnObject::get (ColumnObject.cpp:327)
-> ColumnObject::operator[] ... repeats
at about 2.8 KB of stack per level. The one checkStackSize() that path already
reaches sits inside convertFieldToType, called at ColumnDynamic.cpp:330 after
variant_col.get(n, res) has returned, so it runs only once the descent has
completed and cannot stop the descent that overflows. Measured on a debug build
with an 8 MB stack: 1500 and 2000 levels report TOO_DEEP_RECURSION from that
call, while 3000 and 4000 levels take SIGSEGV on the way down. An -O2 build
behaves the same (these frames are dominated by Field, String and Object
temporaries rather than spills, so optimisation does not shrink them), and the
official 26.8.10.6-lts build dies the same way at default settings.
Checking the stack at the top of ColumnDynamic::get moves the check onto the way
down, once per level. Every data-driven level of this nesting passes through a
ColumnDynamic per-value method, because a JSON object's dynamic paths are
ColumnDynamic columns and its shared-data values are decoded by
SerializationDynamic, which is already guarded.
ColumnObject and ColumnVariant are deliberately left unguarded. Their nested
types come from the declared type, and DataTypeFactory.cpp:128-130 caps a
declared type's parse depth at 150 (debug) / 300, two orders of magnitude below
the depths that overflow; a probe confirms a deep JSON(a JSON(...)) is rejected
with "Maximum parse depth (150) exceeded" and the server survives. Adding a
guard there would also re-litigate 2fcfc07, which removed exactly that
construct one layer down in ClickHouse#115702 for its per-container-value cost.
About twenty further per-value methods on these three columns (insert*,
compareAt, computeHashInto, updateHashWithValue, serializeValueIntoArena,
compress, byteSizeAt, ...) recurse identically, with no observed overflow and no
reproducer; the reproducers for updateHashWithValue and getValueNameImpl are
pre-empted on this base by the analyzer recursion that ClickHouse#120885 guards, so they
are not covered here.
Alternatives rejected: guarding the entry points (eight-plus sites for one arm,
and it guards the symptom); bounding the nesting depth when the value is built
(a behaviour change that rejects values accepted today, and it cannot protect a
read of data an older server already wrote); guarding the operator[] alias as
well as get (operator[] is get, so it would double-check).
The regression test uses 4000 levels, the depth CI found and a depth measured to
overflow both a debug and an -O2 build. It should not be raised much above that:
from about 8000 levels the type-side guard in IDataType::getDefaultSerialization
fires first and returns the same error code without the column recursion ever
running deep.
Found by the AST fuzzer, STID 4709-36d5:
https://github.com/ClickHouse/ClickHouse/actions/runs/35623644754/job/106452545848
Internal second-model review: adjudication log (click to expand)Pre-publication review of this tree: one independent cold read plus one gate pass by a second model
What I verified independently, because a per-value guard invites both questions:
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260921-210900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260921-200600 |
|
Workflow [PR], commit [2831c86] Summary: ❌
AI ReviewSummaryThis PR correctly adds Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 2831c86.
Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code |
…N value
Every text format of Dynamic funnels through one static serializeTextImpl helper, and its
nested_serialize callback re-enters SerializationJSON for a JSON variant, which walks back
into SerializationDynamic for that object's next dynamic path. The depth of that nesting
comes from the data, so nothing bounded the descent: on the official 26.8.10.6-lts build,
at default settings,
SELECT toString(finalizeAggregation(CAST(unhex(materialize(concat('01',
repeat('3000800820000000010161', 4000), '300080082000000000')))
AS AggregateFunction(any, Dynamic))))
terminates the server with a segmentation fault cycling between
SerializationDynamic::serializeTextJSON and SerializationJSON::serializeTextImpl. The
checkStackSize() this PR adds to ColumnDynamic::get does not cover it, because the value is
printed through its serialization rather than read as a Field.
One checkStackSize() at the top of the shared helper therefore covers all eight text formats
of the type (Text, JSON, JSONPretty, CSV, Escaped, Quoted, Raw, XML), which is the same
choke-point argument as for ColumnDynamic::get and mirrors the two guards this file already
carries on the binary paths.
Measured: 855 json/dynamic/variant/object tests with fixed settings, identical failure sets
before and after (36, all local object-storage and format environment failures), zero
TOO_DEEP_RECURSION anywhere in the sweep, and 30/30 runs of the new test green. Reverting
only this guard makes the added query fail with the server dying.
The sibling per-value entrypoints an AI review named (updateHashWithValue reached by
arrayDistinct, compareAt reached by ORDER BY and sorted DISTINCT) do not reach a
segmentation fault with this value shape: the CAST that builds the value itself trips
checkStackSize at about depth 6000, having consumed 4 MB of an 8 MB stack, while
arrayDistinct over the deepest value it can build, depth 5000, completes on an unguarded
binary.
| void ColumnDynamic::get(size_t n, Field & res) const | ||
| { | ||
| /// Object, Dynamic and Variant values nest into each other to a depth that comes from the data, not from the declared type. | ||
| checkStackSize(); |
There was a problem hiding this comment.
This hardens Field materialization, but the same deep Object -> Dynamic -> Variant -> Object walk is still unguarded in constant/projection name generation. PlannerActionsVisitor builds names from ConstantNode::getValueName (src/Planner/PlannerActionsVisitor.cpp:437), which goes through IColumn::getValueName and then ColumnDynamic::getValueNameImpl (src/Columns/ColumnDynamic.cpp:346-375) with no checkStackSize(). That is not just a pathological setting: optimize_const_name_size < 0 explicitly disables the hash fallback in IColumn::getValueName, and TCPHandler still forces optimize_const_name_size = -1 for pre-25.10 WithMergeableState queries (src/Server/TCPHandler.cpp:2811-2815).
So the PR’s contract “deep Dynamic/JSON reads or prints now raise TOO_DEEP_RECURSION instead of terminating the server” is still false for EXPLAIN actions = 1 / projection-name surfaces that stringify the same constant value. This needs the same stack guard on the getValueNameImpl path (or an earlier bounded fallback in IColumn::getValueName) plus a regression with optimize_const_name_size = -1.
There was a problem hiding this comment.
I measured the named path before answering. The mechanism does not hold, but you are right that these surfaces still terminate the server, at a site this PR deliberately leaves to #120885.
On this branch's head (debug build, 8 MiB stacks), with the deep value kept constant and numbers(2) as the source:
| query | optimize_const_name_size |
depth | result |
|---|---|---|---|
SELECT number, <deep const> FROM numbers(2) |
-1 | 1000 | TOO_DEEP_RECURSION, 7739280 of 8388608 bytes |
| same | -1 | 2000 / 3000 / 4000 | SIGSEGV |
EXPLAIN actions = 1 SELECT number, <deep const> FROM numbers(2) |
-1 | 4000 | SIGSEGV |
same query through remote() back to this server |
-1 | 4000 | SIGSEGV |
SELECT number, <deep const> FROM numbers(2) |
256 (default) | 4000 | SIGSEGV |
<deep const> is this PR's value, finalizeAggregation(CAST(unhex(concat('01', repeat('3000800820000000010161', depth), '300080082000000000')), 'AggregateFunction(any, Dynamic)')), without materialize.
Every one of those stacks is getFieldFromColumnForASTLiteralImpl cycling on itself (src/Analyzer/Utils.cpp:1538 -> :1546 -> :1569), and the depth-1000 throw comes from the IDataType::getDefaultSerialization check reached from that same walk. ColumnDynamic::getValueNameImpl is in none of them. The TCPHandler carrier is real, which is why I ran the -1 arms and not only the default ones.
I then applied the two src/Analyzer/Utils.cpp hunks of #120885 on top of this branch and rebuilt. With that walk guarded, depths 2000, 4000 and 5000 with optimize_const_name_size = -1, plus EXPLAIN actions = 1, all raise TOO_DEEP_RECURSION from the new check at Utils.cpp:1421, at 4195456 of 8388608 bytes. At 6000 the CAST that builds the value raises TOO_DEEP_RECURSION first, so 5000 levels is the deepest such value that exists.
So a check in getValueNameImpl changes no outcome on any of those queries, and the regression you ask for cannot assert TOO_DEEP_RECURSION on master today: with optimize_const_name_size = -1 and a deep constant the server dies in the analyzer walk, whose fix carries that same 4000-level constant as its own test. I am not adding the check here.
The wording was fair, though: the changelog entry claimed reads and prints in general, so I narrowed it to the two funnels this PR enforces.
CI finish ledger - 195df7fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260922-053136 |
| SerializeNull serialize_null) | ||
| { | ||
| /// See the comment in deserializeBinary: the same data-driven nesting is walked here, one level per nested value. | ||
| checkStackSize(); |
There was a problem hiding this comment.
serializeTextImpl is now guarded, but the same data-driven Object -> Dynamic -> Variant -> Object recursion is still unbounded on the binary write path. BinaryRowOutputFormat::writeField calls serialization.serializeBinary(...), SerializationDynamic::serializeBinary then recurses into the active variant, and SerializationObject::serializeBinary immediately re-enters dynamic_serialization->serializeBinary(...) for nested dynamic paths.
That means a sufficiently deep value can still exhaust the stack in FORMAT RowBinary (and any other caller of the per-value binary serializer) instead of raising TOO_DEEP_RECURSION. Can we add the same checkStackSize() on the binary write path — at least the Field and ColumnDynamic overloads of SerializationDynamic::serializeBinary, or via a shared helper used by both text and binary writers — and pin it with a focused RowBinary regression?
There was a problem hiding this comment.
I measured the binary path on master before splitting it out, and could not make it fail. With this PR's test value at 5000 levels in a debug build and 6500 on the official 26.9 build (close to the deepest that can be built; deeper values throw TOO_DEEP_RECURSION while being built), FORMAT RowBinary, RowBinaryWithNamesAndTypes, formatRow('RowBinary', ...) and the AggregateFunction(any, Dynamic) state all write the full value, while toString of the same value segfaults without this PR. I found no route to a deeper value: Native input throws TOO_DEEP_RECURSION at 5000 levels, JSON text input stops at about 1000 nesting levels, and CAST from Map or Tuple flattens the nesting. So I am not opening a separate PR for the binary path unless a reproducer turns up.
There was a problem hiding this comment.
A reproducer turned up: the AST fuzzer sent this state through remote(), where the binary write runs on the 320 KiB remote-query coroutine stack and checkStackSize() did not check coroutine stacks. The fix is #127880.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 15 s compile time in total, 8 of them have a recent master baseline. |
CI finish ledger - db8255fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 160 checks completed; CIDB has no other Session id: cron:our-pr-ci-monitor:20261003-233424 |
0882f3a
… value Hash functions (sipHash64, cityHash64, xxHash64, murmurHash3_64, ...) hash a Dynamic or JSON value through ISerialization::serializeForHashCalculation. For JSON, SerializationObject::serializeForHashCalculation calls SerializationDynamic::serializeForHashCalculation for every dynamic, shared or Dynamic-typed path, and a nested JSON variant calls back into Object. The type of every nested value is decoded from the data, so the recursion depth is bounded only by the value, and nothing on this cycle checked the stack. A value deep enough to hash past the end of the stack can still be built, because building it costs less stack per level than hashing it and is already guarded (SerializationDynamic::deserializeBinary). Measured on the official 26.8.21.12 build: sipHash64 over the value from ClickHouse#123940 nested 3500 to 6000 levels deep kills the server with SIGSEGV, while the CAST that builds it succeeds up to 6000 levels. Check the stack at the top of SerializationDynamic::serializeForHashCalculation. Every data-driven re-entry on the hash path passes through it (from JSON paths and from containers of Dynamic), the same choke point ClickHouse#121441 guarded for text serialization. Ordinary values hash byte-identically; a too-deep value now raises TOO_DEEP_RECURSION. Closes ClickHouse#123940 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #120885
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash (stack exhaustion) when reading a
DynamicorJSONvalue as aFieldor printing it in a text format, where theObject/Dynamic/Variantnesting is deep enough to exhaust the thread stack. Both paths now raiseTOO_DEEP_RECURSIONinstead of terminating the server.Description
On 26.8.10.6-lts (official build), at default settings, a value built by
CAST(unhex(concat('01', repeat('3000800820000000010161', 4000), '300080082000000000')), 'AggregateFunction(any, Dynamic)')terminates the server withSegmentation faulttwice over: read as aFieldunderEXPLAIN QUERY TREE SELECT finalizeAggregation(...), which the AST fuzzer reported as STID4709-36d5(job), and printed undertoString(finalizeAggregation(materialize(...))), found while answering the AI review.A
Dynamiccan hold aJSONobject, aJSONobject's dynamic path is aDynamic, andJSONis a legalVariantmember, so the value nestsObject->Dynamic->Variant->Objectto a depth taken from the data rather than from the declared type. Each level passes throughDynamictwice, so I check the stack at both:ColumnDynamic::get, whose only existing check is inconvertFieldToType, after the descent returns, and the sharedserializeTextImplofSerializationDynamic, covering all eight text formats.ColumnObjectandColumnVariantstay unguarded: the onlyObject->Objectroute is a typed path capped at 150/300 levels bydata_type_max_parse_depth, the reason #115702 dropped those guards one layer down. #120885 guards the constant-to-AST-literal walk; neither PR covers the other, and projection naming of a deep constant dies in that walk too.One query per crash, with a shallow control each. Reverting either guard makes its query fail with the server dying; 855
json/dynamic/variant/objecttests keep identical failure sets against an unpatched binary and raiseTOO_DEEP_RECURSIONnowhere. Depth 4000 overflows an-O2build too; past about 8000 a type-side guard fires first.@Avogar: the siblings (
updateHashWithValue,compareAt,computeHashInto,insert*) recurse the same way, butarrayDistinctandORDER BYover the deepest value thisCASTcan build, 5000 levels, both complete unguarded. I left them rather than pay a check per value per level; say the word and they go in.Workflow [PR]
Sync PR [sync-upstream/pr/121441]
Version info
26.10.1.1547-master(included in26.10and later)