Skip to content

Fix DEFAULT expressions that read a Hive partition column - #133299

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-hive-partition-column-in-default
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-hive-partition-column-in-default

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 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 reading a column whose DEFAULT expression uses a Hive partition column (use_hive_partitioning or partition_strategy = 'hive') from file, url, s3, azureBlobStorage, hdfs, their *Cluster variants, the matching table engines and S3Queue/AzureQueue: such a query failed with UNKNOWN_IDENTIFIER, or returned the type default for formats that read every column, such as CSV.

Description

On 26.8.18.2 and 26.10.5.57, SELECT * FROM file('data/k=*/f.jsonl', JSONEachRow, 'c0 Int32, k String, d String DEFAULT k') SETTINGS use_hive_partitioning = 1 fails with UNKNOWN_IDENTIFIER k, and the same read of a CSV file returns an empty d instead of abc. For S3Queue the file is marked Failed and its rows are never ingested. Reported on #131975 (#131975 (comment)).

Cause: StorageObjectStorageSource, StorageFile and StorageURL evaluate defaults (AddingDefaultsTransform) inside the per-file reader, but append the Hive columns only after it, and the format never reads them (#87515).

Change: prepareReadingFromFormat records the Hive columns that a DEFAULT reads (hive_partition_columns_read_by_defaults, subcolumns included, an exact column name such as k.value first). The three readers pass them through one helper, HivePartitioningUtils::makePartitionColumnsForDefaults, to AddingDefaultsTransform, which builds them as constants from the file's path only for a chunk where it evaluates a default that reads them, and adds them only to the block the defaults are computed from. Their own DEFAULTs are not used, and a path value that does not fit the type fails the read, as SELECT k does. A read that needs no such default behaves as before, even if the path lacks the key or holds a value that does not fit its type.

Tests: new 05839_hive_partition_column_in_default (file JSONEachRow/CSV, s3, url, unselected and transitive cases, a Hive column with its own DEFAULT, columns named k.value and k.null, and reads that need no such default over a key that does not fit its type or is missing); 04829_lazy_materialization_hive_partition_defaults asserted the old UNKNOWN_IDENTIFIER and now checks the values. Also verified locally: S3Queue materialized view, fileCluster/s3Cluster/urlCluster, Parquet with PREWHERE and lazy materialization.

Not changed: a DEFAULT over a file column the query does not read fails the same way for any column kind; the legacy Hive engine has the same ordering in its own reader.


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

groeneai and others added 2 commits November 20, 2026 19:05
The file-like readers (`StorageObjectStorageSource::createReader`,
`StorageFileSource`, `StorageURLSource`) evaluate column defaults with
`AddingDefaultsTransform` inside the per-file reader pipeline, but append the
Hive partition columns to the chunk only after that pipeline, and
`prepareReadingFromFormat` never lets the format read a Hive column (ClickHouse#87515).
A default over a Hive column therefore had no input: for formats that read a
subset of columns it failed with `UNKNOWN_IDENTIFIER`, for formats that read
every column (CSV, TSV, ... on File/URL) it silently took the Hive column's
own default or the type default. For S3Queue the file was marked Failed.

`prepareReadingFromFormat` now records the Hive columns that a default of
`columns_description` reads (`hive_partition_columns_read_by_defaults`,
matched with `isSameOrNestedColumn`, so a subcolumn reference records its
parent), `updateFormatPrewhereInfo` carries the field, and the three readers
add those columns as constants from the file's path in front of
`AddingDefaultsTransform` through `HivePartitioningUtils::addPartitionColumnsForDefaults`
(the same parse/convert functions as `addPartitionColumnsToChunk`).
`ExtractColumnsTransform` drops them again, so the source header and reads
whose defaults do not use a Hive column are unchanged.

`AddingDefaultsTransform` indexed `BlockMissingValues`, which is sized to the
format header, by the block position of every defaulted column; a Hive column
with its own DEFAULT appended after the format's columns would be read out of
bounds (libc++ hardening abort in debug builds), so positions the format did
not produce are skipped.

`04829_lazy_materialization_hive_partition_defaults` asserted the old
`UNKNOWN_IDENTIFIER`; it now checks the values.

Related: ClickHouse#131975 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the header comment of addPartitionColumnsForDefaults (the name says it) and shorten two comments to the invariant they state.

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

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

Pre-publication review by an independent model (engine: codex; 3 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ❌ A serialized object-storage plan loses hive_partition_columns_read_by_defaults (prepareReadingFromFormat.h) DISAGREE ReadFromObjectStorageStep is serializable only under #if CLICKHOUSE_CLOUD (ReadFromObjectStorageStep.h:67-75), IQueryPlanStep::isSerializable() defaults to false, and ReadFromFormatInfo::deserialize has no caller in src/. An empty field gives the old behaviour, not a new failure.
2 ❌ A direct SELECT from S3Queue/AzureQueue does not pass the Hive params (StorageObjectStorageQueue.cpp:784) DISAGREE Fixed on master by #131975 (merged after this branch's base). The direct SELECT then reads through StorageObjectStorageSource::createReader, which this PR changes.
3 ⚠️ No S3Queue test DISAGREE No queue code changes here; the queue source calls the same createReader that the s3() query of 05839 exercises. S3Queue materialized view measured locally: master marks the file Failed (UNKNOWN_IDENTIFIER, 0 rows), the fix ingests 1 abc abc.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. data/k=abc/f.jsonl = {"c0":1}, SET use_hive_partitioning = 1; SELECT * FROM file('data/k=*/f.jsonl', JSONEachRow, 'c0 Int32, k String, d String DEFAULT k') gives UNKNOWN_IDENTIFIER k on master every time; the CSV form with k String DEFAULT 'x' gives 1 abc x instead of 1 abc abc.
b Root cause explained? The three file-like readers evaluate defaults in the per-file reader pipeline and append the Hive columns only after it; the format never reads them, so a default over one has no input (subset formats) or takes the Hive column's own default (formats that read every column).
c Fix matches root cause? Yes. The Hive columns a default reads are added from the file's path in front of AddingDefaultsTransform, with the same parse and conversion as the output column. No setting, no guard.
d Test intent preserved / new tests added? New 05839_hive_partition_column_in_default (file JSONEachRow and CSV, s3, url, unselected Hive column, transitive default, subcolumn). 04829_lazy_materialization_hive_partition_defaults asserted the old UNKNOWN_IDENTIFIER and now checks the values.
e Both directions demonstrated? Yes. Both tests fail on a master server and pass with the fix; 05839 50/50 with randomized settings, 04829 20/20. Removing the new bound check in AddingDefaultsTransform aborts the debug build on the CSV case (vector[] index out of bounds).
f Fix is general across code paths? Yes. StorageObjectStorageSource (s3, azure, hdfs, *Cluster, S3Queue/AzureQueue), StorageFile, StorageURL; the lazy-materialization branch keeps such a default on the main branch; the PREWHERE copy of the read info carries the new field. Checked locally: S3Queue materialized view, fileCluster, s3Cluster, urlCluster, parallel replicas. The legacy Hive engine is not changed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. String, LowCardinality(String) and Nullable(String) keys, a .null subcolumn, Array and Map defaults, JSONEachRow, CSV and Parquet, parallel parsing on and off; an unconvertible path value gives the same TYPE_MISMATCH as a selected Hive column.
h Backward compatible? (maintainer-approved exception only) Yes. Reads whose defaults do not use a Hive column are unchanged (checked: an unconvertible Hive key stays silent when no default reads it). No setting or format change.
i Invariants and contracts preserved? Yes. The added columns are appended after the format's columns, so BlockMissingValues positions are unchanged, and ExtractColumnsTransform restores the requested header. The bound check only changes positions that were out of range.

Session id: cron:clickhouse-impl-slot-7:20261120-175200

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [47a5f50]

Summary: ✅


AI Review

Summary

The PR supplies Hive partition values to DEFAULT evaluation in file-like readers and preserves them through PREWHERE and lazy materialization planning. One verified compatibility regression remains: a previously successful conditional default now validates a partition value that its selected branch never uses. This was deliberately retained by the author and is reported here without duplicating the inline discussion.

Findings

❌ Blockers

  • src/Processors/Transforms/AddingDefaultsTransform.cpp:291 — Previously successful reads can now fail without a compatibility setting. [dismissed by author -- https://github.com/Fix DEFAULT expressions that read a Hive partition column #133299#discussion_r4648556244] The dependency walk includes k from an unused conditional branch, and get_extra_inputs calls convertPartitionValueToType before evaluating the expression. With k=abc/f.csv containing 1, followed by a newline:

    SELECT d
    FROM file('k=abc/f.csv', CSV,
        'c0 Int32, k UInt32, d String DEFAULT if(c0 = 1, \'x\', toString(k))')
    SETTINGS use_hive_partitioning = 1,
             short_circuit_function_evaluation = 'enable';

    I reproduced x on released 26.10.5.57 and TYPE_MISMATCH on the PR head's fast-test binary. The author's rationale concerns correcting reads that use the partition value; this input never uses it, so rejecting it still breaks an existing successful read. Preserve this case or provide a versioned compatibility setting that restores the previous behavior, with a focused stateless regression.

Final Verdict

Status: ❌ Block

Preserve the successful conditional read above, or add a versioned compatibility path and regression coverage. No new inline findings were posted; the remaining finding already has a thread and was explicitly dismissed.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). labels Nov 20, 2026
Comment thread src/Storages/HivePartitioningUtils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

37 object files changed (+67.94 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/HivePartitioningUtils.cpp.o 165.25 KiB 184.45 KiB +19.21 KiB (+11.62%)

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

Compile time of recompiled translation units

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

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

Job report

groeneai and others added 2 commits November 20, 2026 21:19
The previous commit added the Hive partition columns that a `DEFAULT` reads
to the stream in front of `AddingDefaultsTransform`, converting the path
value when the file was opened. A read that never evaluates such a default
then failed if the value does not fit the column's type or the path lacks
the key: `SELECT d` over a file where `d` is always present, `SELECT c0` and
`count()` over a `CSV` file (the format reads every column), or `SELECT d, e`
where only the unrelated default of `e` is evaluated. Such reads worked
before.

`AddingDefaultsTransform` now takes a callback that builds extra inputs. It
is called only for a chunk where some default is evaluated, with the columns
those defaults read (transitively), and the Hive helper builds only the
partition columns among them. The stream itself is unchanged, so the bound
check on `BlockMissingValues` is no longer needed.

Reported in ClickHouse#133299 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`AddingDefaultsTransform` collects the columns a default reads and descends
into the defaults of the ones the format does not produce, because those
defaults are inlined into the evaluation. It also descended into the defaults
of Hive partition columns, which the transform takes from the path instead,
so their own inputs were built (and converted) too.

For CSV with `c0 Int32, k String DEFAULT toString(q), q UInt32,
d String DEFAULT k` and the path `k=abc/q=bad/f.csv`, `SELECT d` threw
`TYPE_MISMATCH` converting `bad` to `UInt32` instead of returning `abc`.

The transform now gets the columns the path supplies up front and treats them
as available, like the header columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 21, 2026 00:25

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

…lumns

A physical column named `k.value` can coexist with a Hive partition column
`k`; the dot does not make it a subcolumn of `k`. Both the collection in
`prepareReadingFromFormat` and the per-chunk filter of
`makePartitionColumnsForDefaults` matched by name prefix, so a default that
reads `k.value` converted the unrelated path value of `k`, and an
unconvertible key (`k=abc`, `k UInt32`) failed a read that 26.10.5.57
returns.

`prepareReadingFromFormat` now resolves each identifier of a default with
`tryGetColumnOrSubcolumn` on the storage columns (exact names first, then
subcolumns) and records the Hive columns among the results.
`AddingDefaultsTransform` resolves subcolumns of the extra inputs too (a
Hive column is not in the format's columns description), so the names it
passes to the callback are columns, and the callback matches them exactly.

The defaults are evaluated over the read columns, so a default over an
unread physical `k.null` would resolve to the null map of a Nullable Hive
`k` given to another default, and return `0` where master fails with
`UNKNOWN_IDENTIFIER`. A Hive column with a subcolumn of the same name as
such an unread column is not given to the defaults, which keeps master's
behaviour there.

05839 gets the reported CSV case, one where another default that reads
`k` is populated, which only the exact filter keeps from converting `k`,
and the unread `k.null` case over JSONEachRow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the AsyncInsert job the `INSERT INTO FUNCTION s3(s3_conn, filename =
currentDatabase() || ...) VALUES` fixture write is queued and flushed in a
context without the session database, so `currentDatabase()` evaluates to
`default` there and the object lands at `default/k=abc/f.jsonl`. The
following `s3()` read of `<test db>/k=abc/f.jsonl` then fails with
`S3_ERROR` 404 (deterministic: 11/11 and 48/48 in the CI diagnosis).

The `file()` writes are not affected: their path argument is folded to a
literal before the flush. Same remedy as 05315 (4ab8ff6): set
`async_insert = 0` on that INSERT.

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

Copy link
Copy Markdown
Member

🕵️ @groeneai The fix works on the CI build of 47a5f50. With the Hive columns listed in the structure, all 48 combinations I ran return the right values:

  • JSONEachRow, CSV, TSV and Parquet files, with d String DEFAULT k, a transitive e String DEFAULT concat(d, '!'), m Int64 DEFAULT n * 2 and dd Date DEFAULT dt + 1;
  • optimize_move_to_prewhere and query_plan_optimize_lazy_materialization at 0 and 1;
  • a full read, WHERE d = k, and ORDER BY ... LIMIT 5.

On master all of them fail with UNKNOWN_IDENTIFIER.

One gap: a Hive column that is not in the structure. With use_hive_partitioning = 1 it is still added to the columns, so SELECT k works (as LowCardinality(String), on master too), but a DEFAULT over it still fails on this PR:

-- data/k=abc/n=5/dt=2020-01-05/f.jsonl holds {"c0":1,"d":"x"} and {"c0":2}
SELECT c0, k FROM file('data/k=*/n=*/dt=*/f.jsonl', JSONEachRow, 'c0 Int32') SETTINGS use_hive_partitioning = 1;
-- 1  abc, ...

SELECT c0, d FROM file('data/k=*/n=*/dt=*/f.jsonl', JSONEachRow, 'c0 Int32, d String DEFAULT k') SETTINGS use_hive_partitioning = 1;
-- Code: 47. Unknown expression or function identifier `k` ... In scope SELECT _CAST(k, 'String') AS d, ...

It is the same for CSV, TSV and Parquet. Is this intended? If a DEFAULT should only read columns listed in the structure, a clearer error would help, since k itself can be selected. Otherwise the Hive columns added from the path could be included when collecting what the defaults read.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, this is intended, and it does not come from the read path. The structure is rejected while it is parsed, before any file is listed: EXPLAIN over a path that does not exist fails the same way. A DEFAULT or an ALIAS in the structure can only use the structure's columns, the same check as CREATE TABLE. A Hive column missing from the structure is added later as a virtual column, like _path, and 'c0 Int32, d String DEFAULT _path' fails with the same UNKNOWN_IDENTIFIER, on master too. #111776 rejects the same thing in CREATE TABLE, because a DEFAULT is also evaluated on INSERT, where there are no virtual columns.

Listing the column works with any type. On your files, 'c0 Int32, k LowCardinality(String), n Int64, dt Date, d String DEFAULT k, m Int64 DEFAULT n * 2, dd Date DEFAULT dt + 1' returns 1 x 10 2020-01-06 and 2 abc 10 2020-01-06 on this PR, and UNKNOWN_IDENTIFIER dt on master.

A clearer error needs the path's keys when the structure is parsed, and they are not known there yet. It would be a separate change to the table functions, which I can do if you want it.

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-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants