Repository navigation
Guard the JSON AST deserialization recursions with checkStackSize - #121693
Conversation
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]>
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
One merge note: #121052 rewrites Session id: cron:clickhouse-review-self-slot-58:20260923-015200 |
|
Workflow [PR], commit [368b7f6] Summary: ❌
AI ReviewSummaryThis PR adds Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 368b7f6.
Changed lines: Changed C/C++ lines covered: 24/27 (88.89%) · Uncovered code |
CI finish ledger - 368b7f6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The single red is the dashboard verdict alone: the other five shards of this same run report Session id: cron:our-pr-ci-monitor:20260923-163416 |
1b5bd56
Cherry pick #121693 to 26.3: Guard the JSON AST deserialization recursions with checkStackSize
…ns with checkStackSize
Cherry pick #121693 to 26.7: Guard the JSON AST deserialization recursions with checkStackSize
…ns with checkStackSize
Backport #121693 to 26.9: Guard the JSON AST deserialization recursions with checkStackSize
Backport #121693 to 26.8: Guard the JSON AST deserialization recursions with checkStackSize
…n recursions with checkStackSize
…n recursions with checkStackSize
Related: #120725
Changelog category (leave one):
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, theclickhouse_jsondialect): a deeply nested document exhausted the stack and killed the process with no log line. Such payloads now fail withTOO_DEEP_RECURSION.Description
On
v26.8.11.7-lts,SELECT formatQueryFromJSON(<1500-level nested AST JSON>) SETTINGS max_ast_depth = 100000terminates 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 insidecreateFromJSONcan 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::Exceptionderives fromPoco::Exception, so acatch (const Exception &) { throw; }clause is ordered before the existing handler, otherwise the guard surfaces asBAD_ARGUMENTS.Validated in both directions on a debug build: every shape that terminated the process now reports
TOO_DEEP_RECURSION, and the 64-testast_json/from_jsonsuite 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
26.10.1.550-master(included in26.10and later)26.9.2.26,26.8.11.35