Skip to content

Fix crash on a recursive Avro schema in an Iceberg manifest list during writes - #123084

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-recursive-manifest-list-schema
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-recursive-manifest-list-schema

Conversation

@groeneai

@groeneai groeneai commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123044
Related: #122829
Related: ClickHouse/avro#39
Related: ClickHouse/avro#36
Related: #121211

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Description

On 26.8.10.6 and 26.9.1.1629, an INSERT into an Iceberg table (allow_insert_into_iceberg = 1) whose current snapshot's manifest list has a recursive Avro schema, such as A{b: B{a: A}}, or A{next: ["null", "A"]} with deeply nested data, crashes with a stack overflow (SIGSEGV): Iceberg::forEachAvroEntry carries the list forward through avro-cpp's GenericDatum, which is built and read recursively.

The fix is ClickHouse/avro#39, which makes GenericDatum construction and GenericReader::read throw beyond 256 nesting levels. It is on master through the contrib/avro bump in #121211 (the same commit this PR used to pin), so this PR now only adds the regression test.

Test. 05296_iceberg_recursive_manifest_list_writer replaces a cached manifest list with a required cycle, which fails building the datum, and with a nullable cycle nested 1,000,000 levels deep, which fails reading it, and checks the AVRO_EXCEPTION depth error of each. With the previous contrib/avro pin both cases crash clickhouse-local (exit 139).

🤖 Generated with Claude Code


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

…reader

An INSERT (or ALTER DROP PARTITION, OPTIMIZE, mutation) into an Iceberg table carries the
parent snapshot's manifest list forward through `Iceberg::forEachAvroEntry`, which builds an
`avro::GenericDatum` from the file's own writer schema. avro-cpp constructs and reads
`GenericDatum` recursively without any depth limit, so a manifest list whose schema contains a
named record that reaches itself killed the process with a stack overflow (SIGSEGV):

- a required cycle, `A{b: B{a: A}}`, recursed forever in the `GenericRecord` constructor;
- a nullable cycle, `A{next: ["null", "A"]}`, constructed fine but recursed once per nesting
  level of the data in `GenericReader::read`.

The read path already rejects such a schema: `AvroForIcebergDeserializer` calls
`AvroSchemaReader::avroNodeToDataType`, whose `seen_names` check throws "Recursive Avro schema
is not supported". The carry-forward re-reads the raw file and never went through it. That is
reachable when the reader's result for the same path comes from the metadata files cache (the
file was replaced after it was cached), or when a commit conflict makes the retry carry forward
another writer's snapshot.

Run the same `avroNodeToDataType` on the schema before building the `GenericDatum`, and rethrow
its error as `ICEBERG_SPECIFICATION_VIOLATION` with the file name, like the root-type check
next to it. The writer now accepts exactly the manifest-list schemas the reader accepts. Both
faces are rejected on the schema, before any data is read.

Closes ClickHouse#123044

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 30, 2026
@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; 1 finding) and my own review (1 finding). Nothing blocking.

# Sev Finding Verdict Evidence / action
1 💡 A crash fix belongs under Critical Bug Fix (PR template) DISAGREE Kept Bug Fix: the crash reproduces on 26.8.10.6 and 26.9.1.1629 behind the Beta allow_insert_into_iceberg. Critical is a maintainer's call; happy to relabel.
2 💡 The new catch rewraps every error of the schema check, e.g. a memory-limit error, as ICEBERG_SPECIFICATION_VIOLATION (Utils.cpp:1835) AGREE, not changed Same convention as the read path, which rewraps every error of the same call as INCORRECT_DATA (AvroForIcebergDeserializer.cpp:62-65).

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

Session id: cron:clickhouse-review-slot-10:20260930-141900

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b9e8ef]

Summary: ✅


AI Review

Summary

This PR now reduces to a focused stateless regression test for the two avro-cpp depth-guard paths that used to stack-overflow on Iceberg manifest-list carry-forward. I still see one unresolved correctness gap in the underlying writer path: forEachAvroEntry only fails recursive schemas when avro::GenericDatum construction or reader.read actually walk into the cycle, so some recursive manifest-list schemas still pass and get carried forward. That means the new test's broad "recursive Avro schema" contract is still stronger than what the current code enforces.

Findings
  • ⚠️ Majors
    • [src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp:1839] forEachAvroEntry still accepts recursive manifest-list schemas when the cycle sits in an ignored nullable field and the data stays on the null branch. avro::GenericDatum initializes that union to branch 0, reader.read never descends into the recursive arm, and IcebergWrites then copies only the required fields into a fresh non-recursive record. The write therefore succeeds even though AvroForIcebergDeserializer / AvroSchemaReader still reject the same schema up front as recursive. That leaves the writer/read-path contract divergent, and the new regression does not cover that remaining class of recursive schemas.
    • Suggested fix: restore a schema-level recursive-schema check before constructing avro::GenericDatum, or narrow the test / PR contract to the two depth-guarded cases that are actually covered.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either make the writer reject recursive manifest-list schemas at schema-validation time as well, or explicitly narrow the claimed contract so the PR no longer says a recursive manifest-list schema must fail in general.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 30, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 60e27e3c7 with master 7cbb8ad28 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 796d29517; 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

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

Job report

try
{
/// avro-cpp builds and reads `GenericDatum` recursively without a depth limit, so a recursive schema must not reach it.
AvroSchemaReader::avroNodeToDataType(reader.readerSchema().root());

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 it seems the fix should go to ClickHouse's Avro fork. Is this a regression of something I merged there?

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.

No, it is not a regression from the fork. The unbounded recursion is upstream avro-cpp code that the fork never modified: GenericRecord's constructor builds a GenericDatum per field, and GenericReader::read recurses once per nesting level (the last change to GenericDatum.cc/Generic.cc is from 2019, and apache/avro main is the same). The official 26.8.10.6 and 26.9.1.1629 images crash on the same repro, and both pin contrib/avro at 7b7f6a5bc42e, which is older than ClickHouse/avro#33, ClickHouse/avro#34 and ClickHouse/avro#37. ClickHouse/avro#31 bounds only the textual nesting of the schema, and a self-referencing named type passes it. The minEncodedBytes walk from ClickHouse/avro#34 (not in master's pin yet) is capped at 64, so it adds no new path.

Agreed on the location. I'll bound the nesting depth of GenericDatum construction and GenericReader::read in ClickHouse/avro (throwing avro::Exception), then bump contrib/avro here and drop the Utils.cpp check.

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: ClickHouse/avro#39 makes GenericDatum construction and GenericReader::read throw avro::Exception beyond 256 nesting levels, and 395ebf9 bumps contrib/avro to it and drops the Utils.cpp check. The fork branch is based on the current pin, so the bump carries nothing else. Without it the required cycle and the nullable, array and map cycles nested 1,000,000 levels deep all crash; with it all four fail with AVRO_EXCEPTION. 05296 now also covers the deep case.

Per review, bound the recursion where it happens: the `contrib/avro` bump makes
`GenericDatum` construction and `GenericReader::read` throw beyond 256 nesting
levels, so `forEachAvroEntry` no longer needs to predict avro-cpp's recursion
by running `AvroSchemaReader::avroNodeToDataType` on the schema first.

The bump is based on the current pin, so it carries no other fork change.

The test now also covers a nullable recursive row nested 1,000,000 levels
deep, which overflowed the stack in `GenericReader::read`.
@clickhouse-gh clickhouse-gh Bot added manual approve Manual approve required to run CI submodule changed At least one submodule changed in this PR. labels Oct 1, 2026
…OLATION

With the depth bound in contrib/avro, a recursive or too deeply nested
manifest list failed the Iceberg write with a bare `AVRO_EXCEPTION`
("Cannot build a datum nested deeper than 256 levels") that did not name the
file. Wrap avro errors raised while reading the manifest list with the file
name and the Iceberg error code, as the root-type check next to it already
does and as the reader path (`AvroForIcebergDeserializer`) does for the same
files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Oct 1, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I just merged ClickHouse/avro#39 can you bump the avro submodule in this PR?

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

I did not bump it yet. Moving the pin to avro master (1d1ad4b) also brings in ClickHouse/avro#34, and without ClickHouse/avro#36 its minEncodedBytes walk (run while the file header is read, before ClickHouse gets to reject the recursive schema) does not finish on a recursive record with two self-references.

Measured with SELECT * FROM file('rec2.avro', 'Avro') on a 227-byte file, one row, schema {"type":"record","name":"A","fields":[{"name":"f0","type":["null","A"]},{"name":"f1","type":["null","A"]}]}:

contrib/avro result
6640c55 (master pin) CANNOT_EXTRACT_TABLE_STRUCTURE in 0.5 s
1d1ad4b (avro master) still running when killed after 120 s; the stack is in minEncodedBytes, depth 56 to 64
1d1ad4b + #36 merged locally CANNOT_EXTRACT_TABLE_STRUCTURE in 0.3 s; the #34 check still rejects a block declaring 1,000,000 records in 10 bytes

The current pin 7802524 is the #39 commit and is already on avro master, so this PR can stay as it is. If you'd rather pin avro master here, I'll bump it once #36 is in. #121211 pins d90416a, which has the same walk, so it needs #36 as well.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I Just merged ClickHouse/avro#36 in the avro repo, do the bump please

Moves the pin from the ClickHouse/avro#39 commit to the current master
(merge of ClickHouse/avro#36). Besides ClickHouse#39 (already pinned), this brings in
ClickHouse#34 (bound the declared object count by a schema-derived minimum record
size), ClickHouse#36 (memoise that walk, so it terminates on recursive schemas) and
ClickHouse#37 (test fix).

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

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 8b07686: contrib/avro now points at a56fc2f (avro master, including ClickHouse/avro#36). On that build, the recursive files that hung with 1d1ad4b (two and three self-references) fail in about 0.2 s, the ClickHouse/avro#34 count check still rejects a block that declares 1,000,000 records in 10 bytes, and 05296 passes 20/20. The local Avro/Iceberg stateless tests fail only where they need CI fixtures (MinIO, s3_conn).

while (reader.read(datum))
callback(datum);
}
catch (const avro::Exception & e)

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 only rejects recursion when GenericDatum construction or reader.read actually walks into the cycle. That leaves a real gap versus the current read path: a manifest-list schema that keeps the required Iceberg fields but adds an extra nullable recursive field (for example ['null', 'Self'] with all rows on the null branch) will pass here, because GenericUnion initializes branch 0 only and the carry-forward code ignores extra fields. The write then succeeds and rewrites a snapshot that AvroSchemaReader::avroNodeToDataType still rejects up front as a recursive schema.

Can we keep a schema-level recursive-schema check before building the generic reader (or otherwise align the reader path), so every recursive manifest-list schema fails deterministically with ICEBERG_SPECIFICATION_VIOLATION?

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8b07686

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
AST fuzzer (amd_msan) / MemorySanitizer: use-of-uninitialized-value (STID: 3520-4a97) sanitizer report in code this PR does not change (it touches only the Iceberg writer and contrib/avro). ColumnsDescription::tryGetColumn (ColumnsDescription.cpp:877) dereferences columns.end() for a subcolumn whose storage column no longer exists, reached through StorageMerge -> StorageSnapshot::tryGetColumn. The same frame and origin (ColumnsDescription copy) hit an unrelated PR's BuzzHouse (amd_msan) on 2026-09-27 #122527 (mine, open): ColumnsDescription::rename drops and re-adds the subcolumns, so no stale entry is left after RENAME COLUMN
Mergeable Check, PR rollups, red only because of the row above #122527 (mine, open), the same owner as the row above

All 146 check runs completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261003-050056

while (reader.read(datum))
callback(datum);
}
catch (const avro::Exception & e)

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 we don't need the try catch? Just let throw the avro exception

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.

Right, removed in 60e27e3: forEachAvroEntry is back to its master version, so the error is now AVRO_EXCEPTION ("Cannot build/read a datum nested deeper than 256 levels"), and 05296 expects that.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai maybe I messed up in ClickHouse/avro#39. Is it difficult to add checkStackSize(); checks in that repo?

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Not difficult, but it cannot be a direct call: _avrocpp links only boost and snappy (contrib/avro-cmake/CMakeLists.txt) and does not see src/Common. The clean form is a hook in the fork, e.g. avro::setStackCheck(void (*)()), called next to the two depth checks from ClickHouse/avro#39 (GenericDatum::init, GenericReader::read) and set to DB::checkStackSize by ClickHouse. That is about 20 lines there and 3 here, and the error becomes TOO_DEEP_RECURSION.

I don't think ClickHouse/avro#39 was a mistake, though:

  • The only place ClickHouse reads an untrusted file into a GenericDatum is forEachAvroEntry (the Iceberg manifest list, whose spec schema is a few levels deep), so the 256 cap cannot reject a valid file.
  • The Avro input format and the Iceberg manifest-file reader use ClickHouse's own AvroDeserializer, which already calls checkStackSize (createDeserializeFn, createSkipFn, createAction in AvroRowInputFormat.cpp).
  • 256 is the same value as MAX_AVRO_SCHEMA_DEPTH, which already bounds the schema of that same reader.

I'd keep it as is. If you prefer the hook, I'll open it in ClickHouse/avro and bump it here.

Drop the function-try-block that rethrew avro::Exception as
ICEBERG_SPECIFICATION_VIOLATION, as requested in review: the error from
the ClickHouse/avro depth bound is now reported as AVRO_EXCEPTION
("Cannot build/read a datum nested deeper than 256 levels").
forEachAvroEntry is back to its master version, and 05296 expects
AVRO_EXCEPTION for the two recursive cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# A manifest list with a recursive Avro schema must be rejected by an INSERT into an Iceberg table, not crash.
# `clickhouse local` contains the pre-fix fatal signal to a short-lived subprocess.

CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

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 trim the test and merge with master, the bump is no longer needed?

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.

Yes, the bump is no longer needed: #121211 moved master's contrib/avro to the same a56fc2f, so after merging master (06b76e9) the PR diff is only the test. Trimmed it in 5b9e8ef to the two cases that crashed (required cycle, and a nullable cycle nested 1,000,000 levels), each checking its own AVRO_EXCEPTION depth error. Since the fix itself is already on master, I changed the category to CI Fix or Improvement.

groeneai and others added 2 commits October 5, 2026 09:54
Keep only the recursive record (fails building the datum) and the
1,000,000-level nullable cycle (fails reading it), and assert which of
the two ClickHouse/avro#39 depth checks fires, with its error code.
Drop the controls and the server liveness probe; the test uses only
`clickhouse local`.

The contrib/avro bump is no longer part of this PR: master already
pins the same commit since ClickHouse#121211.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 5, 2026
@PedroTadim

Copy link
Copy Markdown
Member

We no longer need this PR.

@PedroTadim PedroTadim closed this Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 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-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg writer SIGSEGV on recursive manifest-list schema in forEachAvroEntry

2 participants