Skip to content

Cherry pick #121693 to 26.3: Guard the JSON AST deserialization recursions with checkStackSize - #121851

Merged
robot-ch-test-poll2 merged 4 commits into
backport/26.3/121693from
cherrypick/26.3/121693
Sep 24, 2026
Merged

robot-ch-test-poll2 merged 4 commits into
backport/26.3/121693from
cherrypick/26.3/121693

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #121693

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 3 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: #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]>
Guard the JSON AST deserialization recursions with checkStackSize
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Sep 23, 2026
@groeneai

groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Not applicable to 26.3: the code #121693 patches does not exist on this branch

The cherry-pick is dirty for a structural reason rather than a content one. git merge-tree cherrypick/26.3/121693 backport/26.3/121693 reports five conflicts and all five are modify/delete, because every path the patch touches is absent from the base:

  • src/Parsers/ASTFromJSON.cpp, src/Parsers/ASTJSONReadHelpers.cpp
  • tests/queries/0_stateless/04056_ast_json_limits.sql
  • tests/queries/0_stateless/04654_ast_json_depth_guard_max_ast_depth_zero.sh and .reference

The JSON-to-AST deserialization path that #121693 guards is not on 26.3 at all. On both origin/26.3 and this PR's base, git grep -l createFromJSON and git grep -l JSONObjectReader over src/ return nothing and there is no src/Parsers/*JSON* file, and 749fbd04f8b4 (the commit that added src/Parsers/ASTFromJSON.cpp) is not an ancestor of 26.3 (merge-base --is-ancestor rc=1) while it is an ancestor of both 26.8 and 26.9. That check is against the release branches: this PR's base is itself a -s ours merge of master, so the commit is reachable from the base while those five files stay absent from its tree. The first release that carries the deserializer is 26.8, so there is no recursion to guard and nothing user-reachable to fix here.

I think this PR should be closed as not applicable, together with the sibling for the other branch in the same position; I have not closed either myself. #121853 (26.8) and #121854 (26.9) do apply. Both fail to build on a missing Common/checkStackSize.h include that a non-backported prerequisite had added on master, and I have posted the one-line resolution on each.

…rypick/26.3/121693

# Conflicts:
#	src/Parsers/ASTFromJSON.cpp
#	src/Parsers/ASTJSONReadHelpers.cpp
#	tests/queries/0_stateless/04056_ast_json_limits.sql
#	tests/queries/0_stateless/04654_ast_json_depth_guard_max_ast_depth_zero.reference
#	tests/queries/0_stateless/04654_ast_json_depth_guard_max_ast_depth_zero.sh
@robot-ch-test-poll2
robot-ch-test-poll2 merged commit d9e471d into backport/26.3/121693 Sep 24, 2026
1 check passed
@robot-ch-test-poll2
robot-ch-test-poll2 deleted the cherrypick/26.3/121693 branch September 24, 2026 09:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants