Skip to content

Write theta-sketch NDV statistics on Iceberg commits - #131249

Merged
murphy-4o merged 25 commits into
ClickHouse:masterfrom
murphy-4o:iceberg/feat/write-ndv-statistics
Nov 21, 2026
Merged

murphy-4o merged 25 commits into
ClickHouse:masterfrom
murphy-4o:iceberg/feat/write-ndv-statistics

Conversation

@murphy-4o

@murphy-4o murphy-4o commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Iceberg tables written by ClickHouse now record per-column NDV statistics (theta sketches in Puffin files, as Spark's compute_table_stats writes them), so use_iceberg_table_statistics_ndv works for them. Enabled by the new experimental setting iceberg_write_table_statistics_ndv (off by default).

Details

  • Every commit (INSERT, ALTER UPDATE / DELETE, DROP PARTITION, OPTIMIZE) writes or carries forward its snapshot's sketches; expire_snapshots removes the expired ones.
  • Columns are sketched with the Puffin layer's PuffinColumnThetaSketch, which hashes values as Spark does, so sketches from either engine union; a snapshot's sketches union with its parent's through the new unionThetaSketches.
  • Not written for REST or Unity catalog tables yet (TODO set-statistics). A statistics failure never fails the commit.
  • Insert cost: about +10–15% CPU, wall time within noise.
  • Limits: a table that had rows before the setting was on, or a promoted column (int → long), gets no NDV until a full OPTIMIZE rewrites its data, which it does only when the table has position deletes; a full OPTIMIZE keeps only the current snapshot's statistics. A command that sketches a table without rewriting it is a follow-up.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.112-master (included in 26.12 and later)

murphy-4o and others added 2 commits November 13, 2026 18:21
Every commit ClickHouse makes to an Iceberg table writes a Puffin file of
apache-datasketches-theta-v1 sketches, one per column, and registers it in
the metadata statistics of its snapshot, as Spark's compute_table_stats does:
INSERT and ALTER UPDATE union the parent's sketches with the written rows,
ALTER DELETE, DROP PARTITION and OPTIMIZE ... MANIFEST keep the parent's,
OPTIMIZE rebuilds them. expire_snapshots drops the statistics of expired
snapshots. Values are hashed as Spark hashes them, through the new
IColumn::computeMurmurHash3Into. Enabled by the experimental setting
iceberg_write_table_statistics_ndv (off by default).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tistics

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp
@scanhex12 scanhex12 self-assigned this Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0d5fab]

Summary: ✅


AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR adds writer-side Iceberg NDV statistics by publishing per-column theta sketches into Puffin statistics files on inserts, mutations, OPTIMIZE, DROP PARTITION, and expire_snapshots, with read-side interoperability against existing Iceberg metadata. Most of the earlier correctness issues look addressed in the current code, but full data-rewrite OPTIMIZE still drops the statistics for retained historical snapshots, so I cannot approve it yet.

