Skip to content

Fix the Iceberg manifest-list partition summary written for bucket partitions - #119514

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-manifest-list-bucket-partition-summary
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-manifest-list-bucket-partition-summary

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125366
Closes: #118930
Related: #118905

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

The manifest-list field summary that ClickHouse writes for an Iceberg bucket partition carried null bounds next to contains_null = false, which a spec-compliant reader reads as "this field holds no values" and uses to skip the whole manifest, so a filtered scan of such a table returned no rows. A bucket partition field is now described as the Iceberg int the specification gives it, so its bounds are written, and a summary whose bounds cannot be serialized is omitted instead of claiming an empty range, on newly written and on carried-forward manifest-list entries alike.

Description

A field summary with contains_null = false and no lower_bound states that the partition field holds no orderable value, so a manifest evaluator answers ROWS_CANNOT_MATCH and skips the manifest. 26.9 writes exactly that for a bucket spec, because canDumpIcebergStats does not accept the UInt32 that icebergBucket returns. Measured with pyiceberg 0.11.1 on a two-row bucket-partitioned table written by 26.9.1.1629: scan() returns 2 rows, scan(row_filter="s == 'eu'") returns 0. Since #118596 (26.10) the bucket field is Avro long with 8-byte bounds: those filtered reads throw in Spark and PyIceberg (#125366), and Spark ignores ClickHouse's partition-scoped position deletes, so rows removed by DELETE/UPDATE come back (Data lake fuzzer, #128538). Measured on master, two buckets of two data files each: after DELETE WHERE id % 2 = 0 ClickHouse reads 10 rows and Spark 20, after the same UPDATE 20 and 30; with this PR, 10 and 20.

  • ChunkPartitioner publishes the Iceberg field type of a bucket[N] transform, int, and converts the transform result to it. The conversion is exact: N is validated to (0, INT32_MAX] and the result is in [0, N). INSERT, mutations and both compaction writers take their partition types from it, so all of them write int with 4-byte bounds, while UInt32 columns keep the long mapping of [Iceberg spec fix part 2]: Do not store ClickHouse unsigned integers in narrower Iceberg types #118596.
  • generateManifestList no longer publishes an empty-range claim: a tuple with an unserializable bound gets no partitions list (that field is optional), and a list carried forward from the parent snapshot is dropped rather than copied when it makes that claim. Without the second half an affected table keeps republishing its bad summaries through every later INSERT, DELETE and UPDATE. NULL and NaN are unchanged.

#118905's truncate bound width is left out; that issue stays open. year/month/day/hour already get real bounds: #118583 made those transforms return Int32.


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

groeneai and others added 2 commits September 11, 2026 17:28
…rtitions

A manifest-list field summary that says `contains_null = false` and carries no
`lower_bound` states that the partition field holds no orderable value, so a
spec-compliant manifest evaluator (pyiceberg `_ManifestEvalVisitor`, Java
`ManifestEvaluator`) answers ROWS_CANNOT_MATCH and skips the whole manifest. A
filtered external scan of such a table therefore returned no rows while the table
was full of data. Measured with pyiceberg 0.11.1 on a two-row table partitioned by
`icebergBucket(16, s)`: `scan()` gives 2 rows, `scan(row_filter="s == 'eu'")` gives
0. ClickHouse's own reader substitutes infinities for a missing bound, which is why
CI never saw it. Reported as issue ClickHouse#118905; the summary writer reached the INSERT
path in ClickHouse#118796.

Two coupled mistakes produced it.

First, the Iceberg partition field type was taken from the ClickHouse transform
function rather than from the transform. The spec fixes `bucket[N]` as an `int`,
while `icebergBucket` returns `UInt32`, which is outside the accept-list of
`canDumpIcebergStats` even though `getAvroType` already declares it as Avro "int"
and `dumpFieldToBytes` already has a 4-byte arm for it. `ChunkPartitioner` now
publishes `Int32` for a `bucket[N]` field and converts the transform result column
to it before the partition keys and the scatter selector are taken, so the stored
value, the published type and the grouping stay in agreement. The conversion cannot
change a value: `icebergBucket` rejects `N <= 0 || N > INT32_MAX` and returns
`positiveModulo(hash & INT32_MAX, N)`, which is in `[0, N)`. Nullability is carried
through so a `Nullable` source keeps its Avro ["null","int"] union.

Broadening `canDumpIcebergStats` instead was rejected: ClickHouse#118596 moves `UInt32` to the
8-byte branch of `dumpFieldToBytes` and `getAvroType(UInt32)` to "long", so an
admitted `UInt32` bound would become 8 bytes for a 4-byte `int` field, reinstating
the defect fixed in ClickHouse#117571; and that predicate is shared with `canWriteStatistics`,
the per-column data-file gate. Changing the functions' own return types was rejected
too: `icebergBucket` is a general SQL function, so a MergeTree table may use it in
`PARTITION BY`, where `KeyDescription` re-derives the key type from the current
function on every table load while the existing `partition.dat` files hold the old
serialization.

Second, the writer published a contradictory record instead of declining to describe
what it cannot serialize. `generateManifestList` now leaves the optional `partitions`
list out when a tuple holds an orderable value whose bound cannot be written, and
drops a list carried forward from a parent snapshot when that list makes the same
claim. Without the second half, a table written by an affected build keeps
republishing its bad summaries through every later INSERT, DELETE and UPDATE. The
carry-forward check fails closed and never throws: `partitions` is optional, so
dropping it costs a reader one unskippable manifest, whereas throwing would make a
manifest list written by another engine unmergeable. NULL and NaN keep today's
behaviour, which is what the reference implementation writes and is true of them.

The `truncate` bound width, the second half of issue ClickHouse#118905, is deliberately not
fixed here, so the issue stays open. `ChunkPartitioner` passes the transform width as
`UInt64` and `positiveModulo` loses the sign of a negative left operand, so the write
path stores a wrong partition value: an Iceberg table `PARTITION BY
icebergTruncate(10, i32)` holding -1 answers `SELECT count() FROM t WHERE i32 = -1`
with 0. Narrowing that bound first would replace pyiceberg's loud `struct.error` with
a silently pruned manifest, so the width follows the value fix. The `year`, `month`,
`day` and `hour` transforms have the same defect as `bucket` and ClickHouse#118583 already fixes
them by returning `Int32`, which flows through this path with no further change.

Nothing about the encoded partition value or the declared Avro type changes, so no
setting and no `SettingsChangesHistory` entry is involved and existing tables read
back unchanged.

Related: ClickHouse#118905

Co-Authored-By: Claude Opus 5 <[email protected]>
…g path

The published `Int32` partition-key type was asserted nowhere. Deleting the
conversion in `ChunkPartitioner::partitionChunk` left all existing tests green,
because every output downstream of it is identical either way: `Field::safeGet`
permits the `UInt64`/`Int64` slot interchange, `getAvroType` maps both to Avro
"int", and `make_value_datum` handles both Field tags in one arm. So the header
contract could silently become false under a later refactor. The difference is
not observable from SQL, which is what makes a gtest the right tool here: the
two new cases assert the Field's own tag, the only thing that distinguishes the
published type from the transform function's return type.

Writing a real bound is also what first activates ClickHouse's own manifest-list
pruning for a bucket spec, since a missing bound made `ManifestListPruning`
substitute infinities and never skip a manifest. The bucket-transform test now
also reads the table back through a filter, so that path is exercised rather
than assumed.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus a separate cold reviewer pass,
over two gate rounds and one fix round: the first gate round raised the major below, the delta
recheck of the fix round raised nothing. Every finding was fixed; none was overridden.

# Sev Finding Verdict Evidence / action
1 ⚠️ The partition-key conversion in ChunkPartitioner::partitionChunk is asserted by no test: deleting it leaves every serialized output byte-identical (ChunkPartitioner.cpp:138-141) AGREE, fixed @ c0124a5 Field::safeGet permits the UInt64/Int64 slot interchange, and getAvroType maps both source types to Avro int, so the bound, the declared type and the encoded value are all unchanged without the cast. Added IcebergChunkPartitioner unit tests pinning the published Int32 type and the signed Field tag of the returned partition keys, nullable case included, and measured that both redden when the conversion is removed while the three pre-existing cases still pass
2 💡 Nothing exercised a filtered ClickHouse read of a bucket-partitioned table, which is the path this change newly makes prunable AGREE, fixed @ c0124a5 Before this change the manifest-list pruner saw no bound and substituted infinities, so a bucket manifest was never skipped. Added filtered SELECTs to the bucket arm, plus a measured check that a deliberately wrong bound does drop a row, so the assertions are not passive. They also pass without the fix, so they are a guard on the newly live path rather than a regression oracle
3 💡 A test comment described the s == 'nowhere' scan as a control on pruning being active AGREE, fixed @ c0124a5 It is not one: pyiceberg row-filters the rows it decodes as well as the manifest summaries, so that scan returns 0 whether or not a manifest was pruned. Comment corrected; the assertion kept

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding; there are none here.

Two adjacent things I noticed and am deliberately not changing here, for the record:
Compaction.cpp:1297 (the OPTIMIZE history rewrite) passes no partition summaries at all, so
those manifest lists carry no partitions field; that is pre-existing and safe, since an absent
list costs a reader one unskippable manifest and never claims an empty range. And a non-NaN
Float32/Float64 partition value now gets no summary rather than a false one, although a real
IEEE754 bound would be writable, because canDumpIcebergStats is shared with the per-column
data-file statistics gate and widening it reaches much further than this fix should.

