Repository navigation
Antalya-26:6 - iceberg v3: rewriteFiles - Added logic to merge small files into bins - #2420
Conversation
Audit report: Altinity/ClickHouse#2420 (Iceberg bin-pack
|
Audit report: #2420 at c4c4578AI audit note: This review was generated by AI. Audit update for PR #2420 (Iceberg bin-pack All 10 defects from the previous audit (head Confirmed defectsMedium: the v3 guard uses the format version cached when the table object was created, and full compaction still accepts v3 and writes v2 metadata
if (persistent_components.format_version != 2) // set once in the IcebergMetadata constructor
throw Exception(ErrorCodes::BAD_ARGUMENTS, "OPTIMIZE TABLE is supported only for Iceberg format_version 2, got {}", ...);
// Compaction.cpp / getPlan (latest metadata)
if (initial_metadata_object->getValue<Int32>(Iceberg::f_format_version) < 2) // v3 passes
Low: after full compaction, the regenerated
|
…-pack rewrite The error code does not exist in `ErrorCodes.cpp`, which caused a link failure of `clickhouse` and `unit_tests_dbms`. Use `UNFINISHED` for the case where the outcome of the metadata commit is unknown. Co-authored-by: Cursor <[email protected]>
…-pack rewrite The error code does not exist in `ErrorCodes.cpp`, which caused a link failure of `clickhouse` and `unit_tests_dbms`. Use `UNFINISHED` for the case where the outcome of the metadata commit is unknown.
…/Altinity/ClickHouse into iceberg_rewrite_files_compaction
…/Altinity/ClickHouse into iceberg_rewrite_files_compaction Signed-off-by: Kanthi Subramanian <[email protected]>
…/Altinity/ClickHouse into iceberg_rewrite_files_compaction
CI triage for #2420 (
|
|
To use Codex here, create a Codex account and connect to github. |
…ler functions by steps/phase
|
|
||
| auto hint_path = generator.generateVersionHint(); | ||
|
|
||
| const auto commit_result = tryWriteMetadataFileAndVersionHint( |
There was a problem hiding this comment.
Cleanup deletes the files of a committed snapshot when the version hint update throws
When tryWriteMetadataFileAndVersionHint is called, it writes vN+1.metadata.json first and then moves on to updating the version hint. The loop that updates the hint is not wrapped in a try block, so calls such as object_storage->exists can throw after the new metadata is already live. If that happens, the exception leaves commitMetadata while keep_files_on_error is still false, since it is only set on the Unknown path. The catch block in executeBinPackCompaction then calls cleanup, which removes the merged data files, the new manifests and the manifest list.
As a result, the current snapshot points at objects that no longer exist, and the old small files are already marked as deleted in it, so the table can no longer be read. A single transient S3 error while reading the hint or a malformed version-hint.text is enough to trigger this.
Proposed fix: Set keep_files_on_error = true right before calling tryWriteMetadataFileAndVersionHint. Both Conflict branches already call cleanup explicitly, so they would keep working as they do now.
There was a problem hiding this comment.
| if (attempt > 0) | ||
| LOG_INFO(log, "Retrying bin-pack compaction (attempt {}/{})", attempt + 1, MAX_BIN_PACK_RETRIES); | ||
|
|
||
| const auto result = Iceberg::executeBinPackCompaction( |
There was a problem hiding this comment.
OPTIMIZE on a catalog table writes a new snapshot but never commits it to the catalog
When OPTIMIZE runs on a table from a DataLakeCatalog database, the bin-pack path writes merged data files, manifests, a manifest list and vN.metadata.json, and then reports success. However, the catalog is never told about the new metadata, because IcebergMetadata::optimize has no catalog parameter and executeBinPackCompaction only writes the metadata file to storage. The catalog keeps pointing at the previous metadata file, while the new metadata file and its snapshot sit next to it unreferenced.
As a result, catalog readers never see the compaction and every run leaves orphaned files behind. The next OPTIMIZE also picks up the uncommitted metadata file as the latest version, because it finds the latest metadata by listing the directory, so it starts from a state the catalog has never seen. This behavior is new with this PR. Before it, OPTIMIZE on a table without position deletes did nothing. The manifest-only path already handles this case: optimizeManifestFiles takes the catalog and commits through catalog->updateMetadata.
Proposed fix: Pass the catalog and storage ID into optimize the same way as optimizeManifestFiles, and commit through catalog->updateMetadata in commitMetadata when a catalog is present, treating a rejected update as a Conflict.
There was a problem hiding this comment.
passed catalog and storageId to optimize.
| StoredObject(storage_manifest_list_path), WriteMode::Rewrite, std::nullopt, | ||
| DBMS_DEFAULT_BUFFER_SIZE, context->getWriteSettings()); | ||
|
|
||
| generateManifestList( |
There was a problem hiding this comment.
Bin-pack manifests are written without a partition summary in the manifest list
In writeManifestList, there is no entry_partition_summaries argument passed to generateManifestList, so write_partition_summary returns early and the partitions field is left empty for every manifest that bin-packing writes. Readers use that summary to skip whole manifests during scan planning. After an OPTIMIZE on a partitioned table, every scan has to open all of the new manifests, including the per-file ones. The manifest-only rewrite in Compaction.cpp builds these summaries for exactly this reason. Since every manifest written here holds a single partition tuple, the bin's partition key or the kept group's key already contains everything the summary needs.
Proposed fix: Build one summary per manifest from the partition key and plan.partition_types, the same way the manifest-only rewrite does in Compaction.cpp, and pass the vector to generateManifestList.
| size_t result = 0; | ||
| FieldVisitorDump dump_visitor; | ||
| for (const auto & value : row) | ||
| result ^= hasher(applyVisitor(dump_visitor, value)); |
There was a problem hiding this comment.
The hash combiner fix here was reverted by a later commit
The commit b5206fe replaced the XOR in here with boost::hash_combine. The next commit, 7d547c2, changed it back to result ^= ... and removed the boost include, which looks like an accident while resolving a conflict. When values are combined with XOR, (a, b) and (b, a) produce the same hash, and any key with two equal values hashes to 0. Since PartitionKeyEqual still compares the keys, results stay correct, but lookups in the partition maps can degrade for tables that are partitioned on more than one column.
Proposed fix: Restore boost::hash_combine(result, hasher(applyVisitor(dump_visitor, value))) and the <boost/container_hash/hash.hpp> include.
| {"iceberg_target_data_file_size_bytes", 536870912, 536870912, "Target file size for Iceberg bin-packing compaction (default 512 MiB)."}, | ||
| {"iceberg_min_data_file_size_bytes", 402653184, 402653184, "Files below this size are candidates for Iceberg bin-packing compaction (default 384 MiB)."}, |
There was a problem hiding this comment.
I think this should be moved to a newer version block since 26.6.2.20001 already released
| return {new_snapshot, manifest_list_path}; | ||
| } | ||
|
|
||
| MetadataGenerator::NextMetadataResult MetadataGenerator::generateReplaceSnapshot( |
There was a problem hiding this comment.
This seems to be mostly the same as generateManifestOnlySnapshot, the duplicated logic could be moved to a helper function and called in both.
There was a problem hiding this comment.
yes refactored to generateManifestOnlySnapshot
| parent_snapshot_id); | ||
|
|
||
| Poco::JSON::Object::Ptr new_snapshot = new Poco::JSON::Object; | ||
| if (format_version > 1) |
There was a problem hiding this comment.
This if statement check isn't necessary because you already throw if format_version != 2 above so it will always be true
|
Low: A REST catalog rejection never cleans up, so every lost commit race leaks the whole rewrite Low: A failed existence check before the metadata write now leaves the rewritten files behind Low: The new code paths in b1e6fd8 have no tests |
xieandrew
left a comment
There was a problem hiding this comment.
All issues from review comments were fixed, looks good to me.
CI triage — @mkmkmeVerdict: 5 failing checks → 1 PR-caused (expected snapshot update), 4 not PR-caused (flaky / timeout / infra). The actual product tests for this PR are green: every Build, Unit, Integration and Stateless suite passed, including all 1.
|
|
I'll try to reproduce the one with the New defects in #2420Head High:
|
High: on a catalog table, full compaction removes the catalog's current metadata file and never updates the catalog Impact: after OPTIMIZE, Glue or REST still points at a metadata file that has been deleted. Its data files and position-delete files are deleted too, so every reader that goes through the catalog fails, including Spark, Trino and ClickHouse. The command reports success. Compaction.cpp IcebergMetadata.cpp |
CI triage for
|
| Check | Verdict |
|---|---|
Regression settings |
Caused by this PR: the 2 new settings have no snapshot |
| Integration (amd_asan_ubsan, old analyzer, 3/8 and 4/8) | Already fails on the base branch |
Stateless (amd_asan_ubsan, distributed plan, 2/2): 05387_… |
Already fails on the base branch |
Stateless ×3 (cas s3 storage) |
Flaky: MinIO connection refused, every rerun passed |
| Stress test (amd_debug) | Unrelated: a Hybrid table doesn't reload after restart |
Regression ssl_server_3 |
Unrelated (ZooKeeper TLS), no base run to compare |
Regression cas_lightweight_delete_3 |
Infra: job cancelled at the time limit (~5h), no log |
Builds, Fast test and Unit tests (asan_ubsan) (15256 passed, including the new gtest_bin_pack_rewrite) are green. tsan, msan and arm jobs were skipped by CI tags.
1. RegressionTestsRelease / Common (settings): caused by this PR
✘ [ Fail ] '/settings/default values/iceberg_min_data_file_size_bytes'
✘ [ Fail ] '/settings/default values/iceberg_target_data_file_size_bytes'
^ is = SnapshotNotFoundError(
The regression suite compares each setting's default value against a stored snapshot. The two settings this PR adds in src/Core/Settings.cpp don't have one yet. The C++ code is fine.
Fix: add snapshot entries for iceberg_min_data_file_size_bytes and iceberg_target_data_file_size_bytes in Altinity/clickhouse-regression (settings suite), or ask the regression team to refresh the snapshots for antalya-26.6. Nothing needs to change in this PR.
2. Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/8 and 4/8): already fail on the base branch
test_storage_iceberg_no_spark/test_writes_statistics_by_minmax_pruning.py(all 6 params):assert 0 == 3(0 files pruned instead of 3)test_storage_iceberg_with_spark/test_minmax_pruning.py(all 12 params): sameassert 0 == 3test_storage_iceberg_with_spark/test_remote_initiator.py::test_remote_initiator_global_join_without_analyzer[s3]:Code: 206 … No alias for subquery or table function in JOIN
These Iceberg tests are close to what this PR touches, so I checked the base branch. The same 19 tests fail with the same errors on #2713, an unrelated ALTER MODIFY COLUMN backport onto antalya-26.6 (5284d10): 6/6 in shard 3/8 and 13/13 in shard 4/8. They only fail under the old analyzer. This is a known base-branch problem, not this PR.
3. Stateless (amd_asan_ubsan, distributed plan, parallel, 2/2): already fails on the base branch
05387_s3_cluster_remote_initiator_keeps_stripped_join fails 3× here and fails the same way on #2713.
4. Stateless cas s3 storage (amd_binary; amd_asan_ubsan 1/2 and 2/2): flaky
03100_lwu_11_with_mutations, 03169_modify_column_data_loss, 03927_sharded_aggregation, 01710_projection_analysis_reuse_partition. Each one failed only because of a message on stderr, for example:
<Warning> CasBlobPublishAttempt: Publication of CAS blob … failed, attempt 1 of 8: … Connection refused
<Error> AWSClient: Response status: 404, Not Found
CI's automatic diagnosis reran each test with the same settings: "All reruns passed. The failure is not reproducible" (16/16, 15/15, 3/3 and 4/4). None of these are Iceberg tests. Safe to re-run.
5. Stress test (amd_debug): unrelated
Cannot attach table `test_2`.`t3` … ENGINE = Hybrid(…, remote('localhost:9000', currentDatabase(), 'local_warm'), …)
Code: 60. DB::Exception: Table default.local_warm does not exist
The server can't restart after the stress run. A Hybrid table left behind by 03645/03646/03682_hybrid_* saved currentDatabase() unevaluated in its metadata, and at restart that resolves to default. The bug is in the Hybrid engine or those tests, not this PR, and the PR doesn't touch them. It only shows up when the stress run happens to leave that table in place (stress amd_debug passed on #2713, #2655 and #2623). Safe to re-run. It might be worth a separate issue for the Hybrid engine.
6. Regression ssl_server_3: unrelated, no base run to compare
✘ /ssl server/part 3/zookeeper/secure connection (AssertionError). This tests TLS between ClickHouse and ZooKeeper, which this PR doesn't touch. I couldn't find a recent antalya-26.6 run of this suite to compare against, so I can't say for sure whether it already fails on the base branch. Re-run it, and if it fails again on base too, it's a regression-suite issue.
7. Regression cas_lightweight_delete_3: infra
The job was cancelled after 5h01m (04:08 to 09:13). The same suite passed in 1h37m on #2644. No log was uploaded, so I can't see where it hung. The PR doesn't touch MergeTree or lightweight deletes. Re-run it.
Next steps: add the 2 setting snapshots in clickhouse-regression and re-run settings, ssl_server_3, cas_lightweight_delete_3 and the flaky stateless/stress jobs. The Iceberg minmax-pruning and 05387 failures will stay red until they're fixed on antalya-26.6.
Sources: the CI report PRs/2420/cc3e17e…/result_pr.json, the base comparison PRs/2713/5284d10…/result_pr.json, and Actions run 40617739406.
|
The main issues that I find are Glue related. Can you check if we want to fix it here or I can raise an issue and this can be fixed in another followup.
On a Glue Iceberg table, run -- session A
OPTIMIZE TABLE glue_db.events
SETTINGS allow_experimental_iceberg_compaction = 1;
-- session B, after A has written the merged files and re-read metadata_location
INSERT INTO glue_db.events VALUES (1, 'new');
-- session A then finishes; read through Glue
SELECT count() FROM glue_db.events WHERE note = 'new';The count should be
if (catalog)
{
const String current_location = getCatalogMetadataLocation(*catalog, storage_id, context);
if (current_location != catalog_metadata_location)
{
cleanup();
return BinPackCommitResult::Conflict;
}
}
// ... write the metadata file ...
if (!catalog->updateMetadata(namespace_name, table_name, catalog_filename, snapshot, context->getForwardedAuthToken())) Aws::Map<Aws::String, Aws::String> parameters;
parameters["metadata_location"] = new_metadata_path;
parameters["table_type"] = "ICEBERG";bool GlueCatalog::updateMetadata(const String & namespace_name, const String & table_name, const String & new_metadata_path, Poco::JSON::Object::Ptr /*new_snapshot*/, const DB::ForwardedAuthTokenPtr & auth_token) const
{
return updateTableInGlue(namespace_name, table_name, new_metadata_path, auth_token);REST is not affected the same way, because a rejected |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Implement bin-packing
ReWriteFilesoperation that Identifies small data files below a target size threshold(defined in Settings), groups them and merges to a large file, creates a snapshot that marks the old ones as DELETED and the new larger merge file as ADDED.Leave all other files, manifests, and history untouched
CI/CD Options
Exclude tests:
Regression jobs to run: