Skip to content

Fix stack overflow in Avro schema inference on a deep chain of named types - #124644

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:avro-schema-inference-depth-limit
Oct 9, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:avro-schema-inference-depth-limit

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123998
Related: #124053

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 an Avro schema with a long chain of named type references, in schema inference (DESC, or SELECT without an explicit structure, for Avro and AvroConfluent), in reads into a Variant column and in Iceberg manifest reading. Such a schema now fails with an error instead.

Description

On 26.8.18.2, DESC file('deep.avro', Avro) over a valid 12 MB file whose schema chains 100000 named records (A_k { x: A_(k-1) }, each defined in its own array field) crashes the server with a stack overflow. It is the input of #123998, whose header-parsing half was fixed in contrib/avro by #124053; this is the schema-inference half, in src/.

AvroSchemaReader::avroNodeToDataTypeImpl follows named type references, so its recursion depth is the length of the reference chain, which contrib's MAX_AVRO_SCHEMA_DEPTH does not bound. The per-level checkStackSize() added by #102417 stayed in the non-recursive wrapper when #102853 split the recursion out, so it runs once per column. 26.3 is not affected; 26.4 to 26.9 and master are.

avroNodeToDataTypeImpl now calls checkStackSize() on every level, as on 26.3, so all three callers (schema inference, the Variant read path, the Iceberg manifest reader) get TOO_DEEP_RECURSION instead of a stack overflow.

Validation (debug build): the 100000-chain file goes from SIGSEGV after 35 s and 13 GB RSS to an error caused by TOO_DEEP_RECURSION after 10 s and 3.3 GB. Inference builds every field's type before the deepest one throws, so its cost grows with the stack size (15 GiB peak RSS on official 26.3 with an 8 MiB stack). The test therefore runs a 10000-record chain under ulimit -s 1024: master crashes there (debug and official 26.8.18.2), the fix throws in 0.4 s; a 40-record chain still infers. It fails on master and passes with the fix (30/30 runs).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1889-master (included in 26.10 and later)

groeneai and others added 2 commits October 8, 2026 09:08
`AvroSchemaReader::avroNodeToDataTypeImpl` follows named type references,
so its recursion depth is the length of the reference chain, not the JSON
nesting that contrib/avro bounds with `MAX_AVRO_SCHEMA_DEPTH`. A valid file
whose schema chains 100000 named records, each defined in its own array
field, made `DESC file(..., Avro)` recurse ~200000 frames and overflow the
stack (SIGSEGV on 26.8.18.2 server and on master, after ~35 s and 13 GB).

The per-level `checkStackSize()` added by ClickHouse#102417 ended up in the
non-recursive wrapper `avroNodeToDataType` when ClickHouse#102853 split the
recursion into `avroNodeToDataTypeImpl`, so it ran once per root column.

Count the recursion depth against `max_parser_depth` (0 = unlimited) and
throw `TOO_DEEP_RECURSION`, as ClickHouse#107341 does for MsgPack, BSON, ORC, Parquet
and JSON schema inference, and keep `checkStackSize()` per level as a
backstop for a raised or unlimited limit. The limit is passed by all three
callers (schema inference, the Variant read path and the Iceberg manifest
reader), and `max_parser_depth` is added to the Avro/AvroConfluent schema
cache key, so a schema inferred under a higher limit is not served to a
query with a lower one (same as a839800 did for ORC).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An explicit Variant column converts every union branch with
avroNodeToDataType before matching it, so the depth limit passed there
is reachable without schema inference. Add a file whose union has a deep
named-record branch and read it as 'last Variant(Int64)': with the limit
the read fails with TOO_DEEP_RECURSION, without it the branch is
converted unbounded and the read fails with ILLEGAL_COLUMN instead.

Co-Authored-By: Claude Opus 5.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 Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

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 rounds, 6 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ Iceberg manifest cache (keyed by table UUID + path) serves a manifest parsed under a higher max_parser_depth to a query with a lower one DISAGREE A cache hit runs no recursion, and the served object is a correct parse of an immutable file: no crash, no wrong result. The cache already ignores every format setting. For Iceberg the PR only claims "no crash".
2 ⚠️ Iceberg rewraps TOO_DEEP_RECURSION as INCORRECT_DATA AGREE, changelog narrowed The changelog promises the depth error for schema inference only; the existing Iceberg wrap keeps the reason in the message.
3 ⚠️ No test reaches the explicit Variant read call site AGREE, fixed @ f97aca9 New case: last Variant(Int64) over a union with a 2001-level branch; a mutation passing 0 there makes it fail.
4 ⚠️ No test pins the per-level stack check or the Iceberg call site DISAGREE Stack check: deleting it makes the max_parser_depth = 0 run on the 100000-chain file crash, and a deterministic test would need a multi-GB input. Iceberg: would need a hand-written table and manifest for a one-argument call site.
5 💡 Use Critical Bug Fix DISAGREE That category is left to senior maintainers. Bug Fix fits: 26.8.18.2 crashes on this input.
6 ⚠️ Schema inference reports CANNOT_EXTRACT_TABLE_STRUCTURE outside, not TOO_DEEP_RECURSION AGREE, changelog narrowed Schema inference wraps every reader error this way, for all formats. The changelog now says the schema is rejected with an error naming max_parser_depth.
7 ⚠️ The cache-key case would pass if caching silently declined DISAGREE Dropping the setting from the cache key makes the case fail, so the cache is in use. clickhouse-local in the test gets no randomized settings, and the file's mtime is back-dated.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261008-134456

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. DESC file('deep.avro', Avro) on a 100000-link chain of named records (generator of #123998) SIGSEGVs on every run of the unmodified master debug build (35 s, 13 GB RSS, avroNodeToDataTypeImpl frames).
b Root cause explained? Yes. avroNodeToDataTypeImpl follows named type references, so its depth is the reference-chain length, which MAX_AVRO_SCHEMA_DEPTH does not bound; the per-level checkStackSize() from #102417 ended up in the non-recursive wrapper after #102853 split the recursion.
c Fix matches root cause? Yes. The depth bound and the stack check are in the recursion itself, counting every recursive call.
d Test intent preserved / new tests added? Yes. New 05339_avro_schema_inference_deep_named_type_chain: default limit, lowered limit, a chain within the limit, an explicit Variant read, schema cache key. Existing Avro tests pass.
e Both directions demonstrated? Yes. Same file: SIGSEGV on master, TOO_DEEP_RECURSION in 1.1 s with the fix. The new test fails on master and passes with the fix (50/50 runs). Deleting the depth check, the stack check, the cache-key field, or the Variant read path's limit each makes its case fail.
f Fix is general across code paths? Yes. All three callers pass the limit: schema inference (Avro, AvroConfluent), the Variant read path, the Iceberg manifest reader. The deserializer builders already check the stack per level.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All 8 recursive calls (array, union, symbolic, record, map key and value) count. max_parser_depth = 0 stays unlimited with the stack check as backstop; a limit equal to the depth passes, one below fails.
h Backward compatible? (maintainer-approved exception only) Yes. No default changes. Only schemas nested deeper than max_parser_depth (default 1000) with references expanded now fail, and the setting raises the limit, as for the other formats since #107341.
i Invariants and contracts preserved? Yes. seen_names insert/erase pairing is unchanged (the check throws before the insert); depth is passed by value; return types unchanged.

Session id: cron:clickhouse-impl-self-slot-57:20261008-130545

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [71feabe]

Summary: ✅


AI Review

Summary

This PR fixes the real stack-overflow root cause by moving checkStackSize() into AvroSchemaReader::avroNodeToDataTypeImpl, so every recursive expansion of deep named-type chains now hits the guard instead of only the top-level wrapper. I reviewed the current diff, the affected callers (schema inference, the Variant branch-typing path, and Iceberg manifest typing), and the prior discussion, and I did not find any remaining correctness or safety issues in the final version.

Missing context / blind spots
  • ⚠️ The new tests/queries/0_stateless/05339_avro_schema_inference_deep_named_type_chain.sh coverage is tagged no-fasttest, and the slower CI jobs that would exercise it are still pending, so I could only validate that path statically here.
Final Verdict

✅ No new inline findings. From a code-review perspective this looks good to merge once the pending non-fast CI jobs finish.

LLVM Coverage Report

Measured on commit 71feabe.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.70% 79.80% +0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 8, 2026
@groeneai
groeneai requested review from Avogar and PedroTadim October 8, 2026 14:19
const avro::NodePtr & node, std::unordered_set<std::string> & seen_names, bool allow_nullable_tuple_type, size_t max_depth, size_t depth)
{
/// Named type references are followed, so the depth is not bounded by the nesting of the schema JSON.
if (max_depth != 0 && depth > max_depth)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai why can't you use the checkStackSize() function?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It does: this PR calls checkStackSize() on every level of avroNodeToDataTypeImpl (right below this check), and that alone fixes the crash. On master it runs only once, in the non-recursive wrapper avroNodeToDataType (26.3 still has it per level).

The max_parser_depth counter on top follows #107341 (the same counter plus a checkStackSize() backstop in MsgPack, BSON and Parquet schema inference). checkStackSize() throws only after half of the thread's stack is used (1/20 under TSan), so how deep a schema gets, and what it costs before the error, depends on the build and the thread's stack size. Measured with the 100000-level file from #123998, DESC file(..., Avro):

Binary Error Time Peak RSS
official 26.3.42.3 (per-level checkStackSize(), no counter) Stack size too large 8.8-10.8 s 15.3 GiB
this PR, debug, max_parser_depth = 0 (stack check only) Stack size too large 7.6 s 2.6 GiB
this PR, debug, default nested deeper than the limit (1000) 1.0 s 0.56 GiB

For reference, 26.3 reads the same file with an explicit structure in 1.1 s / 2.1 GiB. The counter also lets the test use a 40-level file with max_parser_depth = 50 instead of this one.

If you still prefer only checkStackSize(), I'll drop the counter and its plumbing (the max_depth parameter at the three call sites and the schema cache key).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yes, I prefer checkStackSize()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 71feabe: avroNodeToDataTypeImpl now calls checkStackSize() on every level, and the counter, the max_depth parameter and the cache key change are gone.

The test runs the deep chain under ulimit -s 1024: inference builds every field's type before the deepest one throws, so its cost grows with the stack size (15 GiB peak RSS on official 26.3 with an 8 MiB stack, 1.3 GiB with 1 MiB). With 1 MiB, master still crashes on a 10000-record chain (debug and official 26.8.18.2), and the fix throws in 0.4 s.

@PedroTadim PedroTadim self-assigned this Oct 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Oct 8, 2026
Per review, drop the max_parser_depth counter and its plumbing (the
max_depth parameter at the three callers and the schema cache key).
avroNodeToDataTypeImpl now calls checkStackSize() on every level instead
of once in the non-recursive wrapper, which is what fixes the crash.

The test now runs the deep case under a 1 MiB stack: inference builds
every field's type before the deepest one throws, so its cost grows with
the stack size (official 26.3, which has the same per-level check: 15 GiB
peak RSS with an 8 MiB stack, 1.3 GiB with 1 MiB). With 1 MiB the
unfixed build still crashes on a 10000-record chain (debug and official
26.8.18.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim enabled auto-merge October 8, 2026 17:25
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 9, 2026
Merged via the queue into ClickHouse:master with commit b66c851 Oct 9, 2026
152 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #124644 to 26.9: Fix stack overflow in Avro schema inference on a deep chain of named types
PedroTadim added a commit that referenced this pull request Nov 2, 2026
Backport #124644 to 26.8: Fix stack overflow in Avro schema inference on a deep chain of named types
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants