Skip to content

Fix stack overflow in Avro header parsing on a deep chain of named types - #124053

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:avro-iterative-min-encoded-bytes-walk
Oct 6, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:avro-iterative-min-encoded-bytes-walk

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123998
Related: #121211
Related: ClickHouse/avro#41

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

On master since #121211, reading an Avro file whose schema chains 100000 named records A_k { x: A_(k-1) } crashes with a stack overflow (SIGSEGV) while the header is parsed, on any codec and with any optimize_count_from_files. No release is affected: 26.9's contrib/avro predates the code involved.

readHeader runs MinEncodedBytesWalker (ClickHouse/avro#34 and ClickHouse/avro#36) on every Avro read to bound the declared object count. It recursed through every record field and union branch. Each A_k is defined inside an array field, which the walk does not descend, so neither its memo nor its cycle cut stops a last field ["null", "A_n"] from walking the whole chain on the thread stack.

ClickHouse/avro#41 makes the walk iterative, with its own stack on the heap, the same visit order, memo and cycle cut, so the bound is unchanged for every schema. A depth limit would instead reject files that read fine today. This PR bumps contrib/avro to it.

Other surfaces: GenericDatum is bounded by ClickHouse/avro#39 and building the AvroDeserializer checks the stack per level. Schema inference (DESC without a structure) also recurses through such a chain; that is pre-existing and not changed here.

Validation: 05325_avro_deep_named_type_chain generates such a file, reaching A_n through a required field, with a block that declares more records than its payload can hold. The previous pin crashes (exit 139) while parsing its header; this one rejects the block, which a walk that stopped at named types would accept. A temporary build computing both the recursive and the iterative bound on every read found no difference over 428 generated schemas (DAGs, cycles, unions, every codec) and the Avro and Iceberg stateless tests.


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

Version info

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

…out recursion

Since ClickHouse#121211, `readHeader` in contrib/avro runs `MinEncodedBytesWalker` on every Avro read to
bound the declared object count. It recursed through every record field and union branch,
following named references, so a schema chaining 100000 named records, each defined inside an
array field, overflowed the thread stack while the header was parsed. ClickHouse/avro now walks
the schema with its own stack on the heap, in the same order and with the same memo and cycle
cut, so the bound does not change for any schema.

The test generates such a file and reads it with an explicit structure. The test also checks that
the chain still bounds a block's declared object count.

Reported in ClickHouse#123998.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 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, 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test only checked count() on a file reaching A_n through ["null", "A_n"], so a walk that stops at named types would also pass AGREE, fixed in this PR a second file reaches A_n through a required field and must be rejected with cannot fit in; it fails when the walk returns 0 after resolving a name
2 💡 Description over-stated the deserializer's stack check AGREE, fixed the check runs while the deserializer is built
3 💡 Bare #36 would link to the wrong repository AGREE, fixed written as ClickHouse/avro#36
4 💡 The second file is read with optimize_count_from_files 1 and 0, but on the null codec both take the same path noted, not changed harmless

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-11:20261005-152600

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The reporter's generator (n = 100000), then SELECT count() FROM file('deep.avro', Avro, 'id Int64'): SIGSEGV (exit 139) on every run with the previous contrib/avro pin.
b Root cause explained? readHeader runs MinEncodedBytesWalker on every read, which recursed through every record field and union branch. Each named record is defined inside an array, which the walk does not descend, so nothing is memoised before the last field walks the whole chain: two frames per level, past the 8 MB stack.
c Fix matches root cause? Yes. The walk keeps its own stack on the heap; no depth cap, no guard, no rejected input.
d Test intent preserved / new tests added? New 05325_avro_deep_named_type_chain (the files are generated, nothing binary in the repo). It reads the reporter's file, and a second file whose last field is the chain itself, declaring 2 records in 2 * (n + 1) bytes: only a walk that reaches the bottom of the chain (bound n + 2) rejects it, for optimize_count_from_files 1 and 0. 04947_avro_count_from_files_forward_progress, which pins the bound's behaviour, is unchanged and passes.
e Both directions demonstrated? Yes. The test fails (walker SIGSEGV) with the previous pin and passes with the new one; 50/50 randomized runs pass. A temporary mutation that makes the walk return 0 at every named reference also fails it (the bound check prints 0 instead of 1).
f Fix is general across code paths? The walk has one caller, readHeader, which every DataFileReaderBase reaches (file/url/s3/hdfs/azure Avro, Iceberg manifests). GenericDatum is bounded by ClickHouse/avro#39; AvroDeserializer checks the stack per level. Schema inference is a separate, pre-existing recursion and is not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Chains of 2000, 100000, 300000 and 1000000 levels, closed by a union or a direct field, null/snappy/deflate, optimize_count_from_files 0 and 1. Type wrappers do not apply: the walk runs over the Avro schema before any ClickHouse type exists.
h Backward compatible? (maintainer-approved exception only) Yes. A temporary build computing both walks found the same bound on 854 reads of 428 generated schemas and in the Avro and Iceberg stateless tests. No setting, format or API change.
i Invariants and contracts preserved? The walk still returns a lower bound, memoises by resolved node, cuts a cycle at 0 without memoising it, treats a failed symbol resolution as 0, and computes a union as 1 + its cheapest branch and a record as the sum of its fields. No reference into the frame stack is used after a push.

Session id: cron:clickhouse-impl-slot-4:20261005-125421

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Oct 5, 2026
@groeneai
groeneai requested a review from PedroTadim October 5, 2026 15:57
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d5432a1]

Summary: ✅


AI Review

Summary

This PR bumps contrib/avro to the upstream rewrite that replaces the recursive MinEncodedBytesWalker traversal with an explicit heap-backed stack, and adds a stateless regression test for the deep named-type-chain reproducer plus the lower-bound check that would catch a walk stopping early at named references. I did not find an unresolved correctness, safety, or contract issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit d5432a1.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage).

Newly covered: +204 lines in 62 files (-139 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog submodule changed At least one submodule changed in this PR. labels Oct 5, 2026
@PedroTadim PedroTadim self-assigned this Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d5432a1ab with master 939fed7e1 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

# A chain of named records A_k { x: A_(k-1) }. Each one is defined inside its own array field, so the
# schema nests only a few levels deep, while the last field ["null", A_n] reaches the whole chain.
python3 -c "
import json, sys

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 just trim the test, it's taking too long

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 4a044dc: one generated file and one read instead of two files and three reads (each read of the 100000-record schema took about 70 s under the flaky check's ThreadFuzzer); it still crashes the previous pin and still checks the bound.

The flaky check runs with ThreadFuzzer, which migrates the thread on every mutex operation, so one
read of the 100000-record schema took about 70 seconds there, and the test read it three times,
over the 180 second limit. With the null codec `count()` takes the same header path whatever
`optimize_count_from_files` is, and the file declaring too many records already needs the walk to
cover the whole chain without recursion, so the test now generates and reads only that file.

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

Copy link
Copy Markdown
Member

@groeneai I just merged ClickHouse/avro#41, bump the submodule

ClickHouse/avro#41 was merged as d8ff6d9c9fe4 on the avro master branch.
Its tree is identical to the previously pinned PR head fcc115b5c42e, so
the compiled code does not change; the pin now points at a commit on the
avro master branch instead of the fork branch.

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

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Done in d5432a1: contrib/avro now points at d8ff6d9c9fe4, the merge commit of ClickHouse/avro#41 on the avro master branch. Its tree is identical to the previous pin fcc115b5c42e, so only the gitlink changes.

@PedroTadim
PedroTadim enabled auto-merge October 6, 2026 11:15
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 58c1c26 Oct 6, 2026
149 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 6, 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-issue PR origin: picked up an external GitHub issue manual approve Manual approve required to run CI pr-not-for-changelog This PR should not be mentioned in the changelog 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.

Avro header parsing stack-overflows on deep chain of named record types

3 participants