Skip to content

Respect short_circuit_function_evaluation when pruning files and parts by virtual columns - #125033

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/virtual-column-filter-short-circuit
Oct 10, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/virtual-column-filter-short-circuit

Conversation

@groeneai

@groeneai groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #100827

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 an exception when a WHERE condition on the _file, _path or _part virtual column guards a branch with if, and, or or multiIf, for example WHERE _file LIKE 'events_%' AND toDate(substring(_file, 8, 10)) >= '2024-01-01'. Pruning files and parts by virtual columns now respects short_circuit_function_evaluation instead of evaluating the excluded branch for every file or part name.

Description

On 26.8.18.2, SELECT count() FROM file('dir/*.csv', CSV, 'a Int32, b String') WHERE if(_file LIKE 'events_%', toDate(substring(_file, 8, 10)) >= '2024-01-01', 0) over dir/events_2024-01-01.csv and dir/readme.csv throws CANNOT_PARSE_DATE instead of returning 1. The same happens for _part on MergeTree (_part = 'all_1_1_0' OR intDiv(10, length(_part) - 9) > 0 throws ILLEGAL_DIVISION), for url/s3 paths, and even with short_circuit_function_evaluation = 'force_enable'. The same predicate over an ordinary column returns the right answer.

Root cause: every filter that prunes files, parts or system-table rows by virtual columns was built with a default ExpressionActionsSettings, whose short_circuit_function_evaluation is disable, so all arguments of and/or/if were evaluated for every file or part name.

Change: build these filters with ExpressionActionsSettings(<query context>) (as StorageMerge already does): VirtualColumnUtils::buildFilterExpression (MergeTree parts, Merge, system tables) and the file-list filters of file, url, object storage, data lakes and S3Queue. JIT stays off.

Test 05353_virtual_column_filter_short_circuit covers file, MergeTree, s3 (glob, brace expansion, single key) and url, plus two disable controls that still throw. It fails on master and passes with the fix; reverting any single covered site turns exactly its arms red.

Not changed: a guard on a non-virtual column (b = 'a' AND toDate(substring(_file, 8, 10)) >= ...) still throws, because the pushed-down part of the filter drops that conjunct; that is the broader question of #100827.


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

Version info

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

…umns

The filters that prune files (file, url, object storage globs, brace
expansions and explicit keys, data lakes, S3Queue) and MergeTree parts
or system-table rows by virtual columns were ExpressionActions built
with a default ExpressionActionsSettings, whose
short_circuit_function_evaluation is DISABLE. So and/or/if/multiIf over
_file, _path or _part evaluated every argument for every file or part
name, and a branch that the guard excludes threw:

    WHERE _file LIKE 'events_%' AND toDate(substring(_file, 8, 10)) >= '2024-01-01'
    -> CANNOT_PARSE_DATE on 'readme.csv'
    WHERE _part = 'all_1_1_0' OR intDiv(10, length(_part) - 9) > 0
    -> ILLEGAL_DIVISION

even though the main filter (query settings, `enable` by default) would
not throw, and even with short_circuit_function_evaluation = 'force_enable'.

Build these filters with ExpressionActionsSettings(<query context>), as
StorageMerge already does for its filter. JIT stays off
(CompileExpressions::no). Covers VirtualColumnUtils::buildFilterExpression,
which every buildFilterExpression / filterBlockWithPredicate caller goes
through, and the ten direct constructions in StorageFile, StorageURL,
StorageObjectStorageSource, ObjectStorageQueueSource and IObjectIterator.

A guard on a non-virtual column (`b = 'a' AND toDate(substring(_file, ...))`)
still throws: the pushed-down part of the filter drops that conjunct.
That is the broader question of ClickHouse#100827.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 10, 2026
@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; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test would also pass if pruning silently declined; deferred-set, S3Queue and data-lake sites have no arm DISAGREE Reverting any single covered site turns exactly its arms red; the disable file arm still throws on the fix while the main filter alone returns 1, so it fails if file() pruning declined. Uncovered sites carry the same one-argument edit; the deferred branch has no deterministic route without a failpoint.
2 💡 Uncovered sites (same as 1) AGREE noted, not blocking
3 💡 Issue link hidden inside the template comment AGREE, fixed PR body

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

Session id: cron:clickhouse-review-self-slot-58:20261010-040100

@groeneai groeneai added the groeneai-origin-self PR origin: self-found defect (impact-bar validated) label Oct 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master (cad1583aab75c) and official 26.8.18.2 the _file if(...) filter throws CANNOT_PARSE_DATE and the _part ... OR intDiv(...) filter throws ILLEGAL_DIVISION, every time. The new test fails 10/10 on master.
b Root cause explained? Virtual-column pruning filters used a default ExpressionActionsSettings (short_circuit_function_evaluation = disable), so and/or/if/multiIf evaluated every argument for every file or part name; the query's setting never reached them.
c Fix matches root cause? Yes: the 11 construction sites now pass ExpressionActionsSettings(<query context>). No try/catch, no reordering, no test tag.
d Test intent preserved / new tests added? New 05353_virtual_column_filter_short_circuit: 8 arms over file, MergeTree _part, s3 glob / brace / single key and url, plus 2 short_circuit_function_evaluation = 'disable' controls that must still throw.
e Both directions demonstrated? Master: 0/10. Fix: 10/10. Reverting each covered site alone (7 mutants) turns exactly that site's arms red and nothing else.
f Fix is general across code paths? All 11 sites: VirtualColumnUtils::buildFilterExpression (MergeTree parts, Merge, filesystem(), system tables) and the file-list filters of file, url, object storage, data lakes and S3Queue; deferred, S3Queue and data-lake sites get the identical edit without a dedicated arm.
g Fix generalizes across inputs (params/datatypes/wrappers)? and, or, if, multiIf; LowCardinality(String) _file/_path/_part; enable, force_enable and disable; 50/50 runs with randomized settings, 50/50 without, 10/10 in a Replicated database.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; short_circuit_function_evaluation = 'disable' keeps the old behaviour (asserted). Only queries that used to throw now return a result.
i Invariants and contracts preserved? Same DAG, outputs and filter column; JIT stays off; max_temporary_columns now also applies to this sub-DAG (the main filter already runs under it). 80 existing virtual-column / pruning / system-table tests are identical before and after.

Session id: cron:clickhouse-impl-self-slot-57:20261010-020600

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff1fc6e]

Summary: ✅


AI Review

Summary

This PR fixes virtual-column pruning so the ExpressionActions used for _file, _path, and _part filters inherit the query’s ExpressionActionsSettings, which makes pruning respect short_circuit_function_evaluation the same way the main filter already does. I reviewed the current diff, the touched code paths, the existing discussion, and the current PR state, and I do not see a remaining correctness, compatibility, or test issue that warrants an inline review comment.

Final Verdict

✅ No blocking findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 10, 2026
@groeneai
groeneai requested review from vitlibar and yariks5s October 10, 2026 04:36
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ff1fc6eb5 with master 727bdd7b6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0d2ade023; 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

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit 9acd719 Oct 10, 2026
163 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
fm4v added a commit that referenced this pull request Oct 11, 2026
The targeted AST fuzzers already run on small PRs and caught the `columns were captured` exception from #125033 at a higher rate per run than the untargeted ones (about 1.4% vs 0.8%), so an extra untargeted AST fuzzer adds little. The stress test checks data races under load, which nothing else in a small PR does.
balx pushed a commit to balx/ClickHouse that referenced this pull request Oct 11, 2026
…ct code

The small-PR rule from ClickHouse#120996 skipped every untargeted stress test and fuzzer on a PR with fewer than 100 lines of product code. ClickHouse#125033 (60 lines in `src/`) passed its targeted fuzzers and introduced the exception `Cannot call function A because is has B arguments but C columns were captured` (STID 2458-4cb4), which `AST fuzzer (amd_msan)` and `Stress test (amd_tsan)` found on master a few hours after the merge.

Keep `AST fuzzer (amd_debug)` and `Stress test (amd_tsan)` for small PRs that change at least one line of product code. PRs that change only tests, docs or CI scripts keep skipping all of them.
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Oct 12, 2026
`cloneDAGWithInversionPushDown` gives the copy of an `indexHint` node the
hint's own arguments as children, but added it with the planner's
`function_base`, which `PlannerActionsVisitor` builds for no arguments.
`ReadFromMergeTree::buildIndexes` passes that copy to
`filterPartsByVirtualColumns`, which executes it. Eager execution ignored
the mismatch (`FunctionIndexHint::executeImpl` ignores its arguments), but
since ClickHouse#125033 the part-pruning filter honours
`short_circuit_function_evaluation`, so a hint at a lazily executed
position becomes a `ColumnFunction` over a 0-argument base with N captured
columns, and `ColumnFunction::appendArguments` throws:

    Logical error: 'Cannot capture 1 column(s) because function indexHint has 0 arguments.'

Found by the AST fuzzer (STID 3408-3735).

Build the copy's base for its children through a
`FunctionToOverloadResolverAdaptor` over the same `FunctionIndexHint`, as
`ActionsDAG::buildFilterActionsDAGImpl` already does for hint copies. The
children are kept because `StatisticsPartPruner`,
`optimizeDirectReadFromTextIndex` and `WhatIfFilterAnalysis` read them;
the generated name, the `UInt8` result type and the object behind
`getFunction()` are unchanged, so those readers see the same DAG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to rorylshanks/ClickHouse that referenced this pull request Oct 13, 2026
`splitFilterNodeForAllowedInputs` keeps only the conjuncts of an `and`
that can be evaluated on the allowed (virtual) inputs. When two or more
of them survive, it returned the copied node as is, so the node had fewer
children than the `function_base` it carries was built for. Executing it
eagerly happens to work, because `and` accepts any arity.

Since ClickHouse#125033 these filters honour `short_circuit_function_evaluation`.
A reduced `and` that is a lazily evaluated argument of another
short-circuit function (for example the right side of an `or`) and has a
lazy-suitable descendant is wrapped by `ExpressionActions` as a
`ColumnFunction` with the stale 3-argument function and 2 captured
columns, and `ColumnFunction::reduce` throws `LOGICAL_ERROR: Cannot call
function and because is has 3 arguments but 2 columns were captured`.
Found by the AST fuzzer in `Stress test (amd_tsan)` on master.

Build a fresh `and` for the kept children instead, and convert its result
back to the original type with `addBooleanCondition`, as the single-child
path above already does. `ActionsDAG::removeUnusedConjunctions` rebuilds a
reduced conjunction the same way. This keeps the invariant the `or` branch
and the all-children-kept `and` branch rely on: every returned node has a
function built for exactly its children and the input node's result type.

The new test fails on master (the server aborts) and passes with the fix;
a build from before ClickHouse#125033 also passes it, so the defect is master-only.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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