Repository navigation
Improve iceberg writes for unity catalog - #98162
Conversation
|
Workflow [PR], commit [c9de070] Summary: ❌
AI ReviewSummaryThis PR improves Iceberg write compatibility with Unity/REST catalogs ( PR Metadata
Missing context
Findings
Tests
ClickHouse Rules
User-Lens
Final Verdict
|
| @@ -361,7 +361,7 @@ static constexpr const char * manifest_entry_v1_schema = R"( | |||
| }, | |||
| { | |||
| "name": "split_offsets", | |||
| "type": ["null", {"type": "array", "items": "long", "element-id": 133}], | |||
| "type": ["null", {"type": "array", "items": "int", "element-id": 133}], | |||
There was a problem hiding this comment.
split_offsets must stay array<long> per Iceberg manifest spec (field-id 132 / element-id 133). Changing it to int breaks compatibility with readers that deserialize offsets as 64-bit and can truncate large offsets for big files. Please keep this field as long in v1 too.
| @@ -556,7 +556,7 @@ static constexpr const char * manifest_entry_v2_schema = R"( | |||
| }, | |||
| { | |||
| "name": "equality_ids", | |||
| "type": ["null", {"type": "array", "items": "int", "element-id": 136}], | |||
| "type": ["null", {"type": "array", "items": "long", "element-id": 136}], | |||
There was a problem hiding this comment.
equality_ids should remain array<int> (field IDs are 32-bit in Iceberg). Switching this to long changes the Avro schema and can break compatibility with engines expecting the canonical list<int> type for field-id 135/136. Please revert this item type back to int.
| storage_data_path = write_data_path.substr(s3_prefix.size()); | ||
| } | ||
|
|
||
| filename_generator.setDataDir(write_data_path + "data/", storage_data_path + "data/"); |
There was a problem hiding this comment.
write.data.path is already the configured data directory in Iceberg. Appending data/ here writes files under <write.data.path>/data/ (often ending up as .../data/data/...) and diverges from the configured location provider semantics. Please pass write_data_path and storage_data_path directly (with only trailing-slash normalization) to setDataDir.
| ++i; | ||
| } | ||
| if (!successed_write) | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "Write into iceberg was not successful"); |
There was a problem hiding this comment.
Wrong error code for transaction retry failure
Low Severity
ErrorCodes::BAD_ARGUMENTS is used for a transaction retry exhaustion error, which is misleading. This error occurs when initializeMetadata() fails after MAX_TRANSACTION_RETRIES attempts, indicating a transactional write conflict or infrastructure issue—not invalid user arguments. A more appropriate error code (e.g., DATALAKE_DATABASE_ERROR) would better communicate the actual failure cause to users.
There was a problem hiding this comment.
I agree, maybe use LOGICAL_ERROR ? wdyt ?
There was a problem hiding this comment.
No, logical error is not good there because we can have problems with net and we will get LOGICAL_ERROR in such case, but we shouldn't. I'll change to DATALAKE_DATABASE_ERROR
| ++i; | ||
| } | ||
| if (!successed_write) | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "Write into iceberg was not successful"); |
There was a problem hiding this comment.
If all MAX_TRANSACTION_RETRIES attempts return false (metadata conflict path), we throw here but never delete the staged data files. initializeMetadata calls cleanup(true), which intentionally keeps data files for retry, so after the final retry these files are left orphaned. Please add a final cleanup before throwing (e.g. iterate writer_per_partition_key and call writer.clearAllDataFiles).
| { | ||
| String s3_prefix = bucket.substr(0, bucket.size() - config_path.size()); | ||
| if (write_data_path.starts_with(s3_prefix)) | ||
| storage_data_path = write_data_path.substr(s3_prefix.size()); |
There was a problem hiding this comment.
If write.data.path does not start with the current table location prefix (s3_prefix), we keep the full URI in storage_data_path and later pass it to writeObject. That writes data under the current table storage with an object key like s3://..., while metadata points to the external URI, so readers cannot find the file. Please fail fast for this mismatch (throw an exception) instead of silently accepting unsupported cross-prefix writes.
There was a problem hiding this comment.
I agree that we should throw exception instead of silently failing
| relative_path_with_metadata.getPath(), | ||
| Iceberg::f_added_snapshot_id); | ||
| } | ||
| /// This only happens when we read data written by a old version of iceberg, which violent the spec of iceberg. |
There was a problem hiding this comment.
Typo: this should be violates the spec, not violent the spec.
Please fix this wording in both occurrences in this block to keep exception/comments clear.
| if (properties->has("write.data.path")) | ||
| { | ||
| auto write_data_path = properties->getValue<String>("write.data.path"); | ||
| if (!write_data_path.empty()) |
There was a problem hiding this comment.
Maybe we should throw an exception if its empty, wdyt?
There was a problem hiding this comment.
no, it can be empty and this ok
| /// Why do we need this for version 1? In some version, iceberg-spark has changed the type of field `f_added_snapshot_id` | ||
| /// from 'null, long' to 'long'. See https://github.com/apache/iceberg/pull/11626. |
There was a problem hiding this comment.
Looks like we need to update this comment as its not just version 1 anymore.
|
@scanhex12 I think this PR should not be in 'Not for changelog' category. Maybe Improvement? wdyt ? |
| @@ -50,6 +50,11 @@ class FileNamesGenerator | |||
|
|
|||
| void setVersion(Int32 initial_version_) { initial_version = initial_version_; } | |||
| void setCompressionMethod(CompressionMethod compression_method_) { compression_method = compression_method_; } | |||
| void setDataDir(const String & data_table_dir, const String & data_storage_dir) | |||
| { | |||
| data_dir = data_table_dir; | |||
There was a problem hiding this comment.
❌ This change introduces a build break: setDataDir assigns to data_dir and storage_data_dir, but these members are not declared in FileNamesGenerator.
The current class only has table_location, use_uuid_in_metadata, compression_method, format_name, and initial_version, so this will fail to compile.
Please either add the missing members (and wire them into generateDataFileName) or remove setDataDir until the member storage is implemented.
| @@ -36,7 +36,7 @@ class MultipleFileWriter | |||
|
|
|||
| const std::vector<Iceberg::IcebergPathFromMetadata> & getDataFiles() const | |||
| { | |||
| return data_file_names; | |||
| return data_file_metadata_names; | |||
There was a problem hiding this comment.
❌ This is another compile-time issue: getDataFiles now returns data_file_metadata_names, but the class member is still named data_file_names.
As written, this is an undefined identifier and will break the build.
Please return data_file_names (or rename the member consistently in both header and implementation).
7f6d7d5 to
97a10f5
Compare
|
We need to merge ClickHouse/avro#30 before this PR |
| add_field_to_datum(Iceberg::f_key_metadata); | ||
| if (version == 2) | ||
| { | ||
| add_field_to_datum(Iceberg::f_added_snapshot_id); |
There was a problem hiding this comment.
new_entry.field(f_added_snapshot_id) is already normalized above to a long (handling legacy ['null','long'] values). Calling add_field_to_datum(Iceberg::f_added_snapshot_id) here overwrites that normalized value with the raw datum from old_entry.
For legacy manifests produced by old iceberg-spark (where added_snapshot_id is a union), this reintroduces the incompatible union value into the v2 record and can fail serialization.
Please remove this call and keep the already-normalized assignment.
There was a problem hiding this comment.
agreed, we can remove this line
add_field_to_datum(Iceberg::f_added_snapshot_id);
| { | ||
| auto properties = metadata->getObject(Iceberg::f_properties); | ||
| if (properties && properties->has("write.data.path")) | ||
| filename_generator.setDataLocation(properties->getValue<String>("write.data.path")); |
There was a problem hiding this comment.
When initializeMetadata retries after a metadata conflict, cleanup(true) reloads the latest metadata and updates schema/partition state, but the write.data.path override is not refreshed. Because filename_generator.setDataLocation is only called in the constructor, retries can keep writing data files to a stale location if table properties changed concurrently.
Please reapply write.data.path (or clear it when absent) after reloading metadata in the retry path, so file generation stays consistent with the latest table properties.
| { | ||
| auto properties = metadata->getObject(Iceberg::f_properties); | ||
| if (properties && properties->has("write.data.path")) | ||
| filename_generator.setDataLocation(properties->getValue<String>("write.data.path")); |
There was a problem hiding this comment.
write.data.path handling is currently applied only in IcebergStorageSink (append/insert path), but other write paths still generate data files under table_location/data.
For example, Mutations and Compaction create FileNamesGenerator and call generateDataFileName without reading metadata.properties['write.data.path'], so the same table can end up with mixed data-file locations depending on operation type.
Please propagate the same write.data.path override to these code paths as well (or centralize it in FileNamesGenerator initialization), otherwise the fix is partial and behavior remains inconsistent.
LLVM Coverage Report
Changed lines: 71.18% (121/170) · Uncovered code |
b1315cb
Backport of ClickHouse#98162 (merged upstream as b1315cb for 26.4) onto v26.3.44.2-lts-aiven. Unity Catalog and other REST catalogs serve the Iceberg API under a warehouse prefix, and `config.prefix` already carries it for every read path. The three write paths built their endpoints with `fmt::format("{}/namespaces...", base_url)` instead, dropping the prefix and leaving the namespace unencoded, so `CREATE TABLE` and snapshot commits hit a path the catalog does not serve. Build them the same way the read paths do, from `base_url / config.prefix / NAMESPACES_ENDPOINT` with `encodeNamespaceForURI`. Alongside that, several things in the write path produced metadata that other Iceberg readers reject: - `write.data.path` was ignored, so data files were always written under `<table>/data/` even when the table property pointed elsewhere. - The `manifest_list_v2` Avro schema had no `key_metadata` field (519), while the manifest-list writer copies that field from previous snapshots. - `existing_files_count` was taken from the summary's `total_data_files`, counting files this manifest does not contain. - The partition-spec `key` field was written as `int64` where the spec requires `int32`. - `getMaxSequenceNumber` scanned the snapshot array, which understates the sequence number once a catalog prunes snapshot history. Read the top-level `last-sequence-number` instead. - Snapshot ids were drawn from `[0, INT32_MAX]`; the spec allows the full `int64` range and `0` is not a valid id. - Rewriting manifest-list entries onto the current schema was done only for v1, so v2 entries carrying the old nullable `added_snapshot_id` were passed through unchanged. - `finalizeBuffers` fell out of the retry loop silently when every attempt failed, reporting success for a write that never committed. `MAX_TRANSACTION_RETRIES` is also raised from 100 to 1000. Backport deviations from upstream: master reworked FileNamesGenerator to single metadata-form paths (IcebergPathFromMetadata) and passes a path resolver into generateManifestList; 26.3 still uses the dual {path_in_metadata, path_in_storage} Result and the filename_generator/manifest_lengths signature. The `write.data.path` override therefore derives the storage path via convertMetadataPathToStoragePath, which rejects locations outside the table prefix. The contrib/avro bump in the upstream PR is not included. Rebase notes from v26.3.32.14-lts to v26.3.44.2-lts-aiven: 26.3.44 hardened the v1 manifest-list rewrite with `validate_field_type` and `copy_required_field` helpers and an explicit `AVRO_LONG` check on `added_snapshot_id`. Hoisting the rewrite out of the `version == 1` branch keeps those helpers and drops the now-redundant `isUnion` / `unionBranch` handling, since a null union branch already fails the `AVRO_LONG` check.
Backport of ClickHouse#98162 (merged upstream as b1315cb for 26.4) onto v26.3.44.2-lts-aiven. Unity Catalog and other REST catalogs serve the Iceberg API under a warehouse prefix, and `config.prefix` already carries it for every read path. The three write paths built their endpoints with `fmt::format("{}/namespaces...", base_url)` instead, dropping the prefix and leaving the namespace unencoded, so `CREATE TABLE` and snapshot commits hit a path the catalog does not serve. Build them the same way the read paths do, from `base_url / config.prefix / NAMESPACES_ENDPOINT` with `encodeNamespaceForURI`. Alongside that, several things in the write path produced metadata that other Iceberg readers reject: - `write.data.path` was ignored, so data files were always written under `<table>/data/` even when the table property pointed elsewhere. - The `manifest_list_v2` Avro schema had no `key_metadata` field (519), while the manifest-list writer copies that field from previous snapshots. - `existing_files_count` was taken from the summary's `total_data_files`, counting files this manifest does not contain. - The partition-spec `key` field was written as `int64` where the spec requires `int32`. - `getMaxSequenceNumber` scanned the snapshot array, which understates the sequence number once a catalog prunes snapshot history. Read the top-level `last-sequence-number` instead. - Snapshot ids were drawn from `[0, INT32_MAX]`; the spec allows the full `int64` range and `0` is not a valid id. - Rewriting manifest-list entries onto the current schema was done only for v1, so v2 entries carrying the old nullable `added_snapshot_id` were passed through unchanged. - `finalizeBuffers` fell out of the retry loop silently when every attempt failed, reporting success for a write that never committed. `MAX_TRANSACTION_RETRIES` is also raised from 100 to 1000. Backport deviations from upstream: master reworked FileNamesGenerator to single metadata-form paths (IcebergPathFromMetadata) and passes a path resolver into generateManifestList; 26.3 still uses the dual {path_in_metadata, path_in_storage} Result and the filename_generator/manifest_lengths signature. The `write.data.path` override therefore derives the storage path via convertMetadataPathToStoragePath, which rejects locations outside the table prefix. The contrib/avro bump in the upstream PR is not included. Rebase notes from v26.3.32.14-lts to v26.3.44.2-lts-aiven: 26.3.44 hardened the v1 manifest-list rewrite with `validate_field_type` and `copy_required_field` helpers and an explicit `AVRO_LONG` check on `added_snapshot_id`. Hoisting the rewrite out of the `version == 1` branch keeps those helpers and drops the now-redundant `isUnion` / `unionBranch` handling, since a null union branch already fails the `AVRO_LONG` check.
Backport of ClickHouse#98162 (merged upstream as b1315cb for 26.4) onto v26.3.44.2-lts-aiven. Unity Catalog and other REST catalogs serve the Iceberg API under a warehouse prefix, and `config.prefix` already carries it for every read path. The three write paths built their endpoints with `fmt::format("{}/namespaces...", base_url)` instead, dropping the prefix and leaving the namespace unencoded, so `CREATE TABLE` and snapshot commits hit a path the catalog does not serve. Build them the same way the read paths do, from `base_url / config.prefix / NAMESPACES_ENDPOINT` with `encodeNamespaceForURI`. Alongside that, several things in the write path produced metadata that other Iceberg readers reject: - `write.data.path` was ignored, so data files were always written under `<table>/data/` even when the table property pointed elsewhere. - The `manifest_list_v2` Avro schema had no `key_metadata` field (519), while the manifest-list writer copies that field from previous snapshots. - `existing_files_count` was taken from the summary's `total_data_files`, counting files this manifest does not contain. - The partition-spec `key` field was written as `int64` where the spec requires `int32`. - `getMaxSequenceNumber` scanned the snapshot array, which understates the sequence number once a catalog prunes snapshot history. Read the top-level `last-sequence-number` instead. - Snapshot ids were drawn from `[0, INT32_MAX]`; the spec allows the full `int64` range and `0` is not a valid id. - Rewriting manifest-list entries onto the current schema was done only for v1, so v2 entries carrying the old nullable `added_snapshot_id` were passed through unchanged. - `finalizeBuffers` fell out of the retry loop silently when every attempt failed, reporting success for a write that never committed. `MAX_TRANSACTION_RETRIES` is also raised from 100 to 1000. Backport deviations from upstream: master reworked FileNamesGenerator to single metadata-form paths (IcebergPathFromMetadata) and passes a path resolver into generateManifestList; 26.3 still uses the dual {path_in_metadata, path_in_storage} Result and the filename_generator/manifest_lengths signature. The `write.data.path` override therefore derives the storage path via convertMetadataPathToStoragePath, which rejects locations outside the table prefix. The contrib/avro bump in the upstream PR is not included. Rebase notes from v26.3.32.14-lts to v26.3.44.2-lts-aiven: 26.3.44 hardened the v1 manifest-list rewrite with `validate_field_type` and `copy_required_field` helpers and an explicit `AVRO_LONG` check on `added_snapshot_id`. Hoisting the rewrite out of the `version == 1` branch keeps those helpers and drops the now-redundant `isUnion` / `unionBranch` handling, since a null union branch already fails the `AVRO_LONG` check.
Antalya 26.3 Backport of ClickHouse#98162 - Improve iceberg writes for unity catalog


Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improve iceberg writes for the unity catalog
Documentation entry for user-facing changes
Note
Medium Risk
Changes affect Iceberg write path generation and REST catalog endpoint construction; mistakes could write data to the wrong location or cause commit retries/failures against transactional catalogs.
Overview
Improves Unity/REST catalog compatibility for Iceberg writes by building REST endpoints using the configured catalog
prefixand proper namespace URI encoding.Updates Iceberg metadata generation and writing to better match Unity Catalog expectations: supports
write.data.pathto place data files under a configured data directory, records correct metadata vs storage paths for written data files, and normalizes manifest list paths (removing escaped slashes).Hardens the commit loop by failing the write after exhausting metadata initialization retries instead of silently continuing.
Written by Cursor Bugbot for commit 909f2dab8b211e2af711b3dd957c5ec2d11e75ba. This will update automatically on new commits. Configure here.
Version info
26.4.1.347