Findings
  • ⚠️ Majors
    • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1136] [dismissed by author -- https://github.com/Write theta-sketch NDV statistics on Iceberg commits #131249#discussion_r4609108464] Full OPTIMIZE still rebuilds the metadata from createEmptyMetadataFile, then only writes NDV statistics for the new current snapshot (src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1477). The retained snapshots stay in the rewritten history, but their old statistics / partition-statistics entries are never copied forward, and clearOldFiles then deletes every pre-existing metadata/*.stats object (src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1522). As a result, time-travel reads to retained older snapshots immediately lose use_iceberg_table_statistics_ndv after OPTIMIZE, even though expire_snapshots has not removed those snapshots yet.
      Suggested fix: carry forward the retained statistics / partition-statistics entries when rebuilding metadata_object (replacing only the current snapshot's entry if you want the rebuilt sketch), or otherwise keep those files reachable, and add a regression that reads NDV from an older retained snapshot after OPTIMIZE.
Final Verdict

Status: ⚠️ Request changes
Preserve NDV statistics for retained historical snapshots across full OPTIMIZE (or stop deleting their statistics files), and cover that time-travel case with a focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Nov 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Nov 13, 2026
murphy-4o and others added 3 commits November 14, 2026 20:53
… statistics

The Puffin footer reader stays in `PuffinBlockInputFormat` and now accepts every blob type: the
deletion-vector checks apply only to deletion-vector blobs, so `PuffinMetadata` lists the theta sketch
blobs of Spark and Trino statistics files. `Puffin` still reads deletion vectors only and now checks every
blob's type once, right after the footer, so a `LIMIT` that stops at a deletion vector still rejects a
file that also holds other blobs. `readPuffinFooter`, `readPuffinBlobBytes` and `PUFFIN_MAGIC` are
exported, and `PuffinBlob::toJSON` gives the blob metadata JSON shared by the footer and the table
metadata `blob-metadata`.

`PuffinFile` adds `PuffinReader` (the footer, then blobs decompressed from zstd / lz4 with a 64 MiB cap)
and `PuffinWriter`. The Iceberg NDV statistics write and read their Puffin files through them (replacing
`PuffinThetaSketches`), read the parent file's footer and blob ranges instead of the whole file, and union
only the parent snapshot's own blobs. The theta blob type is one constant, used by the NDV reader too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Take the metadata pointers of SnapshotStatisticsNdv by const reference (clang-tidy performance-move-const-arg).
- Reserve the sketch task slots before scheduling them, so a scheduled task is always tracked.
- expire_snapshots keeps a statistics file that a retained snapshot uses as a deletion-vector container, and lists a file that is both an expired deletion-vector container and an expired statistics file once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp
murphy-4o and others added 4 commits November 15, 2026 11:04
Initialize the Puffin blob compression method for clang-tidy, and revert the hand edit of the generated PuffinMetadata doc: the page regenerates from the format documentation in PuffinBlockInputFormat.cpp, which already has the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e_snapshots

Metadata may spell one object in several ways, e.g. s3:// and s3a://, and
deletion resolves the path, so comparing the raw text could delete a Puffin file
a retained snapshot still uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0d5fab02 with master d8205fe64 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

10 object files changed (+862.66 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/IcebergTableStatisticsNdv.cpp.o new 694.16 KiB +694.16 KiB
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Puffin/PuffinThetaSketch.cpp.o 222.75 KiB 348.57 KiB +125.82 KiB (+56.48%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp.o 631.59 KiB 652.44 KiB +20.84 KiB (+3.30%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

62 translation units recompiled, 488 s compile time in total, 61 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergTableStatisticsNdv.cpp: 6.5 s

Job report

murphy-4o and others added 2 commits November 16, 2026 20:19
Match statistics files with master's storageIdentity in expire_snapshots:
collectExpiredFiles now matches files by storage object, so retained statistics
paths go back into the retained set. Check a Puffin blob's stored length against
the cap before reading it, and bound the zstd window. Add [[nodiscard]] where
modernize-use-nodiscard asks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scanhex12 added a commit that referenced this pull request Nov 16, 2026
…tics writes

Prepares the ground for #131249,
which writes NDV statistics on Iceberg commits:

- `PuffinColumnThetaSketch` is the Theta sketch of one column, with the hashing
  of that PR: values are cast to a type whose `getDataAt` bytes are the Iceberg
  single-value serialization (decimals and `UUID` are encoded explicitly) and
  hashed with the new `IColumn::computeMurmurHash3Into` straight into the hash
  table of an `update_theta_sketch`. The result goes through a `theta_union` and
  gets `p = 1.0`, so it stays byte-identical to Iceberg's sketches. The
  `Puffin` output format and Iceberg statistics writes can both build on it.
- `PuffinBlob::toJSON` and `PuffinReader` (footer, blobs on demand, `zstd` and
  `lz4` blobs) from that PR.
- Blobs of unknown types are listed by `PuffinMetadata` and skipped by `Puffin`,
  as the Puffin specification requires, instead of failing the read.

Related: #131249

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@murphy-4o
murphy-4o marked this pull request as ready for review November 17, 2026 06:21
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 17, 2026
With the setting on for the whole session, the cloud build arms background
compaction on every IcebergLocal table, and clickhouse-local aborts on exit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 17, 2026 11:39

AI review of a later commit does not approve the PR, see the AI Review comment.

murphy-4o and others added 2 commits November 18, 2026 09:22
Use master's Puffin layer (ClickHouse#121982) instead of PuffinFile.{h,cpp}.
- Sketch columns with PuffinColumnThetaSketch; drop the own theta sketch,
  IColumn::computeMurmurHash3Into and its CMake workaround, and put
  minimalTwosComplementOffset back inline in dumpDecimalValue.
- Union snapshot and parent sketches with the new unionThetaSketches in
  PuffinThetaSketch (validation included, a single sketch kept as is), so the
  writer no longer uses DataSketches directly nor needs USE_DATASKETCHES.
- Keep the sketch of a field added after the parent snapshot without an
  initial-default: the parent's rows are all NULL in it.
- expire_snapshots passes the expired statistics files to collectExpiredFiles
  instead of collecting and filtering them separately.
- Drop gtest_puffin_file, which tested master's Puffin reader and writer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…anged type

- Take a parent blob only if the statistics entry's blob-metadata lists it,
  as the readers do.
- Drop the parent sketch of a promoted field (int to long, float to double):
  it hashes the narrower encoding, so a union would inflate the NDV.
- TODO in compaction: the statistics of the retained snapshots, whose files
  clearOldFiles deletes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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
murphy-4o and others added 3 commits November 20, 2026 11:49
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
murphy-4o and others added 2 commits November 20, 2026 21:43
…REST or Unity catalog

The check runs before a commit writes any file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@murphy-4o

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts on this branch.

# Conflicts:
#	src/Core/Settings.cpp
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp
@murphy-4o
murphy-4o enabled auto-merge November 21, 2026 00:57
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 21, 2026 01:25

AI review of a later commit does not approve the PR, see the AI Review comment.

@murphy-4o
murphy-4o added this pull request to the merge queue Nov 21, 2026
Merged via the queue into ClickHouse:master with commit 521c4bc Nov 21, 2026
195 checks passed
@murphy-4o
murphy-4o deleted the iceberg/feat/write-ndv-statistics branch November 21, 2026 04:03
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-experimental Experimental Feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants