Skip to content

Bound the recursion in several parsers and schema readers - #115700

Merged
alexey-milovidov merged 4 commits into
masterfrom
fix-stack-overflow-nested-input
Aug 22, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
fix-stack-overflow-nested-input

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Several places recurse over data or over text that comes from the query or from a file, without
bounding the recursion, so a deeply nested input exhausts the thread stack and takes the whole
server down instead of failing the query:

  • readWKB and friends: Multi* geometries contain nested geometries, and the existing limit on
    the number of elements does not bound the nesting, because every level can hold a single element.
  • JSONMergePatch: parsing is iterative, but copying, merging and serializing the documents recurse
    over the tree.
  • parseRemoteDescription (url, remote, cluster, mysql, postgresql, ...): nested braces
    are expanded recursively, and max_addresses bounds the number of generated addresses, not the
    nesting depth.
  • The CURSOR clause parser of STREAM: the helper recurses directly instead of going through
    IParserBase::parse, so max_parser_depth was not in effect.
  • The CapnProto schema parser: the vendored parser is a recursive-descent one without a depth limit
    of its own, and it runs on a schema that can be passed inline with format_schema_source='string'.
  • The Iceberg schema walk, as defence in depth next to the limit of the JSON parser.

In addition, ParserExecute dereferenced the result of a cast to ASTLiteral without checking it,
so an EXECUTE statement with a non-literal argument dereferenced a null pointer.

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):

Fix server crashes on deeply nested input in readWKB, JSONMergePatch, the address parser of the url/remote/cluster/mysql/postgresql table functions, the CURSOR clause parser and the CapnProto schema parser. Fix a crash in the parser of the EXECUTE statement when an argument is not a literal.


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

Version info

  • Merged into: 26.8.1.1928 (included in 26.8 and later)
  • Backported to: 26.7.6.36, 26.6.4.46, 26.3.26.2

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6883c59]

Summary: ✅


AI Review

Summary

This PR adds stack-depth guards to several user-controlled recursive paths (readWKB, JSONMergePatch, remote address expansion, STREAM CURSOR, Iceberg schema walking, and CapnProto schema parsing/import walking) and fixes the null dereference on non-literal EXECUTE arguments. Most of the hardening looks correct, and the prior CapnProto import-graph hole is fixed, but the CapnProto change still leaves a reachable stack-exhaustion path in normal FORMAT CapnProto input/output.

Findings

❌ Blockers

  • [src/Formats/CapnProtoSchema.cpp:160] The new CapnProto pre-scan only covers schema parsing. CapnProtoRowInputFormat and CapnProtoRowOutputFormat still construct CapnProtoSerializer immediately afterwards, and CapnProtoSerializer::createSerializer recursively descends through nested LIST / STRUCT / Nullable / Map types without any checkStackSize() (src/Formats/CapnProtoSerializer.cpp:848, 933, 1042, 1200, 1365, 1415). A deeply nested schema can therefore still exhaust the stack on actual INSERT / SELECT FORMAT CapnProto, even though DESC format() now fails cleanly. Suggested fix: add the same guard to serializer construction and recursive row read/write paths, and cover it with a regression that instantiates real CapnProto format I/O.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 98/109 (89.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 21, 2026
…no-fasttest`

`clang-tidy` requires `const auto *` for the RapidJSON array iterator, the
style check requires a `-WithMemoryTracking` container in `src/Functions`,
and `JSONMergePatch` is not available in the fast test build, which is built
without RapidJSON.
Comment thread src/Formats/CapnProtoSchema.cpp Resolved
… regressions

The CapnProto nesting check was applied only to the entry schema file, but
`parseFromDirectory` parses the files it `import`s with the same recursive
parser, so a shallow wrapper schema could still smuggle a deeply nested one
in and exhaust the thread stack. Walk the import graph and check every file.

Add the regression tests the review asked for: `EXECUTE` with an argument
that is not a literal over the PostgreSQL wire protocol, and a deeply nested
`CURSOR` clause of `STREAM`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review:

  • Blocker (src/Formats/CapnProtoSchema.cpp): confirmed reproducible — a shallow entry schema that imports a deeply nested one segfaulted the server. checkCapnProtoSchemaNestingDepth now walks the whole import graph (resolving imports the way Cap'n Proto does: absolute against the schema directory, relative against the importing file), with a visited set on the canonical path so import cycles terminate.
  • Added 05036_postgresql_execute_non_literal_argument.sh: EXECUTE p(1 + 1) over the PostgreSQL wire protocol now returns a clean syntax error and the server survives.
  • Added 05035_stream_cursor_deep_nesting.sql: a deeply nested STREAM CURSOR clause now trips TOO_DEEP_RECURSION, proving the pos.increaseDepth / pos.decreaseDepth wiring is in effect.

Also fixed the clang-tidy and style-check failures in jsonMergePatch and tagged 05028_json_merge_patch_deep_nesting as no-fasttest (the fast test build has no RapidJSON).


capnp::StructSchema CapnProtoSchemaParser::getMessageSchema(const FormatSchemaInfo & schema_info)
{
checkCapnProtoSchemaNestingDepth(schema_info.schemaDirectory(), schema_info.schemaPath());

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.

This still leaves a stack-exhaustion path open for actual FORMAT CapnProto use. getMessageSchema() now rejects the entry file and its imports, but both CapnProtoRowInputFormat and CapnProtoRowOutputFormat immediately build a CapnProtoSerializer afterwards, and that code keeps recursing through nested LIST / STRUCT / Nullable / Map types without any checkStackSize() (src/Formats/CapnProtoSerializer.cpp:848, 933, 1042, 1200, 1365, 1415). A deeply nested List(List(...)) schema therefore still reaches unbounded recursion as soon as someone actually does INSERT / SELECT FORMAT CapnProto, even though DESC format() is safe now. This needs the same depth guard on the serializer-construction / recursive row I/O path, and the regression should instantiate real CapnProto input/output rather than only schema inference.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6883c59a1 with master ecc01ef26 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.35 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

10 object files changed (+62.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/CapnProtoSchema.cpp.o 180.07 KiB 206.73 KiB +26.67 KiB (+14.81%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/jsonMergePatch.cpp.o 436.73 KiB 455.23 KiB +18.50 KiB (+4.24%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

13 translation units recompiled, 29 s compile time in total, 13 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

robot-ch-test-poll4 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #115700 to 25.8: Bound the recursion in several parsers and schema readers
robot-clickhouse added a commit that referenced this pull request Aug 25, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #115700 to 26.3: Bound the recursion in several parsers and schema readers
robot-clickhouse added a commit that referenced this pull request Aug 25, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #115700 to 26.5: Bound the recursion in several parsers and schema readers
robot-clickhouse added a commit that referenced this pull request Aug 25, 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 Aug 25, 2026
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
…oint`

On 26.5, `parseWKBFormat` does not support the `MultiPoint` geometry (WKB type 4),
so the type-4 query fails with `BAD_ARGUMENTS` before any recursion happens.
Drop that line and keep the `MultiLineString`/`MultiPolygon` (types 5/6) checks,
which exercise the backported `checkStackSize` guard and return `TOO_DEEP_RECURSION`.

Same adaptation as the sibling backports of #115700.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116320&sha=latest&name_0=BackportPR
PR: #116320

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #115700 to 26.5: Bound the recursion in several parsers and schema readers
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #115700 to 25.8: Bound the recursion in several parsers and schema readers
alexey-milovidov added a commit that referenced this pull request Aug 29, 2026
Backport #115700 to 26.3: Bound the recursion in several parsers and schema readers
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #115700 to 26.6: Bound the recursion in several parsers and schema readers
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #115700 to 26.7: Bound the recursion in several parsers and schema readers
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants