Skip to content

Write Iceberg data files in the inserting thread - #129168

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-multiple-file-writer-format-threads
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-multiple-file-writer-format-threads

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127670

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

TSan reported a data race in La Casa Del Dolor (amd_tsan) (report): MultipleFileWriter::consume reads buffer->count() between the blocks to compare it with iceberg_insert_max_bytes_in_data_file, while the ParallelFormattingOutputFormat collector thread writes the same data file buffer. The format was created with getOutputFormatParallelIfPossible, so an Iceberg INSERT in any row format with parallel formatting (RowBinary, CSV, TSV, JSONEachRow, ...) hit it. The count also lags by an unknown number of blocks, so the files ran past the limit. The Pretty formats render the blocks in a thread of their own after the input pauses (output_format_pretty_squash_consecutive_ms), so the limit did not cut their files. Both exist since #127670, which compares the limit with buffer->count(), and are not in a release.

The data file format is now created with getOutputFormat, as the Iceberg compaction and mutation writers already do, with pretty.squash_consecutive_ms = 0, so every write into the buffer happens in the inserting thread before the next size check. Parquet, ORC and Avro do not support parallel formatting and take the same path as before. #127864 (Parquet parallel encoding) is independent; ORC and Vortex buffer inside the format, which is #128558.

Validation: new test 05444_iceberg_insert_file_size_format_threads (RowBinary and PrettyCompact arms). Without the fix, the TSan server aborts with the CI stack, and a debug build writes files of up to twice the limit and a single PrettyCompact file (10/10). With the fix: 50/50 randomized runs on debug, 20/20 on TSan with no report; each of the two lines is needed by its own arm.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits November 4, 2026 02:18
`MultipleFileWriter::consume` compares `buffer->count()` with
`iceberg_insert_max_bytes_in_data_file` between the blocks. The data file
format was created with `getOutputFormatParallelIfPossible`, so for a row
format with parallel formatting the `ParallelFormattingOutputFormat`
collector thread wrote the same buffer concurrently: a data race reported by
TSan (La Casa Del Dolor, amd_tsan), and a size check that sees a count
lagging by an unknown number of blocks.

Create the format with `getOutputFormat` (the other Iceberg writers,
compaction and mutations, already do), and disable the squashing thread of
the Pretty formats, which also writes the buffer from its own thread and
defers the writes so that the size limit is not applied. Parquet, ORC and
Avro take the same path as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`iceberg_insert_max_bytes_in_data_file` is checked between the blocks
against the size of the data file written so far. Two formats wrote the
file from threads of their own: a row format with parallel formatting
(`RowBinary`; on the unfixed tree TSan reports the race and the files run
past the limit by up to two times), and a Pretty format with squashing
(`PrettyCompact`; on the unfixed tree the whole INSERT lands in one file).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the comment on the in-thread output format of Iceberg data files to one line.

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

groeneai commented Nov 4, 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 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ❌ *MonoBlock Pretty formats still buffer the whole file, so the limit does not cut them (MultipleFileWriter.cpp:82-92) DISAGREE No thread is involved: PrettyBlockOutputFormat::write creates the writer thread only without mono_block, and a MonoBlock format renders on the inserting thread in writeSuffix. One table for the whole output is the definition of the format, the same "not written yet" class as ORC and Vortex (#128558). No change.
2 ⚠️ The test does not deterministically prove the absence of parallel formatting, and the Pretty arm does not assert the file count DISAGREE Without the factory switch the TSan server aborts with the CI stack on every run, and a debug build writes files of up to 2000 rows (10/10). Without the squash line the PrettyCompact arm writes one 420062-byte file on every run; a single file under 200000 bytes would need the format to drop more than half of its 20000 rows.

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

Session id: cron:clickhouse-review-slot-8:20261104-033400

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the unfixed TSan build the RowBinary arm aborts with the CI stack every run (6/6: 5 clickhouse local, 1 server); the PrettyCompact arm writes one file of 420062 bytes at a 100000-byte limit every run (15/15). On an unfixed debug server the RowBinary layout is also wrong 10/10 (files of up to 2000 rows instead of 1000).
b Root cause explained? startNewFile used getOutputFormatParallelIfPossible, so for a row format the ParallelFormattingOutputFormat collector thread writes the data file buffer while consume reads buffer->count() on the pipeline thread (since #127670): a race and a lagging count. A non-mono Pretty format only queues the blocks and renders them from its squashing thread after the input pauses, so the count never grows during the INSERT.
c Fix matches root cause? Yes. The writer that reads the file size between the blocks no longer hands the buffer to another thread: getOutputFormat plus pretty.squash_consecutive_ms = 0, as the Iceberg compaction and mutation writers already do. No guard, no widened bound.
d Test intent preserved / new tests added? New test 05444_iceberg_insert_file_size_format_threads with a RowBinary arm (exact file layout) and a PrettyCompact arm (file size); no existing test changed.
e Both directions demonstrated? Yes, Build-ID verified. Unfixed: TSan abort with the CI stack; debug 10/10 FAIL on both arms. Fixed: 50/50 randomized on debug, 20/20 on TSan with no sanitizer report. Each line is necessary: without the squash line only the Pretty arm is red, without the factory switch only the RowBinary arm is red.
f Fix is general across code paths? Yes. finalize/cancel read the count only after the format joined its threads; compaction and mutations were already serial; StorageObjectStorageSink and DeltaLake read the size only after finalize; Parquet encoders and Vortex write the buffer on the calling thread. Only MultipleFileWriter reads the size between blocks among the getOutputFormatParallelIfPossible callers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All parallel-formatting formats take the same factory branch, all non-mono Pretty variants read the same squash setting; column types do not matter (the shared object is the buffer); partitioned INSERTs use the same writer per partition. *MonoBlock formats buffer by definition and are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Parquet, ORC and Avro files are written exactly as before; row-format files are formatted serially; Pretty files are rendered per block.
i Invariants and contracts preserved? Yes. Restores the single-writer contract of WriteBuffer (a parallel format owns its buffer until finalize). The finalize/cancel order is unchanged and no lock is added.

Session id: cron:clickhouse-impl-slot-4:20261104-024000

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @hanfei1991, could you review this and add the can be tested label so CI runs? It fixes the La Casa Del Dolor TSan data race where MultipleFileWriter::consume read buffer->count() while the parallel formatting collector thread wrote the same buffer: Iceberg data files are now formatted in the inserting thread (getOutputFormat, no Pretty squash thread), so the size check is race-free and the file size limit cuts files again.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bf7e375]


AI Review

Summary

Reviewed PR #129168 at bf7e375dfa269eae7b9f87c0f4df814ff330397a. The change keeps Iceberg data-file formatting on the inserting thread so MultipleFileWriter::consume can safely read the buffer size, with focused RowBinary and PrettyCompact regression coverage. No actionable correctness or safety defects found.

Missing context / blind spots
  • ⚠️ Targeted stateless and TSan CI results are pending. This checkout has no built ClickHouse binary, so the author's reported debug and TSan runs were not independently repeated. Completed targeted jobs would confirm runtime validation.
  • ⚠️ Serializing row-format Iceberg writes has an unmeasured throughput cost, already raised in the existing review thread. A focused before/after insert benchmark would quantify it. The factory change preserves the existing execution paths for Parquet, ORC, and Avro.
Final Verdict

Status: ✅ Approve. No new inline findings; normal CI validation remains pending.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. can be tested Allows running workflows for external contributors labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bf7e375df with master 014fdaa27 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8d750d945; 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, 11 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai why the changelog category is not for changelog?

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Because neither problem is in a release. Both come from #127670, which made MultipleFileWriter::consume compare the limit with buffer->count(). It was merged on 2026-10-24, after the 26.10 branch cut (2026-10-15), and has no backport: 26.10 and v26.10.2.103-stable do not contain b81b4ba6, and consume there still adds chunk.bytes() on the inserting thread (26.10, L87-L94). So this fixes a master-only regression; if 26.11 is cut before it merges, the category should become Bug Fix.

@PedroTadim PedroTadim self-assigned this Nov 4, 2026
@PedroTadim
PedroTadim enabled auto-merge November 4, 2026 12:10
/// the column mapper, so it covers the compaction/mutation rewrite paths too.
FormatFilterInfoPtr format_filter_info = std::make_shared<FormatFilterInfo>(nullptr, context, column_mapper, nullptr, nullptr);
output_format = FormatFactory::instance().getOutputFormatParallelIfPossible(
output_format = FormatFactory::instance().getOutputFormat(

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 are you sure this wont create a performance regression elsewhere?

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.

Not for every format, so I measured it.

Scope: only MultipleFileWriter, i.e. Iceberg INSERT on any object storage. Iceberg compaction and mutations already use getOutputFormat. Parquet, ORC and Avro (the Iceberg data file formats) do not support parallel formatting, so getOutputFormatParallelIfPossible already returned getOutputFormat for them (FormatFactory.cpp:856, :874): no change there. squash_consecutive_ms only affects Pretty*.

Row formats (CSV, TSV, JSONEachRow, RowBinary, ...) lose the formatting threads. Release builds, INSERT INTO <IcebergLocal table> SELECT number, toString(number * 7919), number / 3, toDateTime(number) FROM numbers_mt(N), seconds, master / this PR, median of 3:

Shape Parquet CSV JSONEachRow RowBinary
max_insert_threads = 1, 20M rows 2.54 / 2.58 0.99 / 2.33 1.16 / 3.41 0.90 / 1.34
defaults, 384 cores, 100M rows 2.15 / 2.13 1.09 / 2.02 1.38 / 2.45 0.83 / 1.23
16 cores (taskset), max_threads = max_insert_threads = 16, 50M rows 1.55 / 1.49 1.15 / 0.93 1.46 / 1.42 0.67 / 0.64

So row formats get up to 2.9x slower when there are fewer insert threads than cores, and are not slower when the insert threads already use the cores. Master with output_format_parallel_formatting = 0 gives the same numbers as this PR, so the difference is only the formatting threads.

I'd keep it as is: the parallel path is the TSan race and data files over iceberg_insert_max_bytes_in_data_file (up to 2x in the test), and these formats are not data file formats in the Iceberg spec. Keeping the threads would need a thread-safe byte counter in ParallelFormattingOutputFormat, and the size check would still lag by the blocks being formatted. Tell me if you prefer that.

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 I just realized, the row formats (CSV, TSV, JSONEachRow, RowBinary, ...) should be disallowed as Iceberg formats?

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, I think so, for writes. Measured on master (26.11.1.1316):

  • The Iceberg spec allows only avro, orc and parquet as the file_format of a data file, and ClickHouse writes the format name into the manifest as is (IcebergWrites.cpp:617). PyIceberg 0.11.1 reads the Parquet table and fails on the others: ValueError: 'CSV' is not a valid FileFormat (same for RowBinary, JSONEachRow, Native).
  • ClickHouse reads CSV, TSV and RowBinary tables back only if the reader passes the same format; with the default format it fails (INCORRECT_DATA, CANNOT_PARSE_INPUT_ASSERTION_FAILED, CANNOT_READ_ALL_DATA). PrettyCompact and Markdown tables cannot be read back at all (FORMAT_IS_NOT_SUITABLE_FOR_INPUT).
  • The docs say writes support the formats of the Iceberg spec, and Support other formats (ORC, ...) in iceberg writes #87277 opened writes for ORC and Avro, not for row formats.

The check would allow Parquet, ORC, Avro and Vortex (written into Iceberg on purpose, e.g. 05339_vortex_iceberg_mixed_write_format). All four write the data file on the inserting thread, so with the check the race and the row-format size limit overshoot fixed here are no longer reachable. The only other test that writes a row format is test_writes_create_table_bugs (CSV, 0 rows).

So either:

  1. I replace this PR with the check (a behaviour change for the Beta allow_insert_into_iceberg), or
  2. this PR stays as is and I send the check as a separate PR.

Which do you prefer?

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.

I prefer to go with 1. Also look for the other data lake formats: delta lake, paimon and hudi

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.

OK, I'll replace the change in this PR with the format check. I measured the other lakes on master (26.11.1.1316):

  • Hudi and Paimon have no write path in ClickHouse (INSERT fails with Writes are not supported for engine. (NOT_IMPLEMENTED)). Nothing to check there.
  • Delta Lake has the same gap as Iceberg. The Delta protocol allows only Parquet data files, but a DeltaLakeLocal(path, CSV) table (same for RowBinary, JSONEachRow, PrettyCompact, ORC, Avro) accepts the INSERT, commits a .csv data file to _delta_log, and reading the table back then fails with Not a Parquet file (wrong magic bytes at the end of file).

So the check will allow Parquet, ORC, Avro and Vortex for Iceberg writes and only Parquet for Delta Lake writes, and reject the rest on write. Reading and DESCRIBE of tables declared with another format stay as they are. I'll post here when the PR is updated.

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.

@PedroTadim correction to my plan above: the check you asked for already exists in my #105667, added there after your report (#105667 (comment)). At its head 2a7fd2e8 it rejects any other format with BAD_ARGUMENTS for a new table or a table function, per engine: Iceberg Parquet, ORC, Avro, Vortex; DeltaLake Parquet; Paimon Parquet, ORC, Avro; Hudi Parquet, ORC (test 05037_datalake_unsupported_format_rejected). That rejects the fuzzer's INSERT INTO TABLE FUNCTION icebergLocal(..., format = 'RowBinaryWithNamesAndTypes'). A write-time check here would be a second copy of that list, so I have not written it.

The only path #105667 leaves open is a table attached from a definition stored before the upgrade (ATTACH is exempt there): it can still INSERT in a row format and hit this race.

Which do you prefer?

  1. I close this PR and rely on Reject compression_method argument for data lake engines #105667.
  2. I keep this PR as it is (the version you approved), which also covers those attached tables.

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.

Let's go with 1

@PedroTadim
PedroTadim disabled auto-merge November 4, 2026 12:55
@PedroTadim
PedroTadim enabled auto-merge November 4, 2026 12:56
@PedroTadim
PedroTadim disabled auto-merge November 4, 2026 12:56
@PedroTadim PedroTadim closed this Nov 4, 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... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants