Skip to content

Backfill Iceberg identity-partition columns absent from data files - #110231

Closed
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-identity-partition-backfill-110216
Closed

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-identity-partition-backfill-110216

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #110216

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 a bug where an Iceberg identity-partition column that is absent from the data files (its value stored only in the manifest partition tuple, as produced by Hive-partitioned / Microsoft Fabric tables) was read as NULL for every row. The column is now backfilled from the manifest partition value, so SELECT, WHERE and GROUP BY on it return correct results.

Description

Related issue: #110216

When an Iceberg identity-partition source column is not physically stored in the data files (its value exists only in the Iceberg manifest partition tuple, e.g. Microsoft Fabric / OneLake / Apache XTable-virtualized tables), reading the column returned NULL for every row. count() was correct (served from partition statistics) but selecting the column and any WHERE / GROUP BY on it were silently wrong.

Fix:

  • Each data file's identity-partition values are parsed from the manifest partition spec entries whose transform is identity, mapped to the current schema column name, and carried to the read source (IcebergIterator). The read source overwrites the otherwise NULL-filled output column with the per-file constant (StorageObjectStorageSource).
  • Identity-partition columns are excluded from supportedPrewhereColumns(). Otherwise the planner pushes a filter on such a column into PREWHERE, and the format reader reads the absent column as NULL before the backfill runs, dropping every row. With the exclusion the condition is applied as a regular filter above the source, after the backfill. Filters on physical columns still use PREWHERE.
  • The manifest values are serialized to cluster workers behind a new cluster processing protocol version.

Reproduction (a data file with the partition column removed, leaving the value only in the manifest): see the added test tests/queries/0_stateless/04500_iceberg_identity_partition_backfill.sh, which covers projection, filtering under both PREWHERE modes, count(), GROUP BY, multiple identity-partition columns of different types, and a mixed filter over an identity-partition column and a physical column.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Build a partitioned IcebergLocal table, rewrite each data file dropping the partition column so its value lives only in the manifest, then SELECT id, region, val ... WHERE region='East' returns 0 rows (prewhere on) and SELECT id, region, val returns NULL for region. Every time. See test 04500.
b Root cause explained? An identity-partition column present in the Iceberg schema but absent from the data file is NULL-filled by the reader (SchemaProcessor::createColumnConstWithDefaultValue). The manifest partition tuple holds the real value but was used only for pruning. Additionally, a filter on such a column is pushed into PREWHERE, so the native reader reads it as NULL and drops all rows before any backfill.
c Fix matches root cause? Yes. (1) Carry per-file identity-partition values from the manifest to the read source and overwrite the NULL-filled column. (2) Exclude identity-partition columns from supportedPrewhereColumns() so the filter runs above the source, after backfill.
d Test intent preserved / new tests added? New SQL-based test 04500_iceberg_identity_partition_backfill.sh asserts row output (not just count) under both PREWHERE modes, plus projection, count, GROUP BY, multiple partition columns of different types, and a mixed identity+physical filter. No existing test weakened.
e Demonstrated in both directions? Yes. Without the PREWHERE-exclusion the WHERE region='East' (prewhere on) case returns 0 rows; with the fix it returns the 2 matching rows. Chunk backfill fixes projection/off-prewhere; the exclusion fixes on-prewhere. Verified against a real server and clickhouse-local (buildId matched).
f Fix is general, not a narrow patch? Handles any number of identity-partition columns, String and Int types, Nullable partitions (NULL manifest value stays NULL), multi-column partition specs, and mixed WHERE (physical cols still use PREWHERE). Values populated for all files via the manifest, not just the reproduced one.
g Generalizes across inputs / types / wrappers? Verified: String, Int32, Nullable(String) partitions; single and multi-column partition specs; region IS NULL; combined region='East' AND tier=1; mixed region='East' AND val='c'. Non-partitioned / column-present tables unaffected (column still excluded from PREWHERE but data present → correct).
h Backward compatible? Yes. Read-only behavior change (previously-wrong results become correct). Cluster serialization of the new values is gated behind a new DBMS_CLUSTER_PROCESSING_PROTOCOL_VERSION_WITH_ICEBERG_IDENTITY_PARTITION_COLUMNS; older workers negotiate the lower version and skip the field. No on-disk/setting default change.
i Invariants and contracts preserved? Chunk overwrite matches by requested-column position and row count. PREWHERE exclusion only removes columns from the eligible set (correctness-safe; PREWHERE is an optimization). Metadata parse is best-effort: on failure it excludes nothing and falls back to the pre-existing behavior.

Session id: cron:clickhouse-worker-slot-1:20260713-085300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @divanik — could you review? This backfills Iceberg identity-partition columns that are absent from the data files (value only in the manifest tuple, e.g. Fabric/OneLake), and excludes them from PREWHERE so filters on them return correct rows. Fixes #110216.

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e0394be]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR fixes the wrong-results path for Iceberg identity-partition columns that are stored only in the manifest tuple by backfilling them at read time, threading the pinned snapshot through the PREWHERE checks, and adding targeted tests. The core absent-column case is covered, but the current implementation still leaves two regressions: it disables PREWHERE for all identity-partition columns even when the data files still contain them, and the generic proxy forwarding now lets lazy table proxies make the PREWHERE decision from proxy metadata instead of the nested table's live snapshot.

Findings

