Skip to content

Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) - #102065

Open
il9ue wants to merge 79 commits into
ClickHouse:masterfrom
il9ue:feature/iceberg-truncate-upstream
Open

il9ue wants to merge 79 commits into
ClickHouse:masterfrom
il9ue:feature/iceberg-truncate-upstream

Conversation

@il9ue

@il9ue il9ue commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Implement TRUNCATE TABLE for Iceberg engine

TRUNCATE TABLE on any Iceberg-backed table previously threw a hardcoded NOT_IMPLEMENTED exception in StorageObjectStorage::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): Added supportsTruncate() and truncate(ContextPtr, ICatalog, StorageID) virtual methods. Default implementation throws NOT_IMPLEMENTED; IcebergMetadata overrides both.

Delegation (StorageObjectStorage.cpp): Removed the hardcoded NOT_IMPLEMENTED block. Now checks data_lake_metadata->supportsTruncate() and delegates to data_lake_metadata->truncate().

Core truncation logic (IcebergMetadata.cpp): Implements the full Iceberg truncation workflow:

  1. Read current snapshot chain and metadata version
  2. Construct FileNamesGenerator with the correct URI format (full s3:// URI for transactional/REST catalogs, bare path otherwise)
  3. Call MetadataGenerator::generateNextMetadata() with new is_truncate=true parameter, producing a spec-compliant overwrite snapshot with zeroed totals and correct deleted_records/deleted_data_files from the parent snapshot
  4. Write empty Avro manifest list to object storage
  5. Write v<N+1>.metadata.json to object storage
  6. Atomically commit via catalog->updateMetadata() passing the snapshot object

MetadataGenerator (MetadataGenerator.cpp/.h): Added is_truncate parameter to generateNextMetadata(). When true, sets operation=overwrite, zeroes cumulative totals, and populates deleted_records/deleted_data_files from the parent snapshot summary.

Manual Avro OCF serialization (IcebergWrites.cpp): For the empty manifest list case, avro::DataFileWriter is bypassed entirely. The vendored Avro C++ calls writeHeader() eagerly in its constructor, committing the binary encoder state. Post-construction setMetadata("avro.schema", ...) calls corrupt StreamWriter::next_ causing a NULL dereference on close(). Additionally, the Avro C++ library strips unknown field properties (including field-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]. No contrib/ changes needed. The Avro OCF format is stable and well-specified; the standard DataFileWriter path is unaffected for non-empty manifest lists.

Bug fixes included in this PR:

  • IcebergStorageSink::initializeMetadata() was passing the full table metadata_object to catalog->updateMetadata() instead of new_snapshot. RestCatalog::updateMetadata() reads snapshot-id from its 4th argument — passing the wrong object caused Poco::InvalidAccessException on every INSERT to a REST catalog table.
  • Mutations.cpp::writeMetadataFiles() had the same bug — passing metadata instead of new_snapshot to catalog->updateMetadata(), breaking all ALTER TABLE DELETE/UPDATE on REST catalog tables.
  • RestCatalog::updateMetadata() was silently swallowing HTTP exceptions with return false. Added LOG_WARNING to preserve diagnostics while keeping the retry contract intact (callers treat false as a retryable conflict signal).

Test coverage (test_iceberg_truncate.py)

Case Description
1 PyIceberg creates table with 3 rows; ClickHouse truncates via REST catalog
2 SELECT count() returns 0 from ClickHouse immediately after truncation
3 PyIceberg cross-engine validation: table.scan().to_arrow() returns 0 rows
4 Table remains writable: new row inserted via PyIceberg, ClickHouse reads count = 1
5 Restart test: truncate → restart ClickHouse → verify count = 0, insert new row → verify count = 1

All 19 integration tests pass across S3, Azure, and local backends.

Changelog category (leave one):

  • Experimental Feature

Changelog entry:

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 entry for user-facing changes

  • 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 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.

-- Truncate an Iceberg table via REST catalog
SET allow_experimental_insert_into_iceberg = 1;
TRUNCATE TABLE my_iceberg_db.`my_namespace.my_table`;

-- Table is now empty
SELECT count() FROM my_iceberg_db.`my_namespace.my_table`; -- 0

-- Table remains fully writable after truncation
INSERT INTO my_iceberg_db.`my_namespace.my_table` VALUES (1, 'A');
SELECT count() FROM my_iceberg_db.`my_namespace.my_table`; -- 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]

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
```
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9256a8]

Summary: ✅


AI Review

Summary

Reviewed #102065 at b9256a86d102d0c28e0b636fd8c0f646866a2b1f, including the full diff, current implementations, 46 review threads and their replies, and top-level discussion. The PR adds metadata-only TRUNCATE TABLE for Iceberg, including catalog tables using parallel replicas. Four correctness blockers remain. All findings below already have discussion threads; dismissed findings are retained here without duplicate inline comments or reopening those threads.

Findings

❌ Blockers

  • A lost metadata-write response can delete a committed snapshot's manifest list. IcebergMetadata.cpp:934 clears commit_result_unknown and deletes the manifest list whenever writeMetadataFileAndVersionHint returns false. However, writeMetadataFile in Utils.cpp:417 also returns false after transport failures. A catalog-less S3 metadata PUT can succeed before its response is lost, leaving published metadata referencing the manifest list this branch deletes. A successful retry does not repair that retained snapshot. Preserve artifacts until rejection is established by reconciliation, preferably through the shared helper. The family is tracked by Iceberg native writes: one lost response on a metadata.json PUT destroys the table and deletes the committed snapshot's data — an ambiguous commit is treated as a conflict and cleaned up #112081; Do not clean up an Iceberg commit whose outcome is unknown #115390 remains open. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r4517588068] Deferring the shared fix leaves the new truncate cleanup unsafe; the TODO does not classify the outcome.

  • An HTTP retry can turn a successful REST commit into destructive conflict cleanup. IcebergMetadata.cpp:950 treats updateMetadata == false as proof that the snapshot never became live. RestCatalog::sendRequest still uses ordinary HTTP retries (RestCatalog.cpp:1933), and ReadWriteBufferFromHTTP::nextImpl can repeat POST initialization. If the first POST commits and loses its response, the repeated POST fails its old snapshot requirement with HTTP 409. The caller then deletes the first commit's live manifest list. Disable transport retries for this commit or reconcile the proposed snapshot before cleanup. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r3604661264] Returning false only for HTTP 409 does not prove that an earlier transport attempt was rejected.

  • Unsupported Hive catalogs are rejected after publishing empty metadata. IcebergMetadata.cpp:836 accepts every catalog. HiveCatalog is nontransactional and inherits the throwing ICatalog::updateMetadata. On writable S3 storage, truncate first publishes its empty metadata file and can advance an existing version hint, then throws at the catalog call. The unknown-outcome handler preserves those files. Hive readers retain the populated snapshot while direct-path readers can select the empty one despite the failed statement. Reject unsupported catalog types before writing anything, as alterPartition already does. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r4589446891] The thread was resolved silently; the current implementation still has no rejection before publication.

  • Full compaction can resurrect rows after truncate. Compaction.cpp:1067 accepts the new DELETE snapshot, but writeMetadataFiles skips it at line 1140. Concrete trace on a standalone format-version 2 table: append rows 1, 2; delete row 1 using a position-delete mutation; truncate; run OPTIMIZE TABLE with experimental compaction enabled. The retained position-delete file makes plan.need_optimize true. Compaction rewrites the original append with surviving row 2, skips both the mutation and truncate snapshots, and publishes metadata whose current snapshot is that append. Row 2 becomes visible again. A later append instead retains a dangling parent reference to the skipped truncate. Preserve the truncate snapshot and ancestry, or reject such histories before rewriting. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r3669745973] Declaring compaction unsupported does not prevent the current code from accepting and committing this history.

⚠️ Majors

  • Truncating UUID-named standalone metadata can prevent subsequent writes. IcebergMetadata.cpp:872 chooses the filename scheme solely from catalog presence. A direct-path PyIceberg table with only UUID-named metadata and no version hint gets a new v<N>.metadata.json. Subsequent writes reject the mixed directory in getLatestMetadataFileAndVersion. Continue the source naming scheme through the shared generator, or reject the transition before publication. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r4579358736] Other writers sharing this defect does not preserve writability after the new truncate operation; the reply's issue link is still a placeholder.

💡 Nits

  • MetadataGenerator.cpp:278 substitutes zero for missing parent totals, then publishes those values as deleted-records and deleted-data-files. Missing optional totals mean unknown removals, even though the new empty snapshot's totals are correctly zero. Omit unknown removal counters or derive them from manifests; correct the accompanying comment. [dismissed by author -- https://github.com/Implement TRUNCATE TABLE for Iceberg engine (REST catalog support) #102065#discussion_r3599311612] The current code still reports zero removals for populated external snapshots lacking these optional totals.
Tests
  • ⚠️ Add fault coverage where the metadata PUT or REST commit is applied before its response is lost; verify every published snapshot remains readable after cleanup and retries.
  • ⚠️ Add a standalone regression for position-delete mutation → truncate → full compaction, checking current rows and retained snapshot ancestry. Rejecting compaction without changing table state is sufficient if support is deferred.
  • ⚠️ Cover Hive rejection without new metadata or hint changes, and direct-path PyIceberg truncate followed by another write.

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 & Safety

The empty DELETE snapshot's consumers were traced through SnapshotSummary/getHistory (operation parsing), totalRows/totalBytes and IcebergIterator (zero totals and empty lists), subsequent insert/mutation manifest generation (empty parent lists), manifest compaction (empty list below the threshold), and snapshot expiration/file traversal (empty lists contribute no files). Full data compaction drops the snapshot, as described above. Commit cleanup was checked across direct-path, REST, Glue, Unity, Hive, and sibling insert/mutation paths; unresolved shared commit-outcome fixes must preserve artifacts until rejection is known.

Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 8, 2026
…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]>
il9ue added 3 commits April 10, 2026 16:21
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]>
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]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 14, 2026
@grantholly-clickhouse
grantholly-clickhouse force-pushed the feature/iceberg-truncate-upstream branch from 429ef28 to 9f14372 Compare July 14, 2026 21:37
grantholly-clickhouse and others added 5 commits July 16, 2026 11:07
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]>
@asya-ch

asya-ch commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

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.

@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 19, 2026
@asya-ch

asya-ch commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Opened PR #133838 to help with the failing CH Inc Sync job.

This branch has not been deployed

No deployments
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... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants