Skip to content

Keep the schema and partition spec when Iceberg OPTIMIZE TABLE rewrites a table - #129564

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:iceberg-optimize-keep-partition-spec
Nov 13, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:iceberg-optimize-keep-partition-spec

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #129498
Related: #123982
Related: #109838

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):

Fixed OPTIMIZE TABLE on an Iceberg table (allow_experimental_iceberg_compaction) committing an empty partition spec and a renumbered schema: a later ALTER TABLE ... DELETE left the rows it matched visible, a second OPTIMIZE TABLE failed with LOGICAL_ERROR, and a table whose field ids are not in column order (for example a column added after a Tuple column) read other columns' values after OPTIMIZE. A data file whose partition tuple has a different number of values than the default partition spec is now refused with a NOT_IMPLEMENTED error before anything is written. Closes #129498.

Description

Data compaction (writeMetadataFiles) commits metadata built by createEmptyMetadataFile(..., partition_by = nullptr, ...): an empty spec 0 and a schema numbered 1..N in column order. The rewritten data files, their statistics and the manifests keep the source field ids and partition spec, so:

The change:

  • writeMetadataFiles copies schemas, current-schema-id, last-column-id, partition-specs, default-spec-id and last-partition-id from the source metadata; last-column-id is raised over all field ids, as ADD COLUMN does for tables written by 26.6 and older.
  • compactIcebergTable checks, before writing any file, that every data file's partition tuple has the default spec's arity, else NOT_IMPLEMENTED. This replaces the LOGICAL_ERROR for tables whose spec changed to another number of fields, and for tables already compacted by an earlier version.

Files of an older spec with equal arity are still rewritten under the default spec (#124114). #109838 copies these keys too, among larger changes.

Validation, all red on master: the stateless test (a DELETE after OPTIMIZE, a second OPTIMIZE, a column added after a Tuple column); Spark cases for DROP PARTITION FIELD (the error, no file written) and ALTER COLUMN region FIRST (rows and partitions after OPTIMIZE, INSERT, DELETE); the existing default-spec-1 Spark case checks that the partition keys are kept.


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

Version info

  • Merged into: 26.11.1.2174-master (included in 26.11 and later)

groeneai and others added 3 commits November 5, 2026 16:42
…ioned table

Data compaction (writeMetadataFiles) built the metadata it commits from
createEmptyMetadataFile(..., partition_by = nullptr, ...), so it committed an
empty spec 0 (no fields, last-partition-id 999) while every rewritten manifest
and the manifest list kept the source table's default spec and its partition
tuples. Every later writer reads the committed spec: INSERT and ALTER ... DELETE
wrote `[]` tuples, so the position deletes never matched the compacted files and
the deleted rows stayed visible, and the next OPTIMIZE read 0 partition columns
from the committed spec while the old files still carried 1-value tuples, which
generateManifestFile reports as LOGICAL_ERROR "Iceberg manifest partition arity
mismatch: 0 partition columns but 1 values" (aborts debug builds). Any second
data OPTIMIZE on a partitioned table hits it; the emptied partition in the issue
is not needed.

writeMetadataFiles now copies partition-specs, default-spec-id and
last-partition-id from the source metadata, so the committed metadata defines
the spec (id, field ids, transforms) the rewritten manifests are written under.
Only the partition keys are copied: schema preservation interacts with how the
rewritten snapshots are stamped with the current schema id and is handled with
its own refusal in ClickHouse#109838.

Data compaction rewrites every data file under the default spec, so a tuple of
another arity cannot be written (a table whose spec another engine changed to a
different number of fields, or a table already compacted by an earlier version).
compactIcebergTable now checks every data file's tuple against the default spec
before writing anything and refuses with NOT_IMPLEMENTED; a missing default spec
is ICEBERG_SPECIFICATION_VIOLATION (master dereferenced a null spec there).
generateManifestFile keeps its LOGICAL_ERROR guards, since its other callers
compute tuples from the spec they pass.

Tests: a stateless test with the issue's two symptoms (a DELETE after OPTIMIZE,
then a second OPTIMIZE), and a Spark integration case (DROP PARTITION FIELD) that
checks the error, the rows, and that the refused OPTIMIZE writes no file.

Closes ClickHouse#129498

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reads apply position delete files whether or not compaction ran, so the
row-count assertions of the test also passed when both OPTIMIZE calls were
silent no-ops. Count the POSITION_DELETE entries of system.iceberg_files
before and after each OPTIMIZE (the pattern of 04815) and require that
there were some before and none after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a changed default spec

`test_optimize_position_delete_other_partition_spec` builds a table whose
default partition spec is 1 (`REPLACE PARTITION FIELD`), the one case where
`partition-specs`, `default-spec-id` and `last-partition-id` all differ from
what `createEmptyMetadataFile` writes. Compare the three keys before and after
`OPTIMIZE`; on master all three change (default spec 1 -> 0, last partition id
1001 -> 999, two specs -> one empty spec 0). The metadata lookup moves into a
helper shared with `test_optimize_refuses_partition_tuple_of_another_arity`.

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

groeneai commented Nov 5, 2026

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

Pre-publication review by an independent model (engine: codex; 4 findings over three rounds) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ An older spec of the same arity is re-stamped under the default spec, so pruning can miss its files DISAGREE (separate defect) The re-stamping code is unchanged by this PR and shows the same wrong pruning on master; refusing such tables would reject input master compacts and that test_optimize_position_delete_other_partition_spec requires. Rewriting each manifest under its source spec is #124114. Disclosed in the description.
2 ❌ Copied specs can bind to another column after drop/add schema evolution DISAGREE Unevolved tables get the same field ids on CREATE and on compaction. On id-shifted tables master already writes this spec into every rewritten manifest header (which the reader uses) and writes the data files with the source ids under the renumbered schema, so no correctly compacted table changes. Schema preservation is #109838.
3 ⚠️ 05516 also passes if both OPTIMIZE calls do nothing AGREE, fixed @ 1c76917 The test now checks that each OPTIMIZE removes the position delete files.
4 ⚠️ No test fails if default-spec-id or last-partition-id stops being copied AGREE, fixed @ 7b97927 test_optimize_position_delete_other_partition_spec (default spec 1) now checks that OPTIMIZE keeps all three keys; it fails on master with all three changed.

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

Session id: cron:clickhouse-review-slot-9:20261105-180600

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's SQL on a debug build of master d7a894a1ce72: the second OPTIMIZE TABLE aborts every time with Iceberg manifest partition arity mismatch: 0 partition columns but 1 values. No emptied partition is needed (DELETE WHERE k = 1, then k = 5, aborts too).
b Root cause explained? writeMetadataFiles commits metadata from createEmptyMetadataFile(..., partition_by = nullptr, ...): an empty spec 0, while the rewritten manifests keep the source spec and 1-value tuples. Later DELETEs use the empty spec and never match the compacted files; the next OPTIMIZE passes 0 partition columns with 1-value tuples to generateManifestFile.
c Fix matches root cause? Yes. The commit now copies partition-specs, default-spec-id and last-partition-id from the source metadata. A pre-flight before any write refuses (NOT_IMPLEMENTED) the tuples that cannot be written under the default spec.
d Test intent preserved / new tests added? New stateless test 05516_iceberg_optimize_keeps_partition_spec_129498 (a DELETE after OPTIMIZE, then a second OPTIMIZE), a new Spark case test_optimize_refuses_partition_tuple_of_another_arity (DROP PARTITION FIELD), and the existing test_optimize_position_delete_other_partition_spec (default spec 1) is extended with assertions only: OPTIMIZE keeps partition-specs, default-spec-id and last-partition-id.
e Both directions demonstrated? Both new tests fail on master (5 rows left instead of 0, then the abort; the Spark case aborts at OPTIMIZE), the extended case fails on master with all three keys changed, and all pass with the fix. The new stateless test passed 50/50 randomized runs.
f Fix is general across code paths? OPTIMIZE ... MANIFEST copies the current metadata, so it keeps the specs. INSERT, mutations and DROP PARTITION build on the current metadata. The only other createEmptyMetadataFile caller is CREATE TABLE, which passes PARTITION BY. generateManifestFile keeps its LOGICAL_ERROR guards: its other callers compute tuples from the spec they pass.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked identity, two fields (identity + icebergBucket), a day transform, unpartitioned, and a Nullable source with NULL values. Format v1 and LowCardinality partition columns fail earlier, on existing checks.
h Backward compatible? (maintainer-approved exception only) Yes. No setting and no format change. The committed metadata matches what CREATE TABLE writes. Inputs that used to throw LOGICAL_ERROR now throw NOT_IMPLEMENTED, before anything is written.
i Invariants and contracts preserved? The committed metadata defines every spec that a live manifest names, and data compaction writes no tuple of another arity. The refusal runs before getOldFiles/writeDataFiles; the Spark case checks that the file list is unchanged.

Session id: cron:clickhouse-impl-slot-41:20261105-152800

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni @scanhex12, could you review this and add the can be tested label so CI runs? Data compaction committed metadata with an empty partition spec while the rewritten manifests kept the table's spec, so later DELETEs missed the compacted files and the next OPTIMIZE hit the partition arity logical error; it now copies partition-specs, default-spec-id and last-partition-id, and refuses a partition tuple of another arity with NOT_IMPLEMENTED before writing anything.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8feebfc]

Summary: ✅


AI Review

Summary

The change preserves schema field IDs and partition specifications when Iceberg data compaction rebuilds metadata, and rejects incompatible partition tuple lengths before writing files. The current code addresses the schema-binding concern raised in the discussion. No new correctness or safety findings; approve with the metadata nit below.

PR Metadata

The selected Improvement category does not match the bug fix: the 26.9 release branch already rebuilds compaction metadata with an empty partition spec and renumbered schema. Replace the category with:

### Changelog category (leave one):
- Bug Fix (user-visible misbehavior in an official stable release)

The required changelog entry is present, specific, and describes the affected operations and the new refusal. No entry replacement is needed.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so runtime tests were not independently repeated. The current Praktika report reports success, but its available per-job responses did not expose individual results for the added tests. The review also uses the focused regression coverage and the author's documented before/after runs; an accessible current per-test report would close this verification gap.
Findings

💡 Nits

  • PR description, changelog category: use Bug Fix as detailed above. This was already raised in the conversation; no duplicate inline comment was posted.
Final Verdict

Status: ✅ Approve. No code changes requested. Correct the changelog category before merging.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8feebfcf4 with master 4a760bb3a (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.

Object file sizes

4 object files changed (+39.55 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp.o 1.00 MiB 1.04 MiB +39.37 KiB (+3.83%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.75, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 14.0 s +9.2 s (+196%)
Compile time of recompiled translation units

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

Job report

@PedroTadim PedroTadim self-assigned this Nov 9, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The fix for #129498 looks right to me. Copying partition-specs, default-spec-id and last-partition-id makes the committed metadata agree with the rewritten manifests, and the arity check runs before any file is written. On a table (a, p) PARTITION BY p with rows 1..4, I ran DELETE WHERE a = 1, OPTIMIZE, DELETE WHERE a = 3, OPTIMIZE. On the CI build of 7b97927 the second DELETE removes its row ([2,4]), the second OPTIMIZE succeeds, and a later INSERT is pruned correctly by p. On master 26.11.1.1642 the second DELETE has no effect ([2,3,4]), and the second OPTIMIZE fails with Iceberg manifest partition arity mismatch: 0 partition columns but 1 values.

One point about the spec being committed now. writeMetadataFiles builds the new schema with createEmptyMetadataFile, which renumbers the top-level columns 1..N in their current order, while the copied spec keeps the source-ids of the source schema. The two agree only while the source's top-level ids are 1..N in column order. A table whose columns were reordered (e.g. Spark ALTER COLUMN p FIRST) or that had a column dropped before the partition column does not satisfy this, and then source-id names another column, or none, in the committed schema. Master already uses that binding for the rewritten manifests (ChunkPartitioner gets the new current_schema). Before, the committed spec was empty, so every later INSERT and DELETE ignored the binding; now they use it. Could the copied fields be remapped through the column names (old source-id to name to new id), or could compaction refuse a table whose ids are not 1..N in order? A drop is not reachable today: after ALTER TABLE t DROP COLUMN b, the OPTIMIZE that follows a DELETE already fails with NOT_FOUND_COLUMN_IN_BLOCK (Not found column in block), on master too.

Also, #109838 carries the same copy in writeMetadataFiles, so whichever is merged second will conflict there.

groeneai and others added 2 commits November 9, 2026 12:18
writeMetadataFiles committed the schema built by createEmptyMetadataFile,
which numbers the top-level columns 1..N in their current order, while
writeDataFiles writes the rewritten files with the source schema's field
ids (its column mapper and the manifest statistics both come from the
source current schema). When the source ids are not 1..N in column order
(a column added after a Tuple column, Spark's ALTER COLUMN ... FIRST),
reads after OPTIMIZE bound the file columns to other columns, and the
copied partition spec's source-id named another column, so OPTIMIZE of
such a partitioned table failed with BAD_GET in the manifest-list
partition summary.

Copy schemas, current-schema-id and last-column-id from the source
metadata together with the partition keys. Remapping the spec through
the column names would leave the data files and statistics on the old
ids, and refusing such tables is not needed once the ids are kept.

Raised in review of ClickHouse#129564.

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

Tables written by 26.6 and older record a last-column-id that does not
count nested field ids. The copied value is raised with
getLastAssignedFieldId, as ADD COLUMN already does, so a writer that
trusts last-column-id cannot reuse an existing id after OPTIMIZE.

The reordered-columns test now checks that OPTIMIZE removed the position
delete, so it cannot pass with a no-op OPTIMIZE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Keep the partition spec when Iceberg OPTIMIZE TABLE rewrites a partitioned table Keep the schema and partition spec when Iceberg OPTIMIZE TABLE rewrites a table Nov 9, 2026
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I took neither option: the compacted metadata now keeps the source schema as well (8c2af16).

The renumbered schema was wrong for more than the spec: writeDataFiles writes the rewritten files with the source field ids (its column mapper, like the manifest statistics, is built from the source current schema). Remapping the spec through the names would have left those files on the old ids. writeMetadataFiles now also copies schemas, current-schema-id and last-column-id, so the copied source-ids and the files' field ids both refer to the committed schema.

Measured on debug builds of master 1d607cb1acf, the previous head 7b97927 and the new head:

  • ClickHouse only: (a Int64, n Tuple(x Int64, y Int64)), then ADD COLUMN p Nullable(Int64) (id 5, after the tuple's 3 and 4), a row (2, (20, 200), 2000) plus a deleted one, OPTIMIZE. Master and 7b97927: the next query in the session fails with Code: 743 ... schema-id 0 is bound to two different schemas, and a fresh process reads (2, (200, 0), NULL). New head: (2, (20, 200), 2000).
  • Your reorder case: Spark PARTITIONED BY (region), ALTER COLUMN region FIRST, a position delete. Master and 7b97927: OPTIMIZE fails with Code: 170 ... Bad get: has String, requested Int64 (source-id 2 is id in the renumbered schema). New head: OPTIMIZE removes the delete, a later INSERT ('c', 4) goes to partition {'c'}, and a later DELETE applies.

Both are tests now: a case in 05516_iceberg_optimize_keeps_partition_spec_129498 and test_optimize_keeps_field_ids_of_reordered_columns. 6aea43a also raises the copied last-column-id over all field ids with getLastAssignedFieldId, as ADD COLUMN does: tables written by 26.6 and older record a too-small value, which the renumbering used to reset.

On #109838: its writeMetadataFiles loop copies every table-level key except the snapshot state, a superset of this hunk, so the conflict resolves by keeping that loop. I'll do it on whichever of the two merges second.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai how is this not a bug fix when the server aborted in the issue?

@groeneai

Copy link
Copy Markdown
Collaborator Author

You're right. I had filed it as Improvement only because the path needs allow_experimental_iceberg_compaction, but the misbehavior is in a stable release: on the official 26.10.2.103 build, the (a, p) PARTITION BY p sequence from your earlier comment leaves row 3 visible after the second DELETE ([2,3,4]), and the second OPTIMIZE throws the same LOGICAL_ERROR (Code 49).

I switched the category to Bug Fix, reworded the changelog entry and put that measurement in the description. The pr-bugfix label and the Bugfix validation jobs follow on the next CI run, since labels are set when a run starts.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 34a5d1a Nov 13, 2026
203 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Nov 19, 2026
…g-insert-column-count-oob-109835

Conflicts with ClickHouse#129564 (keep schema and partition spec in Iceberg `OPTIMIZE TABLE`):
- `compactIcebergTable`: keep master's partition-tuple arity check (`NOT_IMPLEMENTED`) first, then this PR's stricter schema-id and partition-spec guards, sharing one lookup of the default spec.
- `writeMetadataFiles`: this PR copies all table-level keys, which subsumes master's list of keys; keep master's `last-column-id` recomputation after the copy.
- `test_optimize_position_delete_other_partition_spec`: keep this PR's expectation that `OPTIMIZE` is refused, and check that the metadata is unchanged; keep master's new tests.

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 22, 2026
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... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants