Skip to content

Fix stack overflow in the CapnProto schema compiler on long chains of declarations - #125900

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-capnproto-schema-compiler-recursion
Oct 15, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-capnproto-schema-compiler-recursion

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125782

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 (stack overflow) on a CapnProto schema with a long chain of type expression suffixes (Int32.a.a..., Int32()()...) or of declarations that refer to each other (constants, aliases, struct fields, annotations, imports). Such a schema is now rejected with The CapnProto schema is nested too deeply. Closes #125782.

Description

On 26.8.21.12, one DESC format(CapnProto, '') with a schema of 20000 chained constants, aliases, structs or .a suffixes crashes the process with SIGSEGV (stack overflow). Master crashes too: the bracket check from #115700 and #125487 does not see these chains.

That check bounds the bracket nesting of the schema text. The schema compiler recurses along other axes: once per .member or () suffix, once per link of a chain of declarations that refer to each other by name, and once per level of its dependency traversal.

contrib/capnproto now points to the fork's ClickHouse/v1.5.0 branch: upstream v1.5.0, whose lexer limits bracket nesting to 64 levels, plus the fork's patches and two new commits:

  • The parser rejects an expression with more than 64 .member or (...) suffixes before building its tree. That tree is torn down recursively in destructors, so no throwing check can stop it later.
  • Chains of declarations are only visible after name resolution, so the compiler bounds those: an opt-in hook runs at the top of BrandScope::compileDeclExpression and Compiler::Node::traverse, and its error passes through the compiler's catch sites. A depth counter cannot bound these chains: one level's stack cost differs about 10x across chain kinds and builds.

ClickHouse installs checkStackSize as the hook and reports both errors as The CapnProto schema is nested too deeply (CANNOT_PARSE_CAPN_PROTO_SCHEMA).

The new test has one deep case per path (member_chain, application_chain, nested_suffix_chains, alias_chain, const_chain, struct_chain_with_defaults, enum_annotation_chain) plus a short valid control. All deep cases fail on master and 26.8 and give Code 622 with the fix. On the final tree, a sweep of 21 chain shapes up to 50000 links, suffix chains of up to 1000000 links, and a 5000-file import chain shows no crash; the 16 upstream Cap'n Proto schemas give unchanged results.


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

Version info

  • Merged into: 26.10.1.2493-master (included in 26.10 and later)
  • Backported to: 26.9.20.20, 26.8.29.6, 26.7.32.6, 26.3.53.7

… declarations

`checkCapnProtoSchemaNestingDepth` bounds the bracket nesting of the schema
text, which drives the recursion of the Cap'n Proto lexer and parser. The
schema compiler recurses along a different axis: once per `.member` or `()`
suffix of a type expression, and once per link of a chain of declarations
that refer to each other by name (aliases, constants, annotations, struct
field types, superclasses, imports). Such a chain has no deep nesting, so a
`DESC format(CapnProto, '')` with a schema of 20000 chained declarations
crashed the process with SIGSEGV.

Bump `contrib/capnproto` to a fork commit that lets the embedder plug a stack
check into the compiler's recursion, install `checkStackSize` there, and
report the result as `The CapnProto schema is nested too deeply`
(CANNOT_PARSE_CAPN_PROTO_SCHEMA), the same error as the bracket check.

The parser also builds one level of its parse tree per `.member` or `()`
suffix, and that tree is torn down recursively (`OrphanBuilder::euthanize`
-> `WireHelpers::zeroObject`) when the parser is destroyed or a statement
fails to parse. That recursion runs in destructors, where no throwing check
can stop it, so 100000 suffixes still crashed after the compiler check had
fired. The text check therefore also tracks the depth of the expression tree
(`.` and closing brackets add a level, `,` `;` `}` end an expression) and
rejects more than DBMS_DEFAULT_MAX_PARSER_DEPTH levels with the same error.

Closes ClickHouse#125782

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 Gate B runs, 1 nit in total) plus my own review of each round; one fix round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The parse tree of a long .member / () chain is torn down by a recursive WireHelpers::zeroObject in destructors, which no throwing check can stop AGREE, fixed @ 762ff37 Measured: 100000 to 1000000 suffixes still gave SIGSEGV after the compiler check. The text check now bounds the expression depth; all of them now give Code 622
2 💡 Any exception from the hook is reported as "nested too deeply" AGREE, no change Documented in compiler.h; checkStackSize only throws for depth in practice
3 💡 The submodule commit is not fetchable yet AGREE, by design It becomes fetchable once the ClickHouse/capnproto PR is open; the gitlink is checked against refs/pull/3/head of ClickHouse/capnproto#3
4 💡 The same "nested too deeply" throw appears twice in checkCapnProtoSchemaNestingDepth AGREE, no change Two adjacent sites in one function
5 💡 Under TSan checkStackSize fires at 1/20 of the stack, not 1/2 AGREE, no change The in-tree CapnProto schemas compile only a few levels deep; the TSan lanes of this PR exercise it
6 💡 checkStack() is declared in the public compiler.h of the fork AGREE, no change Fork-only; no behaviour impact
7 💡 Over 1000 annotations on one declaration would count as one deep expression AGREE, no change Not a realistic schema; the 16 upstream schemas and all in-tree CapnProto tests are unaffected

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261014-221600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. DESC format(CapnProto, '') over a schema with 20000 chained constants, enum annotations, or a struct chain whose links are loaded by default values, or 100000+ .a / () suffixes (also with a parse error after the chain): rc 139 every run on master (debug) and 26.8.21.12.
b Root cause explained? Yes. The bracket check bounds the lexer/parser only. The compiler recurses once per suffix and once per link of a chain of declarations resolved by name (BrandScope::compileDeclExpression), and once per level of the dependency traversal (Compiler::Node::traverse). The parse tree of a suffix chain is also destroyed recursively (WireHelpers::zeroObject), in destructors.
c Fix matches root cause? Yes. Suffix chains are visible in the text, so the text check also bounds the parse-tree depth they produce, before the tree exists. Declaration chains are only visible after name resolution, so the compiler calls checkStackSize at its two recursive choke points (opt-in hook in the ClickHouse/capnproto fork). Both report the existing The CapnProto schema is nested too deeply.
d Test intent preserved / new tests added? Yes. New test 05397_capnproto_deep_schema_declaration_chains: one deep case per path (member, application and nested suffix chains, constants, struct defaults, enum annotations) plus a short valid control. Removing the text bound, its nesting rule, the hook install, either check, or the rethrow turns it red, each on exactly its cases.
e Both directions demonstrated? Yes. Every deep case fails on master and 26.8.21.12 (SIGSEGV, or an ordinary error for the nested suffix case) and gives Code 622 with the fix; the control output is unchanged.
f Fix is general across code paths? Yes. The text bound covers every suffix production (.member, application, brackets inside a chain) and the parse-error path; the compiler checks sit in the two functions every declaration chain recurses through; the one catch site inside the recursion rethrows.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 21 chain shapes x 14 sizes (10 to 50000), suffix chains up to 1000000 (also followed by a parse error), a 5000-file import chain, the 1000/1001-level boundary, file and string schema sources: no crash. No column type dimension applies.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. A schema is newly rejected only with a single expression deeper than 1000 levels, or when compiling it needs more than half the thread stack; the 16 upstream Cap'n Proto schemas and the existing CapnProto tests are unaffected. The fork hook is off by default.
i Invariants and contracts preserved? Yes. The text counter is local to the per-file scan and never pops its base level. The hook's exception is converted at the hook boundary, so only kj exceptions cross capnp frames, and the checks run before any state change.

Session id: cron:clickhouse-impl-slot-6:20261014-214900

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa69861]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 1/8) FAIL
test_modify_engine_on_restart/test.py::test_modify_engine_on_restart FAIL cidb IGNORED

AI Review

Summary

This PR rebases the embedded capnproto compiler onto the updated fork, installs the new compiler stack-check hook in CapnProtoSchemaParser::getMessageSchema, and adds regression coverage for the long declaration and suffix chains that previously ended in SIGSEGV. The updated upstream catch-site handling, the new chain-focused stateless test, and the existing import-depth coverage leave me without a remaining correctness or evidence gap that warrants blocking this change.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR. labels Oct 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @vitlibar, could you review this and add can be tested? I cannot set labels at the moment. Long flat CapnProto schemas (.a / () suffix chains, chains of constants, aliases or structs) overflow the stack in the Cap'n Proto parser and compiler: the text check now also bounds the depth of suffix chains, and the compiler calls checkStackSize through a new hook in ClickHouse/capnproto#3.

@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Oct 14, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@Algunenano Algunenano self-assigned this Oct 15, 2026
@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 15, 2026
groeneai and others added 2 commits October 15, 2026 10:03
A chain of 20000 `using A{i} = A{i+1}` aliases resolved from a field type
SIGSEGVs on master and on 26.8/26.9 release images (crashes from between
2000 and 5000 links there) and gives Code 622 with the fix. Each hop goes
through `Alias::compile` -> `compileDecl` -> `compileDeclExpression`, so the
existing check covers it; the case pins the changelog's alias claim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…parser

`contrib/capnproto` now points to `ClickHouse/v1.5.0`: upstream v1.5.0 with
the internals patch, the `std::nullptr_t` fix and the stack check hook. Its
parser rejects an expression with more than 64 `.member` or `(...)` suffixes
before building the tree, so the text check no longer tracks them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Oct 15, 2026
@Algunenano

Copy link
Copy Markdown
Member

I've updated the Capnproto contrib to v1.5.0 and added the commit there, plus bringing the needed changes we already had and an extra fix to simplify our own code checks (control the recursion in the contrib instead of externally ourselves)

The msan flaky check failed with "Test runs too long (> 180s)": 05397 took
196-203s per run there (140s on 762ff37). Now that the parser rejects more
than 64 suffixes, the 200000-suffix chains only add lexing time, and the
declaration chains were about 6-35 times longer than needed.

The CI binaries of ac2531f reject the chains at these lengths:
amd_binary alias 1412, const 575, enum annotation 614, struct with
defaults 3478 (tsan and debug at or below that), suffixes at 65. The new
lengths (suffixes 20000, declaration chains 5000, struct chain 12000) still
give Code 622 on amd_binary, msan, tsan and debug, and still SIGSEGV on
master and 26.8.18.2. One uncontended msan run: 37.2s -> 16.9s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fa69861

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
Integration tests (amd_tsan, 1/8) / test_modify_engine_on_restart/test.py::test_modify_engine_on_restart not from this PR (it only changes the Cap'n Proto schema checks): a TSan data race between the background statistics refresh (MergeTreeData::refreshStatistics reads the part path) and restoreMetadataInZooKeeper moving parts to detached after the conversion restart. The sanitizer halt leaves count() at 0. The same test fails the same way on master today (768cf08, e0d2931) #125927 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125927 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261015-150015

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 15, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #125900 to 26.8: Fix stack overflow in the CapnProto schema compiler on long chains of declarations
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #125900 to 26.9: Fix stack overflow in the CapnProto schema compiler on long chains of declarations
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #125900 to 26.7: Fix stack overflow in the CapnProto schema compiler on long chains of declarations
Algunenano added a commit that referenced this pull request Oct 16, 2026
Backport #125900 to 26.3: Fix stack overflow in the CapnProto schema compiler on long chains of declarations
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 21, 2026
…to schema compiler on long chains of declarations
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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). manual approve Manual approve required to run CI 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 submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CapnProto schema with long .member or () suffix chain crashes with SIGSEGV

5 participants