Skip to content

Do not return columns that only PREWHERE uses from file and url reads - #124124

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:file-url-remove-prewhere-only-columns
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:file-url-remove-prewhere-only-columns

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124029

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reads from file and File, and from url and URL over HTTP(S), with a PREWHERE (including a WHERE moved to PREWHERE) no longer return the columns that only the PREWHERE uses, so the Parquet reader does not filter and copy them. For example, SELECT count() FROM hits PREWHERE URL <> '' over ClickBench's hits.parquet takes about 40% less time, and ClickBench Q31 and Q32 over File(Parquet) use about 6-7% less CPU.

Description

optimizePrewhere keeps every PREWHERE input among the PREWHERE outputs, so ReadFromFile and ReadFromURL returned the columns the condition was computed from even when no step above used them. ReadFromMergeTree already removes such columns in removeUnusedColumns; ReadFromFile and ReadFromURL did not implement it.

They now implement removeUnusedColumns through one helper in prepareReadingFromFormat, which removes the pass-through PREWHERE inputs the parent does not need (and the PREWHERE column itself, as ReadFromMergeTree does) from a copy of the PREWHERE actions and from the format header. The Parquet reader then reads them as PREWHERE-only columns, the path an explicit multi-column PREWHERE already takes. Nothing is removed with a DEFAULT column or a row policy. FormatFilterInfo::initKeyConditionOnce also collects the PREWHERE inputs missing from the header when there is no filter DAG. Object storage (ReadFromObjectStorageStep) applies the PREWHERE after the format for files with a changed schema, so it is not changed here.

The patch is from the issue, with the row-policy check moved into the helper.

Release build, File(Parquet) over hits.parquet, 10 alternating A/B server runs, paired ratio and 95% CI:

Query wall time user CPU
count() ... PREWHERE URL <> '' -41% [-49, -32] -23% [-26, -19]
sum(ResolutionWidth) ... WHERE URL <> '' -37% [-48, -24] -23% [-27, -18]
count() ... PREWHERE SearchPhrase <> '' -27% (n.s.) -13% [-15, -11]
Q31 / Q32 n.s. -7% / -6%
Q2, Q21, 0.1%-selectivity WatchID filter n.s. n.s.

Results were identical, also in a differential run of Q31, Q32 and Q37-Q43 across a settings matrix. #122952 changes the removeUnusedColumns interface; if it lands first, I will port this PR to it.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 6, 2026 01:23
`optimizePrewhere` keeps every PREWHERE input among the PREWHERE outputs
(`splitAndFillPrewhereInfo`, needed for DEFAULT expressions), and
`updatePrewhereOutputsIfNeeded` does the same for an explicit PREWHERE that
reads one column. `ReadFromMergeTree` drops the outputs the parent does not use
in `removeUnusedColumns`; `ReadFromFile` and `ReadFromURL` did not implement it,
so the Parquet reader filtered and copied those columns only for the next step
to drop them (ClickBench Q31: 13M non-empty `SearchPhrase` strings).

`ReadFromFile` and `ReadFromURL` now implement `removeUnusedColumns` through
`removeUnusedPrewhereInputsFromFormatInfo`, which removes the pass-through
PREWHERE inputs the parent does not need from a copy of the PREWHERE actions and
from the format header. The Parquet reader then reads them as PREWHERE-only
columns (`FormatFilterInfo::additional_columns`, `only_for_prewhere`), the path
an explicit multi-column PREWHERE already takes. The PREWHERE column itself
leaves the output the same way, as `remove_prewhere_column`, when nothing above
uses it. Nothing is removed with a DEFAULT column (`AddingDefaultsTransform`
evaluates it over the returned columns) or a row-level filter (its inputs stay
in the header), and never a hive partition or virtual column.
`initKeyConditionOnce` fills `additional_columns` also without a filter DAG,
since a PREWHERE input can now be missing from the header whatever the filter
DAG is.

Object storage applies the PREWHERE after the format for files whose schema
changed, which needs the inputs, so `ReadFromObjectStorageStep` is not changed.

Release build, File(Parquet) over hits.parquet, 10 alternating A/B runs:
`count() PREWHERE URL <> ''` -41% wall / -23% CPU, `sum(ResolutionWidth) WHERE
URL <> ''` -37% / -23%, `count() PREWHERE SearchPhrase <> ''` -13% CPU,
Q31 / Q32 -7% / -6% CPU; controls unchanged; results identical.

Patch from issue ClickHouse#124029.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the duplicated contract comment in ReadFromURL and two comments restating function names; condense the removeUnusedPrewhereInputsFromFormatInfo doc to two lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 6, 2026
@groeneai

groeneai commented Oct 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; 3 rounds, 3 findings) plus my own cold review of every round.

# Sev Finding Verdict Evidence / action
1 ⚠️ A bare-column PREWHERE f still returned f from the read (getRemovablePrewhereInputs) AGREE, fixed @ 6224263 the PREWHERE column leaves the output as remove_prewhere_column, as in ReadFromMergeTree; EXPLAIN and result lines added
2 ⚠️ The row-group pruning check used read_rows, which file() counts after the PREWHERE, so it could not fail AGREE, fixed @ 6224263 the test asserts ParquetPrunedRowGroups > 0; it reads 0 with input_format_parquet_filter_push_down = 0
3 💡 The changelog entry claimed every url read, but s3:///az:///hdfs:// URLs go to object storage AGREE, fixed the entry says url and URL over HTTP(S)
4 💡 The no-filter-DAG additional_columns fill and the hive/virtual exclusion have no SQL route today noted, not blocking kept: they hold the invariant the removal relies on

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

Session id: cron:clickhouse-review-slot-9:20261006-012600

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN header = 1 SELECT id % 10 AS k, count(), sum(w) FROM file('t.parquet') WHERE s <> '' GROUP BY k: the ReadFromFile header holds the PREWHERE-only s on master, every time; same for SELECT count() ... PREWHERE u <> '' (header u) and for url().
b Root cause explained? splitAndFillPrewhereInfo (and updatePrewhereOutputsIfNeeded for an explicit PREWHERE) keep every PREWHERE input among the PREWHERE outputs. ReadFromMergeTree drops the unused ones in removeUnusedColumns; ReadFromFile / ReadFromURL did not implement it, so the Parquet reader filtered and copied those columns only for the next step to drop them.
c Fix matches root cause? Yes: the two reading steps implement the existing plan-level removal contract (canRemoveUnusedColumns / removeUnusedColumns), and the reader's existing PREWHERE-only path (additional_columns, only_for_prewhere) reads the removed inputs.
d Test intent preserved / new tests added? New 05327_file_url_prewhere_only_columns.sql (EXPLAIN oracles for file() moved WHERE, explicit PREWHERE, url(), a pruning key, a bare-column PREWHERE f / WHERE f; the DEFAULT guard; results for wrappers, globs, hive, virtual columns, bare-column filters; row group pruning on a removed key via the ParquetPrunedRowGroups profile event) and tests/performance/parquet_prewhere_only_columns.xml.
e Both directions demonstrated? The new test fails on the unpatched build in exactly the 6 EXPLAIN lines (1 1 instead of 1 0) and passes with the patch; 50/50 randomized runs pass. Reverting the StorageFile, StorageURL, DEFAULT guard or PREWHERE-column hunks each fails the matching line.
f Fix is general across code paths? ReadFromFile (file(), File, globs, archives, stdin) and ReadFromURL (url(), URL, failover, *Cluster workers) share one helper. ReadFromObjectStorageStep is deliberately unchanged: it applies the PREWHERE after the format for schema-changed files, which needs the inputs. Only Parquet supports PREWHERE, so other formats are a no-op.
g Fix generalizes across inputs (params/datatypes/wrappers)? Results identical for Nullable, IS NULL, LowCardinality, Array (has), Tuple element, globs, hive partitions, _file, small max_block_size; differential of ClickBench Q31, Q32, Q37-Q43 over 11 setting combinations (query_plan_remove_unused_columns, optimize_move_to_prewhere, Parquet filter/bloom/page/dictionary push-down off, max_threads 1/16, max_block_size 100) gives identical hashes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or serialization change; with query_plan_remove_unused_columns = 0 the plan is unchanged.
i Invariants and contracts preserved? The step's output header and kept_output_positions stay consistent (removed names leave format_header, source_header, requested_columns, columns_description); the PREWHERE actions are changed on a copy, since the old info may share them; a removed PREWHERE column is marked remove_prewhere_column and its filter node stays in the actions' outputs, where the reader looks it up; every PREWHERE / row-level filter input missing from the header is in FormatFilterInfo::additional_columns with or without a filter DAG, so the reader still finds it and row group pruning still sees it.

Session id: cron:clickhouse-impl-slot-40:20261005-224503

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [217abc8]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
04227_materialized_cte_reused_with_in_subquery FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
02346_non_negative_derivative NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
02151_hash_table_sizes_stats_joins_reordered NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
AST fuzzer (amd_release, oracle) FAIL
AST fuzzer oracle mismatch FAIL cidb
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 4/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 5/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

Reviewed #124124 at 217abc8d06c44c2f7a482631f25205f5c09536de. The change removes unused pass-through PREWHERE columns from ReadFromFile and ReadFromURL outputs while preserving the inputs needed by Parquet filtering. No actionable findings identified. The focused stateless test passes in CI, and the PR provides before/after performance measurements. On the PR-head binary, 34 successful local comparisons produced identical results with query_plan_remove_unused_columns enabled and disabled; EXPLAIN confirmed the intended header pruning. Three additional probes failed identically in both modes and were excluded from the passing comparisons.

Final Verdict

Status: ✅ Approve. No required changes identified.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). labels Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

One query was flagged: ClickBench Q20 is -40.0% faster (220 ms to 132 ms), and CPU time fell by about half. The shift is large and consistent, so the hard-trust rule keeps the improvement verdict as it is. The attribution does not fit the diff, though. This PR only drops PREWHERE-only columns from the output of file()/url() reads (ReadFromFile, ReadFromURL, FormatFilterInfo), and ClickBench Q20 reads the MergeTree hits table, which never runs that code. Do not count this gain as an effect of the PR. Re-running against an exact-base baseline should confirm whether it comes from a master change between the base and the PR head. The new parquet_prewhere_only_columns perf test is the right place to measure what this change actually does.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 132 -40.0% <0.0001 cpu: Real -40.0% gain with CPU time down from 2898 to 1525 ms, but this diff only changes file()/url() reads. Q20 reads the MergeTree hits table, so the gain probably comes from the base build.

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: db9e297d-4fa0-48c4-b455-290dd8824ce1
  • MIRAI run: 014a6e03-15e0-45cd-833e-fd053fdba913
  • PR check IDs:
    • clickbench_97868_1791941745
    • clickbench_98143_1791941753
    • clickbench_98279_1791941761
    • tpch_adapted_1_official_98301_1791941762
    • tpch_adapted_1_official_98547_1791941915
    • tpch_adapted_1_official_98657_1791941924

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 217abc8d06c44c2f7a482631f25205f5c09536de was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

…where-only-columns

Adapt `ReadFromFile::removeUnusedColumns` and `ReadFromURL::removeUnusedColumns` to the single-pass
interface of removing unused columns from master: they now take the unneeded output positions and return
the dropped ones, and `canRemoveColumnsFromOutput` no longer exists.

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

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()). groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

File and URL reads return columns that only PREWHERE uses; dropping them makes ClickBench q31/q32 on Parquet 5-7% faster

2 participants