Skip to content

Fix 0 rows from Hive-partitioned files when a query needs no column of the data file - #123381

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-hive-partition-smallest-column
Oct 3, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-hive-partition-smallest-column

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120319

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 reads of Hive-partitioned files (.../key=9/...) that need no column of the data file, such as count() with optimize_count_from_files = 0 or SELECT key, _row_number, returning no rows (Native threw an exception) when a partition column was smaller than the data columns. The wrong 0 was also cached and returned by later count() queries. The same reads of a structure that lists only partition columns returned no rows or threw an exception for most formats. Affects file, url, s3 and other object storages.

Description

Requested in #120319 (comment), from the flaky check of #120319 (report): 05233_hive_partition_strategy_format_extensions got count() = 0 when the runner drew optimize_count_from_files = 0.

On 26.3 and 26.8, with x/key=9/b.jsonl containing {"s":"a"}:

SELECT count() FROM file('x/key=9/b.jsonl', JSONEachRow) SETTINGS optimize_count_from_files = 0; -- 0, expected 1
SELECT key, _row_number FROM file('x/key=9/b.jsonl', JSONEachRow); -- no rows, expected 9 0

When a query needs no column of the data file, prepareReadingFromFormat reads its smallest column. The candidates included the Hive partition columns, so the Int64 key beat Nullable(String). Since #87528, partition columns are never read from the data file, so key was dropped from the format header. A row format with an empty header returns no rows, and the 0 went into the row-count cache. Native failed with LOGICAL_ERROR instead.

The fallback now picks the smallest non-partition column, as 5b4e7ed did for Delta Lake. A structure that lists only partition columns (for example 'key Int64' over a=1/key=9/...) has no other column: those columns are now kept in the format header and read from the file as the structure declares, as before #87528, while the result still takes their values from the path. With the empty header, 19 of 23 formats returned no rows or failed on such reads. Filters and the Parquet top-K threshold are then not pushed into the format, which would see the file's values instead of the path's (ORC skipped a whole file on WHERE key = 9 when it stored 10); #122109 adds top-K for object storage and needs the same check.

The test covers s3 and file: count(), the cached count and _row_number, a partition-columns-only structure with top-K, WHERE and a row policy (Parquet, ORC), and Native. It fails on master and passes 50/50 randomized runs with the fix.


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

Version info

  • Merged into: 26.10.1.1364-master (included in 26.10 and later)

…f the data file

When a query needs no column of the data file (count() without the
count-from-files shortcut, only Hive partition or virtual columns,
`_row_number`), `prepareReadingFromFormat` falls back to reading the
smallest column of the data file. The candidates still contained the
Hive partition columns, and an integer or Date key is smaller than any
Nullable or String data column, so a partition column was chosen. Since
ClickHouse#87528 partition columns are never put into the format header, so the
header became empty: row formats then return no rows (and the 0 is
stored in the row-count cache), Native throws LOGICAL_ERROR.

Pick the smallest non-partition column instead, as 5b4e7ed did for
Delta Lake. A structure that lists only partition columns has no other
column, so the previous choice is kept for it: the count-from-files path
and Parquet already read such a structure correctly.

Found by the flaky check of ClickHouse#120319 (05233 with a randomized
optimize_count_from_files = 0).

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

groeneai commented Oct 2, 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) plus my own review, two rounds; the second round (after the fixes below) had no findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ A read-time INCORRECT_DATA for a structure of only partition columns rejected reads that master answers correctly (count-from-files path, Parquet) AGREE, fixed the check is dropped; such a structure keeps the previous fallback
2 💡 The Native LOGICAL_ERROR was not covered by the test AGREE, fixed Native arm added
3 ⚠️ The cached-count arms do not prove a cache hit DISAGREE on master both arms print 0 while the uncached count of the same file is 1, so the arm fails without the fix

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

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM file('x/key=9/b.jsonl', JSONEachRow) SETTINGS optimize_count_from_files = 0 over a one-row file returns 0 on master, 26.8.2.7 and 26.3.33.24 on every run, with both input_format_parallel_parsing values.
b Root cause explained? Yes. When no data-file column is needed, prepareReadingFromFormat reads the smallest column among the data-file columns, which included the Hive partition columns. The Int64 key is chosen, then dropped from the format header (partition columns are never read from the file), the header is empty, the row format returns no rows, and the 0 is cached.
c Fix matches root cause? Yes. The fallback picks the smallest non-partition column (same as 5b4e7ed for Delta Lake). No guard on the cache, no tag, no bound change.
d Test intent preserved / new tests added? New test 05316: s3 and file, count(), cached count, _row_number, a use_hive_partitioning = 0 control, a partition-columns-only structure and Native.
e Both directions demonstrated? Yes. Master: the 4 count and 2 _row_number arms fail and the Native arm aborts the server. Fix: OK, 50/50 randomized. Reverting the fallback fails the same arms. Dropping the fallback to all columns when no other column exists gives LOGICAL_ERROR: No available columns for the partition-columns-only structure.
f Fix is general across code paths? Yes. One shared function serves file, url, s3, azureBlobStorage, hdfs, S3Queue and their *Cluster variants. Delta Lake already has its own non-partition fallback. url and s3 were checked by hand.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked 10 formats (CSVWithNames, TSVWithNames and TSKV were wrong, Native gave LOGICAL_ERROR, all are fixed). Also checked Int64, Date and LowCardinality(Nullable) keys, paths with three keys, explicit and inferred structure, a data column smaller than the key, and an empty glob.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or new validation. A structure listing only partition columns keeps the previous column choice, and its reads give the same results as on master (checked for JSONEachRow and Parquet, with and without the count-from-files path).
i Invariants and contracts preserved? Yes. When the data file has a non-partition column, the format header always contains one. Otherwise the choice is the same as on master. getSmallestColumn gets an empty list only when it did before.

Session id: cron:clickhouse-impl-slot-5:20261002-004100

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1737975]

Summary: ✅


AI Review

Summary

This PR fixes the empty-reader-header path for Hive-partitioned file-like reads when the query needs no data-file columns, and it carries the fix through the partition-only compatibility case by keeping row production correct while withholding format-level filtering/top-K decisions from path-derived partition columns. I did not find any remaining correctness, caching, or format-pushdown issues in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 1737975.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 37/38 (97.37%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). label Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

A structure can list only Hive partition columns when the path has more
keys than the structure, e.g. 'key Int64' over 'a=1/key=9/data.jsonl'
(the sanity check rejects only a structure equal to the partition
columns). The fallback then has no other column to pick, and dropping the
partition columns from the format header left it empty. Most formats
cannot read with an empty header: of 23 formats measured, 12 returned no
rows on every path that reads the file (optimize_count_from_files = 0,
_row_number), TSV, CSV, Avro, JSONCompactEachRow, Native and
CustomSeparated threw a LOGICAL_ERROR, Values failed to parse; only
Parquet, ORC, Arrow and ArrowStream were correct.

Keep the columns in the format header when nothing else is left, so they
are read from the file as the structure declares, which is what happened
before ClickHouse#87528. Their values are not returned: the requested partition
columns still come from the path. For the same reason, a partition
column must not arm the Parquet top-K filter, which would otherwise
compare the file's values with a threshold built from the path's values
and drop rows of the result.

Structures with a data column and RawBlob/One with an inferred schema
are not affected.

Found by the AI review of ClickHouse#123381.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With a structure of only Hive partition columns the format reads them
from the file (previous commit), but the query takes their values from
the path. The query filter was still passed to the format, so the format
filtered on the file's values: ORC built its search argument on them and
skipped a file storing key = 10 under key=9/, so WHERE key = 9 returned
0 rows (master returned all of them, its format header was empty), and
Parquet pruned row groups the same way (on master too, through the
filter's additional columns).

Every column of such a structure is a partition column, so the format
filter has nothing it may use. Drop it for file, url and object storage
reads, and use the same check for the Parquet top-K filter of file.

Found by the AI review of ClickHouse#123381.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Oct 2, 2026

auto parser_shared_resources = std::make_shared<FormatParserSharedResources>(settings, num_streams);
auto format_filter_info = std::make_shared<FormatFilterInfo>(filter_actions_dag, context, nullptr, query_info.row_level_filter, query_info.prewhere_info);
auto format_filter_info = std::make_shared<FormatFilterInfo>(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai don't S3 and azureBlobStorage engines also support Hive partitioning? Aren't there other engines that support this as well?

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.

Yes. s3, azureBlobStorage and hdfs (and *Cluster on the replicas) all read through ReadFromObjectStorageStep::initializePipeline, which this PR changes the same way (ReadFromObjectStorageStep.cpp:127); file, url and their *Cluster variants go through ReadFromFile / ReadFromURL. The empty-header part is shared by all of them in prepareReadingFromFormat. The only other reader with partition columns is S3Queue / AzureQueue, which creates its reader without a FormatFilterInfo (ObjectStorageQueueSource.cpp:1242), so nothing is pushed into the format there.

Measured on azureBlobStorage (Azurite), ORC file storing key = 10 under c=1/key=9/ with structure 'key Int64': WHERE key = 9 returns 10 rows with this PR and 0 without the filter change, and count() with optimize_count_from_files = 0 over a=1/key=9/ with the same structure returns 1 (0 on master).

if (!boost::iequals(storage->format_name, "Parquet"))
return false;

if (info.formatReadsHivePartitionColumns())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai why this? What about other engines with topKDynamic filtering?

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.

Because of the fallback in prepareReadingFromFormat: for a structure of only partition columns, the partition column is now in format_header, so the format_header check below passes and the Parquet reader would compare the file's key with a threshold taken from the path's key. Without this check, ORDER BY key LIMIT 3 in the test returns 10 10 10 instead of 9 9 9.

ReadFromFile is the only supportsTopKDynamicFilter override on master; ReadFromMergeTree has its own top-K path and no partition columns. #122109 adds the same format_header check for object storage, so it needs this exclusion too. If it merges first, I'll add the check to ReadFromObjectStorageStep here.

return res;
}

bool ReadFromFormatInfo::formatReadsHivePartitionColumns() const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵️ formatReadsHivePartitionColumns() withholds filter_actions_dag from the format, but query_info.row_level_filter is still passed into FormatFilterInfo in all three places. For a partition-only structure the format then reads the partition column from the file, so a row policy on that column would be evaluated against the file's value rather than the path's — the same key = 10 vs key = 9 mismatch the WHERE case avoids.

It can't happen through a table function, since row policies target tables, but a File, URL or S3 table with a row policy on a partition column and a partition-only structure would reach it. PREWHERE is fine — master already rejects partition columns there.

Could you either withhold row_level_filter the same way, or add a test arm showing a row policy on a partition column still returns the right rows?

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.

A row policy on a partition column does not reach query_info.row_level_filter: supportedPrewhereColumns() of File, URL and object storage excludes the partition columns, so the planner keeps the policy as a Filter (Row-level security filter) step above the read (can_push_down_filter in PlannerJoinTree.cpp). Its condition reaches the format only through filter_actions_dag, which is withheld here. In the partition-only case the only policy that can still be pushed down is a constant one (USING 0 shows up as Row level filter inside ReadFromFile, with no filter step above), so withholding row_level_filter would drop it.

Added the test arm in 1737975: a File and an S3 table over files storing key = 10 under key=9/, a policy key = 9 returns every row and key = 10 returns none. Without the filter change the first one returns no rows.

Separately, with a structure that also has ordinary columns, master has the same mismatch: WHERE key = 9 (or a key = 9 policy) returns 0 for a Parquet file storing key = 10 under key=9/, because the whole filter still goes to the format there. I can fix that in this PR by not passing the format the conjuncts on partition columns, or in a separate PR, whichever you prefer.

A row policy on a hive partition column is never pushed into the read as
`row_level_filter`: `supportedPrewhereColumns` of `File`, `URL` and object
storage excludes the partition columns, so the planner keeps the policy as a
filter step above the read, and its condition reaches the format only as the
filter DAG, which is withheld when the format reads a partition column.
Cover it on a `File` and an `S3` table whose file values differ from the path,
with a policy that admits the path value and one that admits only the file value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim enabled auto-merge October 2, 2026 19:03
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit 403ee61 Oct 3, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Oct 9, 2026
…t the data file

A Hive partition column and a requested virtual column are added by the source
after the format produced the chunk, but the read steps of `file`, `url` and
object storage passed the whole pushed-down filter to the format. Since ClickHouse#104435
`FormatFilterInfo::initKeyConditionOnce` adds every filter input missing from
the format header to the KeyCondition, so the Parquet reader resolved such a
column to the data file's own column of the same name and pruned row groups,
pages and dictionaries by the file's values. When the file stores other values
than the path (or a physical `_file` column), `WHERE key = 9` on `key=9/` and a
row policy on the partition column returned no rows, while `SELECT key` showed
9 for every row. Regression since 26.8.

`ReadFromFormatInfo::getFormatFilter` now gives the format the filter without
the conjuncts that reference a Hive partition column or a requested virtual
column (`splitFilterDagForAllowedInputs` with a partial result, so `key = 9 AND
v < 10` still prunes on `v`). The files iterator keeps the full filter, and the
`Filter` step above still applies all of it. It replaces the
`formatReadsHivePartitionColumns() ? nullptr : filter_actions_dag` rule of
ClickHouse#123381, which covered only the structure with partition columns alone. Data
lakes keep their virtual-column conjuncts, because Iceberg reads its row
lineage columns from the data file; they have no Hive partition columns, so
their filter is unchanged.

Closes ClickHouse#123717

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 12, 2026
…to 26.8

The 26.8 branch has neither #123381
(`ReadFromFormatInfo::formatReadsHivePartitionColumns`) nor the query condition
cache for TopK reads of Parquet files (`makeTopKQueryConditionCacheKey`,
`queryConditionCacheHash`, `FormatFilterInfo::top_k_filter`), none of which are
marked for backport. So the backport keeps only the fix itself:

- `ReadFromFormatInfo::getFormatFilter` drops the conjuncts on hive partition and
  virtual columns from the filter pushed into the format (without the
  `formatReadsHivePartitionColumns` early return);
- `file`, `url` and object storages use it;
- `FormatFilterInfo::hasFilter` also accounts for the row-level filter and
  PREWHERE, and the object storage source uses it for the row count cache.

The TopK query condition cache part (`computeConditionHash`, the key change and
the test `05353_query_condition_cache_top_k_virtual_column_conjunct`) is not
applicable to 26.8 and is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 12, 2026
…e conflicts

The release branch lacks the prerequisites the original change was built on:
the TopK query condition cache of `ReadFromFile`
(`makeTopKQueryConditionCacheKey`) and `formatReadsHivePartitionColumns`
from #123381. So only the fix
itself is backported:

- `ReadFromFormatInfo::getFormatFilter` drops the conjuncts on Hive partition
  and virtual columns from the filter passed to the format, and is used by
  `ReadFromFile`, `ReadFromURL` and `ReadFromObjectStorageStep`.
  `formatReadsHivePartitionColumns` is not needed: on 26.9 the format header
  never contains a Hive partition column.
- `FormatFilterInfo::hasFilter` also covers the row-level filter and PREWHERE
  and is used for the row count cache of object storage reads.

`FormatFilterInfo::computeConditionHash` and the test
`05353_query_condition_cache_top_k_virtual_column_conjunct` only concern the
TopK query condition cache, which does not exist on 26.9, so they are dropped.

Original pull request: #124991

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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()). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants