Skip to content

Fix PREWHERE throwing when a predicate pushed into the scan by apply_string_filters_during_scan is read elsewhere - #128734

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:string-filters-shared-conjunct-guard
Nov 3, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:string-filters-shared-conjunct-guard

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115848

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 (for example from throwIf) in a query whose PREWHERE had several substring conditions on one String column, pushed into the scan by apply_string_filters_during_scan, when the result of one of them was also used elsewhere in PREWHERE.

Description

On 26.10.2.103 with default settings, this valid query throws FUNCTION_THROW_IF_VALUE_IS_NON_ZERO although every value contains '1' (it returns 6878 with apply_string_filters_during_scan = 0); a Parquet file behaves the same:

CREATE TABLE t (s String, k UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t SELECT concat('1', leftPad(toString(number), 5, '0')), number FROM numbers(20000);
SELECT count() FROM t PREWHERE throwIf(NOT (s LIKE '%1%')) = 0 AND s LIKE '%1%' AND s LIKE '%2%';

The scan filter of a column requires all its conditions, so a value that matches '%1%' but not '%2%' is read as an empty string, and s LIKE '%1%' becomes false for it. The conjunction rejects that row anyway, but NOT (s LIKE '%1%') sees the flipped value. The existing guard in extractStringValueFilters (added in #115848 for PREWHERE throwIf(empty(s)) = 0 AND s LIKE ...) only rejects nodes that read the column directly.

Now, for a column whose conditions come from two or more predicates, every node that depends on the column, also through other nodes, must be a part of the conjunction (a top-level and, an extracted conjunct, or the predicate itself); otherwise the filter is not applied to that column. With a single predicate nothing can flip, so such columns keep the old behaviour (including every query of string_filters_during_scan.xml).

The new test covers a shared predicate, an alias, a shared position, a nested and and a Parquet file. Each of the five fails on master with code 395 and passes with the fix. Three controls check that the filter is still applied. The string_filters tests pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1247-master (included in 26.11 and later)
  • Backported to: 26.10.8.13

…ere in PREWHERE

`StringValueFilter` requires all conditions of a column. With conditions from two
or more predicates on one column, a value that matches one predicate but not
another is replaced by an empty string during the scan, so the first predicate is
false for it although it is true on the original value. The row is rejected by
the conjunction anyway, but any other PREWHERE expression that consumes that
predicate's result observes the flipped value:

    PREWHERE throwIf(NOT (s LIKE '%1%')) = 0 AND s LIKE '%1%' AND s LIKE '%2%'

throws `FUNCTION_THROW_IF_VALUE_IS_NON_ZERO` although every value contains '1'
(also via an alias, a shared `position` node, or a nested `and` read elsewhere),
in MergeTree and in Parquet, with default settings.

The existing guard only rejects nodes that read the column directly. For a column
whose conditions come from two or more readers, also require every node that
depends on the column (transitively, aliases transparent) to be part of the
conjunction: a top-level `and`, an extracted conjunct, or a reader. Otherwise the
filter is not applied to that column. With a single reader nothing can flip (a
value failing the filter fails that reader's own conditions), so such columns
keep the old behaviour, e.g. `position(s, 'x') > 0 AND position(s, 'x') < 100`.

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

groeneai commented Nov 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; 0 findings on this head).
My own review found no code issue; two wording fixes to the PR description were made before publication.

# Sev Finding Verdict Evidence / action
1 ❌ (plan review) a flipped reader can change short-circuit evaluation of an unrelated conjunct, so an exception from it may no longer be raised DISAGREE With the filter off the same conjuncts in another order, or as WHERE, also return the result without the exception: that exception is not a property of the query. Under the new rule a flip only turns a conjunct false for a row that is rejected anyway, so it can only skip evaluations, never add one.

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

Session id: cron:clickhouse-review-self-slot-58:20261102-182900

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The query in the description throws code 395 on every run on master and on 26.10.2.103 (default settings); the new test fails 10/10 randomized runs on master, and each of its five arms fails 10/10 on its own.
b Root cause explained? The scan filter of a column requires all its conditions. With conditions from two predicates, a value matching only the first is read as an empty string, so the first predicate is false for it. The old guard only rejected nodes that read the column directly, so a node consuming that predicate's result (NOT, a comparison of a shared position, a nested and) saw the flipped value.
c Fix matches root cause? Yes. The applicability rule in extractStringValueFilters now also covers transitive consumers for columns with conditions from two or more predicates; same layer and same disposal as the existing direct-reader and row-policy guards. No reader change, no setting.
d Test intent preserved / new tests added? New test 05153_string_filters_shared_conjunct_prewhere_guard: five arms that fail on master, plus three controls asserting the filter is still applied. Each control is reddened by a different wrong variant of the rule (measured with mutant builds). No existing test changed.
e Both directions demonstrated? Yes: master code 395, fix 1000 / 6878, for the test, every arm, and the description's query (MergeTree and Parquet). 50/50 randomized runs pass with the fix.
f Fix is general across code paths? Both callers (ReadFromMergeTree, the Parquet reader's PREWHERE setup) use this one function, which inspects the whole PREWHERE DAG, so split PREWHERE steps are covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? LIKE, position and its comparisons, aliases and nested and in the test; Nullable(String) and dictionary-encoded Parquet measured (fail on master, pass with the fix). LowCardinality(String) and FixedString columns are never filtered.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change. Only a column with conditions from two or more predicates and another consumer of them loses the scan filter; other queries keep their plans.
i Invariants and contracts preserved? A replaced value is now observed only by nodes whose only effect is rejecting the row, for every column. Function signatures unchanged; plan-time only, linear in the DAG size.

Session id: cron:clickhouse-impl-self-slot-57:20261102-175800

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @CurtizJ, could you review this and add the can be tested label so CI runs? With two or more substring conditions on one column, the scan filter replaces a value that matches only some of them with an empty string, which flips a shared condition for another PREWHERE node that consumes it (throwIf(NOT (s LIKE '%1%'))); extractStringValueFilters now disables the filter for such a column unless every node depending on it is part of the conjunction.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [95c155f]

Summary: ✅


AI Review

Summary

This PR prevents spurious exceptions in PREWHERE by disabling scan-time string filtering when multiple predicates on one column have transitive consumers outside the filtering conjunction. The regression test covers shared predicates, aliases, position, nested conjunctions, and Parquet, with controls preserving the optimization in safe cases. No actionable findings at head 95c155fc25cc7ecc61c82e25d4580368bf98e8b4.

Missing context / blind spots
  • ⚠️ Runtime validation relies on the author's reported before/after runs: this checkout has no ClickHouse binary or build directory. The successful fast-test job skips the new test because it requires Parquet; functional CI has not yet reported results. A passing functional/bugfix-validation run of 05153_string_filters_shared_conjunct_prewhere_guard would close this independent-validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; functional CI should complete before merge.

@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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 95c155fc2 with master aed52c22e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 55e1ca2ea; 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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Nov 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit c1740f0 Nov 3, 2026
353 of 355 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 19, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #128734 to 26.10: Fix `PREWHERE` throwing when a predicate pushed into the scan by `apply_string_filters_during_scan` is read elsewhere
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. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants