Skip to content

Reject deeply nested JSON documents instead of overflowing the stack - #120887

Merged
Avogar merged 8 commits into
masterfrom
fix-json-type-deep-recursion
Oct 15, 2026
Merged

Avogar merged 8 commits into
masterfrom
fix-json-type-deep-recursion

Conversation

@Avogar

@Avogar Avogar commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

The JSON parsers build the document iteratively, so its nesting depth is bounded only by the input, but three places walked the parsed document recursively without any bound: ObjectJSONNode::traverseAndInsert, when inserting into a JSON column (which also appended to the path at every level, making the memory spent on paths quadratic in the depth); DynamicNode::elementToDataTypeImpl, when inferring the type of a value of a dynamic path from nested arrays; and jsonElementToString, when writing a parsed document back as a string (JSONExtractRaw, JSONExtract to String, shared data, error messages). A deeply nested document exhausted the thread stack in all three and killed the process. This was reachable with allow_simdjson = 0, where the RapidJSON parser parses iteratively and so survives any depth, passing it on to these consumers; the default SimdJSON parser rejects documents deeper than its own limit of about 1024.

The first two are now bounded by max_parser_depth, as JSON schema inference already is, and all three keep a checkStackSize backstop. The limit on type inference matters beyond its own recursion: the inferred type is as deep as the document, and the recursions over that type afterwards - building its name, its extract tree, its column, destroying it - have no guard of their own.

As a result, with allow_simdjson = 0 a document nested deeper than max_parser_depth (1000 by default) is now rejected with TOO_DEEP_RECURSION where it was previously parsed. The limit is tunable, and the default parser already rejected such documents.

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 crash caused by a stack overflow when a deeply nested JSON document was parsed into a JSON column or passed to the JSONExtract family of functions. Such documents are now rejected with the TOO_DEEP_RECURSION error.


Workflow [PR]
Sync PR [sync-upstream/pr/120887]

Version info

  • Merged into: 26.10.1.2484-master (included in 26.10 and later)
  • Backported to: 26.9.20.19, 26.8.29.5, 26.7.37.9, 26.3.59.10

The JSON parsers build the document iteratively, so its nesting depth is
bounded only by the input, and three places walked that document
recursively without any bound:

- `ObjectJSONNode::traverseAndInsert`, when inserting into a `JSON`
  column; it also appended to the path at every level, making the memory
  spent on paths quadratic in the depth.
- `DynamicNode::elementToDataTypeImpl`, when inferring the type of a
  value of a dynamic path from nested arrays.
- `jsonElementToString`, when writing a parsed document back as a string
  (`JSONExtractRaw`, `JSONExtract` to `String`, shared data, error
  messages).

A deeply nested document exhausted the thread stack there and killed the
process. Bound the first two by `max_parser_depth`, as JSON schema
inference already does, and keep a `checkStackSize` backstop in all
three. The limit on type inference matters beyond its own recursion: the
inferred type is as deep as the document, and the recursions over that
type afterwards (building its name, its extract tree, its column,
destroying it) have no guard of their own.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bf178a2]

Summary: ✅


AI Review

Summary

This PR fixes the stack-overflow path for deeply nested JSON in the main JSON-column traversal, dynamic-type inference, and JSON-to-text rendering, and most of the follow-up fixes are in the right direction. I still see one remaining correctness gap in the JSON-column paths: when the recursion is already past input_format_json_max_depth, the new code probes checkStackSize before it checks the configured depth limit, so on builds where the stack backstop fires first the row still escapes as TOO_DEEP_RECURSION instead of going through the existing false + error path. That keeps the fix build-dependent and leaves input_format_allow_errors_* / restoreColumnObject behavior inconsistent for the exact case this PR is trying to regularize.

Findings
  • ⚠️ Majors
    • [src/Formats/JSONExtractTree.cpp:1987] DynamicNode::elementToDataTypeImpl still calls checkStackSize before the explicit input_format_json_max_depth guard. Once a document is already deeper than the configured limit, that ordering lets a low-stack build throw TOO_DEEP_RECURSION before returning false, so SerializationJSON::deserializeObject still bypasses its normal INCORRECT_DATA path and input_format_allow_errors_* cannot reliably skip the row.
      Suggested fix: check depth > format_settings.json.max_depth first, then call checkStackSize only for still-allowed depths.
    • [src/Formats/JSONExtractTree.cpp:2249] ObjectJSONNode::traverseAndInsert has the same ordering bug, with the extra risk that an early checkStackSize exception still skips the local restoreColumnObject(prev_size) rollback in insertResultToColumn. That means the PR’s row-format behavior is still build-dependent: some builds will report a normal parse error, others will still surface TOO_DEEP_RECURSION first.
      Suggested fix: move the explicit depth-limit check ahead of checkStackSize here as well, then keep checkStackSize only as the backstop for inputs that are still within the configured limit.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Swap the order of the explicit depth-limit check and checkStackSize in the DynamicNode and ObjectJSONNode recursion sites.
    • Keep the existing regression coverage for the normal limit path, and add one focused case that proves a too-deep JSONEachRow row stays skippable under input_format_allow_errors_* on the JSON-column path.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... labels Sep 18, 2026
@nihalzp nihalzp self-assigned this Sep 28, 2026

@nihalzp nihalzp 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.

The fix looks good.

The PR body and change log entry seems to be from a different PR.

We can consider using input_format_json_max_depth instead of max_parser_depth. input_format_json_max_depth seems more appropiate.

max_parser_depth = 0 means unlimited, while input_format_json_max_depth = 0 means no nesting at all; something to think about.

`input_format_json_max_depth` is the JSON-specific limit on the nesting
depth of a parsed document, so use it for the two depth checks instead of
the general `max_parser_depth`. Both default to 1000, so the default
behaviour does not change. The value is taken literally, as the only
other user of the setting does, rather than treating 0 as unlimited.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The test forces `allow_simdjson = 0` to exercise the `RapidJSON` parser,
which the Fast test build does not include, so there the JSON functions
raise `NOT_IMPLEMENTED` instead of the expected error.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120887&sha=6606580d54fd6fb4965cfc42e1843b3334f00d52&name_0=PR&name_1=Fast%20test
PR: #120887

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Formats/JSONExtractTree.cpp Outdated
/// checkStackSize is the backstop.
checkStackSize();
if (depth > format_settings.json.max_depth)
throw Exception(ErrorCodes::TOO_DEEP_RECURSION,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These new TOO_DEEP_RECURSION throws escape SerializationJSON::deserializeObject instead of coming back through the existing false + error path. That changes row-format behavior in two ways:

  1. deserializeObject no longer rewraps the failure as INCORRECT_DATA, so IRowInputFormat will not treat a too-deep row as skippable under input_format_allow_errors_* (isParseError() does not include TOO_DEEP_RECURSION).
  2. In the JSON column path the exception also bypasses ObjectJSONNode::insertResultToColumn's restoreColumnObject(prev_size) cleanup, so the safe continuation path here is still the existing false/error flow.

So a single pathological row in JSONEachRow still aborts the whole import instead of being handled like other malformed rows. Can we funnel this limit failure back through the normal parse-error path (or catch+restore locally and rethrow as INCORRECT_DATA)? The sibling throw in DynamicNode::elementToDataTypeImpl has the same issue.

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit bf178a28aaeef9346f584c577de6cf5e17789820 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Throwing from the traversal escaped the `false` + `error` protocol that
the JSON extract tree uses for malformed input: the failure was not
rewrapped as `INCORRECT_DATA`, so `isParseError` did not hold for it and
a single too-deep row aborted a whole import instead of being skipped
like any other malformed row, and the partially filled column was not
restored. Report the limit through `error` instead. `checkStackSize`
still throws, being a last-resort guard.

The test now keeps every document that survives parsing shallow: such a
document is walked again by consumers whose recursion the setting does
not bound, for example the conversion of a constant to an `AST` literal.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120887&sha=902d3408260a1c543731539176e02a0eb9f26b7e&name_0=PR
PR: #120887

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Formats/JSONExtractTree.cpp Resolved
Avogar and others added 2 commits October 9, 2026 12:13
`jsonElementToString` walks a parsed document whose nesting depth comes
from the input, and two of its uses could not afford an unbounded walk.

An error message quotes the element it is about, so producing one could
recurse as deep as the document and build a huge string; messages now
render at most a fixed number of levels and elide the rest.

A `String`, `LowCardinality(String)` or `FixedString` column takes the
rendered text as its value. A value cannot be elided, so one nested
deeper than `input_format_json_max_depth` is now rejected through the
`false` + `error` path, like any other value that cannot be read. The
`String` column renders directly into the column's characters, so the
characters are truncated back when that fails. As a result, extracting
a too-deep value as a `String` yields the default, which is what the
`SimdJSON` parser already does, since it refuses such a document.

Rendering raw text (`JSONExtractRaw`) stays unbounded, with
`checkStackSize` as its guard.

Each case in the test now has a single possible rejector: which of the
limit and the backstop comes first depends on the build.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120887&sha=94f1d66740a9ee2bcf481a6530da9f4e72471c39&name_0=PR
PR: #120887

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Formats/JSONExtractTree.cpp Resolved
Avogar and others added 2 commits October 13, 2026 15:17
`JSONExtractRaw` rendered an element without a depth bound while the
extract tree bounds it by `input_format_json_max_depth`, so the two ways
of asking for an element as text disagreed: `JSONExtract(x, 'String')`
gave the default for a value nested too deep, while `JSONExtractString`,
which forwards a non-string value to the raw renderer, raised
`TOO_DEEP_RECURSION`. Bound the raw renderer the same way, so all of
them treat such a value as one that cannot be extracted. The `SimdJSON`
parser already behaves this way, since it refuses to parse a document
that deep at all.

`JSONExtractArrayRaw` and `JSONExtractKeysAndValuesRaw` keep one element
per element of the input, with the default for one that cannot be
rendered.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Oct 15, 2026
Merged via the queue into master with commit 3ad196f Oct 15, 2026
177 checks passed
@Avogar
Avogar deleted the fix-json-type-deep-recursion branch October 15, 2026 15:14
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #120887 to 26.8: Reject deeply nested JSON documents instead of overflowing the stack
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #120887 to 26.9: Reject deeply nested JSON documents instead of overflowing the stack
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 21, 2026
Avogar added a commit that referenced this pull request Oct 21, 2026
Resolve the conflict of backporting #120887 ("Reject deeply nested JSON
documents instead of overflowing the stack") to 26.7: the `String` node
keeps the new depth-bounded rendering, but the buffer is created without
`json_max_string_column_growth_step`, which 26.7 does not have.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Avogar added a commit that referenced this pull request Oct 21, 2026
Resolve the conflicts of backporting #120887 ("Reject deeply nested JSON
documents instead of overflowing the stack") to 26.3:

- The `String` node keeps the new depth-bounded rendering, but the buffer
  is created without `json_max_string_column_growth_step`, which 26.3
  does not have.
- The `Variant` node error keeps the 26.3 message text and quotes the
  element with the bounded `jsonElementToStringForError`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
robot-ch-test-poll3 added a commit that referenced this pull request Oct 21, 2026
Cherry pick #120887 to 26.3: Reject deeply nested JSON documents instead of overflowing the stack
robot-clickhouse added a commit that referenced this pull request Oct 21, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Oct 21, 2026
Cherry pick #120887 to 26.7: Reject deeply nested JSON documents instead of overflowing the stack
robot-clickhouse added a commit that referenced this pull request Oct 21, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 21, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 21, 2026
Backport #120887 to 26.7: Reject deeply nested JSON documents instead of overflowing the stack
alexey-milovidov added a commit that referenced this pull request Oct 22, 2026
Backport #120887 to 26.3: Reject deeply nested JSON documents instead of overflowing the stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... 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-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