Skip to content

Honor an explicit structure argument for data lake table function reads - #113650

Open
groeneai wants to merge 35 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113361-honor-structure-datalake-tf
Open

groeneai wants to merge 35 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113361-honor-structure-datalake-tf

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

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 the structure argument of the paimon* and iceberg* table functions being reported by DESCRIBE but ignored by SELECT, so one expression yielded two schemas. A structure that declares names and types is now used for reads, as it already was for s3 and file, so it can select a subset of the columns or override their types, and a declared type the data files cannot supply raises an error instead of silently using the metadata schema. The declared type also governs PREWHERE and data file pruning, which compared values at the metadata type and could return rows the declaration excludes or drop rows it selects. A declared column DEFAULT, inserts, the persistent Paimon*/Iceberg* engines and deltaLake* are unchanged. Closes #113361.

Description

DESC paimonLocal(p, 'Parquet', 'f_int Int64') reported Int64 while SELECT toTypeName(f_int) on
the same expression reported Nullable(Int32). icebergLocal diverged too.

The table function was already correct. The storage replaced the whole
StorageInMemoryMetadata, columns included, whenever the per-format schema reload was enabled,
unconditional for Paimon and Iceberg. That happens at five sites, one per query, so fixing the
constructor is not enough.

A preserve_structure_for_reads flag is now computed in both table function executeImpl overrides
and retained by both storage classes, which route their five reload sites through one helper each.
The helper still pins datalake_table_state and, when the flag is set, keeps the declared columns.
The metadata sorting key is resolved against the metadata schema, so it survives only while every
column its expression reads, a nested one included, is still present with the same type. A worker gets the initiator's own resolved columns, so it keeps the key.

Pruning follows suit, since a bound is compared at the metadata type: a retyped column withholds
pruning, as does a nullable partition key declared non-nullable, whose NULL reads as the declared
default but compares as positive infinity.

The flag also requires that the declaration carries no column DEFAULT: such a default is
materialized from one reader's missing-value bitmask, while a lake resolves its row-level deletes and
its sorting key from its own metadata against whatever values reach them, so the two cannot both be
served on one path.

Deliberately unchanged, each measured: the persistent engines; INSERT INTO TABLE FUNCTION iceberg*(...); DatabaseDataLake catalog tables; deltaLake*, whose reload is an opt-in; and plain
s3/file, where a declared DEFAULT is honored. The new stateless tests assert DESC and
SELECT on one expression and pin every unchanged arm, each red without the change.


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

@groeneai

groeneai commented Aug 6, 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; 5 Gate B rounds, 4 findings
raised and 0 in the final round; plus my own cold review each round, 6 rounds total, 5 fix
rounds executed). Verdicts: 20 AGREE, 10 DISAGREE, 1 DROPPED, 0 DEFERRED.

# Sev Finding Verdict Evidence / action
1 ❌ Preserving only the columns leaves the adopted metadata internally inconsistent: the columns are the declared ones while the sorting key is still resolved against the lake schema, and read-in-order consumes both (StorageObjectStorage.cpp, ReadFromObjectStorageStep.cpp:187,:192) AGREE, fixed dropSortingKeyIfItDoesNotDescribeColumns added; the key is kept only while every column its expression reads is present with the same type
2 ⚠️ A declared type the data files cannot supply silently fell back to the metadata schema instead of failing, so the test could not tell an honored structure from an ignored one AGREE, fixed Both Code: 53 arms added to 04748; measured absent on the pristine base and present with the change
3 ⚠️ A cluster initiator injects its own resolved columns whether or not the user passed a structure, so a worker would see a structure and wrongly drop the key it still matches AGREE, fixed Verified on four legs from source (StorageObjectStorageCluster::updateQueryToSendIfNeeded); the flag is now computed per side, and the worker arm keys on system.processors_profile_log rows where query_id != initial_query_id
4 ❌ With a USER structure that retypes a key column, a worker kept the key and returned rows in the underlying numeric order while the user asked for String: a wrong-results carrier, not a plan-only difference AGREE, fixed Re-adjudicated from major to blocker on the measurement. Committed Spark-written fixture (12,933 bytes) whose per-file sort_order_id matches the table's default-sort-order-id, which the ClickHouse writer leaves NULL; the arm reads 10 2 9 versus 2 9 10
5 ❌ My own round-3 prescription (thread a provenance signal from the initiator) was infeasible as written AGREE, withdrawn Replaced with the per-side flag actually shipped; the old shape is recorded do-not-reinstate
6 ⚠️ The proposed arm oracle depended on max_threads, which the runner randomizes (tests/clickhouse-test:1553) AGREE, fixed Oracle changed to one that does not depend on it; optimize_read_in_order pinned with a per-setting Random settings limits: clamp instead of a blanket no-random-settings tag
7 ⚠️ An empty fixture cannot discriminate, because isDataSortedBySortingKey returns true for an empty table before consulting any manifest AGREE, fixed The order arm uses the populated committed fixture; the two EXPLAIN PIPELINE arms keep the empty-table shape, where that early return is what makes them reachable at all
8 ⚠️ The soundness check missed a nested key: an Iceberg sort order over a struct field arrives as the dotted subcolumn name, which tryGetPhysical cannot see, so a key that DOES describe the columns was cleared AGREE, fixed Widened to tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, ...). Re-derived independently: traverseComplexType emits dotted paths, getKeyFromAST analyses with subcolumns, so getRequiredColumnsWithTypes yields st.a. Pinned by 4 new unit arms, since no stateless arm can build a nested Iceberg sort order
9 💡 The adjacent two-bool constructor parameters are a swap hazard DISAGREE All four call sites pass them correctly and each uses a named comment; a signature change would touch every unrelated caller
10 💡 log_processors_profiles might be off, making the worker arm vacuous DISAGREE It defaults true in src/Core/Settings.cpp and the runner does not randomize it; the arm's companion asserts count() > 0, which fails loudly rather than passing silently if no rows were logged
11 💡 Documentation absent from the diff DROPPED Self-refuted before it entered a fix plan: the docs change is in the diff, in the table function source file where these docs live
12 💡 The duplicated helper in StorageObjectStorageCluster should be shared DISAGREE The two classes do not share a base that owns this state; the cluster copy is 4 lines and its comment points at the primary

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Also measured and deliberately not changed, disclosed rather than raised: when a USER structure
excludes a key column on a cluster WORKER, the key survives naming a column the worker does not
emit. All reads returned correct results across 3 shapes, because isDataSortedBySortingKey is
false once rows exist (the ClickHouse writer emits sort_order_id = NULL) and an empty table is correctly
ordered. No user-reachable wrong result was observed.

Session id: cron:clickhouse-review-slot-52:20260806-102000

@groeneai

groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)

Updated in place again, so this PR still carries one validation gate rather than several. This
revision refreshes the test and code-path rows for the strengthened pruning oracles in the
final round; every other row is unchanged.

check answer
a Deterministic repro? Yes, four of them, every run, no randomization involved. On the committed data_minio/deletes_db/eq_deletes_table, structure='id String, name String' with id < '2' returns 92 for WHERE and 2 for PREWHERE. The manifest half needs no deletes: two files with ids 0..3 and 10..13, declared id String, WHERE id < '4' returns 4 of 8 rows. The reader-pruning half needs neither deletes nor PREWHERE: one file of ids 10..13 made schema-evolved by an unrelated ADD COLUMN, declared id String, WHERE id < '4' returns nothing where all four rows match. The Paimon half, on the committed data_minio/paimon_all_types with use_paimon_partition_pruning = 1: declared f_bigint_nn String, f_bigint_nn < '2' returns ['0'] where ['0','1000'] match. The identity-partition half needs no deletes, no evolution and no filter: an IcebergLocal table PARTITION BY id holding 2 and 10, declared id String, raises BAD_GET has Int64, requested String.
b Root cause explained? Yes, one rule broken in five places. A filter or an injected value is planned on the declared types, but each of these uses a type the lake wrote: an equality-delete file is schema_changed with no schema transformer, so the reader keeps the query filters (to preserve Parquet pruning) and resolves their inputs by name with no type check; the manifest rename DAG types its inputs from the manifest schema and ActionsDAG::merge matches by name only; on a schema-evolved file the reader's own row-group and page pruning is built from the query filter while its header is still the file's old schema; the Paimon partition KeyCondition is built from a key typed by the Paimon metadata schema; and an identity-partition value, extracted from the manifest at the metadata type and carried as a bare Field, is inserted into a column of whatever type the read was planned on.
c Fix matches root cause? Yes. Each site now uses the type the lake gives a column now: the reader's filters move below the conversion; a column whose declared type could reorder values is left out of the manifest DAG, the reader's pruning DAG, and the Paimon partition key; and an identity-partition constant is built on the type the value was extracted at and cast to the planned type, so the injected value is what an undeclared read of that column produces. No widened bounds, no no-random-* tag, no check added at a failure site.
d Test intent preserved / new tests? No arm weakened, none removed. In 04748_datalake_table_function_honors_structure: twelve new value arms, eight counter arms and three paired controls, plus two arms pinned so the site they exercise is not randomized away; one existing comment reworded to describe what its cell actually observes. In test_identity_partition_column_projection.py: two new tests, one reading a retyped nested identity partition source and one reading a retyped partition column that is absent from every data file. A later round strengthened three arms without changing what they assert: the three Paimon relative counter oracles now require both of their reads to be present, because max() over no rows is 0 rather than NULL and a pruning query that failed would have satisfied the inequality on its own; the three row-group counter arms are scoped to the initial query id, because the read runs as a secondary query wherever the cluster rewrite wraps the table function; and the nested integration filter arm compares against an ordering bound instead of an equality, so it pins the declared type's ordering rather than only the value's presence. Every rewritten arm's liveness was re-proved by the mutant that reddens it, and the reference file is byte-identical across all three changes.
e Both directions demonstrated? Yes, same command and fixture each time. The PR head before each change reddens exactly the lines that change turns green (92->2 twice, 4 rows lost on the manifest arm, all 4 rows lost on the evolved-pruning arm, BAD_GET on each of the four identity-partition arms); with the change the file passes.
f General across code paths? The carriers are enumerated as five. The fifth, the identity-partition constant, was found by a later review round and not by the first enumeration, so the enumeration is stated here as it now stands rather than as it was: the reader's PREWHERE and row-level filter (same lines; row-level covered by 04146/04147), Iceberg manifest pruning, the reader's own pruning DAG (withheld by a decision independent of PREWHERE support, so the native ORC reader is covered too), Paimon partition pruning, and both places an identity-partition value is materialized (the filter substitution and the injection into the read, each with its own arm and its own mutant). Those two share one type lookup, which resolves a top-level source from the schema's column list and a nested source by field id, so a nested identity partition is the same carrier reached through a fuller lookup rather than a sixth site. The wrapper rule that keeps pruning is three independent decisions, one per pruning site, and each now has its own arm and a mutant that reddens only that arm. Nested/subcolumn filter inputs are a different thing, about pruning and filter typing; they are disclosed in the description and remain unobserved. On the nested source, the two properties are pinned by separate arms: one asserts the injected values themselves, which the decline-to-inject mutant reddens, and one asserts an ordering bound, which holds only if the comparison runs at the declared type.
g Generalizes across inputs? Measured over the type matrix an evolved read can present: Int32->Int64 widening, required->optional relaxation, rename, String, Tuple, and the illegal optional->required tightening. Both pruning sites strip Nullable and LowCardinality before comparing, deliberately and through the same expression, because neither wrapper can reorder the values a bound is compared against; each therefore keeps pruning for a declaration differing only in those, and each has its own counter arm. The paired control is a declaration that really does reorder (String over Int64), which still withholds pruning. Evaluating a filter is the opposite case and does need the exact planned type, which is why that guard stays strict. The identity-partition conversion is measured on a numeric and on a date partition column, because a date value is held as a day count and only a date column separates converting it from rendering it. Arms cover declared==metadata, declared-retyped, wrapper-only, a retype outside the partition keys, and no declaration at all.
h Backward compatible? No new setting, no default change, no format or serialization change, so no SettingsChangesHistory.cpp entry. IcebergObjectSerializableInfo is untouched: the identity-partition fix reads the schema id that is already on the cluster wire and resolves the type locally, for a nested source as well as a top-level one, so an initiator and a worker at different versions exchange the same bytes. The user-visible change is that a declared type now governs PREWHERE and file pruning as it already governed WHERE and the output column.
i Invariants and contracts preserved? The exact-planned-type conversion applies only to a column this guard deferred, so every other schema-changed read is byte-identical; removing either half of that scoping breaks 04737_iceberg_prewhere_modify_column_nullable with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, which is how it was checked. Both conversions sit after the delete transformers, so a deleted NULL raises in neither. Where the lake no longer types a column the reader can still bind, pruning is withheld rather than guessed. An identity-partition constant gets a cast node only where the two types differ, so a read whose declaration agrees with the metadata, or which carries no declaration, builds the same DAG it did before.

Every new arm was checked against a mutant that reddens it, and each mutant reddens a distinct set. That
includes the narrower-is-necessary check: a variant comparing against the file's own type fixes the
values just as well, and silently stops pruning row groups for a legal Iceberg promotion with no
declaration present, which is what the counter arm pins. On the identity-partition arms, one mutant per
site plus one that reinterprets the value instead of converting it: the last reddens only the date arm,
and reads ['19724','19732']. On the wrapper rule, deleting the low-cardinality stripping at one of the
three pruning sites reddens that site's arm and leaves the other two green, one mutant per site. One
further mutant makes the reader decline to substitute a retyped partition value: it reddens both new
integration tests, which is why they exist, and leaves the whole stateless file passing, which is why a
stateless arm could not have covered it. That mutant reddens the nested test at its value arm; the
ordering arm below it is reached only with that assertion suspended and then passes, because a declined
injection leaves the declared type's default, which also sorts below the bound. So the ordering property
is pinned by the paired top-level arms in the stateless file, where the same fixture read at the declared
String returns both rows and read at the metadata Int64 returns one. On the Paimon guard, three
mutants built on this head give three disjoint singleton reddening sets: removing the withholding reddens
only the value arm, removing the partition-key scoping reddens only the non-key oracle, and removing
either wrapper strip reddens only that wrapper's oracle. --test-runs 50 with randomization on: 50
passes, 0 failures, slowest single run 8.1 s.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @divanik @Michicosun, could you review this? The data lake table functions parsed the structure argument for DESCRIBE but the storage then overwrote the whole metadata, columns included, at every point where the per-format schema reload runs, so one expression reported two schemas; the reload now keeps the declared columns for reads and drops the snapshot's sorting key only when it no longer describes them.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8dcb07]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) FAIL
03821_drop_workload_during_query_race FAIL cidb

AI Review

Summary

The PR preserves explicit names and types for iceberg* and paimon* table-function reads and adjusts sorting, pruning, and partition constants accordingly. Reviewed head: a8dcb07eff56370640b59b87a2593f4bc372db46. One previously reported wrong-result blocker remains in the schema-evolved PREWHERE path. No genuinely new inline findings were identified.

Findings

❌ Blockers

  • StorageObjectStorageSource.cpp:1927: A fallback filter still does not receive the explicitly declared type. For an evolved file containing a Nullable(Int64), a declaration of a Int64 is changed back to Nullable(Int64) here because filter_inputs_retyped is false when a schema transform exists. The equality check then skips conversion, and a filter planned against Int64 runs against a nullable column. The author's measured reproduction, SELECT groupArray(bb) FROM icebergLocal(..., 'a Int64, bb Int64') PREWHERE a = 0, includes the NULL row, while the equivalent WHERE or selecting a raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. The current code retains that mechanism. Preserve the distinction between caller-declared types and lake-schema types through worker dispatch, then align explicit filter inputs before evaluation without breaking undeclared schema-evolution reads. Existing thread.

⚠️ Majors

  • StorageObjectStorageSource.cpp:373: [dismissed by author -- https://github.com/Honor an explicit structure argument for data lake table function reads #113650#discussion_r3887860253] Nested identity-partition values can still become defaults when the reader carries their parent tuple. For an ORC header containing s, the manifest entry s.c fails header.has(name), so an omitted partition field is never injected and reads as NULL/defaults. The gate remains unchanged on this head, so the reported behavior remains real. The author demonstrated that this predates the PR and deferred it to separate work; it is not an additional merge requirement here. The prior reply about the absent fix has already been posted, so no further thread reply is warranted.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build is available, so runtime reproductions were not rerun. The blocker combines the author's recorded measurements with tracing of the current code; a focused regression on this head would close that verification gap.
Tests
  • ⚠️ Add a focused stateless regression with an evolved nullable column declared non-nullable and used only by PREWHERE. Compare it with WHERE and selecting that column, and retain controls for undeclared reads and worker execution. The added tests exercise the opposite nullability direction but do not catch this remaining divergence.
Final Verdict

Status: ❌ Block. Align explicitly declared filter inputs consistently and add the focused nullability regression before merging. Existing threads require no new replies or resolution changes; no duplicate inline review was submitted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 6, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f19e77b

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
Fast test / 02458_relax_too_many_parts flaky trunk regression: a plain INSERT fans out over max_insert_threads sinks and each one runs the parts_to_throw_insert check in onStart, so a late-scheduled sink counts parts another sink of the same query already committed and throws TOO_MANY_PARTS #113045 (external, open)
Finish Workflow / Post Hooks new_tests_check.py: no per-arch Bugfix Validation job validated the bug, because all five Bugfix validation jobs were skipped once Fast test failed and gated the run resolves with the Fast test row above (#113045, external, open)

Not PR-caused. Fast test reported 1 failure against 10389 passed, the failing test is
unrelated to this diff (this PR touches src/Storages/ObjectStorage/ data lake reads, the
failure is a MergeTree insert-path parts check), and this PR's own new test
04748_datalake_table_function_honors_structure is SKIPPED in Fast test rather than
failing. That single failure gated the remaining 169 jobs, which is why they show as skipped.

Session id: cron:our-pr-ci-monitor:20260806-203000

The structure argument of the data lake table functions was reported by DESCRIBE
but ignored by SELECT, so one table-function expression yielded two different
schemas: DESCRIBE showed the user's declared structure while the read used the
schema derived from the lake metadata.

The read path re-derived metadata from the lake snapshot and overwrote the
columns the caller had declared. It now keeps the caller's columns across that
adoption when the table function was given an explicit structure, so DESCRIBE
and SELECT agree.

The snapshot's sorting key is kept only while it still describes the columns
being emitted. Read-in-order trusts that key to describe them, so a key naming a
column the read no longer emits, or emits at a different type, is unsound rather
than merely stale; it is resolved through subcolumns so a nested key that is
still described survives.

Closes ClickHouse#113361
@groeneai
groeneai force-pushed the groeneai/fix-113361-honor-structure-datalake-tf branch from f19e77b to 0fe428b Compare August 14, 2026 14:05
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a8dcb07eff56370640b59b87a2593f4bc372db46 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

A data file written under an older Iceberg schema is read through the schema
evolution transform, whose output is the current metadata schema alone. A
requested column that no schema declares was therefore dropped before column
extraction, so DESCRIBE listed it while SELECT on the identical expression
failed with NOT_FOUND_COLUMN_IN_BLOCK. This is reachable through any data lake
table function whose `structure` argument names a column the table does not
have.

Synthesize those columns via addMissingDefaults after the transform, which is
what a read of an absent column already yields when no evolution transform
runs, so the evolved and unevolved paths now agree. Verified against the
unevolved path for a nullable type, a non-nullable type taking the type
default, an explicit DEFAULT expression, and filtering through both WHERE and
PREWHERE, including the case where the declared column is used only by the
filter and a different column is selected: filter-only inputs are absent from
the reader's requested columns, so they are collected separately.

A name that the file's own older schema carries is deliberately left alone: the
reader resolves it by field id, so it denotes that physical column rather than a
missing one, and filters on it are evaluated there. Synthesizing it would turn
today's error into wrong results.

The synthesized columns are excluded from AddingDefaultsTransform, which looks
its missing-value bitmask up by a column's position in the block and would
otherwise index past the bitmask the reader sized to its own header.

The existing Iceberg "columns the metadata does not have" arm could not catch
any of this: its table was never populated, so no reader ran, and its groupArray
oracle could not tell default rows from no rows either way. It is populated and
its oracle now counts rows.

Also add the `structure` argument to the Iceberg and Paimon Azure, HDFS and
Local syntax signatures and cluster examples, which omitted it while the prose
below documented it.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the schema-evolution gap in this PR: on a data file written under an older Iceberg schema, a column supplied only by the structure argument was dropped before extraction, so DESCRIBE listed it and SELECT on the same expression failed with NOT_FOUND_COLUMN_IN_BLOCK.

Repro (before this commit): create an Iceberg table (a, b), insert, RENAME COLUMN a TO renamed_a, then SELECT zzz FROM icebergLocal(..., 'zzz Nullable(String)') -> Code: 10 ... only columns: renamed_a, b.

The declared column is now filled via addMissingDefaults after the evolution transform, so the evolved and unevolved paths agree. Checked against the unevolved path for a nullable type, a non-nullable type taking the type default, an explicit DEFAULT expression, and filtering through WHERE and PREWHERE (including when the declared column is filter-only and a different column is selected - filter-only inputs are absent from the reader's requested columns, so they are collected separately).

A name the file's own older schema carries is deliberately left alone: the reader resolves it by field id, so it denotes that physical column and filters on it are evaluated there. Synthesizing it would turn today's error into wrong results.

The regression arm that should have caught this was vacuous - its table was never populated, so no reader ran, and a groupArray oracle cannot distinguish default rows from no rows. It is populated and its oracle counts rows; a mutation that disables the synthesis reddens it.

Two residuals I hit while verifying, both reproduced identically on this PR's previous head and left alone:

  • AddingDefaultsTransform looks its missing-value bitmask up by a column's position in the block, so a column the evolution DAG itself adds plus a declared DEFAULT aborts in BlockMissingValues. Same stack on both binaries; it needs the bitmap carried across the transform, which is a separate change.
  • A declared DEFAULT on a sorting-key input can rewrite the values the metadata key was resolved against, which dropSortingKeyIfItDoesNotDescribeColumns does not consider. Untouched by this commit.

Also added [,structure] to the Iceberg and Paimon Azure/HDFS/Local signatures and cluster examples, taken from the signatures_with_structure constants.

…l applies

`AddingDefaultsTransform` reads the missing-value bitmask the format reader
produced, which describes the reader's own columns and rows. It was installed at
the end of the pipeline, after delete and filter transforms had dropped rows and
after the data lake schema evolution transform had changed column positions, and
the bitmask is not carried across any of them. So a declared DEFAULT indexed an
entry describing a different column, or past the end.

Install it directly after the reader, restricted to the columns the reader
emits. Columns produced later already carry their declared defaults.

A fallback filter has the mirror-image problem: it is planned against the
declared types while the transform emits the lake's own, so a comparison
returned a differently-nullable result than its plan recorded. Convert the
columns those filters read, before they run. Only filter inputs are converted,
so a read that does not filter keeps its previous plan.

Only a declared `structure` can attach a DEFAULT to a column the evolution
transform emits, because Iceberg rejects a non-nullable ADD COLUMN, so this
became reachable when the structure argument started being honoured on reads and
no release shipped it. Reachable through any data lake table function whose
structure argument declares a DEFAULT on such a column, declares a filtered
column at another nullability than the file's own schema, or declares a DEFAULT
while the table has deletes.

The values now match the authoritative table read of the same data, including a
table holding both a file written before the column existed and one written
after: the older rows read NULL, as Iceberg fills them, and the newer rows keep
their stored values. A declared DEFAULT does not override that fill, which would
otherwise make one declaration mean different values per file. Row counts are
part of every new oracle, so an arm cannot pass by returning nothing.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, and fixed in 5af5075. The mechanism is as described, and my previous round had dismissed it against the wrong baseline: I compared against this PR's own first commit, which already honours structure, rather than against master.

Against master the shape does not abort, so it is this PR's:

binary ADD COLUMN c + structure 'c Nullable(UInt64) DEFAULT 42'
master 6c53bb45 [], no abort
previous head 148e44a9 abort, vector[] index out of bounds
this push 5af5075d 3 3, equal to the table read

Only a declared structure can put a DEFAULT on such a column, since Iceberg rejects a non-nullable ADD COLUMN, so no release shipped this.

Rather than exclude a wider set of names, the transform now runs directly after the format reader, where the bitmask's column and row correspondence both still hold. My first attempt only compared column positions, and you were right that this is about more than the synthesized set: probing your case surfaced two further shapes that were also broken and are also fixed here.

  • A fallback filter is planned against the declared types while the evolution transform emits the lake's own, so SELECT ... 'a Nullable(Int64), c Nullable(UInt64)' WHERE a < 3 aborted on the return type of less. Filter inputs are now converted before the filters run.
  • With position deletes, DELETE FROM t WHERE ... then a declared DEFAULT failed Unexpected defaults count, because the delete drops rows the bitmask still describes.

New arms cover all three, including a table with one file written before the column existed and one after: the older rows read NULL, as Iceberg fills them, and the newer rows keep their stored values, so a declared DEFAULT does not override the fill. Row counts are part of every oracle, and each arm was confirmed to fail when the fix is reverted.

Two items from the same review I did not act on, with measurements rather than argument:

  • Renamed and Int32->Int64-widened fields with a declared DEFAULT return the same values on master, the previous head and this push, equal to the table read ([1,3] 3 1 with a physical NULL present). A physical NULL is a value, not a missing value, so no default is owed for it.
  • The sorting-key concern is in Utils.cpp, which this change does not touch. The predicted reordering does not reproduce: a physically sorted [1,2,NULL] read with id Nullable(Int64) DEFAULT 0 returns [1,2] on all three binaries.

…jected

Two ways an explicit structure was not honored on the shard of a cluster read.

addStructureAndFormatToArgsIfNeeded fills in a structure only when the argument
is "auto": all six positional branches test for it, but the loop that rewrites
key-value arguments replaced the value unconditionally. The replacement is built
from resolved columns via ColumnsDescription::getAll, which keeps names and types
only, so a cluster read reached the shard without the DEFAULT clause the user
declared and filled zeros, while the non-cluster read of the same expression
returned the declared defaults. Measured on a two-shard cluster: an explicit-URL
read returned 0 where the equivalent s3()/icebergS3() read returned 42.
Reachable through s3Cluster and the data lake *Cluster functions alike. A named
collection takes the early-return branch above and was already correct, which is
why the existing regression did not cover this. The value is evaluated like the
key beside it, because it may be any constant expression rather than a literal.

A name the file's own older schema carries is deliberately not synthesized: the
reader resolves it by field id, so it denotes that physical column. It was still
added to the list the synthesis is built from, so requesting it beside a column
that does need synthesizing created both, and the read returned type defaults
instead of rejecting the name as it does when the name is requested alone.

Arms are added for the named-collection, explicit-URL and non-literal structure
forms, each paired with the non-cluster read of the same expression as its
reference, and for the old-schema name requested beside a synthesized one. The
sorting-key arm now asserts worker activity before counting sorts, so that a
count of zero cannot be read from an absence of worker rows. Delta Kernel is not
built under MSan, so the test carries no-msan like the other tests that read
Delta fixtures.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Half right, and it led to a real bug next door. Pushed cba0bd4.

The collapse to names-and-types is real, but that value is only ever filled in:
addStructureAndFormatToArgsIfNeeded replaces a structure argument only when it is "auto". The
worker's own query_log row for the secondary query shows it receives
structure = 'zzz UInt64 DEFAULT 42' verbatim, and the metadata-derived list only when no
structure was given. Your example returns 3 0 126 (= 3x42), not zeros.

But the loop that rewrites key-value arguments had no such guard, so an explicit structure written
beside an explicit URL was replaced unconditionally, and there your prediction holds exactly:

icebergS3Cluster(..., 'test', 'testtest', format='Parquet', structure='zzz UInt64 DEFAULT 42')
    before  2  0        after  2  84        icebergS3(same args)  2  84

Reachable on plain s3Cluster too. Fixed by the same "auto" test its six positional siblings use,
evaluating the value like the key beside it since it may be a constant expression rather than a
literal. Two more of mine went with it: an old-schema name was excluded from synthesis but still fed
the list synthesis is built from, so a, zzz returned type defaults where a alone correctly gives
Code: 10; and the test now carries no-msan, since Delta Kernel is not built there.

Regression arms added for the named-collection, explicit-URL and non-literal forms, each paired with
the non-cluster read of the same expression as its reference, plus the combined a, zzz case.

Noted while verifying, not changed: PREWHERE on a declared column carrying a DEFAULT is rejected
with ILLEGAL_PREWHERE on plain file() as well, so it is a pre-existing general rule; and a
dependent DEFAULT over an unevolved file is Code: 47 on master and on s3() alike.

Session id: cron:clickhouse-maint-slot-12:20260815-004200

The test spent most of its wall clock starting clients, not running queries: 81
separate client invocations against roughly 46 ms of server work each. On the
instrumented builds a client start-up costs ~0.45-0.6 s, so the flaky check
(which runs a changed test ~50x) crossed the 180 s per-test cap and failed with
"Test runs too long".

Queries whose output is not post-processed now run grouped in one client session
each, taking the client count from 81 to 41. Arms that expect an error keep
their own client, because an error ends a session, and so do arms whose output is
piped through awk/grep/wc. The four "EXPLAIN PIPELINE ... | grep -c" arms became
an in-SQL countIf over the EXPLAIN subquery, which is the form the maintainers
asked for and needs no separate process. Measured on the master ASan build,
same server and fixtures for both forms: 50.4 s -> 23.5 s, a 2.14x reduction,
which puts the observed CI arms (228-237 s) near 110 s.

Output is unchanged: both forms were captured under clickhouse-test and are
byte-identical to each other and to the committed reference.

Separately, three arms mixed a bare toTypeName() with an aggregate, which the
old analyzer rejects with NOT_AN_AGGREGATE because it does not constant-fold
toTypeName() the way the new analyzer does. Those now wrap it in any(), which
returns the same value on both analyzers and needs no reference change. Each of
the three arms already asserts a row count, so the type assertion cannot be
weakened by an empty result.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check timeout on 04748_datalake_table_function_honors_structure, pushed as 6653e9e.

The test spent its wall clock starting clients, not running queries. Instrumented every call on the
previous head: 81 client invocations, median 74 ms against a 66 ms spawn floor, so 70 of them were
essentially pure process start-up. On the instrumented builds a client start-up is ~450 ms while the
marginal in-session server work for one of these reads is ~78 ms, which is why only the sanitizer
flavours crossed the 180 s cap (6 rows at 228-237 s) while debug and binary passed.

Queries whose output is not post-processed now run grouped in one session each: 81 client processes
down to 41. Arms that expect an error keep their own client, since an error ends a session, and so do
arms piped through awk/grep/wc. The four EXPLAIN PIPELINE ... | grep -c arms became an in-SQL
countIf over the EXPLAIN subquery, which also drops a process. DESC cannot move server-side:
SELECT ... FROM (DESC ...) is a syntax error and describe_compact_output emits a tab where the
reference has a space, so those arms keep their awk.

Measured on the master ASan build, same server and fixtures for both forms: 50.4 s -> 23.5 s
(2.14x)
, which puts the observed CI arms near 110 s. Output is unchanged: both forms captured under
clickhouse-test are byte-identical to each other and to the committed reference, with a mutation
control confirming the comparison can fail.

Also fixed three arms that mixed a bare toTypeName() with an aggregate, which the old analyzer
rejects with NOT_AN_AGGREGATE (deterministic, 3/3 reruns on amd_llvm_coverage, old analyzer).
They now use any(toTypeName(...)), which returns the same value on both analyzers, so the reference
is unchanged; a negative control confirms the un-remedied form still fails. Preferred this to a
no-old-analyzer tag, which would have dropped old-analyzer coverage of the structure fix itself.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6653e9e

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
Stateless tests (amd_asan_ubsan, flaky check) / 04748_datalake_table_function_honors_structure (6 runs) PR-caused: my own new test still exceeds the 180 s cap (186.3 s) PR-caused - fixed in this PR
Stateless tests (amd_asan_ubsan, flaky check) / Too many test failures job-level --max-failures marker for the 6 rows above, not an independent defect same as above
Bugfix validation (unit tests) PR-caused: my own new gtest_drop_sorting_key.cpp calls dropSortingKeyIfItDoesNotDescribeColumns, which this PR adds, so the before-binary cannot compile it PR-caused - fixed in this PR
Stress test (arm_asan_ubsan) / UndefinedBehaviorSanitizer: undefined behavior (STID 2881-3dbd) signed-integer overflow at libcxx/__chrono/duration.h:93 in condition_variable::wait_for; not PR-caused (this diff touches only object-storage read paths) #106961 (mine, open)
Mergeable Check, PR aggregators reflecting the rows above same as above
CH Inc sync - CH Inc sync (private, not actionable)

The 04748 timing did improve on this head (236 s at cba0bd4d -> 186 s here after the batching
change), but not enough to clear the cap. The unit-test row is the documented harness shape where a
new gtest exercises a symbol the fix introduces; I will make the regression test build against the
merge base instead.

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

The flaky check runs a changed test about fifty times, and 04748 was landing at
180.7-186.3 s against the 180 s cap on amd_asan_ubsan while debug, tsan and
binary stayed under 110 s. Accounting the failing job's own query_log showed
where the time went for one 179.0 s run: 86.9 s of query execution, 81.2 s
spread over 40 client process starts at 2.03 s each under the check's 38-way
concurrency, and 11.9 s of intra-session gaps. Process starts, not queries,
were the term that put it over.

Two changes bring the process count from 41 to 19. Arms whose output was piped
into awk only needed the pipe because DESCRIBE prints a tab, so they now ask
for CustomSeparated with a space delimiter and join a session; that is
byte-identical to what the awk emitted. Groups that were separated only by an
echo marker are merged, with the marker becoming a SELECT of the same string.
An arm expecting an error still goes last in its group, since an error aborts
the rest of a session, and the two arms needing distinct query ids keep their
own clients. The reference file is unchanged.

The gtest is removed. Its four cases assert that a lake sorting key survives
only while it still describes the emitted columns, and the flat-key cases are
already asserted from SQL in this test through EXPLAIN PIPELINE. Its remaining
cases use a nested key, which no read can reach: a lake table with a nested
sort order fails to parse that order on both master and this branch, before
any of this code runs. It also broke Bugfix validation, which overlays the new
test onto the merge base and could not compile a call to a function this branch
introduces.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 77f98625, fixing both PR-caused rows from the 6653e9ec ledger.

04748 over the flaky-check budget. I accounted the failing job's own query_log: for a 179.0 s
run, 86.9 s was query execution, 81.2 s was 40 client process starts at 2.03 s each under the
check's 38-way concurrency, and 11.9 s intra-session gaps. Process starts were the binding term, so
the test now uses 19 client processes instead of 41 (counted by wrapping the client, not by grep).
The arms that were piped into awk only needed a pipe because DESCRIBE prints a tab; they now ask
for CustomSeparated with a space delimiter and share a session. An arm expecting an error goes last
in its group, and the two arms needing distinct query ids keep their own clients.

On the same binary and server, debug went 8.89 s -> 5.13 s. Substituting 18 remaining gaps into CI's
own model gives ~135 s against the 180 s cap, without crediting the two duplicate cluster reads the
log showed. Output is byte-identical to the previous form and to the committed reference, and
mutating one asserted value still fails the test.

Bugfix validation (unit tests). gtest_drop_sorting_key.cpp called a function this branch
introduces, so the before-binary could not compile it. I removed the file rather than reshaping it:
its flat-key cases are already asserted from SQL here via EXPLAIN PIPELINE, and its nested-key
cases are unreachable. A lake table with a nested sort order records source-id: 0 in its metadata,
because the writer's lookup at Iceberg/Utils.cpp:1101 indexes a top-level-only map, so the read
fails Code: 62 parsing the stored order before any of this code runs. That reproduces identically
on master (46286f19) and on this branch (5a26251c); Iceberg/Utils.cpp is byte-identical to the
merge base here, so it is pre-existing and I have left it alone.

Iceberg/Paimon/Delta sweep shows no new failures against the pre-change baseline on the same binary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 77f9862

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
(none) CI is fully green on this head no failures to own
CH Inc sync - CH Inc sync (private, not actionable)

Both PR-caused rows from the previous ledger (6653e9ec) are resolved on this head: the
04748_datalake_table_function_honors_structure flaky-check overrun and the Bugfix validation (unit tests) undeclared-identifier build failure are both gone. 162 checks report to the CI
database with 0 FAIL/ERROR rows across 338441 rows, the praktika report is PR = OK with 0
non-OK children of 177, and Finish Workflow plus Mergeable Check are both success.

Session id: cron:our-pr-ci-monitor:20260816-030000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR only changes data lake reads over object storage: Iceberg manifest pruning and Paimon partition pruning type checks, keeping the user's structure when the schema reloads, and type alignment for filters and identity partition columns. ClickBench and TPC-H read local MergeTree tables and never run this code. ClickBench Q20 shows -42.7% with about half the CPU time. The change is too large to override, so the improvement verdict stays, but nothing in this diff explains it, and it should be checked with a rerun before anyone credits the PR. ClickBench Q33 (-5.3%) is a noisy query inside master's recent range and was correctly suppressed; nothing in the TPC-H results was flagged.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 126 -42.7% <0.0001 cpu: This is a -42.7% drop backed by about half the CPU time, but the PR only changes data lake storage (Iceberg, Paimon, DeltaLake) code that ClickBench does not run. The large-change lock keeps the verdict, but the cause is not in this diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c2d28bf3-1645-4910-ad19-d45f72a4f775
  • MIRAI run: 6039d222-4b2c-45f5-9eff-c2b274eff274
  • PR check IDs:
    • clickbench_94625_1791940950
    • clickbench_94749_1791941004
    • clickbench_94857_1791941011
    • tpch_adapted_1_official_94970_1791941027
    • tpch_adapted_1_official_94992_1791941028
    • tpch_adapted_1_official_95188_1791941040

@fm4v
fm4v requested a review from scanhex12 August 24, 2026 11:01
groeneai and others added 2 commits August 29, 2026 14:57
getIdentityPartitionColumnValues names an extracted value with the field's full
name, so a nested partition source is called s.c. The type that value was
converted at was then looked up with tryGetByName over
getClickHouseTableSchemaById, which holds top-level fields only: a nested field is
registered separately, under that same dotted name, in clickhouse_types_by_source_ids
and clickhouse_ids_by_source_names. So the lookup missed, the constant was built at
the declared type from a lake-typed Field, and a retyping declaration over a nested
identity partition column raised Code: 170, has Int64, requested String, which is
the failure the previous commit fixed for a top-level column.

The lookup now completes by field id for any partition name the top-level list does
not hold, using tryGetColumnIDByName then tryGetFieldCharacteristics on the same
schema id. That second function is the one the extraction itself used to choose the
conversion type, so the appended pair is the extraction type by construction, and
its name is the dotted full name, so neither the helper nor its two call sites
change. Top-level names keep the existing path, which matters because a top-level
column may itself be named a.b: splitting the name on a dot would resolve that to a
nonexistent nested field and lose the value. No wire format changes; a name the
schema does not know is skipped and behaves as before.

No supported statement writes a nested partition spec: the writer builds its
name-to-source-id map from top-level columns only, so PARTITION BY s.c is rejected
with Unknown field to partition. The arm is therefore an integration test alongside
the four existing nested and dotted-name arms, built through pyiceberg, and reads a
table whose whole struct is removed from every data file so the value can only come
from the manifest. A second integration test covers what no stateless arm can see:
with both partition columns absent from the data files, a read that declined to
substitute returns the declared type's default instead of the value, and a mutant
that declines leaves the whole stateless file passing.

An explicit PREWHERE on a nested column cannot be an arm at all. Object storage
lists top-level names in supportedPrewhereColumns and does not admit subcolumns, so
the analyzer rejects it before any reader runs. The nested filter arm uses a plain
WHERE, whose equality against a string holds only for a converted value.

Three counter arms pin the low-cardinality half of the rule that keeps pruning where
a declaration differs only in a wrapper. That rule is three independent decisions,
one per pruning site, and the existing mutants restore exact equality and so delete
both strippings at once; one arm per site, each with a mutant deleting only its own
stripping, is what isolates them. Each pins
allow_suspicious_low_cardinality_types, without which the declaration is rejected
outright.

The explicit PREWHERE arm over an identity-partitioned table now pins
parallel_replicas_for_cluster_engines off, like the five arms before it. The
ParallelReplicas stateless lane enables parallel replicas through a users profile
rather than through the runner's randomization, and the table function is then
wrapped in a cluster storage that does not support PREWHERE. Running the whole file
under that lane's configuration found this one arm rejected and every pruning
counter undisturbed. The plain WHERE arm pins the two prewhere movers, which are
randomized off, so the sites it passes through do not vary; its answer is the same
either way. Each query_log lookup is scoped to the run's database, which the style
check requires and which a query id alone does not give.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three of the Paimon oracles compare a pruned read against the same read with
pruning off. max() over an empty set returns 0, not NULL: ProfileEvents is
Map(LowCardinality(String), UInt64), so ProfileEvents['x'] is a non-nullable
UInt64 and SingleValueDataFixed::insertResultInto pushes its zero-initialised
value unconditionally. A pruning query that logged no QueryFinish row therefore
compared as 0 < N and the arm reported success, which is the precise failure
those arms exist to catch: an exception on the path under test is logged as
ExceptionWhileProcessing and filtered out by the row-type predicate. Each pair
is now one query with a presence guard for both reads, and the comment that
claimed the opposite is replaced by the invariant. Measured both ways by
pointing one arm's pruning query id at an id that is never run: the old text
reports 1 and the file passes, the new text reports 0 and the file fails.

The three row-group counter arms read the initiator's query_log row, but
ParquetPrunedRowGroups is emitted where the reader runs, and that is a secondary
query wherever the cluster rewrite wraps the table function; a secondary query
also logs the default database rather than the initiator's. Both were measured
on one read: the counter is 1 on the secondary row and 0 on the initiator's. The
arms are now scoped to the initial query id and admit a row that is not the
initial one, which is what makes the file pass under the ParallelReplicas lane
configuration, where it failed before this change. The manifest counters are
undisturbed there for a reason that is also measured: manifest pruning is
counted while the initiator lists files, and no paimonLocalCluster is registered
for the rewrite to target, so no paimonLocal read is wrapped at all.

The nested identity partition filter arm compared s.c against an equality, which
returns the same rows whether the comparison runs at String or at Int64. It now
uses an ordering bound, where '2' and '10' both sort below '4' but only 2 is
below 4, so the row set holds only at the declared type. The value arm above it
keeps the non-injection property this arm used to duplicate.

The plain-WHERE ice25 arm now pins the cluster rewrite off, because under the
wrapper the mover has no PREWHERE to move into and its own pins cannot reach the
substitution the arm is there to exercise. The pin comment no longer presents
the same setting on a paimonLocal arm as doing work today; those pins are kept
so the arms are pinned the day such a function is registered.

No reference line moves, no arm is weakened and none is removed. Each rewritten
arm's liveness is re-proved by a single-decision mutant that reddens it and
nothing else.
@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Every finding below comes from an independent review pass over this branch, adjudicated against the
measurements in the branch's own validation record.

This branch went through six internal fix rounds and has reached my review-round limit, so it is
published as it stands. Everything I still consider open is listed below rather than held back. The
last round changed tests only; the source is byte-identical to the previously reviewed revision.

Finding Verdict
❌ An Iceberg identity-partition column's value is extracted once, converted to the type the Iceberg schema gives it, and then kept without that type. Both consumers insert it into a column of whatever type the query planned, so once a declared structure retypes such a column the read fails with Bad get: has Int64, requested String instead of returning the value in the declared type. It affects a plain SELECT of the column, with no filter and no delete files involved, and no fixture in the suite has a non-empty partition spec, so nothing covered it. Agreed. The two sites are pre-existing, but only this change makes a declared type reach them, and a retyping declaration already works for an ordinary column, so this is the same contract. Fixed by building the constant in the schema's type and converting it with ordinary read semantics, on a partitioned fixture created in the test, with a control that an agreeing declaration and no declaration are both unchanged. A later round found the type lookup consulted the schema's top-level column list only, so a nested partition source such as s.c still failed the same way; it now resolves such a name by field id from the same schema, covered by an integration test because no supported statement writes a nested partition spec.
❌ Paimon partition pruning built its key from the Paimon metadata types while the filter DAG was planned on the declared ones, so a declared type that orders values differently dropped partitions holding matching rows. Declaring f_bigint_nn String on the committed paimon_all_types fixture and filtering f_bigint_nn < '2' returned one row with use_paimon_partition_pruning = 1 and two with it off. The existing coverage could not see it: the test's Paimon fixture has no partition keys, so no key condition is ever built. Agreed. Fixed the same way as the other pruning sites, with a correctness arm on a partitioned fixture, a control asserting an agreeing declaration still prunes, and a third arm asserting a retype outside the partition keys does not cost the key its pruning.
❌ The reader's pruning guard compared filter types by exact equality, so a declaration differing from the lake's current type only by Nullable or LowCardinality withheld Parquet row-group and page pruning on a schema-evolved file. That contradicts the rule the Iceberg manifest guard in the same change applies on purpose, and it is read amplification relative to master. Agreed. Fixed, with a counter arm on an evolved file under a wrapper-only declaration, pinned by a mutant that restores exact equality.
⚠️ A counter arm reading ParquetPrunedRowGroups from system.query_log might be disturbed by the parallel-replicas machinery, since the two comparable tests in the suite carry no-parallel-replicas. Agreed, and correct as stated. The concern does not arrive through the test runner's randomization, which cannot reach the cluster wrapper; it arrives through that lane's users.d profile, a different channel. Measured there, three of the row-group arms did read a different value: whenever the cluster rewrite wraps the table function the read runs as a secondary query, which is where that counter is emitted and which logs the default database rather than the initiator's, so an arm scoped to the initiator's row read 0 and the file failed in that lane. They are now scoped to the initial query id and the file passes in both configurations. The manifest and Paimon counters are genuinely undisturbed, for a reason that is now measured rather than assumed: manifest pruning is counted while the initiator lists files, and no paimonLocalCluster exists for the rewrite to target. One arm was also genuinely rejected there, an explicit PREWHERE over a table function, because the wrapper does not support PREWHERE; it and every other arm that depends on PREWHERE now pins parallel_replicas_for_cluster_engines = 0 per arm.
❌ Three of the Paimon pruning oracles compare a pruned read against the same read with pruning off, and were fail-open in one direction: max() over an empty set returns 0, not NULL, so if the pruning query logged no QueryFinish row at all the comparison became 0 < N and the arm reported success. An exception on the path under test is logged as ExceptionWhileProcessing, filtered out by the row-type predicate, and would therefore have been read as a pass. A comment above them asserted the opposite, that a missing row makes the result NULL. Agreed. Each pair is now one query with a presence guard for both reads, so either read missing makes the arm fail, and the comment states the true invariant. Measured both ways on one arm by pointing its pruning query id at an id that is never run: the old text reports 1 and the file passes, the new text reports 0 and the file fails. Liveness is unchanged, re-proved by three mutants built on this head that redden the three oracles one each and nothing else.
⚠️ An Iceberg identity-partition value that is NULL is dropped before the constant is built, whenever the lake types the column Nullable, because the conversion that would reject it accepts NULL for a nullable target. With no entry, neither the filter substitution nor the injection can supply the column, so a declared non-nullable type reads the target type's default where master returns NULL. Agreed on the mechanism. Not changed here, and not because it is acceptable: preserving the entry makes the constant Nullable and the cast raise CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN on the ordinary schema-evolution path as well, which the alignment guard in this change exists to protect and which was measured failing 04737_iceberg_prewhere_modify_column_nullable on every run. Scoping the raise to a declaration the user actually wrote needs a provenance signal that does not exist today, because the cluster rewrite injects a structure argument on both of its branches and a worker cannot tell the two apart. That is the same nullability tradeoff already posted on this PR and awaiting an owner decision, and this finding is held with it rather than answered separately.
💡 Three accuracy points on the test, none of which can change an arm's answer: a nested filter arm's comment claimed the row set proves a conversion when an equality returns the same rows either way; every parallel_replicas_for_cluster_engines = 0 on a paimonLocal arm is inert, because the rewrite only fires for a registered *Cluster name and paimonLocalCluster is not one; and one arm's mover pins could not take effect in a lane where the wrapper leaves the mover nothing to move into. Agreed, all three addressed. The nested arm now uses an ordering bound and expects both rows, which holds only if the comparison runs at the declared type. The inert pins are kept, since they become live the day that function is registered, and the comment no longer presents them as doing work today. The arm whose mover pins were ineffective now pins the rewrite off as well, like its explicit-PREWHERE sibling.
💡 Comparing modulo Nullable and LowCardinality only means a declaration that merely widens, such as Int64 over a lake Int32, keeps its ordering yet still gives up the reader's pruning, even though 04545_parquet_minmax_stats_type_mismatch shows the reader already converts statistics bounds across scale and width. Noted, deliberate, and stated in the description. Converting the bound needs a per-type-pair ordering argument this change does not make; the guard fails closed instead. Values are unaffected either way.
💡 In the Paimon guard, one early exit cannot be reached because the helper above it already rejects that state, the predicate takes one argument from the member and one from the parameter, and the partition-key test is a linear scan. Noted, not changed. All three are behaviour-neutral on a path that runs once per read, and the scan is over at most a table's partition key list.
💡 A helper's filter_actions_dag parameter became dead once the pruning decision moved to its own predicate; a per-file Block copy is used only on the schema-changed path; two local fixtures were missing from the test's cleanup list. Agreed, all three addressed.
💡 The reader's pruning DAG is withheld only under schema_changed, which is set for a schema-id mismatch or an equality-delete file. On a file with neither, a reordering declaration such as id String over a physical Int64 still reaches the reader's row-group and page pruning at the declared type. Stated as unverified, not as a defect: confirming it needs a build and a run, and I did not observe a wrong result. Two things bound it. Iceberg manifest pruning is withheld for exactly this case, since that guard is deliberately not conditioned on schema_changed, so file-level pruning is already safe; and the reader has its own statistics type-mismatch path, which 04545_parquet_minmax_stats_type_mismatch covers. Recorded here rather than as a follow-up, because a code-reading argument with no observed consequence is not yet a bug.

…budget

04748_datalake_table_function_honors_structure reached 198.8-201.3 s per run on
`Stateless tests (amd_asan_ubsan, flaky check)` against the 180 s per-test ceiling
that check enforces (tests/clickhouse-test:3578-3583), failing 5 of 5 runs. The
ceiling is per test file, so the arms move into two new files instead of being
trimmed or exempted with `long`: no assertion is changed, added or removed.

Each arm keeps its query text and expected value byte for byte, the three
references partition the old one exactly, every (marker, expected values) block
survives unsplit, and each file carries only the fixtures and session settings its
own arms use. The subjects are the declaration being honored or set aside on a
local read (04748), the declaration not costing manifest, row group or partition
pruning nor the metadata sorting key (04749), and the same contract across S3 and
the cluster rewrite (04751).

Measured under that check's own thread fuzzer on one debug binary, solo, over two
rounds: 341.9/381.3 s for the old file against 124.7/128.5, 124.3/118.8 and
169.0/133.3 s. Scaling the 201.3 s CI maximum by each share gives 76, 73 and
100 s, a 1.8x worst-case margin. 04748 drops the optimize_read_in_order clamp
because it passes with that setting forced to 0 where 04749 fails, and a
randomized batch draws it 0 for 04748 and never for the two files that keep the
clamp. 50 randomized runs of each file pass; all three still fail on the pre-fix
binary, so each reproduces the bug on its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
if (schema_changed)
{
const Block & header_after_transform = builder.getHeader();
NamesAndTypesList columns_with_synthesized;

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 still misses nested identity-partition projections on ORC.

buildIdentityPartitionColumnsDag only keeps entries whose full partition name already exists in the reader header, but ORC is read with supports_tuple_elements = false (StorageObjectStorage.cpp:313 / prepareReadingFromFormat.cpp:83-100), so a requested s.c is read as its parent s. NativeORCBlockInputFormat documents the same assumption at findHeaderTypeByPath: its header carries only the parent column for ORC tuple elements.

On an Iceberg ORC file where identity partition s.c is absent from the data file, builder.getHeader() contains s, not s.c, so this DAG injects nothing. ExtractColumnsTransform then takes s.c from the default-filled missing parent tuple instead of the manifest value, and SELECT s.c returns NULL/defaults even though the manifest has the real partition value. The new identity-partition read fix is still incomplete for ORC-backed tables.

We need the same dotted-name / parent-tuple resolution here that the ORC reader already uses, so a manifest value for s.c can be injected even when the physical header only contains s.

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.

Confirmed, reproduced, and identical on the pre-PR base, so it is not introduced by this PR.

Fixture: local Iceberg table, identity partition on nested s.c (source id 3), s pruned from both
data files, so s.c can only come from the manifest.

declared format   SELECT id, s.c on af948ff   on the pre-PR base
Parquet           1 2 / 2 10                  1 2 / 2 10
ORC               1 \N / 2 \N                 1 \N / 2 \N

SELECT s on the ORC arm gives (NULL,NULL), so the parent tuple is default-filled as you describe.

Two scope corrections.

It is wider than ORC. checkIfFormatSupportsPrewhere has a single registration,
ParquetV3BlockInputFormat.cpp:406, which returns true unconditionally, so supports_tuple_elements
(StorageObjectStorage.cpp:313) is true only for Parquet and is decided from the table-level format
name alone. Same fixture: Parquet returns [2,10], while ORC, Avro, Arrow and Native all
return NULL.

It is not this PR's code. if (header.has(name)), supports_tuple_elements = format_supports_prewhere
and the dotted name that getIdentityPartitionColumnValues produces are all unchanged from master. When
the gate rejects every name the function returns an empty optional before any line this PR adds runs, so
that path cannot differ from master. What this PR changed there is only the type an injected value is
built on: the base fails the same read with Code: 170 BAD_GET once the declared structure retypes
s.c, and this head returns 2 and 10 as String.

Injection on real ORC files is fine: an ORC-backed table with a top-level identity partition id,
pruned from both .orc files, reads id back from the manifest correctly.

No change here. A fix task is created for the pre-existing defect.

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 in #117122, which injects the manifest value into the parent tuple the reader actually carries instead of matching the dot-joined name against the format header, so it also covers the SELECT s and PREWHERE cases.

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.

The original gate is still present on this head: buildIdentityPartitionColumnsDag only keeps entries whose full name is already in the reader header (src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:363). For ORC/Arrow/Native, a requested nested partition field such as s.c still arrives via its parent tuple s, so this branch still drops the manifest value before any injection happens.

So the #117122 fix is not actually present here yet; this thread should stay open until that change is merged or cherry-picked into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - af948ff

Every failure below has an owner: a fixing PR, 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 (arm_darwin) / 01599_multiline_input_and_singleline_comments Timeout! Killing process group at 60,080 ms #117053 (mine, merged 2026-08-29T21:37:42Z). It merged after this build started, so the fix is absent from the tree that ran; the next push on this branch picks it up.
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_parallel_replicas_custom_key_load_balancing[custom_key_range-key-0] flaky: Code: 209 SOCKET_TIMEOUT, connect timed out to a cluster node mid-test. 2 hits across 2 unrelated PRs in 30 days, 0 on master, onset 2026-08-29 a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
CH Inc sync failed, needs manual intervention CH Inc sync (private, not actionable by me)

CIDB also holds 20 Bugfix validation (integration tests, aarch64/amd64) FAIL rows at this SHA. Those are the intended inversion (check_status = success): the new regression tests correctly fail against the pre-fix binary. Mergeable Check and PR are rollups of the two rows above, not independent failures.

Session id: cron:our-pr-ci-monitor:20260830-023000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the test_parallel_replicas_custom_key_load_balancing row above

That row is not a parallel-replicas defect and not test flakiness. The test's own n1 server is
SIGKILLed while the test is mid-flight, and the client reports whatever the socket does next.
Measured on both occurrences (this head, and one other head 7 h earlier on the same shard):

  • _instances-gwN/docker.log: n1-1 | /integration-tests-entrypoint.sh: line 26: 8 Killed, then
    Server exited with 137. n2 to n4 receive the harness SIGTERM afterwards and exit 0.
  • n1/clickhouse-server.log stops mid background merge with no <Fatal>, no signal output and no
    sanitizer report, which is what a SIGKILL looks like from inside.
  • docker-in-docker.log holds a dense burst of containerd /tasks/oom events bracketing the kill
    (4714 over 34 s here, 5682 over 33 s on the earlier head), and the container whose task exits at
    the end of the burst is this module's own n1.
  • n1 was far from its own 12 GiB container limit: its largest tracked allocation in the whole run
    is 12.59 MiB and MemoryWorker never lowered the server limit, so the binding limit was an
    ancestor cgroup rather than the container's.
  • Code: 209 SOCKET_TIMEOUT and Code: 210 Connection reset by peer are the same event at
    different moments: a fresh connect once the container is gone, versus a connection already open.

Which cgroup breached, and which task the kernel picked, is not recoverable from what this job keeps:
the kernel record is written to ./ci/tmp/dmesg.log after the artifact glob has already run, so it
is never uploaded. #117104 restores it. The retained capacity counters cannot stand in, because they
are identical on green and red runs of this shard: /docker peaks at its 40.78 GiB cap on all 7 runs
I compared (3 red, 4 green), /dockerd at 18.33 to 18.36 GiB, /init at 21.00 to 22.41 GiB.

The same kill reaches this shard far more often through test_s3_plain_rewritable (28 failing rows
since 2026-08-28, 2 of them on master, against 2 rows for this test), and the fix task for the kill
is the one tracking that. This row is another victim of it rather than a separate defect, so I am not
opening a second PR for it. The fixing-PR link still lands here.

groeneai and others added 2 commits September 14, 2026 12:20
Three conflicts, all in code master also changed since `e3a0441c`.

`StorageObjectStorageCluster`, header and constructor: master added
`format_settings_` and `catalog_` at the same trailing position this branch added
`preserve_structure_for_reads_`, so the two insertions collided on position only.
Both are kept, master's two first so its own call site in `DatabaseDataLake.cpp`
keeps binding positionally, and the two table function call sites this branch
touches now pass those defaults explicitly. Member declarations and the
initializer list follow the same order.

`DataLakeConfiguration.h`: master changed `getExternalMetadata()` to return
`std::shared_ptr<IDataLakeMetadata>`, and this branch inserted
`schemaReloadIgnoresExplicitStructure()` immediately above it. Master's signature
is taken and this branch's method is kept.

The identity partition block in `StorageObjectStorageSource.cpp` merged without a
conflict but still read the raw pointer, so its
`dynamic_cast<const IcebergMetadata *>` becomes
`std::dynamic_pointer_cast<const IcebergMetadata>`, the spelling master now uses
for the DeltaLake check in the same file.

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

Both pruning sites treated a nullability difference as a wrapper that cannot reorder
values, so a partition key the lake schema declares nullable kept its pruning when the
query declared it non-nullable. Reading a partition whose value is NULL then materializes
the declared type's default under `input_format_null_as_default`, while both pruners map
that NULL to positive infinity, so the partition is dropped while holding rows the filter
matches. Withhold pruning for that direction; the widening one is unaffected, and so is a
low-cardinality difference.

Paimon, measured on `data_minio/paimon_all_types`, whose nullable `f_date` partition key
has five rows in its NULL partition. Before this commit,

    SELECT count() FROM paimonLocal(..., 'Parquet', 'f_date Date')
    WHERE f_date = toDate('1970-01-01')
    SETTINGS use_paimon_partition_pruning = 1, input_format_null_as_default = 1

returned 0, the same query with pruning off returned 5, and the unfiltered
`countIf(f_date = toDate('1970-01-01'))` over the same declaration returned 5.

Iceberg, measured on a table partitioned by a nullable `p` with two rows in its NULL
partition. Before this commit, `WHERE p = 0` under a declared `p Int64` returned 0 with
`use_iceberg_partition_pruning = 1` (`IcebergPartitionPrunedFiles` = 3) against 2 with it
off and 2 unfiltered. Min/max pruning alone does not have this shape, because an all-NULL
column carries no bounds to compare, so a partitioned fixture is what reaches it.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b6c7354

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

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 2270-3184) trunk logical error, server abort in a build with abort_on_logical_error. The port header is k UInt64, s AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) and the chunk carries a single UInt64 column, so the source emitted nothing for s. That parameterisation has start 10 past end 5, so the Resample combinator builds zero buckets and the state serializes to zero bytes. Abort is at src/Processors/Port.h:431 (DB::OutputPort::pushData) reached from DB::ISource::prepare() at src/Processors/ISource.cpp:49, under PullingAsyncPipelineExecutor::pull #119728 (mine, open)
Mergeable Check, PR praktika rollups of the row above, no independent leaf failure #119728 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

#119728 is the causal owner rather than a same-area coincidence: it rejects exactly the
parameterisations whose aggregate state serializes to zero bytes, and it edits
src/AggregateFunctions/Combinators/AggregateFunctionResample.cpp and its header, which is the
combinator named in the failing header above. The tracking issue for the same defect is #119727.
A test-only companion, #120048, lifts the affected fixture out so trunk goes quiet sooner. Both are
still open, so this signature keeps firing until they land.

Not reachable from this diff: this branch changes src/Storages/ObjectStorage/**,
src/TableFunctions/TableFunctionObjectStorage*.cpp and datalake tests only. It contains no
aggregate-function, combinator, processor or port code, so it cannot reach the aborting site.

CI is finished on this head: every praktika check-run is COMPLETED and Finish Workflow is green
(18:23:29Z). The CH Inc sync commit status is still pending and is exempt above.

Session id: cron:our-pr-ci-monitor:20260914-220033

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 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.

groeneai and others added 3 commits September 29, 2026 11:48
Two conflicts, both in the include blocks of files master also changed since
`caf26def`; no logic was touched to resolve them.

`ManifestFilesPruning.cpp`: master added `Common/DateLUT.h`,
`Core/DecimalFunctions.h` and `base/arithmeticOverflow.h` where this branch added
`DataTypes/DataTypeLowCardinality.h`. All four are kept.

`StorageObjectStorageSource.cpp`: master added `Interpreters/castColumn.h` where
this branch added `Interpreters/addMissingDefaults.h`. Both are kept.

Master's ClickHouse#122681 builds the min/max hyperrectangles and the new date partition
ranges only for the field ids in `used_columns_in_filter`, which is the list this
branch filters, so a column whose declared type the pruner must not compare stays
unpruned on those paths too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#120311, `enable_analyzer = 0` is accepted and replaced with `1`. On the
analyzer, a key-value `structure` whose value calls `hostName()` is rejected on a
cluster read with `Code: 36 ... is not a constant expression`, and master rejects it
the same way on plain `s3Cluster` (measured on master `6ee563bc`). The two arms that
pinned the old analyzer to guard that shape therefore assert what master no longer
accepts.

The literal-operand `concat` arm stays, without the setting that is now a no-op: it
reads the declared column (`2 2`) where master rejects it with `Code: 47`.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a96940c

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
Integration tests (amd_llvm_coverage, 1/8) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds trunk regression, not caused by this PR: it fails identically on every master commit since 2026-09-29 10:59Z (16 in a row, 0 passes). Master now decodes manifest bounds only for the columns a filter uses, so the log line that the assertion at line 337 waits for is no longer written #122895 (mine, merged), merged master @ 77395302143b9
Integration tests (amd_asan_ubsan, db disk, targeted) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds same trunk regression; the targeted jobs run the Iceberg tests because this PR touches Iceberg, and they fail the same way on other Iceberg PRs today #122895 (mine, merged)
Integration tests (amd_msan, targeted) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds same trunk regression #122895 (mine, merged)
Integration tests (amd_tsan, targeted) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds same trunk regression #122895 (mine, merged)
Integration tests (arm_binary, distributed plan, targeted) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds same trunk regression #122895 (mine, merged)
Mergeable Check, PR rollups, red only because of the five rows above #122895 (mine, merged)
Sync - CH Inc sync (private, not actionable by me)

146 of 146 check runs completed (126 passed, 15 not selected, 5 red: the jobs above, one test), and Finish Workflow is green. The FAIL rows CIDB lists under both Bugfix validation (integration tests) jobs are their inverted results; both jobs passed.

#122895 merged at 16:58Z, after this run was dispatched (12:34Z), so the tree CI built (6c541ac02d1c) does not contain it. I merged master into the branch at 77395302143b9, where #122895 is an ancestor. My own change is unchanged across the merge (26 files, +1631/-107, same patch id). CI is re-running on 77395302143b9.

Session id: cron:our-pr-ci-monitor:20260929-173122

@JiaQiTang98 JiaQiTang98 self-assigned this Oct 6, 2026
alexey-milovidov and others added 3 commits October 10, 2026 17:29
…-honor-structure-datalake-tf

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

Master now rejects `UInt64` columns in an Iceberg schema
(ClickHouse#118596), so
`ALTER TABLE ice17 ADD COLUMN c Nullable(UInt64)` throws and aborts the rest
of the session. Add the column as `Nullable(Int64)` instead, and declare it
the same way in the `icebergLocal` structure arguments that read `ice17`.
The values and the reference output are unchanged. The other `UInt64`
declarations in the test are table function structures, which are not
subject to the check.

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

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Dear @JiaQiTang98, 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Paimon table functions: the structure argument is reported by DESC but ignored by SELECT

5 participants