Repository navigation
Conversation
Prior to this change, TRUNCATE TABLE on any Iceberg engine threw a hardcoded NOT_IMPLEMENTED exception in StorageObjectStorage::truncate(). This forced users to DROP and recreate tables to clear data, breaking REST catalog bindings and requiring re-initialization of downstream consumers. Truncation is implemented as a metadata-only operation consistent with the Iceberg spec: generate a new overwrite snapshot with an empty manifest list, write v<N+1>.metadata.json, and atomically commit via the REST catalog. Physical file cleanup is left to standard Iceberg GC, consistent with how Spark and PyIceberg handle truncation. Architecture: - StorageObjectStorage::truncate() — removed hardcoded NOT_IMPLEMENTED; delegates to new IDataLakeMetadata::supportsTruncate() / truncate() virtual interface - IcebergMetadata::truncate() — reads snapshot chain, generates overwrite snapshot (MetadataGenerator gains new is_truncate param), writes empty manifest list, writes versioned metadata JSON, atomic REST catalog commit Notable implementation detail — manual Avro OCF serialization: For the empty manifest list, avro::DataFileWriter is bypassed entirely. The vendored Avro C++ calls writeHeader() eagerly in its constructor, committing the binary encoder state. Post-construction setMetadata() calls corrupt StreamWriter::next_ causing a NULL dereference on close(). Since PyIceberg strictly requires field-id in the avro.schema header entry (which the Avro library strips during schema node serialization), the OCF header is written directly (~20 lines: magic + metadata map + sync marker). No contrib/ changes needed. Also fixed in this change: - IcebergStorageSink::initializeMetadata() and Mutations.cpp were both passing the full metadata_object to catalog->updateMetadata() instead of new_snapshot, silently breaking all INSERTs and mutations on REST catalog tables with Poco::InvalidAccessException - New Feature Added `TRUNCATE TABLE` support for the Iceberg database engine. The operation is metadata-only: it generates a new empty snapshot and atomically commits it to the catalog (REST/transactional backends supported). Physical file cleanup is handled by standard Iceberg GC. - [ ] Documentation is written (mandatory for new features) `TRUNCATE TABLE` is now supported for Iceberg tables backed by a REST catalog. The command clears all visible rows by committing a new empty snapshot. It does not physically delete data files — garbage collection of orphaned files is handled by standard Iceberg maintenance operations. Example: ```sql SET allow_experimental_insert_into_iceberg = 1; TRUNCATE TABLE my_iceberg_db.`my_namespace.my_table`; SELECT count() FROM my_iceberg_db.`my_namespace.my_table`; -- 0 ```
|
Workflow [PR], commit [b9256a8] Summary: ✅
AI ReviewSummaryReviewed #102065 at Findings❌ Blockers
💡 Nits
Tests
The Praktika reports, fetched with the repository CI-report tool, report 15,225 passed tests, 4,488 skipped, and no failures. No local server binary or build directory was available; the traces above are source analysis, not newly executed reproductions. Performance & SafetyThe empty Final VerdictStatus: ❌ Block Distinguish rejected and unknown commit outcomes, reject unsupported catalogs before publication, and preserve or safely reject truncate histories during full compaction. Preserve standalone-table writability across metadata naming schemes and add focused regression coverage. |
…tion - Route truncate metadata commit through `writeMetadataFileAndVersionHint` so that `metadata/version-hint.text` is updated when `iceberg_use_version_hint=1`. Without this, readers using version-hint lookup remain pinned to pre-truncate metadata, making TRUNCATE invisible. - Change `deleted_records`/`deleted_data_files` parsing from `std::stoi`/`Int32` to `std::stoll`/`Int64` in `MetadataGenerator` truncate summary generation. `std::stoi` throws `std::out_of_range` for tables with more than ~2.1B rows, breaking TRUNCATE on large tables. Signed-off-by: Daniel Q <[email protected]>
If `catalog->updateMetadata()` fails after writing the manifest list and metadata JSON to object storage, both files are now removed and the metadata cache is invalidated. This mirrors the cleanup pattern used in `IcebergStorageSink::initializeMetadata()` and `Mutations::writeMetadataFiles()` to prevent storage leaks and stale cache state on transient failures. Signed-off-by: Daniel Q <[email protected]>
Signed-off-by: Daniel Q <[email protected]>
The test was failing with `ConnectionRefused` to `localhost:8182`. The `BASE_URL_LOCAL_RAW` constant was hardcoded to `http://localhost:8182` instead of using the dynamically assigned port from the cluster fixture. Replace the hardcoded URL with `started_cluster.iceberg_rest_catalog_port`, matching the pattern used in `test_read_in_order_with_pyiceberg.py`. Signed-off-by: Daniel Q <[email protected]>
…ote it On version conflict, `writeMetadataFileAndVersionHint` returns false without writing `storage_metadata_name`. The previous cleanup unconditionally deleted it on any exception, which could remove a metadata file committed by a concurrent writer — corrupting the table. Added `metadata_written` flag set only after `writeMetadataFileAndVersionHint` confirms a successful write. `storage_metadata_name` is removed in cleanup only when `metadata_written=true`. The manifest list is always safe to remove unconditionally since it carries a unique random snapshot ID belonging only to this session. Signed-off-by: Daniel Q <[email protected]>
429ef28 to
9f14372
Compare
Resolve conflict in MetadataGenerator.cpp: upstream replaced the inline `sum_with_parent_snapshot` lambda with the more robust `setSnapshotTotals` helper (which fails on a parent snapshot missing a data total instead of corrupting the summary, and treats missing delete totals as 0). Our branch had added a truncate special-case that zeroes every table-wide total. Keep upstream's `setSnapshotTotals` for the normal write path and re-apply the truncate zero-reset as an explicit `if (is_truncate)` branch, so a truncated table's snapshot summary reports empty `total-*` counters while non-truncate writes benefit from upstream's hardening. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
I discussed with @grantholly-clickhouse offline. The scope of this PR is getting too large and hard to review. We will re-implement as a series of smaller PRs. |
|
Opened PR #133838 to help with the failing CH Inc Sync job. |
Implement
TRUNCATE TABLEfor Iceberg engineTRUNCATE TABLEon any Iceberg-backed table previously threw a hardcodedNOT_IMPLEMENTEDexception inStorageObjectStorage::truncate(). This PR implements it as a metadata-only operation consistent with the Iceberg spec, with full support for REST (transactional) catalog backends.What changed
New virtual interface (
IDataLakeMetadata.h): AddedsupportsTruncate()andtruncate(ContextPtr, ICatalog, StorageID)virtual methods. Default implementation throwsNOT_IMPLEMENTED;IcebergMetadataoverrides both.Delegation (
StorageObjectStorage.cpp): Removed the hardcodedNOT_IMPLEMENTEDblock. Now checksdata_lake_metadata->supportsTruncate()and delegates todata_lake_metadata->truncate().Core truncation logic (
IcebergMetadata.cpp): Implements the full Iceberg truncation workflow:FileNamesGeneratorwith the correct URI format (fulls3://URI for transactional/REST catalogs, bare path otherwise)MetadataGenerator::generateNextMetadata()with newis_truncate=trueparameter, producing a spec-compliant overwrite snapshot with zeroed totals and correctdeleted_records/deleted_data_filesfrom the parent snapshotv<N+1>.metadata.jsonto object storagecatalog->updateMetadata()passing the snapshot objectMetadataGenerator (
MetadataGenerator.cpp/.h): Addedis_truncateparameter togenerateNextMetadata(). When true, setsoperation=overwrite, zeroes cumulative totals, and populatesdeleted_records/deleted_data_filesfrom the parent snapshot summary.Manual Avro OCF serialization (
IcebergWrites.cpp): For the empty manifest list case,avro::DataFileWriteris bypassed entirely. The vendored Avro C++ callswriteHeader()eagerly in its constructor, committing the binary encoder state. Post-constructionsetMetadata("avro.schema", ...)calls corruptStreamWriter::next_causing a NULL dereference onclose(). Additionally, the Avro C++ library strips unknown field properties (includingfield-id) during schema node serialization, causing PyIceberg to reject the manifest list. The OCF header is therefore written directly (~20 lines):[magic][metadata map with full schema JSON][sync marker]. Nocontrib/changes needed. The Avro OCF format is stable and well-specified; the standardDataFileWriterpath is unaffected for non-empty manifest lists.Bug fixes included in this PR:
IcebergStorageSink::initializeMetadata()was passing the full tablemetadata_objecttocatalog->updateMetadata()instead ofnew_snapshot.RestCatalog::updateMetadata()readssnapshot-idfrom its 4th argument — passing the wrong object causedPoco::InvalidAccessExceptionon every INSERT to a REST catalog table.Mutations.cpp::writeMetadataFiles()had the same bug — passingmetadatainstead ofnew_snapshottocatalog->updateMetadata(), breaking allALTER TABLE DELETE/UPDATEon REST catalog tables.RestCatalog::updateMetadata()was silently swallowing HTTP exceptions withreturn false. AddedLOG_WARNINGto preserve diagnostics while keeping the retry contract intact (callers treatfalseas a retryable conflict signal).Test coverage (
test_iceberg_truncate.py)SELECT count()returns 0 from ClickHouse immediately after truncationtable.scan().to_arrow()returns 0 rowsAll 19 integration tests pass across S3, Azure, and local backends.
Changelog category (leave one):
Changelog entry:
Added
TRUNCATE TABLEsupport for the Iceberg database engine. The operation is metadata-only: it generates a new empty snapshot and atomically commits it to the catalog (REST/transactional backends supported). Physical file cleanup is handled by standard Iceberg GC.Documentation entry for user-facing changes
TRUNCATE TABLEis now supported for Iceberg tables backed by a REST catalog. The command clears all visible rows by committing a new empty snapshot to the catalog. It does not physically delete data files — garbage collection of orphaned files is handled by standard Iceberg maintenance operations.Requires
allow_experimental_insert_into_iceberg = 1.Cross-engine clients (PyIceberg, Spark) reading from the same REST catalog will see the empty snapshot immediately after the commit.
Workflow [PR]
Sync PR [sync-upstream/pr/102065]