⚠️ Majors

  • [src/Storages/ObjectStorage/StorageObjectStorage.cpp:441] The new exclusion set is table-wide: every identity-partition source column is removed from supportedPrewhereColumns(), even though many Iceberg tables still materialize that column in the data file. ClickHouse's own writer does exactly that, so PREWHERE region = ... used to be safe on those tables. After this change the direct table starts rejecting that query with ILLEGAL_PREWHERE, and row-policy / auto-PREWHERE pushdown is disabled through wrappers for no correctness reason.
    Suggested fix: distinguish identity columns that really need manifest backfill from identity columns that are still read physically, and exclude only the former from the PREWHERE contract.

  • [src/Storages/StorageProxy.h:28] StorageProxy::supportedPrewhereColumns now forwards the caller's snapshot into the nested storage, but StorageProxy::getStorageSnapshot does not create a nested-storage snapshot. For StorageTableProxy that snapshot can still be the cached CREATE TABLE schema, while StorageTableProxy::read later rebuilds a fresh nested snapshot from the live table before executing. That reintroduces analysis/execution divergence for lazy-loaded Iceberg tables after external schema changes or query-scoped snapshot selection.
    Suggested fix: make StorageTableProxy build a nested snapshot for the PREWHERE check the same way StorageTableFunctionProxy already does, instead of inheriting the generic proxy forward.

Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 364/391 (93.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@fm4v
fm4v requested a review from scanhex12 July 13, 2026 09:31
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed both review findings in eb6b75d (spec-evolution exclusion across all live specs; row-level-security kept out of in-source pushdown). cc @scanhex12 @divanik

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Both findings reproduce on demand. A: after evolving to a new default spec that drops region's identity transform, SELECT ... WHERE region='East' on old-spec files returns 0 rows. B: a USING region='East' row policy returns 0 rows / count 0.
b Root cause explained? A: getIdentityPartitionColumns matched only default-spec-id, so a column that lost its identity transform in the new spec stopped being excluded from PREWHERE, and old-spec files that omit it read NULL then get dropped. B: the planner pushed the row policy into the in-source row_level_filter path whenever supportsPrewhere(), so it evaluated against the reader's synthetic NULL before the backfill.
c Fix matches root cause? Yes. A: iterate ALL partition-specs (dedup by name). B: push the policy in-source only when every referenced column is in supportedPrewhereColumns() (identity columns are already excluded there).
d Test intent preserved / new tests? Yes. Two regressions added to 04500 covering exactly A and B; existing assertions unchanged.
e Both directions? Yes. Both new cases FAIL on the pristine binary (0 rows) and PASS with the fix (rows 1,3 / count 2). Verified by reverting+rebuilding.
f Fix general, not narrow? Yes. B is fixed at the pushdown decision, so it also protects hive-partition and any other column a storage reports as prewhere-unsupported, and isNull()-style policy predicates.
g Generalizes across inputs? Yes. Covered single- and multi-column identity partitions; String and Int32 identity columns already in the test; policy checked under prewhere on and off.
h Backward compatible? Yes. No format/setting change. Storages returning nullopt from supportedPrewhereColumns() (MergeTree) skip the new check and behave exactly as before.
i Invariants preserved? Yes. When a column IS prewhere-supported the pushdown path is unchanged; only columns that were always unsafe to push now stay in WHERE.

Session id: cron:clickhouse-worker-slot-6:20260713-102400

@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the two new bot findings on 9063d55.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Finding D: gtest IcebergObjectSerializableInfoIdentityPartitionColumnsFailClosedOnOldProtocol deterministically fails without the fix (no throw) and passes with it. Finding C is a concurrent-commit race; not deterministically reproducible via a stateless test without heavy failpoint plumbing between snapshot-pin and analysis, so it is covered by the pinned-state threading plus the existing spec-evolution/backfill regressions confirming behavior is preserved.
b Root cause explained? C: getIdentityPartitionColumns re-fetched the latest metadata via getRelevantState(), so a commit that renamed/dropped the identity source column after the query pinned its snapshot made the exclusion set diverge from the pinned snapshot, letting the planner push the old column into PREWHERE and reintroduce the NULL/drop bug. D: the v9 identity_partition_columns payload was version-gated but silently omitted for protocol-8 workers, so an old worker read the absent column as NULL and returned wrong rows.
c Fix matches root cause? C: derive the exclusion set from the pinned datalake_table_state (threaded through getIdentityPartitionColumns), fall back to a fresh fetch only when nothing is pinned. D: fail closed with UNKNOWN_PROTOCOL when the payload is non-empty and the worker protocol is too old, mirroring read_source_index.
d Test intent preserved / new tests added? Existing stateless sections (backfill, spec-evolution, row-policy) unchanged and still pass. Added two gtest regressions: identity_partition_columns round-trip and the old-protocol fail-closed throw.
e Both directions demonstrated? Finding D gtest: FAILS on the pristine binary (Build ID 926d295, no throw -> FAIL()), PASSES after the fix (7/7 in the suite). Stateless test passes with the Finding C fix.
f Fix is general across code paths? C: the pinned-state parameter is threaded through the whole getIdentityPartitionColumns chain (IDataLakeMetadata / StorageObjectStorageConfiguration / DataLakeConfiguration / IcebergMetadata) and the single caller supportedPrewhereColumns(). D: the sender-side check sits at the one serialization site; the read_source_index sibling already fail-closes.
g Fix generalizes across inputs? C: exclusion set already spans all live specs and all identity source columns (any type). D: the throw fires for any non-empty identity_partition_columns regardless of column count/type; empty stays backward-compatible (verified by the no-throw case in the gtest).
h Backward compatible? Yes. New behavior is gated behind the existing v9 protocol bump; older-protocol serialization now fails closed rather than silently downgrading (a wrong-results bug), matching the established read_source_index policy. No setting default or on-disk format change.
i Invariants and contracts preserved? C: the query now observes one coherent pinned snapshot for both file iteration and PREWHERE exclusion (the invariant the storage pins the snapshot to guarantee). D: upholds the cluster-protocol contract that correctness-critical payloads are never silently dropped.

Session id: cron:clickhouse-worker-slot-4:20260713-164500

cc @scanhex12 @divanik

@groeneai

Copy link
Copy Markdown
Collaborator Author

Also fixed a PR-caused regression in test_writes_field_partitioning (0 failures on master over 9424 runs; deterministic on this PR across every sanitizer build). Root cause: the backfill fed the manifest partition value to convertFieldToType, but Iceberg stores partition values in physical encoding (timestamp as int64 microseconds, date as int32 days). For scale-backed target types (DateTime64, Time64, Decimal) that raw integer overflowed with DECIMAL_OVERFLOW. Fix: for those types the tick is already the column's internal value, so the column is built by inserting it as a DecimalField with the target type's scale; other types keep the normal value conversion. Regression coverage added to 04500_iceberg_identity_partition_backfill (temporal/large-int partitions absent from the file, and partitions present in the file).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local: create an IcebergLocal table partitioned by a DateTime column, drop it from the parquet, SELECT -> DECIMAL_OVERFLOW every time.
b Root cause explained? Iceberg stores the timestamp partition value as int64 microseconds (1756298096000000). convertFieldToType(Int64, DateTime64(6)) treats the integer as a logical value and multiplies by the scale -> overflow.
c Fix matches root cause? Yes. For scale-backed types (tryGetDecimalScale non-empty) the manifest integer is already the internal tick, so it is inserted as DecimalField<Decimal64>(tick, scale) rather than value-converted.
d Test intent preserved / new tests added? Existing sections unchanged. Added: temporal/large-int identity partitions absent from the file (was overflow); identity partitions present in the file (the test_writes_field_partitioning layout).
e Both directions demonstrated? FAILS on pristine (Build ID 926d295, DECIMAL_OVERFLOW), PASSES with fix (Build ID f9e0b16). Full 04500 stateless test passes on a real server.
f Fix is general across code paths? Single backfill site. The guard covers all scale-backed target types (Decimal, DateTime64, Time64) via tryGetDecimalScale, not just DateTime64.
g Fix generalizes across inputs? Verified for DateTime/DateTime64, Date/Date32, Int64/UInt64 (both Int64 and UInt64 Field kinds handled), Decimal, String, and absent-vs-present-in-file.
h Backward compatible? Yes. Read-path only; corrects wrong/overflowing output, no format or setting change.
i Invariants and contracts preserved? Yes. The produced column matches the requested column type (verified: no TYPE_MISMATCH); block structure unchanged; other types keep the original conversion path.

Session id: cron:clickhouse-worker-slot-4:20260713-164500

@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the three review findings (commits 2810977 + ba805a3): the snapshot-derived PREWHERE exclusion, the old InterpreterSelectQuery row-policy path, and fail-closed on an unresolvable identity-partition set.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for the old-analyzer row policy: SELECT ... FROM iceberg_tbl SETTINGS enable_analyzer = 0 under a row policy on an identity-partition column raised ILLEGAL_PREWHERE / dropped rows before the fix; passes after. The concurrent-commit snapshot race is a TOCTOU and is not deterministically reproducible in a stateless test; it is fixed structurally by routing the exclusion off the pinned storage_snapshot->metadata.
b Root cause explained? (C) supportedPrewhereColumns() re-fetched mutable storage-global metadata, so a concurrent commit between analysis (snapshot pin) and this call could flip the exclusion set. (386) The old ISQ path populated row_level_filter / built PREWHERE aliasing on supportsPrewhere() alone, bypassing the column gate. (390) catch(...) return {} was fail-open: any metadata read error re-enabled the wrong-results path.
c Fix matches root cause? Yes. (C) thread the query's pinned snapshot into supportedPrewhereColumns() and derive from storage_snapshot->metadata. (386) add canPushRowPolicyToSource() mirroring PlannerJoinTree and gate all three old-path sites. (390) throw instead of return {}.
d Test intent preserved / new tests added? Existing 04500 assertions unchanged; added row-policy-on-identity-column run under enable_analyzer = 0.
e Both directions demonstrated? Yes. Old-analyzer row-policy query threw ILLEGAL_PREWHERE on the pre-gate binary (build 45c3450); returns only region='East' rows (and count 2) after (build 78d489a). Full 04500 diff-clean pass on the fixed binary.
f Fix is general across code paths? Yes. The snapshot is threaded into every supportedPrewhereColumns() caller (new + old analyzer, optimizePrewhere, CollectTableExpressionData) and forwarding overrides (StorageAlias/StorageDummy/StorageURL); the row-policy gate covers both analyzer paths; fail-closed lives at the single resolution point.
g Fix generalizes across inputs? Applies to any identity-partition column regardless of type (the exclusion is name-based, unaffected by Nullable/LowCardinality wrappers), any WHERE/row-policy predicate, and both analyzers.
h Backward compatible? Yes. New virtual param defaults to nullptr (falls back to the prior fresh-fetch behavior); no setting/format/protocol change. Fail-closed turns a former silent-wrong-result into a loud error only when metadata is genuinely unreadable.
i Invariants and contracts preserved? Yes. supportedPrewhereColumns() still returns the PREWHERE-safe column set; the row policy is enforced exactly once (in-source when safe, else above the source via FilterStep); no lock/ownership changes.

Session id: cron:clickhouse-worker-slot-7:20260713-180900

Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the Merge-over-Iceberg PREWHERE finding (commit 03cd4e9). cc @scanhex12 @divanik

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Merge over an IcebergLocal child with an identity-partition column absent from the data files, then ... PREWHERE region='East' through the wrapper. On pristine it is silently pushed to the child and returns zero rows; deterministic.
b Root cause explained? StorageMerge::supportedPrewhereColumns computed the PREWHERE-safe set from same-name/same-type matching only, never consulting children. So an identity-partition column the child (StorageObjectStorage) excludes was re-marked safe at the Merge level. ReadFromMerge::createPlanForTable forwards the built prewhere_info straight into each child storage->read, so the child never re-rejects it, and the filter runs in the reader ahead of the manifest backfill (reads synthetic NULL, drops rows).
c Fix matches root cause? Yes. The wrapper now intersects its candidate set with each child's own supportedPrewhereColumns(child_snapshot), so a column any child excludes stays out of Merge-level PREWHERE.
d Test intent preserved / new tests added? New regression in 04500_iceberg_identity_partition_backfill.sh: Merge + IcebergLocal, asserting explicit PREWHERE on the identity column is rejected (ILLEGAL_PREWHERE) through the wrapper, as it already is on the table directly. No existing assertion weakened.
e Both directions demonstrated? Yes. Pristine (Build ID d7b8777): NO_ERROR_WRONG (silent empty) -> test FAILS. Fixed (Build ID b32debe): ILLEGAL_PREWHERE -> test PASSES. Both on Build-ID-verified binaries.
f Fix is general across code paths? Yes. The intersection applies to every child in the Merge, any storage that overrides supportedPrewhereColumns (hive-partition columns get the same protection). Children returning nullopt (plain MergeTree) add no exclusion, so non-object-storage children are unaffected.
g Fix generalizes across inputs? Covered by the existing same-name/same-type loop plus the per-child intersection; the exclusion is keyed off the child's own reported set, so it holds for any identity-partition column type the child excludes.
h Backward compatible? Yes. No setting, format, or wire change. Only tightens which columns are eligible for Merge-level PREWHERE (correctness), never loosens.
i Invariants and contracts preserved? Yes. supportedPrewhereColumns still returns a subset of the Merge columns; the per-child call passes the child's own snapshot (getStorageSnapshot(child_metadata, context)), matching the non-defaulted signature every other caller uses.

Session id: cron:clickhouse-worker-slot-0:20260714-005300

Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the three latest clickhouse-gh[bot] review findings (commit bd99f17).

  • MaterializedView wrapper (StorageMaterializedView.cpp): FIXED. supportedPrewhereColumns now delegates to the target's own supportedPrewhereColumns(target_snapshot) and intersects, so an identity-partition column the target excludes is not re-marked PREWHERE-safe through the MV. Regression added to 04500.
  • LowCardinality peel (StorageObjectStorageSource.cpp:569): NOT ACTIONABLE. The described fallback is unreachable: LowCardinality(DateTime64/Time64/Decimal...) and LowCardinality(Nullable(DateTime64)) are rejected at type-parse time (ILLEGAL_TYPE_OF_ARGUMENT). No valid schema reaches the branch; bare/Nullable scale-backed types are already peeled by removeNullable. Not adding a speculative change without a reproducer (details in-thread).
  • Merge snapshot-coherency (StorageMerge.cpp:384): the residual concurrent-metadata-change window is the pre-existing, explicitly-accepted StorageMerge race documented at canMoveConditionsToPrewhere (lines 325-330, "Store tables inside StorageSnapshot" TODO), uniform across all engines. This PR strictly narrows the hole (the wrapper now consults children at all). Closing the race requires the Merge-snapshot-pinning refactor, a separate change (details in-thread).
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT ... FROM mv PREWHERE region='East' over an MV on an IcebergLocal target whose region identity-partition column is absent from the data files. Pristine b32debe returns zero rows silently; the query should return rows 1,3.
b Root cause explained? StorageMaterializedView::supportedPrewhereColumns computed the PREWHERE-safe set from view/target same-name+same-type matching only, never consulting the target's own supportedPrewhereColumns. The IcebergLocal target excludes an identity-partition column (backfilled from the manifest after the reader runs); the MV re-marked it PREWHERE-safe, so the predicate was pushed below the backfill in the target reader, evaluated against synthetic NULL, and dropped matching rows.
c Fix matches root cause? Yes. The MV now delegates to target->supportedPrewhereColumns(target_snapshot) and intersects, so any column the target rejects stays out of MV-level PREWHERE.
d Test intent preserved / new tests added? New regression in 04500_iceberg_identity_partition_backfill.sh: explicit PREWHERE on the identity-partition column through an MV over IcebergLocal must be rejected (ILLEGAL_PREWHERE). No existing assertions weakened.
e Both directions demonstrated? Yes. Pristine b32debe: NO_ERROR_WRONG + zero rows (bug present). Fixed be8e452: ILLEGAL_PREWHERE and the full 04500 test passes (1 passed, 0 failed).
f Fix is general across code paths? Yes. The sibling wrappers were audited by the bot across this review series: StorageMerge (intersect with children, prior commit 03cd4e9) and the direct IcebergLocal path (original PR). MV was the remaining wrapper; now covered.
g Fix generalizes across inputs? The MV delegation is type-agnostic (it forwards the target's exclusion set regardless of column type). The related LowCardinality-input concern (StorageObjectStorageSource) was verified non-reproducible: LowCardinality(scale-backed) is an invalid type, so no input matrix entry reaches that path.
h Backward compatible? Yes. No setting/default/format change. The MV only excludes MORE columns from an internal PREWHERE optimization when the target rejects them; results are unaffected for targets that don't exclude anything (nullopt adds no exclusion).
i Invariants and contracts preserved? Yes. supportedPrewhereColumns returns a subset of the view's columns; intersecting with the target's subset preserves that. getStorageSnapshot(target_metadata, context) is the same construction already used elsewhere in this file (e.g. getQueryProcessingStage). No lock/lifetime change.

Session id: cron:clickhouse-worker-slot-1:20260714-030800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. Failpoint datalake_simulate_uninitialized_metadata forces the unresolved-metadata path; WHERE region='East' returns empty (rows dropped) and explicit PREWHERE region='East' fail-opens (no error) on the pre-fix binary, every run.
b Root cause explained? Cold/reattached data lake table reached through an MV/Merge wrapper has current_metadata == nullptr at analysis (wrapper refreshes child metadata only later, at read). getIdentityPartitionColumns() returns {}, so supportedPrewhereColumns() re-marks the identity-partition column PREWHERE-safe -> predicate pushed below the manifest backfill -> reads synthetic NULL / drops rows.
c Fix matches root cause? Yes. Fail closed: when a data lake config has unresolved metadata, supportedPrewhereColumns() returns an empty set (nothing PREWHERE-safe) rather than the full set, so the predicate cannot be pushed below the backfill until metadata resolves.
d Test intent preserved / new tests added? New tests only; no existing assertion weakened. Added a cold-metadata section to 04500.
e Demonstrated both directions? Yes. Pristine-guard binary (1a285c4): auto-WHERE empty + PREWHERE fail-open. Fixed binary (856a42d): auto-WHERE returns rows 1,3 + PREWHERE rejected ILLEGAL_PREWHERE. Full 04500 passes on the fixed binary.
f Fix general, not a narrow patch? Yes. The fail-closed guard lives in the shared StorageObjectStorage::supportedPrewhereColumns() and a base-class hasInitializedMetadata() predicate, so it covers all data lake engines (Iceberg/Delta/Hudi/Paimon) and every wrapper (MV/Merge/Alias/URL) that delegates into it, not only the reported MV case.
g Generalizes across inputs/types? Yes. The guard keys off "metadata unresolved", independent of column type or partition transform; it excludes the whole column set conservatively, so all identity/backfilled columns are covered.
h Backward compatible? Yes. No setting/format/protocol change. Behavior differs only for a data lake table whose metadata is not yet resolved at wrapper analysis (previously wrong results); non-data-lake tables and the warm direct path are unchanged.
i Invariants preserved? Yes. supportedPrewhereColumns still returns a subset of real columns; nullopt vs empty-set semantics respected (empty = nothing PREWHERE-safe). hasInitializedMetadata() is const and never forces initialization, so the analysis path stays side-effect-free.

Session id: cron:clickhouse-worker-slot-1:20260714-044200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed both clickhouse-gh[bot] findings from the 05:43Z review in 98e5057.

Finding G (Decimal32 BAD_GET): scale-backed identity-partition backfill now wraps the manifest tick in a DecimalField of the target column's own width. Finding H (MV snapshot-coherency): StorageMaterializedView::supportedPrewhereColumns refreshes the target's external metadata at analysis, mirroring readImpl.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? G: yes, backfillIdentityPartitionColumn with a Decimal32 type + Int64 tick throws BAD_GET on demand (unit test). H: coherency gap verified in source (analysis reads cached target metadata, readImpl refreshes); no deterministic single-process SQL repro possible.
b Root cause explained? G: ColumnDecimal<T>::insert calls Field::safeGet<T>(); Decimal64/DateTime64/Time64 share Field tag Decimal64 but Decimal32/128/256 have distinct tags, so the hard-coded DecimalField<Decimal64> mismatched the column. H: getInMemoryMetadataPtr does not refresh the data lake state; only updateExternalDynamicMetadataIfExists runs update()+setDataLakeTableState, so the analysis-time PREWHERE decision could use stale target metadata.
c Fix matches root cause? Yes. G: dispatch the DecimalField on the target decimal width. H: refresh the target metadata at analysis, mirroring readImpl.
d Test intent preserved / new tests added? Yes. New gtest_identity_partition_backfill.cpp (4 cases). Existing 04500 sections unchanged and still pass.
e Demonstrated in both directions? G: unit test throws Bad get: has Decimal64, requested Decimal32 on the pre-fix helper, passes for all four widths after. H: full 04500 passes; no isolated A/B feasible (see a).
f Fix is general, not a narrow patch? Yes. G: all four decimal widths + Nullable inner type + DateTime64/Time64 covered; non-scale types keep convertFieldToType. H: applies to any data lake MV target; no-op for non-data-lake.
g Generalizes across inputs/wrappers? Yes. G covers Decimal32/64/128/256, Nullable(Decimal*), DateTime64, Time64, and the plain-integer path.
h Backward compatible? Yes. No format/setting/default change; behavior only corrected.
i Invariants/contracts preserved? Yes. G: DecimalField scale/width now matches the column's ColumnDecimal<T>. H: PREWHERE-exclusion decision and the read now observe the same refreshed target snapshot.

Session id: cron:clickhouse-worker-slot-1:20260714-060600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8c50520

Every failure below has an owner: a fixing PR, or CH Inc sync (exempt).

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) — Server died / Unknown error crash (chronic; 11 master + 20+ unrelated PRs / 30d; interrupted batch includes 03915_exchange_tables_race) #109747 (ours, open) — Int256*Float64 partial-result LOGICAL_ERROR on concurrent EXCHANGE TABLES type-swap
Mergeable Check / PR rollup of the above #109747 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

The prior PR-caused flaky check TOO_LONG on our new test 04500_iceberg_identity_partition_backfill was fixed on this head (added long tag, 8c50520). No PR-caused failure remains.

Session id: cron:our-pr-ci-monitor:20260714-160000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8c5052082307ce19262ad61529e18e42efc96708

All non-exempt checks have finished. Every failure has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error flaky server-died in the coverage DBReplicated+WasmEdge shard (157 PRs / 14d, unrelated to this Iceberg diff) a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
Stateless tests (*, flaky check) / 04500_iceberg_identity_partition_backfill (older SHA 98e5057) flaky-check on our new test — PASSES on current HEAD 8c50520 across all 5 flaky-check sanitizers resolved on current HEAD (no longer failing)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260716-073000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the clickhouse-gh[bot] finding: exclude Iceberg identity-partition columns from PREWHERE through the Buffer and Proxy wrappers (the last two wrappers not yet covered after Merge/MaterializedView). Pushed 2e967c2.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT ... FROM <Buffer over IcebergLocal> PREWHERE region = 'East' where region is an identity-partition column absent from the data files. Pristine binary: returns 0 rows silently (NO_ERROR_WRONG); it must be ILLEGAL_PREWHERE.
b Root cause explained? StorageBuffer forwards supportsPrewhere() to the destination but never overrides supportedPrewhereColumns() (IStorage default = nullopt = all columns PREWHERE-safe), and read() forwards prewhere_info/row_level_filter straight into destination->read(). StorageProxy inherits the same unrestricted default and forwards query_info into the nested read. So the identity-partition column is re-marked PREWHERE-safe at the wrapper, the predicate is pushed below the manifest backfill in the child reader, and rows are dropped.
c Fix matches root cause? Yes. StorageBuffer::supportedPrewhereColumns delegates to the destination's own set and intersects with the same-name/same-type (conversion-compatible) column set; StorageProxy::supportedPrewhereColumns delegates to the nested storage's set. Mirrors the Merge/MaterializedView intersection already in this PR.
d Test intent preserved / new tests added? New regression in 04500: Buffer-over-IcebergLocal, explicit PREWHERE on the identity column must be rejected (ILLEGAL_PREWHERE). No existing assertions weakened.
e Both directions demonstrated? Yes. Pristine binary d2077fa2: Buffer section NO_ERROR_WRONG, test FAILs. Fixed binary bea78a2c: ILLEGAL_PREWHERE, full 04500 PASSES.
f Fix general across code paths? Yes. StorageProxy covers StorageTableProxy, StorageTableFunctionProxy, and the URL scheme dispatch (all its subclasses). Combined with the Merge/MaterializedView fixes, every prewhere-forwarding wrapper now consults the child.
g Generalizes across inputs? The exclusion is derived from the child's own supportedPrewhereColumns, which already handles the full identity-partition column type matrix and the cold/unresolved-metadata fail-closed case; the Buffer intersection is on name+exact-type so no wrapper-specific type gap is introduced.
h Backward compatible? Yes. No setting, format, or on-disk change. Only narrows which columns a wrapper reports as PREWHERE-safe; a destination returning nullopt (all safe) is unchanged, so non-data-lake destinations behave exactly as before.
i Invariants and contracts preserved? supportedPrewhereColumns contract (nullopt = unrestricted, concrete set = whitelist) upheld: no destination -> nullopt (matches supportsPrewhere()==false); otherwise a concrete intersected whitelist. No lifetime/ownership or concurrency contract touched.

Session id: cron:clickhouse-worker-slot-0:20260717-170900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2aad5a0

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / 8 tests (03915_exchange_tables_race, 00943_mv_rename_without_inner_table, 03784_h3_invalid_inputs, 04306_dictionary_sources_documentation, 02100_multiple_hosts_command_line_set, 00228_shard_quantiles_deterministic_merge_overflow, 03006_join_on_inequal_expression_fast_2, "Unknown error") server-death cascade in the amd_llvm_coverage s3 job (server aborted mid-job -> Connection refused (localhost:9000) NETWORK_ERROR 210 + Lost connection to server); all 8 are victims of one server death, not real per-test failures; unrelated to this Iceberg PR fixing PR #109747 (ours, open)

The PR-caused Fast test failure (00910_buffer_prewhere_different_types) from the previous head 2e967c2 was fixed in this PR @ 2aad5a0 (StorageBuffer::supportedPrewhereColumns now delegates to the destination and stays unrestricted when the destination imposes none).

Session id: cron:our-pr-ci-monitor:20260718-013000

@@ -0,0 +1,393 @@
#!/usr/bin/env bash
# Tags: no-fasttest, long

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai could you please overwrite this test as integration?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Replaced the stateless test with a Spark integration test: tests/integration/test_storage_iceberg_with_spark/test_identity_partition_backfill.py. It writes a real hive-partitioned Iceberg table, then rewrites the data files to drop the identity-partition column (Spark writes it into the files, so we strip it and assert it is absent) so the value lives only in the manifest tuple. Covers backfill, WHERE/PREWHERE, count, GROUP BY, spec evolution, and a row policy on the identity column.

{
/// Test-only: emulate a cold / reattached table whose metadata is not yet resolved at
/// wrapper analysis time, so the fail-closed PREWHERE path reproduces deterministically. See #110216.
fiu_do_on(FailPoints::datalake_simulate_uninitialized_metadata, { return false; });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai why do we need to simulate something? I think it's better to generate parquet files with hive-style partitioning and null columns

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, removed. The datalake_simulate_uninitialized_metadata failpoint and its hooks are gone; the integration test now drives the real code path with genuine hive-partitioned files, so nothing is simulated.

else
table_state = getRelevantState(local_context).second;

auto metadata_object = getMetadataJSONObject(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai are you sure that we need to go to the object storage and request metadata file? This class supposed to store metadata about the table

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. getIdentityPartitionColumns no longer goes to object storage. getState already parses the metadata object, so it now also extracts the identity-partition source columns (across all partition specs) into a mutex-guarded, metadata-version-keyed map on the instance. getIdentityPartitionColumns is a pure in-memory lookup on that map (fail-closed on error / unresolved metadata).

NamesAndTypesList exclude = hive_partition_columns_to_read_from_file_path;
if (configuration->isDataLakeConfiguration())
{
/// Fail closed when the data lake metadata is not resolved yet. The direct query path

@scanhex12 scanhex12 Jul 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai could you please delete or truncate your comments?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Truncated the comments here and in the other touched files to short invariants; the rationale moved to the commit message.

/// backfill and drops rows. Delegate to the destination's own supportedPrewhereColumns; when it
/// restricts, keep only Buffer columns whose name is destination-safe. Stays unrestricted when the
/// destination is (read() reconciles differing source column types). See issue #110216.
std::optional<NameSet> supportedPrewhereColumns(const StorageSnapshotPtr & query_snapshot) const override;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai I think that it's a new feature. We didn't have support for the supportedPrewhereColumns before. please remove this method override from the storages that didn't have it before

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed. StorageBuffer and StorageProxy no longer override supportedPrewhereColumns (they had no such method before this PR); the exclusion stays scoped to the storages that already implemented it (Merge, MaterializedView, ObjectStorage, URL, File, Alias, Dummy). Note this leaves the Buffer/Proxy-over-Iceberg PREWHERE-pushdown path uncovered; happy to address it separately if you want it.

Both tests asserted only the resulting rows, which also hold when nothing at all is
PREWHERE-safe: the fail-closed empty set keeps the filter above the backfill and produces the
same output. So neither test could tell the all-spec exclusion or the row-policy pushdown from
a blanket refusal, and the one existing plan assertion covers only the direct current-spec case.

Assert the split in the plan for both, in the form the maintainers ask for: a physical
predicate must move to PREWHERE while the identity-partition column must not.

Mutation-tested: with supportedPrewhereColumns forced to return an empty set unconditionally,
the filtered EXPLAIN yields no rows in both cases, so the added assertions fail. On the real
binary both report the physical column in PREWHERE and the identity column absent.
Each review round answered a challenge by writing the justification into the source, and
nothing removed any of it, so seven blocks had grown to four lines apiece. Keep the local
invariant a reader needs at that spot and drop the rest, which is already in the commit
messages and on the review threads. Comment-only; the behaviour is unchanged and was
re-verified against the same fixture.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3a25129

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
Fast test / 00980_merge_alter_settings trunk regression exposed by merged #109000, not this diff #113045 (external, open)
Finish Workflow / Post Hooks CI harness (new_tests_check.py: all four per-arch Bugfix validation jobs SKIPPED/DROPPED, so none measured the regression test) a fix task is pending (investigating at full effort - fixing-PR link to follow here)

Config Workflow is success on this head and 169 check-runs are skipped because this run was configured down after the earlier full run.

Why the Fast test red is not caused by this PR. A Fast test failure is normally PR-caused, so I checked it rather than assuming. The failing statement is INSERT INTO table_for_alter VALUES (1, '1') on an EMPTY table, rejected with Code: 252 ... Too many parts (1 with average size of 437.00 B) ... parts_to_throw_insert = 1 - the only part counted is the one that INSERT wrote itself. That is exactly the mechanism #113045 describes: since #109000 (Support max_insert_threads for plain INSERTs, merged 2026-08-01T20:48Z) every parallel sink runs onStart and the checks are unordered against each other's writes, so a late-scheduled sink counts a part its own query already committed. This branch contains #109000 (compare reports ahead=486, behind=0 from its merge commit), which is why the shape is reachable here.

Timeline corroborates: over 60 days 00980_merge_alter_settings has 9 failures, and every Fast test occurrence except one predating this bar falls after #109000 merged - including one on the master merge queue (gh-readonly-queue/master/pr-112959, 2026-08-02) with no PR diff involved at all. This PR touches Iceberg/ObjectStorage reading plus storage-interface plumbing; it adds no write path and does not touch MergeTreeSink, ReplicatedMergeTreeSink, SinkToStorage or InsertDependenciesBuilder.

Post Hooks. Bugfix validation per-arch jobs: [(functional, amd64) SKIPPED, (functional, aarch64) SKIPPED, (integration, amd64) DROPPED, (integration, aarch64) DROPPED] - passed: none. No arch measured the regression test, so the hook reds even though nothing about the test was shown to be wrong. This is the known harness defect, not a statement about this PR's test.

Session id: cron:our-pr-ci-monitor:20260804-010000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Resolution of the Finish Workflow / Post Hooks (new_tests_check.py) row on my CI finish ledger

I promised a fixing-PR link for this row. There will not be one: I investigated the hook
and concluded no fix to it is warranted. Recording that here rather than leaving the
promise open.

new_tests_check.py reds Post Hooks when no per-arch Bugfix validation job reported a
strict success. Measured over the last 30 days, that happens for two reasons, and neither
is a defect in the hook:

  1. The per-arch jobs were dropped or skipped by an upstream failure. In a 12 hour
    sample every one of the 10 rows with this text resolved to a real upstream red on the
    same head (a Fast test failure, a Build (arm_tidy) failure) that dropped the whole
    downstream matrix, or to a genuine "bug does not reproduce on this arch" verdict. The
    hook is relaying that faithfully; suppressing it would remove signal. Fix or re-run the
    upstream job and this row clears on its own.
  2. The validation job aborted with no completed test row. I first read this as the
    gate passing on zero evidence. It is not: in 12 of 12 sampled runs the job uploaded a
    core dump whose thread matches that PR's own bug (core.MergeMutate for a mutation
    bug, core.QueryPullPipeEx for a SELECT bug, and so on). On a debug or sanitizer
    master-HEAD binary a reproduced logical error aborts the server, which is exactly a
    zero-row abort, and reconcile_bugfix_crash_repro documents that abort as the bug
    reproducing. So the verdict is correct.

Two smaller diagnostics gaps I am not fixing here, since both change what
clickhouse-test reports rather than fixing a bug: the wedged server's logs are not
collected, so the fatal-message check greps an empty directory and the report shows
Failed: 0, Passed: 0, Skipped: 0 with no hint that a core was captured; and distinct
StopTesting causes are not given distinct exit codes the way the global time limit and
max-failures stops are.

Resolves one content conflict in StorageObjectStorageSource.h: master's
parquet-lazy-materialization line added the LazyObjectStorageFileRegistry
forward declaration at the same spot where this branch declares
backfillIdentityPartitionColumn. Both declarations are kept.

The backfill in generate() still runs before the hive-partition append and
before master's new __global_row_index append, so the positional indices it
takes from requested_columns stay valid.
Comment thread src/Storages/StorageMerge.cpp Resolved
…ings

supportedPrewhereColumns answered an empty set when the data lake metadata could not be
resolved. That is a per-table answer with a cross-table effect: StorageMerge intersects the
contract of every regex-matched child before it applies _table and access filtering, so the
empty set also stripped the column from children the query can actually read.

Measured with one healthy child and one Iceberg child unreachable at query time:
SELECT id FROM mrg PREWHERE val > 15 WHERE _table = 'healthy' raised
"does not support column val in PREWHERE" (ILLEGAL_PREWHERE), where master returns the rows.
The read already skips the excluded child, so the query had no reason to fail. This was the
residual left by the earlier commit that stopped the same probe raising FILE_DOESNT_EXIST.

Answer the pre-exclusion contract instead: without resolved metadata no identity-partition
column can be named, and the hive exclusion does not need metadata. Reads are unaffected,
because read() resolves the metadata again and still fails on a child that is really broken:
count() over the whole Merge and a direct query on the child both raise FILE_DOESNT_EXIST as
before, and a child that becomes reachable between analysis and execution also fails there
rather than applying PREWHERE to a backfilled column.

The identity-partition exclusion itself is unchanged on the resolvable path: with region
absent from the data files, filtering on it still returns its rows, explicit PREWHERE on it
is still refused directly and through Merge, the automatic move still keeps it out of the
Prewhere step, and a physical column is still eligible.
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e0394bef6 with master 86e654b84 (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
Binary Master PR Δ
programs/clickhouse-stripped 691.19 MiB 688.22 MiB -2.96 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

235 object files changed (+267.10 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/IcebergDataObjectInfo.cpp.o 200.39 KiB 233.00 KiB +32.60 KiB (+16.27%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp.o 308.04 KiB 337.85 KiB +29.81 KiB (+9.68%)
src/CMakeFiles/dbms.dir/Interpreters/ClusterFunctionReadTask.cpp.o 187.35 KiB 215.67 KiB +28.32 KiB (+15.11%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp.o 1.12 MiB 1.14 MiB +21.31 KiB (+1.85%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorage.cpp.o 2.42 MiB 2.44 MiB +18.38 KiB (+0.74%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/registerStorageObjectStorage.cpp.o 1.28 MiB 1.30 MiB +18.04 KiB (+1.37%)
src/CMakeFiles/dbms.dir/Databases/DataLake/DatabaseDataLake.cpp.o 1.39 MiB 1.40 MiB +16.80 KiB (+1.18%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/StorageObjectStorage.cpp.o 524.16 KiB 540.26 KiB +16.09 KiB (+3.07%)

737 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

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

Job report

…analysis

supportedPrewhereColumns answers the pre-exclusion contract when the data lake metadata cannot
be resolved, so that an unreachable child does not strip a column from its reachable Merge
siblings. That contract cannot name the identity partition columns, and nothing downstream
re-checked the filters once the metadata became available.

Measured on a Merge over an Iceberg child whose data directory is hidden during analysis and
restored a few tens of milliseconds later, with region absent from every data file: 2 of 27
attempts returned zero rows with no error, where the same query without PREWHERE returned rows
1 and 3. The rows were dropped because the filter ran below the manifest backfill and read a
default. The fallback branch was confirmed to have executed on both attempts.

Reject such a filter in read(), where the identity partition list is finally known. Reads that
never enter the fallback are unaffected: the identity exclusion still applies on the resolvable
path, an unreachable child still leaves its siblings' columns eligible, and a physical column is
still eligible. After the change the same sweep gives 0 of 27, and the eight assertions covering
the original backfill fix still hold.
The guard added in the previous commit only runs when the PREWHERE contract was answered before
the data lake metadata resolved. Every existing test resolves the metadata during planning, so
none of them reached it: removing the guard left them all green.

Reach it deterministically with a failpoint that makes supportedPrewhereColumns answer as if the
metadata were unresolved, which is the state a wrapper reaches for a cold or briefly unreadable
child. The identity partition filter then survives into the read step and must be refused.

Verified by neutering the guard and rebuilding: with it the query is refused and a plain filter
still returns rows 1 and 3, without it the query returns no rows at all. A filter on a physical
column stays allowed in both arms, so the refusal is not blanket.
The rename and time-travel test asserted only returned rows, which a blanket refusal on the
pinned-snapshot path would also produce, so it did not show that the schema-keyed exclusion is
what keeps the old schema's partition column above the backfill. Assert the split, as the other
two cases already do.

Two comments claimed the unresolved-metadata path returns an empty supported-column set. It no
longer does, so they now name the mutation they rule out instead.
The test claimed region is absent from its data files. ClickHouse writes the partition column into
the files it produces, so the claim was wrong and would mislead the next reader into thinking the
test covers the backfilled value. It asserts the PREWHERE contract.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7635837

Every failure below has an owner: a fixing PR (ours 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_asan_ubsan) / Sanitizer (STID: 1367-26c6) LSan reference-cycle leak, bystander (not this diff) #113397 (external, open)
Bugfix validation (unit tests) harness inconclusive: the base branch moved contrib/NuRaft after this branch split a fix task owns it, blocked on the harness design question posted on #111495 (fixing-PR link to follow on this PR)

Both rows are easy to misread, so the evidence is spelled out.

Sanitizer (STID: 1367-26c6) is the PromQL/materialized-CTE retain-cycle family tracked in #114291
and #113954. I pulled the 7.0 MB stderr.log rather than reading the truncated report excerpt:
1018 leak blocks, 0 direct, 1018 indirect, 427839 byte(s) leaked in 2649 allocation(s). 81 blocks
reach a PromQL entry point (StorageTimeSeriesSelector::readImpl, TableFunctionTimeSeriesSelector::executeImpl,
StoragePrometheusQuery::readImpl) and 65 carry a materialized-CTE frame. The job runs with
ASAN_OPTIONS=malloc_context_size=10 and 653 of 1018 blocks are capped at exactly 10 unique PCs, so
the remaining unattributed blocks are not evidence of a second cycle and every per-frame count is a
lower bound. Zero direct leaks means nothing owns these objects - the signature of an abandoned cycle,
not of a missing free. This PR cannot be the cause: its 36 files contain no PromQL, TimeSeries,
materialized-CTE or query-tree path. #113397 is absent from the build that failed here, proven by
blob equality rather than commit distance: its pre-image for src/Processors/QueryPlan/MaterializingCTEStep.h
is 97935ebf769dbdec2b41784109abd94b30406259, which is exactly what this head serves.

Bugfix validation (unit tests) is inconclusive, not a regression. The job says so verbatim:
"Submodule state differs between the merge-base and the checkout (contrib/NuRaft) ... This is
inconclusive - NOT a reproduction or a refutation." This PR does not touch contrib/NuRaft or
.gitmodules; the pin is f8546f7087928572e72a8254d4bc78a3cfcd29c3 at both this head and the PR base,
i.e. master moved it after the branch split. The validator cannot populate the before-worktree at the
merge-base pin, so it aborts rather than validate against the wrong submodule code. Measured breadth of
this harness class since 2026-07-25: 92 distinct commits across 65 distinct PRs, ~1.1 rows per commit,
making it the largest single error class in that job.

My own attempted harness fix was #111495; I closed it because the repopulation it added sits after an
early return in ci/jobs/unit_tests_bugfix_validation_job.py and is therefore unreachable. The open
design question (drop digest_config for the unit validator and report SKIPPED, versus leaving the
guard as is) is posted on that PR and is what the fix task is waiting on.

Session id: cron:our-pr-ci-monitor:20260811-200000

The guard rejects a row policy on an identity partition column for the same reason it rejects a
PREWHERE condition, but only the PREWHERE branch was exercised. Verified the added case fails
closed on a table whose contract was answered without metadata.
The two refusal assertions count lines matching an error token on the merged
stdout/stderr of the client. clickhouse-test exports
CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=warning and shell_config.sh turns that into
--send_logs_level=warning, so the server forwards its own <Error> executeQuery
record for the same exception and the count is 2, not 1. It passed when authored
because a client run without that setting emits only the client-side report.
Reproduced and fixed under the real runner: the pre-fix file produces the exact
CI diff (-1/+2 on all three lines), the fixed file passes 10/10 with
randomization on and 10/10 with it off.

Uses the sed replacement already used by 15 other stateless tests rather than
appending a second --send_logs_level: a duplicate option is rejected outright
("cannot be specified more than once") unless --allow_repeated_settings is
present, and that flag comes from clickhouse-test, not shell_config.sh.

Also matches the read-time wording instead of the bare code on the two armed
assertions. The analysis-time contract raises ILLEGAL_PREWHERE too, for a column
it can name, so the previous token could not tell the new guard from it: with the
guard neutered (identity_partition_names cleared) the old oracle still read 1.
Against the tightened oracle that mutant flips both assertions to 0. The final
assertion keeps the bare code on purpose, since there it is the analysis-time
contract that must refuse.
/*exclude=*/ hive_partition_columns_to_read_from_file_path);

auto identity_partition_columns
= configuration->getIdentityPartitionColumns(query_context, metadata_snapshot->datalake_table_state);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getIdentityPartitionColumns returns every identity-partition source column from the table metadata, and this branch excludes them from supportedPrewhereColumns() unconditionally. That is broader than the bug being fixed: ClickHouse's own Iceberg writer still materializes the identity-partition column in the Parquet files (the new 04310_iceberg_identity_partition_late_filter_guard.sh explicitly notes that region is physically present), so PREWHERE region = ... on those tables is still safe.

After this change the direct table now rejects that query with ILLEGAL_PREWHERE, and row-policy / auto-PREWHERE pushdown is disabled through every wrapper, even though no manifest backfill is involved. Can we narrow the exclusion to files that actually omit the source column instead of treating every identity partition as backfilled-only?

bool supportsPrewhere() const override { return getNested()->supportsPrewhere(); }
bool canMoveConditionsToPrewhere() const override { return getNested()->canMoveConditionsToPrewhere(); }
std::optional<NameSet> supportedPrewhereColumns() const override { return getNested()->supportedPrewhereColumns(); }
std::optional<NameSet> supportedPrewhereColumns(const StorageSnapshotPtr & query_snapshot) const override { return getNested()->supportedPrewhereColumns(query_snapshot); }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This forward is not safe for StorageTableProxy. StorageProxy::getStorageSnapshot builds a proxy-owned snapshot from base_metadata, and on first access that base_metadata is just the cached CREATE TABLE schema; StorageTableProxy::read() later ignores it and rebuilds a fresh nested snapshot from storage->getInMemoryMetadataPtr(context, false) before executing.

By passing the proxy snapshot into nested supportedPrewhereColumns(), StorageObjectStorage now decides the Iceberg PREWHERE contract from possibly stale proxy metadata while the read uses the nested table's current metadata. After an external schema change or a query-scoped snapshot selection, analysis can admit/exclude different columns than the nested read actually sees. StorageTableFunctionProxy had to build a nested snapshot explicitly for this same reason; StorageTableProxy needs the same treatment instead of inheriting the generic proxy forward.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The first finding is right, and I measured it rather than reasoning about it. On a table written by
ClickHouse's own Iceberg writer (so region is physically in the Parquet files):

pristine master this branch
WHERE region='East' 1, 3 1, 3
PREWHERE region='East' 1, 3 Code: 182 ILLEGAL_PREWHERE

So valid input that master accepts is now rejected. Row policies are not affected in results
(1, 3 on both) - there only the pushdown is lost.

I do not think the suggested remedy works, though. supportedPrewhereColumns() is a table-level
contract answered at analysis time (6 call sites: InterpreterSelectQuery.cpp:889,2511,2675,
CollectTableExpressionData.cpp:325, optimizePrewhere.cpp:254, PlannerJoinTree.cpp:1786), and no
file list exists yet at any of them - per-file data first appears in IcebergIterator::next, during
read. Master also already answers this the table-wide way for the sibling case: with
hive_partition_columns_to_read_from_file_path excluded unconditionally, pristine master gives
WHERE region='East' -> 1, 3 but PREWHERE region='East' -> ILLEGAL_PREWHERE, without asking
whether an individual file contains the column. And the manifest cannot support the narrow version
safely: columns_infos exists, but every ColumnInfo member is optional
(ManifestFile.h:47-52), so "no stats for this column" is indistinguishable from "column absent",
and a column that is present and genuinely all-NULL looks the same again. Gating the exclusion on
that fails open, which is the row-dropping bug this PR is about.

Two ways to resolve the regression, and I would rather you picked than guess:

  1. keep the table-level exclusion, consistent with the hive-partition precedent above - explicit
    PREWHERE on an identity-partition column becomes an error, results are never wrong; or
  2. exclude only when the table actually has files omitting the column - still table-level, resolved
    from the pinned snapshot, but it needs a metadata pass I have not written.

On the second finding the mechanism is real - StorageProxy::getStorageSnapshot keeps the caller's
base_metadata and StorageTableProxy::read rebuilds its own snapshot, and datalake_table_state
(what selects the identity columns) is only ever set by StorageObjectStorage*/IcebergMetadata,
never by a proxy. But that forward is scheduled for removal under @scanhex12's point 5, so I have not
touched it.

One correction on that point, since master moved after the review: supportedPrewhereColumns now
exists on both StorageBuffer.h:127 and StorageProxy.h:28 on master, added upstream by #112326
(8363be4f36, aab81e4d7d, merged 2026-08-03). My diff on those two files is only the signature
change this PR's API change forces, not a new override. Removing them as agreed would now delete
methods master owns, so I have left them and would like your call.

No code change in this round.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e0394be

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
Bugfix validation (unit tests) harness inconclusive: the base branch moved contrib/NuRaft, contrib/llvm-project and contrib/musl after this branch split a fix task owns it, blocked on the harness design question posted on #111495 (fixing-PR link to follow on this PR)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

176 check-runs, all completed: 161 success, 14 skipped, 1 failure. Config Workflow and
Finish Workflow are green, and the praktika report has 0 dropped jobs with 15 real skips, so
the single red is the whole failure set. CIDB reports 0 test-level FAIL/ERROR rows for this
commit, consistent with the failure being job-level rather than a test.

The one row is inconclusive rather than a regression, and the job says so verbatim: "Submodule
state differs between the merge-base and the checkout (contrib/NuRaft, contrib/llvm-project,
contrib/musl) ... This is inconclusive - NOT a reproduction or a refutation." The direction is
measurable and it is not mine: this PR changes no submodule and no .gitmodules entry, and all
three pins are identical at my head and at the PR base (f8546f7087928572e72a8254d4bc78a3cfcd29c3,
588b33887bd57ed2e5df6b15ea26d657e7ff0cef, 150648a85853e3868872829e68682c79dc4fe21a) while
master now carries different ones. So master moved them after the split, and the validator cannot
populate its before-worktree at the merge-base.

I should be plain about where that owner stands rather than implying work is queued: the fix task
is parked awaiting a decision on the harness design, not actively in progress. My own earlier
attempt at it is #111495, closed, because the repopulation it added sits after an early return in
unit_tests_bugfix_validation_job.py and is unreachable. The consequence for this PR is that the
unit-test arm gives no evidence either way about my regression test, rather than evidence against
it.

No Fast test, Style check, Docs check or Config Workflow red, so nothing is PR-caused.

Session id: cron:our-pr-ci-monitor:20260812-073000

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@scanhex12 scanhex12 self-assigned this Aug 24, 2026
@scanhex12

Copy link
Copy Markdown
Member

Dirty slop, I'll redo it by myself better I think

@scanhex12 scanhex12 closed this Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, leaving it closed.

Two things from this branch that are independent of the implementation, in case they save time on the rewrite:

  • The reproducer: identity-partition columns absent from the data files, covering projection, filtering under both optimize_move_to_prewhere values, count(), GROUP BY, several identity columns of different types, and a mixed identity plus physical predicate.
  • Temporal and decimal partition values are a trap. Iceberg serializes them in physical encoding (int64 microseconds, int32 days), so passing the manifest value through convertFieldToType applies scale semantics and throws DECIMAL_OVERFLOW for DateTime64, Time64 and Decimal targets. It reproduced deterministically in test_writes_field_partitioning on every sanitizer build and never on master. Inserting the raw value as a width-correct DecimalField was what fixed it.

#110216 is still open, so I will leave the fix with you.

@scanhex12

Copy link
Copy Markdown
Member

I'll continue here #116129

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 groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg: identity-partition column reads as NULL when data files don't contain it (Hive-partitioned / Fabric-virtualized tables)

3 participants