Skip to content

Support specifying or auto-assigning Parquet field_ids for output columns - #101783

Closed
Onyx2406 wants to merge 149 commits into
ClickHouse:masterfrom
Onyx2406:feat/parquet-column-field-id
Closed

Onyx2406 wants to merge 149 commits into
ClickHouse:masterfrom
Onyx2406:feat/parquet-column-field-id

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds the setting output_format_parquet_auto_assign_field_ids : Bool, default false, to write Parquet files with column field_id metadata. Apache Iceberg identifies columns by field_id rather than by name.

When enabled, every output column and every nested field (Array element, Map key/value, Tuple subfields) gets a unique sequential field_id starting at 1, in schema DFS order, matching the convention used by Iceberg writers.

SET output_format_parquet_auto_assign_field_ids = 1;

INSERT INTO FUNCTION file('iceberg.parquet')
SELECT 1 AS a, 'x' AS b, 42 AS c;
-- a -> 1, b -> 2, c -> 3

When writing to a data lake table that provides its own field ids (e.g. Iceberg), the setting is ignored: the table metadata is the source of truth. Geo columns written as WKB under GeoParquet get a single top-level field_id. A top-level column whose dotted name collides with a nested path of another column (e.g. a.b and a Tuple(b ...)) is rejected with BAD_ARGUMENTS.

An earlier version of this PR also had an explicit per-column override setting (output_format_parquet_column_field_ids); it was removed after review.

Test

tests/queries/0_stateless/04321_parquet_column_field_ids.sh writes Parquet files with clickhouse-local, reads the field_id metadata back with pyarrow, and covers flat and nested types, geo columns, the default (no field_ids), an Iceberg table (its own ids are kept), and the dotted-path collision error.

Closes: #58753

Changelog category (leave one):

  • New Feature

Changelog entry:

Added the setting output_format_parquet_auto_assign_field_ids to auto-assign sequential Parquet field_ids to every output column and nested field, matching the Apache Iceberg writer convention.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Onyx2406 added 3 commits April 4, 2026 18:39
Add `output_format_parquet_column_field_ids` setting to specify Parquet
field IDs per column (e.g., 'col_a: 10, col_b: 20'). This is needed
for Apache Iceberg compatibility.

Fixes ClickHouse#58753
…ring

- Restore accidentally deleted `query_plan_optimize_join_order_randomize`
  entry in the 26.4 block of `SettingsChangesHistory.cpp`
- Rename test 04069 to 04077 to avoid collision with
  `04069_index_type_with_settings`
- Update Parquet file prefixes inside the test SQL from `04076_` to
  `04077_` to match the new test number
- Change "non-negative integers" to "integers" in the
  `output_format_parquet_column_field_ids` description since Parquet
  uses signed int32 for field_id
Comment thread src/Core/FormatFactorySettings.h Resolved
@alexey-milovidov alexey-milovidov self-assigned this Apr 5, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

.

@alexey-milovidov

Copy link
Copy Markdown
Member

Shouldn't it be possible to assign field ids automatically? How does Iceberg do it?

NOTE: the code for this change is folded into the preceding merge commit
`d66467fbf65` because it touched conflict-resolution lines in
`FormatSettings.h`. This empty commit is a marker that describes the
intent; the actual diff lives in that merge commit.

Rework per alexey's review (ClickHouse#101783):

1. `output_format_parquet_column_field_ids` is now `Map(String, Int32)`
   instead of a `String` mini-language (`'a: 1, b: 2'`). Users configure it
   as structured data, matching how `http_response_headers` and
   `additional_table_filters` are defined.
2. New `output_format_parquet_auto_assign_field_ids` (`Bool`, default
   `false`). When on, every output column gets a sequential Parquet
   `field_id` starting at 1 (Iceberg writer convention). Any column
   present in `output_format_parquet_column_field_ids` keeps its
   overridden id; auto-assignment fills the remaining columns and skips
   ids already taken by overrides.
3. The parquet output format validates overrides against the actual
   output header: unknown columns, duplicate ids, and non-covering
   overrides (when auto-assign is off) all error with BAD_ARGUMENTS.
4. Test (`04080_parquet_column_field_ids.sql`) rewritten for the new
   JSON map syntax and extended to cover auto-assign, mixed
   override+auto-assign, and the new error paths.
@Onyx2406 Onyx2406 changed the title Support specifying field_id for columns when writing Parquet files Support specifying or auto-assigning Parquet field_ids for output columns Apr 18, 2026
alexey-milovidov and others added 5 commits May 12, 2026 02:07
…-field-id

# Conflicts:
#	src/Formats/FormatFactory.cpp
#	src/Formats/FormatSettings.h
#	src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp
The PR was originally written against `26.4`, but master has since
opened a `26.5` block. New settings introduced by an unmerged PR
belong to the current development version, so move
`output_format_parquet_column_field_ids` and
`output_format_parquet_auto_assign_field_ids` accordingly. Also wrap
literal names in inline code in the descriptions for consistency.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The old Arrow-based Parquet writer was removed in master (commit
80f3bb8, `Remove old Parquet writer and reader implementations`),
so `output_format_parquet_use_custom_encoder` is now obsolete and the
two writer paths the test exercised have merged into one. Drop the
duplicated arrow-encoder test case and tighten the comment; the
remaining cases still cover overrides, auto-assign, mixed mode, the
no-setting default, and the three error conditions.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`output_format_parquet_column_field_ids` is declared as a `Map` and
included by every storage engine that pulls in
`LIST_OF_ALL_FORMAT_SETTINGS`. Each engine forwards its setting types
through its own `_SETTINGS_SUPPORTED_TYPES` list, so without adding
`Map` to that list the `KafkaSettings##TYPE` (and equivalent)
helper-name expansion fails to compile with `unknown type name
'KafkaSettingsMap'`. Add `Map` to all nine such engines
(`Kafka`, `Hive`, `Set`, `RabbitMQ`, `FileLog`, `StorageObjectStorage`,
`ObjectStorageQueue`, `NATS`, `DataLakeStorage`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… setting

`SettingFieldMap` always stores `Map(String, String)`, so the value
field always arrives as a `String` and never as `Int64`/`UInt64`. The
original parser dispatched on `Int64`/`UInt64` and rejected everything
else, which made every well-formed `SET output_format_parquet_column_field_ids = ...`
throw `BAD_ARGUMENTS: values must be integers`.

Parse the string value with `tryParse<Int64>` instead, and keep the
existing range check that rejects negatives and values above
`Int32::max`. Tighten the test to use the canonical `Map(String, String)`
literal syntax (`{'a': '10', ...}`) instead of JSON inside a string,
add a case covering a non-integer value, and update the setting's
docstring example to match.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [526ea22]

Summary: ✅


AI Review

Summary

Adds optional recursive field_id assignment to Parquet output while preserving data lake metadata mappings. Request changes: the advertised Apache Iceberg numbering convention does not match the generated IDs for nested schemas.

Findings

⚠️ Majors

  • src/Core/FormatFactorySettings.h:2010: For a Array(Int64), b Int64, standalone output assigns a=1, a.element=2, b=3, whereas Apache Iceberg assigns sibling IDs first: a=1, b=2, a.element=3. Standalone files therefore do not necessarily match an independently created Iceberg table, even before schema evolution. Align the algorithm or remove the compatibility guarantee and document the need to verify target IDs.
Tests
  • ⚠️ If retaining the Iceberg numbering claim, compare standalone output and an Iceberg table for the same nested schema. The existing Iceberg test exercises metadata precedence and cannot prove the standalone numbering matches.
Final Verdict

Status: ⚠️ Request changes. Correct the Iceberg numbering contract; if retaining it, align the implementation and add the focused schema comparison.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 12, 2026
`getFormatSettings` runs on every query, including SELECTs that don't
write Parquet, so parsing the `output_format_parquet_column_field_ids`
value to `Int32` in `FormatFactory` made `SETTINGS
output_format_parquet_column_field_ids = {'a': 'oops'}` fail
client-side with `Error on processing query: ...`. Tests using `{
serverError BAD_ARGUMENTS }` then saw a client error instead of a
server error and reported "Expected server error ... but got no server
error".

Keep the raw `Map(String, String)` values in `FormatSettings` and do
the integer parse + range check inside `ParquetBlockOutputFormat`'s
`buildColumnFieldIds`, alongside the existing unknown-column /
duplicate-id checks. The same error now reaches the test framework as
a normal server error.

Also fix the test so it's re-runnable under the flaky check: switch
the success cases from `INSERT INTO FUNCTION file('<fixed-name>')` to
`currentDatabase() || ...` and set `engine_file_truncate_on_insert =
1`, so a second run doesn't trip `CANNOT_APPEND_TO_FILE`. Convert the
four error cases from `INTO OUTFILE` to `INSERT INTO FUNCTION
file(...)` so the validation errors arrive as server errors that `{
serverError BAD_ARGUMENTS }` recognises.

See CI report:
ClickHouse#101783

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 7 commits May 18, 2026 21:30
…ataLake settings

The PR adds an `output_format_parquet_column_field_ids` setting of type
`Map(String, Int32)`. Master subsequently moved to a constexpr settings
layout that requires every type used by any setting in the merged list to
appear in the supported-types macro for that settings class.

Without this fix the build fails in `DatabaseDataLakeSettings.cpp` with a
VLA diagnostic, because the layout computation hits an undeclared
`SettingTypeTag` value for `Map`.

Fast-test build report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/101783/463edd23905aa45f867156b09f6e7e3eadc02666/fast_test/build_clickhouse/build_clickhouse.log

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…actory time

Addresses review feedback on PR ClickHouse#101783:

* ClickHouse#101783 (comment) ("Don't use mini-languages inside strings. Instead, use structured data like Map.")
* ClickHouse#101783 (comment) (datalake column-id mapping precedence)

`FormatSettings::Parquet::column_field_ids` now stores `Int32` directly
instead of `String`, and `FormatFactory` parses the `Map` setting at SET
time. Integer values can be passed natively (`{'a': 1, 'b': 2}`) instead of
encoded as strings; quoted-integer strings are still accepted for
compatibility.

When a datalake (e.g. Iceberg) writer hands `ParquetBlockOutputFormat` a
column-id mapping, that mapping is now authoritative; combining it with
`output_format_parquet_column_field_ids` or
`output_format_parquet_auto_assign_field_ids` raises `BAD_ARGUMENTS`
instead of silently producing a Parquet file whose `field_id`s no longer
match table metadata.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses ClickHouse#101783 (comment):
the previous SQL test only round-tripped values, so a regression that dropped
`field_id` metadata from the Parquet schema would not have been caught.

The test is now a shell script that uses pyarrow to read the written Parquet
schema and print `field_id`s for each column. Covers explicit overrides,
auto-assign, mixed override + auto-assign, the default (no `field_id`) path,
string-encoded ids for compatibility, and the error cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ClickHouse's settings parser only accepts string literals as `Map` values
(integer literals fail with `SYNTAX_ERROR`), so the user-visible setting is
`output_format_parquet_column_field_ids = {'col_a': '1', ...}`. Update the
test to use that syntax everywhere and the docs / setting description to
match.

The local C++ side still accepts both `Int64`/`UInt64` (for programmatic
callers) and `String` (for SQL callers), so no implementation change is
needed.

Verified end-to-end with the local build — all five round-trip cases and
all five error cases match the reference.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The push to the fork is blocked by the missing `workflow` OAuth scope. Restore
`.github/workflows/pull_request.yml` to the pre-merge state so the branch can
be pushed; the next maintainer-driven sync to master will pull the latest
workflow definition.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 18, 2026
…-field-id

# Conflicts:
#	.github/workflows/pull_request.yml
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed e00a1375175..10b576c2038: merged current master (clean, no conflicts; the PR diff against master is unchanged at 56 files, +2468/-66). clickhouse builds, and 04814_parquet_field_ids_in_table_definition and 05397_parquet_field_ids_delta_lake_definition pass locally.

The only red check on the previous head was CH Inc sync with build failed. In the private sync PR only Build (amd_msan) failed. All 23 other builds passed, including arm_msan, amd_asan_ubsan, amd_tsan and amd_debug, so a compile error in this change is unlikely. I could not read that job's log or rerun it with my credentials, so this push re-triggers the sync instead.

The five unresolved review threads are still waiting on the same product decision: keep explicit nested-path overrides (output_format_parquet_column_field_ids) for matching existing external schemas, or drop that setting and decide whether automatic field_id assignment becomes the default. That is a maintainer decision.

# Conflicts:
#	src/Storages/ObjectStorage/registerStorageObjectStorage.cpp
#	tests/integration/test_storage_azure_blob_storage/test.py
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed d9aaf16508d..0ca71742f4e: merged current master to resolve two conflicts. In registerStorageObjectStorage.cpp I kept both sides: the Parquet field_id validation and the deferred write-capable switch, then master's data lake settings_changes block. In test_storage_azure_blob_storage/test.py I kept both new tests. clickhouse builds. The only red check was 05339_iceberg_top_k_query_condition_cache, which was also failing on master until about 2026-10-22 14:00 UTC (the PR's last merge came before the fix), so this merge pulls in the fix. The five open review threads still need the maintainer product decision described there: whether to keep explicit nested-path overrides or make automatic IDs the default.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed ca1ca570a92..1a7448890ba: the only red check was Build (arm_tidy, 3/4). The previous merge of master left a duplicate #include <algorithm> in registerStorageObjectStorage.cpp, and clang-tidy reports that as readability-duplicate-include. I removed it, and the translation unit builds. The five open review threads still need the same maintainer product decision: keep explicit nested-path overrides (output_format_parquet_column_field_ids), or drop that setting and decide whether automatic field_id assignment becomes the default.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch. The merge was clean, and the clickhouse binary builds after it. The remaining CI failures are unrelated to this PR:

@groeneai, investigate the librdkafka TSan data race in test_multi_consumer_quota (report above) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The open review threads still need a maintainer product decision (keep explicit nested-path overrides, or switch to auto-assigned IDs only), so I have not changed the design.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: ClickHouse/librdkafka#23 (base ClickHouse/v2.15.1, the branch contrib/librdkafka is pinned to). It is open and mergeable, and needs a review.

Cause: rd_kafka_toppar_handle_Offset reads rktp->rktp_op_version after releasing the toppar lock (rdkafka_partition.c:1516 and :1520), assuming it runs on the toppar handler thread. While the consumer handle is being destroyed, the broker thread fails the pending OffsetRequest with RD_KAFKA_RESP_ERR__DESTROY (rdkafka_broker.c:5084), and rd_kafka_buf_callback then calls the handler inline on the broker thread, which races with the locked write in rd_kafka_toppar_op_version_bump. The patch reads the field once, under the lock.

A second race that hits the same Kafka TSan jobs (rktp_ts_fetch_backoff, written without the lock in rd_kafka_toppar_fetch_backoff) is fixed in ClickHouse/librdkafka#24. Once they merge, I'll send the ClickHouse PR that bumps the submodule.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 8fd6a6c9599..a0beecf1dab: merged current master. The merge was clean, the PR's file list did not change, and clickhouse builds.

The CI failures on the previous head are unrelated to this PR:

@groeneai, thanks for linking ClickHouse/librdkafka#23 and ClickHouse/librdkafka#24 for the Kafka TSan race.

I did not change the design. The five open review threads still need the maintainer product decision: keep explicit nested-path overrides (output_format_parquet_column_field_ids), or drop that setting and decide whether automatic field_id assignment becomes the default.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 CH Inc sync failed because the private sync branch conflicted with private master in registerStorageObjectStorage.cpp, StorageObjectStorage.h and test_storage_azure_blob_storage/test.py. I resolved this in the sync branch: its tree is now private master plus this PR's diff at a0beecf1dab. In StorageObjectStorage.h it keeps both this PR's switchToWriteCapableObjectStorage and the private-only getTableFormatSettings. The four affected translation units pass a syntax check. The sync PR now reports MERGEABLE, so the check should re-run.

The only other red check is Build profile diff. It is an infrastructure failure (LogClusterNotReady: the endpoint never became ready while querying CIDB) and unrelated to this PR.

Nothing in the PR itself changed. The five open review threads still need the maintainer product decision described there: keep the explicit nested-path overrides (output_format_parquet_column_field_ids), or drop that setting and decide whether automatic field_id assignment becomes the default.

alexey-milovidov and others added 7 commits October 29, 2026 08:52
…y auto-assign

The reviewer accepted everything except the manual assignment feature, which
introduced a new dotted-path notation, and asked why the code was so complex.
This commit removes the `output_format_parquet_column_field_ids` setting and
all the code that existed only to support it:

- `Map` registration in the format settings traits of every engine;
- the definition-time validation in `File`, `URL`, object storage, `Kafka`,
  `NATS`, `RabbitMQ` and data lake engines (`validateParquetFieldIdSettingsInDefinition`);
- the rules that reset ambient values of the settings for table definitions and
  Iceberg tables, and the deferred write-capable object storage client;
- the tests and integration tests for all of the above.

Only `output_format_parquet_auto_assign_field_ids` remains. It is now ignored
when a data lake table provides its own field ids (the table metadata is the
source of truth), instead of being an error, so an ambient value of the
setting can never break writes to Iceberg tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
)", 0, \
{"25.7", false, true, "A new setting to allow to write information about geo columns in parquet metadata and encode columns in WKB format."}) \
DECLARE(Bool, output_format_parquet_auto_assign_field_ids, false, R"(
When enabled, every output column and every nested field (`Array` `element`, `Map` `key`/`value`, `Tuple` subfields) is assigned a unique Parquet `field_id` automatically: sequential, starting at 1, in schema DFS order, matching the convention used by Apache Iceberg writers. Iceberg identifies columns by `field_id` rather than by name.

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.

⚠️ Major: DFS numbering does not match Apache Iceberg's convention

For a Array(Int64), b Int64, the standalone writer assigns a=1, a.element=2, b=3. Apache Iceberg's AssignFreshIds.struct reserves IDs for sibling fields before descending, producing a=1, b=2, a.element=3. The IDs differ even for a newly created table with no schema evolution.

Consequently, producing standalone files for an independently created Iceberg table, as in the linked issue, gives conflicting IDs despite this compatibility promise. Readers bind by ID, so matching column names cannot repair the mismatch. The test's Iceberg case uses the metadata-mapping path and does not establish that standalone numbering matches it.

Please either use Iceberg's assignment order and compare both paths for the same nested schema, or remove the convention guarantee from the setting description, format documentation and changelog, and explain that generated IDs must be checked against the target schema.

@alexey-milovidov

Copy link
Copy Markdown
Member

Just to clarify the motivation behind this feature: - it is needed to manually write Parquet files that are intended to be used in Iceberg.

Is this a frequent need? I doubt so.

@alexey-milovidov

Copy link
Copy Markdown
Member

I don't think we should merge this. ClickHouse can now write to Iceberg tables directly, with field ids from the table metadata, and Iceberg handles foreign Parquet files without field ids through name mapping (schema.name-mapping.default, used by add_files).

Auto-assigned ids are actively dangerous: this PR's own test shows depth-first numbering for (a, t Tuple(x, y), b) as a=1, t=2, t.x=3, t.y=4, b=5, while our Iceberg writer assigns a=1, t=2, b=3, t.x=4, t.y=5 (siblings first, as in Iceberg's AssignFreshIds). Iceberg matches columns by id, so such a file would silently read the wrong column. Even for flat schemas, sequential ids diverge after the first schema evolution.

Closing. If there is a concrete workflow that name mapping doesn't cover, let's discuss it in #58753.

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.). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support specifying field_id for columns when writing to Parquet files

5 participants