Session id: cron:clickhouse-review-slot-9:20260911-173600

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no randomization: CREATE TABLE t (id Int32, v Int32) ENGINE = IcebergLocal(...) PARTITION BY icebergBucket(16, id) + INSERT ... SELECT number FROM numbers(1, 8) writes 6 manifest-list entries, each {contains_null: false, lower_bound: null, upper_bound: null}. The carry-forward half reproduces on a table written by the pre-fix binary.
b Root cause explained? The Iceberg partition field type is read off the ClickHouse transform function rather than off the transform, so icebergBucket's UInt32 falls outside canDumpIcebergStats and no bound is written; the summary writer then publishes contains_null = false with no bounds, which a spec-compliant manifest evaluator reads as "this field holds no orderable value" and answers ROWS_CANNOT_MATCH. ClickHouse's own reader substitutes infinities for a missing bound, so only external readers saw it.
c Fix matches root cause? Yes, at both seams: ChunkPartitioner publishes the spec type (int) for bucket[N] and converts the result column to it; generateManifestList omits a partitions list it cannot fill truthfully. Nothing is widened or suppressed. canDumpIcebergStats is deliberately not broadened: #118596 moves UInt32 to the 8-byte branch and getAvroType(UInt32) to "long", so an admitted UInt32 bound would become 8 bytes for a 4-byte int field, reinstating #117571's bug; that predicate is also shared with the per-column data-file gate.
d Test intent preserved / new tests added? No existing assertion changed or relaxed; all 10 pre-existing parametrizations of the summary test file and #117571's test_ch_write_pyiceberg_read_bound_width still pass. 5 new arms / 8 parametrizations added across two existing files, plus 2 gtest cases pinning the published partition-key type, which is the one part of this change no SQL- or Avro-visible output can distinguish. Each new gtest case was proved to fail when the type conversion is removed, and the 3 pre-existing cases pass in that same arm.
e Both directions demonstrated? Yes. Fresh INSERT: null bounds before, the 4 little-endian bytes of the bucket after. pyiceberg 0.11.1: scan(row_filter="s == 'eu'") returns 0 before and 1 after, with the unfiltered scan at 2 both times as a setup control and s == 'nowhere' at 0 after as proof that pruning is active. Carry-forward: the pre-fix binary writes the table, the fixed binary's ALTER TABLE ... DELETE drops the bad list while the pre-fix binary propagates it. All 8 new parametrizations fail on the unfixed binary.
f Fix is general across code paths? getResultTypes() is the single seam, so every consumer moves together: INSERT summaries, INSERT manifest-entry Avro type (declared "int" before and after) and value, DELETE/UPDATE position-delete manifests, and OPTIMIZE ... MANIFEST ONLY. The invariant hunk covers both manifest-list paths, fresh and carried-forward. Disclosed pre-existing gap, not fixed here: ordinary compaction's manifest-list rewrite (Compaction.cpp:1297) passes no summaries at all, so its entries get partitions = null, which is "no information" and never the empty-range claim.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable(String) bucket source tested for both the value and the NULL row; the published type is re-wrapped with makeNullable, preserving the Avro ["null","int"] union. LowCardinality/Array/Map/Tuple are unreachable (getIcebergType has no case for them and a partition source must be a scalar). The conversion is exact over the whole domain: icebergBucket validates 0 < N <= INT32_MAX and returns a value in [0, N), so no checked cast and no defensive range test is needed. Types whose bounds cannot be serialized (Float32/Float64 measured) are covered by the invariant hunk, with NaN as the negative control.
h Backward compatible? (maintainer-approved exception only) Yes, measured in both directions. Neither the declared Avro type nor the encoded partition value changes; only a bound appears where none was written. No setting, so no SettingsChangesHistory entry. No reader change, so historical 8-byte bounds keep decoding. A MergeTree table written by the pre-fix binary with PARTITION BY icebergBucket(5, x) reads, OPTIMIZEs and accepts new inserts identically under the fixed one. Disclosed behaviour change: an entry whose bounds cannot be serialized, and a pre-fix carried-forward summary, now carry no partitions list, so a reader opens manifests it previously skipped incorrectly.
i Invariants and contracts preserved? The conversion happens before the partition Fields and the scatter selector are taken from the column, so grouping, published type and stored value cannot disagree, and a non-wrapping conversion cannot merge two partitions. getResultTypes() keeps its one-type-per-partition-field arity. The carry-forward validator is read-only and fails closed: it never throws (partitions is optional, so throwing would make another engine's manifest list unmergeable) and it checks the datum's resolved type before every value<T>(). It drops the list on any shape it cannot fully inspect: a non-array non-null datum, a non-record element, a record missing contains_null/lower_bound/upper_bound, a non-boolean contains_null, or a missing lower or upper bound next to contains_null = false. The new pre-pass is the only added early return; the existing unpartitioned early return is unchanged and still covered by its test.

Session id: cron:clickhouse-impl-slot-6:20260911-171100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @SmitaRKulkarni, could you review this? The Iceberg partition field type was taken from the ClickHouse transform function rather than from the transform, so icebergBucket's UInt32 fell outside canDumpIcebergStats and the manifest-list field summary went out with null bounds next to contains_null = false, which a spec-compliant reader treats as an empty range and uses to skip the whole manifest.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9bf2212]

Summary: ✅


AI Review

Summary

The PR publishes Iceberg bucket[N] partition keys as Int32, writes matching four-byte manifest bounds, and removes invalid carried-forward summaries with missing bounds. The focused regression coverage exercises declared Avro types, nullable keys, filtered PyIceberg reads, manifest compaction, and carry-forward sanitization. No actionable findings remain at 9bf22128b89fdd76bacf5b941a79bd49b33f2c67.

Consumers of the changed partition-key representation were traced:

  • IcebergStorageSink and the mutation writers use the converted keys and published types together for grouping, manifest schemas, and bounds.
  • Both compaction writers derive partition types through ChunkPartitioner; existing manifest values use the compatible signed integer carrier.
  • AlterDropPartitionExecutor converts requested partition values to the published type; IcebergPartitionCalculator forwards the converted keys.
  • generateManifestFile and ManifestPartitionSummary accept signed keys; ManifestListPruner decodes the four-byte bounds into its inferred integer type.

The earlier temporal-transform finding is resolved. The author's decision to exclude mixed null/NaN summaries from affected pre-release master builds is accepted: both the multi-partition writer and float-bound support entered 26.11, and preserving valid null/NaN summaries retains pruning. No thread replies or new inline comments are needed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Sep 11, 2026
`getResultTypes()` described itself as "the Iceberg partition field types", but
`icebergPartitionFieldType` corrects only `bucket[N]`. The `year`, `month`, `day`
and `hour` transforms are computed by `toYearNumSinceEpoch`,
`toMonthNumSinceEpoch`, `toRelativeDayNum` and `toRelativeHourNum`, which return
`UInt16` or `UInt32`; the Iceberg specification has no unsigned type, so for those
specs the accessor hands back a ClickHouse type rather than an Iceberg one. A
caller trusting the old wording would have assumed a conversion that does not
happen.

The compaction test's docstring described the encoder serializing the transform's
unsigned result. Compaction reads the published type, so it now serializes the
Iceberg `int` instead. Both reach the same four-byte cast in `dumpFieldToBytes`,
so the bytes written are unchanged.

Comment text only. The rebuilt binary is byte-identical.

Co-Authored-By: Claude Opus 5 <[email protected]>
`OPTIMIZE TABLE ... MANIFEST` rewrites the manifest list through its own
`generateManifestList` call, so it writes field summaries of its own. Nothing
asserted them: the existing compaction test reads the table only unfiltered, which
holds whether a summary carries a correct bound, carries none, or is absent.

The new arm decodes the rewritten manifest list. It pins the four pre-OPTIMIZE
entries and the manifest-list name, because a compaction that silently does nothing
leaves summaries satisfying the same oracle, and it resolves the newest snapshot by
`(last-updated-ms, metadata version)` instead of through `get_last_snapshot`, whose
timestamp-only comparison leaves a same-millisecond tie to `os.listdir` order.

On the parent commit the arm fails on the bound, giving
`[(False, None, None, None)]` where the fix gives
`[(False, None, b'\x06\x00\x00\x00', b'\x06\x00\x00\x00')]`, so compaction was
writing the same empty-range claim as the insert path.

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

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

17 translation units recompiled, 120 s compile time in total, 17 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +6.4 s (+6%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c9a8d62

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Reading from materialized CTE 'a' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID 2467-2c2d) trunk bug, not caused by this branch: it aborts in MemorySource::generate() (ReadFromMemoryStorageStep.cpp:87), a query-planner path this diff does not touch, and the same signature is on 26 unrelated pull requests plus 3 master runs in the last 30 days #117311 (mine, open)
Bugfix validation (unit tests) harness inconclusive, not a test result: contrib/openldap and contrib/xz moved on master after this branch split, so the before-worktree cannot be populated at the merge-base pins. The job says so itself, "This is inconclusive, NOT a reproduction or a refutation". This branch changes no submodule #117948 (mine, open)

Two notes on reading the rest of this run, neither of them an unowned failure:

Mergeable Check and PR are aggregators. They report the two rows above and are not a third
defect; Mergeable Check names only the stress row.

The Bugfix validation (integration tests, amd64/aarch64) FAIL rows are the expected ones. Those
jobs invert their status, so my new regression arms failing on the base binary is exactly what makes
both jobs report green.

On the first row, in the interest of not overstating a link: #117311 is an in-flight fix in this
family, and it attaches the correlated-subquery set builder below the materialized CTE steps so a
set cannot be built before the gate exists. I have not reproduced this particular stress query, so I
have not proven that its sub-shape is the one #117311 closes. If it survives that merge I will
re-own it here rather than let the line go stale.

Session id: cron:our-pr-ci-monitor:20260912-020037

groeneai and others added 2 commits October 3, 2026 12:26
…t-list-bucket-partition-summary

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp
ClickHouse#118583 made the `year`, `month`, `day` and `hour` partition transforms
return `Int32`, so after merging master the claim that they publish an
unsigned type no longer holds.

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

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5d73983

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on 4 master commits today (87 PRs in 24h); the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a parallel replica reads the row-policy table of a SQL SECURITY DEFINER view as default, not as the definer (ACCESS_DENIED); 47 PRs in 24h on this new job #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 95 PRs in 24h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521, #123729 and the fix task above

None of these touches the Iceberg manifest-list partition summaries this PR changes. All 160 checks completed; apart from the expected inverted rows of the two green Bugfix validation (integration tests, *) jobs, CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-173335

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

groeneai and others added 4 commits October 14, 2026 07:53
… filtered in Spark

Since ClickHouse#118596 maps `UInt32` to Iceberg `long`, a `bucket[N]` partition field
whose type comes from the transform's `UInt32` result is declared Avro `long`
with 8-byte manifest-list bounds, and Spark/PyIceberg fail a read filtered on
the bucketed column (ClickHouse#125366). This PR publishes `Int32` for that field, so the
declared type stays `int` on current master as well.

- The no-Spark compaction arm now asserts the declared Avro type of the
  manifests `OPTIMIZE ... MANIFEST` writes, which it previously did not check.
- The Spark compaction test reads the table back filtered on `id = 5`.
  Iceberg projects only `=`/`IN` through `bucket`, so equality is what makes
  Spark evaluate the rewritten partition values and bounds.
- Two comments that said the manifest declares `int` "before and after this
  fix" / "keeps" the union are no longer true on master and are reworded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test inserted 4 batches that each covered all 4 buckets, so the table
already had one manifest per partition, `OPTIMIZE ... MANIFEST` returned early
without writing anything, and Spark read only its own metadata. Every Spark
read in the test, including the filtered one from the previous commit, passed
on master for that reason.

Insert 8 batches instead (same 80 rows), so compaction rewrites the manifests,
and check that it committed a `replace` snapshot before Spark reads the table.
The read filtered on `id = 5` now fails on master and passes with this PR. A
range filter on `id` fails on master too, so equality is not the only predicate
that reaches the rewritten partition values, as the previous commit message
suggested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The docstring described only the encoder exception the test was first written
for. Say what it checks now: compaction writes the bucket field as the Iceberg
`int`, so Spark can read the rewritten table filtered on the bucketed column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the four comment blocks to their invariants and drop the one on where the bucket cast sits.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Test-only round for #125366 (no src/ code change), reviewed by a cold reviewer pass and an independent model (engine: codex).

# Sev Finding Verdict Evidence / action
1 💡 The Spark bucket compaction test's docstring described only the encoder exception it was first written for, not the filtered Spark read it now checks AGREE, fixed @ 31582bd Docstring now states the property: compaction writes the bucket field as the Iceberg int, so Spark can read the rewritten table filtered on the bucketed column

Severity: ❌ blocker / ⚠️ major / 💡 nit.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%. 26.9: a PARTITION BY icebergBucket(16, id) INSERT writes {contains_null: false, lower_bound: null, upper_bound: null}. Master (#118596): the field is declared Avro long with 8-byte bounds, and after OPTIMIZE TABLE ... MANIFEST Spark where("id = 5") throws IllegalArgumentException: Wrong class, expected java.lang.Integer, but was java.lang.Long.
b Root cause explained? The Iceberg partition field type is read off the ClickHouse transform function, so icebergBucket's UInt32 is used for an Iceberg int field. On 26.9 canDumpIcebergStats rejects UInt32, so no bound is written next to contains_null = false, which a manifest evaluator reads as an empty field and prunes. On master #118596 maps UInt32 to long, so the field is declared and bounded as long.
c Fix matches root cause? Yes: ChunkPartitioner publishes the spec type (int) for bucket[N] and converts the result column to it; generateManifestList omits a partitions list it cannot fill truthfully. canDumpIcebergStats is not broadened, and UInt32 columns keep #118596's long.
d Test intent preserved / new tests added? No assertion relaxed. New: no-Spark summary arms (incl. the declared int after OPTIMIZE ... MANIFEST), a pyiceberg filtered-read arm, 2 gtest cases on the published key type, a filtered Spark read after compaction. The Spark compaction fixture now really rewrites (8 manifests for 4 buckets, pinned by a replace snapshot); with the old one OPTIMIZE was a no-op.
e Both directions demonstrated? Yes, on the merge with master d245b78661ac9: #125366's reproducer gives long / 8-byte bounds on master and int / 4-byte bounds with the fix; the Spark arm, the no-Spark summary arms and the pyiceberg bucket arm fail on master and pass with the fix. With the old fixture the replace pin fails (append).
f Fix is general across code paths? getResultTypes() is the single seam: INSERT, DELETE/UPDATE, OPTIMIZE ... MANIFEST, data compaction and ALTER ... DROP PARTITION all use it. The invariant covers fresh and carried-forward manifest-list entries.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable(String) source tested for the value and the NULL row. The conversion is exact (N in (0, INT32_MAX], result in [0, N)). Unserializable Float32/Float64 bounds are covered by the invariant, NaN as the negative control.
h Backward compatible? (maintainer-approved exception only) Against every release the declared type and stored value are unchanged; only a bound appears where none was written. Against unreleased master (#118596) a bucket field goes back from long to int; existing manifests are not rewritten and ClickHouse still reads them. No setting, no reader change.
i Invariants and contracts preserved? The conversion happens before the partition Fields and scatter selector are taken, so grouping, published type and stored value agree. The carry-forward validator is read-only, never throws, and drops a list it cannot fully inspect.

Session id: cron:clickhouse-impl-slot-6:20261014-084100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @SmitaRKulkarni, could you review this? ChunkPartitioner now publishes a bucket[N] partition field as the Iceberg int (converting the UInt32 that icebergBucket returns), so manifest-list summaries get real 4-byte bounds instead of null bounds with contains_null = false (26.9), and on current master the field is no longer declared long with 8-byte bounds (#125366).

…t-list-bucket-partition-summary

# Conflicts:
#	tests/integration/test_storage_iceberg_interoperability_local/test_interoperability.py
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8b1a8d2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / complex_array_creation #0, #1 not from this PR: these queries build arrays of arrays ([[zero], [zero]], [[], [zero]]) and never reach the Iceberg write code this PR changes. Slower by 35% and 39% (157 to 212 ms, 161 to 224 ms). The same two queries were reported slower on arm on 3 other PRs and on master in the last 14 days #128389 (ours, open)
Mergeable Check, PR praktika rollups of the row above #128389 (ours, open)

The Bugfix validation (integration tests) FAIL rows are the expected inversion (the new tests fail on master); both jobs passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261102-173007

…t-list-bucket-partition-summary

Conflict in IcebergWrites.cpp: master (ClickHouse#128880) now aggregates the
manifest-list partition summary over all entries of a manifest
(`ManifestPartitionSummary`, with `bounds_unavailable` per field)
instead of passing one (value, type) pair per field.
`canWritePartitionSummary` now checks `bounds_unavailable`, so a
manifest with any value that has no Iceberg bound serialization still
omits the optional `partitions` field rather than publishing a field
summary without bounds, which readers take as "only nulls or NaNs".
The write loop takes master's form; its `bounds_unavailable` check and
comment are dropped because the guard above already returns early.

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
groeneai and others added 2 commits November 23, 2026 13:50
…t-list-bucket-partition-summary

Conflict in IcebergWrites.cpp, two hunks:
- The summary write loop: master (ClickHouse#129812) only reworded the comment on
  its `bounds_unavailable` check. Kept this branch's form, which has no
  check: `canWritePartitionSummary` already returns early for a manifest
  with such a field.
- The manifest-list carry-forward: master (ClickHouse#130800) rebuilds each count
  in the new list's shape with `copy_count`. Took master's counts and
  kept this branch's guarded copy of `partitions`.

Conflict in ChunkPartitioner.h: master added `[[nodiscard]]` to
`getResultTypes`; kept it together with this branch's comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#129812 the Iceberg writer serializes `Float32`/`Float64` bounds,
including in the manifest-list partition summary, so the tuple holding
1.5 now gets a bounded summary instead of none. No other partition type
that ClickHouse can write lacks a bound serialization any more (`UUID`
partitions are rejected at INSERT), so the test now asserts the real
bound and keeps the NaN case, which still has no bound and must keep its
summary.

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

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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

1 participant