Skip to content

Guard the JSON AST deserialization recursions with checkStackSize - #121693

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:json-ast-reader-stack-guards
Sep 23, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:json-ast-reader-stack-guards

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120725

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 crash when deserializing an AST from JSON (formatQueryFromJSON, the clickhouse_json dialect): a deeply nested document exhausted the stack and killed the process with no log line. Such payloads now fail with TOO_DEEP_RECURSION.

Description

On v26.8.11.7-lts, SELECT formatQueryFromJSON(<1500-level nested AST JSON>) SETTINGS max_ast_depth = 100000 terminates the process with SIGSEGV, zero output and no stack trace.

Root cause: the reader's only bound is a counter compared against max_ast_depth (or 1000 when it is 0). A count is not a stack budget, so raising the setting removes the bound, and the 1000 ceiling is itself unsafe on a smaller thread stack. Three recursions are involved and none checked the stack. One of them is the JSON text parser's descent, which finishes before any AST node exists, so no check inside createFromJSON can observe it.

Fix: checkStackSize() on each recursive entry, placed after that recursion's existing bound check so a binding bound keeps its own message. DB::Exception derives from Poco::Exception, so a catch (const Exception &) { throw; } clause is ordered before the existing handler, otherwise the guard surfaces as BAD_ARGUMENTS.

Validated in both directions on a debug build: every shape that terminated the process now reports TOO_DEEP_RECURSION, and the 64-test ast_json/from_json suite plus the round-trip oracles stay green.

Accepted depth is now bounded by the stack rather than by a count, so payloads close to the old limit can be rejected where they previously succeeded, and the exact boundary depends on the build's frame size. That is the intended consequence of bounding the stack, not a side effect.

No CI job covers this route, so there is no failing job to link. The guard was requested twice in review (#120507 comment 4044903531 and #120725 discussion_r4071837075); both earlier asks landed in post-construction validation walks, which are not the recursion that overflows first.


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

Version info

  • Merged into: 26.10.1.550-master (included in 26.10 and later)
  • Backported to: 26.9.2.26, 26.8.11.35

groeneai and others added 2 commits September 23, 2026 01:40
Deserializing an AST from JSON (formatQueryFromJSON, the clickhouse_json
dialect) recursed with no stack check. Its only bound was a counter compared
against effectiveJSONDeserializationMaxDepth(), i.e. max_ast_depth when set and
1000 otherwise. A count is not a stack budget: safety is
stack_size / per_level_frame_cost, and both factors move independently of any
setting. Measured per-level cost in a debug build is ~6.1 KiB for the AST node
descent, ~1.0 KiB for the structured Field descent and ~65 B per JSON container
level, so the 1000-level ceiling is only ~1.4x safe on an 8 MiB stack and is
unsafe at 4 MiB, while raising max_ast_depth removes the bound outright.

On v26.8.11.7-lts a 1500-level nested AST JSON document at
max_ast_depth = 100000 terminated the process with SIGSEGV, zero output and no
stack trace, the overflow having prevented the fault handler from running.

Three distinct recursions are involved and none checked the stack:

  - createFromJSON(const Poco::JSON::Object &), the AST node descent;
  - readFieldFromObjectImpl, the structured Field descent, which adds no AST
    nodes and so is bounded only by its own limit;
  - Poco::JSON::Parser's own descent over the JSON text, which completes before
    a single AST node exists, so no check inside createFromJSON can observe it.
    A valid one-node Literal carrying an ignored 200000-level array member was
    enough to exit 139.

checkStackSize() is now called on each recursive entry, after that recursion's
existing bound check so that whenever a bound is the binding limit its own
message still wins. The check is unconditional because the stack, not a
setting, is the thing being bounded; gating it on the ceiling would leave the
default-settings 4 MiB crash reachable by construction.

DB::Exception derives from Poco::Exception, so the existing
catch (const Poco::Exception &) converted the handler's TOO_DEEP_RECURSION into
BAD_ARGUMENTS. A catch (const Exception &) { throw; } clause is ordered before
it. That was the failure mode which looks like a working guard.

Two stale comments are corrected: our Poco fork does enforce setDepth
(ParserImpl.cpp:145 in handleArray and :165 in handleObject both test
_currentDepth >= _depth, against a JSON_DEFAULT_DEPTH of 1000), so the claim
that the bracket pre-scan is the actual enforcement was wrong, and it was the
stated reason that pre-scan exists. One line records in its place what the
setDepth call does here, which the call alone does not show: it RAISES that
1000-level default to the pre-scan's budget, and that is what makes the deep
text descent reachable at all.

Rejected alternative: capping the ceiling with min(max_ast_depth, 1000). It
rejects input that works today (formatQueryFromJSON(parseQueryToJSON(...)) of a
600-nested-abs query, AST depth ~1204, returns 3016 bytes at
max_ast_depth = 200000 and is rejected at 1000), and it still would not bound
the stack: a depth-900 payload SIGSEGVs at default settings on a 4 MiB stack.

Deliberate consequence: accepted depth is now stack-bounded rather than
count-bounded. checkStackSize() permits 50% of the thread stack (5% under
TSAN), and the bisected trip depths sit at exactly that fraction of the
previous crash depth (711 against 1459 node levels, 4302 against 8565 Field
levels). In a debug build, node payloads deeper than ~690 are therefore
rejected where they previously succeeded up to 1000. Release frames are smaller
so that window sits deeper, which was not measured. A recursion bounded by the
stack cannot also promise a count.

Tests: three arms in 04056_ast_json_limits, one per guarded recursion, each
verified by its captured stack frames to trip the guard it names rather than a
neighbouring limit, and each exiting 139 on the unfixed binary. Every one of
those thresholds scales as 1 / per_level_frame_cost, which is a build property,
so the depths are placed with margin over the depth at which the UNFIXED binary
crashes (13.7x and 2.9x in a debug build) rather than over the guard's own trip
depth: that is what keeps the pre-fix failure reachable in a build whose frames
are cheaper. For the same reason the arms assert only that a controlled error
replaces the crash, never which of the three guards reports it. 04654 case 3
asserted which of two bounds rejects a payload; once the recursion is
stack-bounded that is a property of the build's stack budget (measured: the
Field bound's own message at 8 MiB, TOO_DEEP_RECURSION at a TSAN-parity 840 KiB
budget), so that arm now asserts the controlled rejection. It still fails on an
unrelated error.

Field::restoreFromDump is left alone: its dump parser is flat, so a nested dump
is rejected with CANNOT_RESTORE_FROM_FIELD_DUMP before it can recurse, measured
at depth 20000 for both Array_ and Tuple_ shapes.

Related: ClickHouse#120725

Co-Authored-By: Claude Opus 5 <[email protected]>
Delete the comment narrating the pre-scan/handler division of labour (the
surviving lines below it already state the budget's semantics), and reduce the
three property comments to one standalone line each. Drops the inaccurate claim
that setDepth "raises" Poco's default: the budget is a multiple of the effective
max_ast_depth, so it is lower than Poco's 1000 for max_ast_depth <= 125.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 blockers adjudicated, 1 upheld and fixed, 1 refuted; 4 nits)

An independent cold review plus a second-model gate ran over this diff twice, on the original tree and
on the fix round, before it was opened. Both raised the same concern about the new tests from different
angles; it is fixed. One blocker I raised myself was wrong, and I am recording the refutation rather
than dropping it.

Finding Verdict
❌ The two new depth arms in 04056_ast_json_limits.sql sat too close to the thresholds they probe: checkStackSize() trips at a fraction of the stack rather than at a depth, so every threshold scales with the build's frame size, and the Field arm sat only 1.17x above the depth at which the unfixed binary crashes in a debug build. AGREE, fixed in 5c0091fd7b2f5: arms re-centred to 20000 and 25000, with the margin measured over the depth at which the unfixed binary crashes (13.7x and 2.9x in debug) rather than over the guard's own trip depth, since that is the margin that keeps the pre-fix failure reachable where frames are cheaper. No arm asserts which of the three descents reports first, because all three raise the same code. The optimized-build window is reasoned from debug frame costs, not measured; CI's release and sanitizer legs are the check on it.
❌ Field::restoreFromDump is a fourth recursion in the same reader with no stack guard, bounded only by the same raisable max_ast_depth, so it looked like the identical defect left unfixed. DISAGREE, unreachable: every recursive branch extracts elements with a flat find_first_of scan that cannot span a balanced nested element and then fails if (!comma && tail != "]"), so Array_[Array_[UInt64_1]] is already rejected as CANNOT_RESTORE_FROM_FIELD_DUMP and the deepest achievable recursion is 2. Probed at depth 20000 with the bound opened: Code: 536, no crash. #121052 reaches the same conclusion independently, so src/Core/Field.cpp is untouched.
💡 The changelog category should be Critical Bug Fix, since the template lists crashes there. DISAGREE. That label is not self-selected; it is applied on a maintainer's explicit request. The three legs of Bug Fix hold: a released version (v26.8.11.7-lts) terminates, from a documented function and a documented setting.
💡 Two added comment lines claimed more than holds: the one above parser.setDepth(...) said the call raises Poco's 1000-level default, and the 04056 block says its depths sit past every bound in any build. AGREE on both. The first claim is no longer in the diff. Precisely: the call sets that bound to the pre-scan budget, which is eight times the effective depth limit, so it sits below Poco's default whenever max_ast_depth is under about 125, and it is never the binding limit either way, because the pre-scan compares the raw text against the same budget first. The second stands as noted, not blocking: the arm depths sit below every semantic bound on purpose, so that only a stack check can answer them, and past only the stack trip points.
💡 checkStackSize() is a no-op inside a stackful coroutine or fiber, so such a context would keep the overflow. Noted, not blocking: that gap belongs to the guard itself, which ClickHouse uses at every one of its call sites, and no such path reaches this function today.
💡 The accepted-depth narrowing at default settings, measured at node depth 800 and 999 in a debug build, and the 04654 case-3 assertion broadening. Both intended and disclosed. The case-3 arm still demands a controlled rejection; an unrelated error produces no output and reds the test.

One merge note: #121052 rewrites readFieldFromObjectImpl around the lines carrying the second guard
and rewrites case 4 of 04654, while this PR rewrites case 3 of the same file. Neither contains any
stack check, so they are not duplicates, but whichever lands second will need a textual resolution.

Session id: cron:clickhouse-review-self-slot-58:20260923-015200

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [368b7f6]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
order_by_read_in_order #1 FAIL dashboard IGNORED
set_index #0 unstable query history IGNORED

AI Review

Summary

This PR adds checkStackSize coverage to the three recursive phases of JSON AST deserialization: the raw Poco::JSON::Parser descent, AST-node reconstruction in IAST::createFromJSON, and structured Field reconstruction in readFieldFromObjectImpl. I checked the live diff, the surrounding parser/helpers, and the added regression tests, and I did not find a remaining reachable recursion path in formatQueryFromJSON or the clickhouse_json dialect that still bypasses the new guards.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 368b7f6.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 24/27 (88.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 23, 2026
@Algunenano Algunenano self-assigned this Sep 23, 2026
@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 23, 2026
Comment thread src/Parsers/ASTFromJSON.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 368b7f6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 2/6) CI harness, not this diff: the shard is red only on the confirmed regression(s) on the performance dashboard verdict, a gate that reds unrelated PRs with a regression which does not reproduce on a re-run of the same head (here: 3 too long, 1 unstable; 1 confirmed regression(s)) #121090 (mine, open), with #121189 (mine, open)

The single red is the dashboard verdict alone: the other five shards of this same run report
too long and unstable queries too and are GREEN, so query runtime is not the failing
criterion. 134 checks succeeded and 39 were skipped; Mergeable Check and PR are the
praktika aggregators reflecting the one red above, not separate failures.

Session id: cron:our-pr-ci-monitor:20260923-163416

@Algunenano
Algunenano added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 1b5bd56 Sep 23, 2026
174 of 177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 23, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 24, 2026
Cherry pick #121693 to 26.3: Guard the JSON AST deserialization recursions with checkStackSize
robot-clickhouse added a commit that referenced this pull request Sep 24, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Sep 24, 2026
Cherry pick #121693 to 26.7: Guard the JSON AST deserialization recursions with checkStackSize
robot-clickhouse added a commit that referenced this pull request Sep 24, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 24, 2026
Backport #121693 to 26.9: Guard the JSON AST deserialization recursions with checkStackSize
clickhouse-gh Bot added a commit that referenced this pull request Sep 24, 2026
Backport #121693 to 26.8: Guard the JSON AST deserialization recursions with checkStackSize
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.

5 participants