Repository navigation
Conversation
With enable_join_runtime_filters = 1 a probe-side "Apply runtime join filter" FilterStep is planted (joinRuntimeFilter.cpp) and optimizeTree.cpp re-runs tryMergeExpressions, tryMergeFilters and tryPushDownFilter a second time, top-down. tryMergeExpressions' Filter-over-Expression branch (mergeExpressions.cpp:82-113) then fuses a subquery's Projection into that FilterStep, which makes the subquery's SELECT-list expressions required OUTPUTS of the filter step: they are computed for every row the step reads, and only filtered afterwards. The first pass already prevents exactly this. trySplitFilter (splitFilter.cpp:41) leaves the minimal condition DAG in the FilterStep and lifts everything else it computes into an ExpressionStep above it; it is registered in the first-pass list at Optimizations.h:257 and query_plan_split_filter defaults to true. The re-run loop ran three of those four rewrites and omitted this one, so the second sweep re-fused without re-splitting. For the query in ClickHouse#121909 that means CAST(c3, 'Array(String)') became an output of a filter sitting directly above ReadFromMergeTree, so it ran on the c4 = false row that WHERE c4 removes, and the query failed with Code: 130 CANNOT_READ_ARRAY_FROM_TEXT. The guard is first in the condition, so this is output materialisation rather than an evaluation-order fault, which is why the PREWHERE read-step grouping and the runtime-filter key placement are both unrelated to it. The call is guarded on typeid_cast<FilterStep *> because trySplitFilter is two rewrites behind one name: its first statement delegates to trySplitJoin (splitFilter.cpp:43-44), which pulls a JoinStepLogical's single-side ON conditions out of join_operator.expression and plants a new FilterStep under each join child. Only the filter branch is wanted here, and the join branch is reachable at this point: convertLogicalJoinToPhysical is deliberately skipped in the preceding traversal when enable_parallel_replicas is set (optimizeTree.cpp:344-345) and returns early under make_distributed_plan, so logical joins are still in the plan; the join-order optimizers re-populate pushable ON conditions after the first pass (joinOrderGreedy.cpp:100, joinOrderDPSub.cpp:481); and at query_plan_split_filter = 0 the first pass never ran trySplitJoin at all while the runtime-filter rerun forces this call anyway. This traversal also lacks the first pass's child-insertion hygiene, so keeping it to the one rewrite it needs avoids an unmeasured behaviour change in the two configurations that file's own comments call intolerant of late step insertion. extra_settings is passed rather than a default-constructed struct for the reason the comment above the three sibling calls gives, and additionally because trySplitFilter reads push_down_volume_reducing_functions to keep the nodes tryPushDownVolumeReducingFunction wants below the filter (splitFilter.cpp:59-64); a zeroed struct would disarm that anti-oscillation guard. The change is scoped to the runtime-filter rerun traversal. Other post-first-pass merge sites carry the same invariant and are deliberately left alone: none of them has a witness here, and extending to unmeasured sites would be a speculative change. The call sits after the while loop rather than inside it, so the loop's convergence is untouched. Termination is safe: traverseQueryPlan visits the inserted child, whose own split is a no-op through split.second.trivial(), and tryMergeExpressions merges only Expression+Expression and Filter+Expression, never Expression-over-Filter, so the shape the split produces cannot be re-fused. Measured with EXPLAIN PLAN description = 1, actions = 0: the split adds exactly one Expression step, taking the reproducer's plan from 13 lines to 14, and stacking three Filter/Expression pairs over the join still adds exactly one (13 to 14) rather than one per pair. EXPLAIN PLAN actions = 1 cannot be used for this: QueryPlan::explainPlan's skip_expressions (QueryPlan.cpp:680-687) walks past every Expression step while actions and compact are both set, and compact defaults to true, so that renderer reports an unchanged line count no matter what the optimization did. The two plan-dump references gain the resulting Expression-over-Filter step, with no asserted data value moving. The runtime filter is still built and applied, with identical RuntimeFiltersCreated, RuntimeFilterRowsChecked and RuntimeFilterRowsPassed counts on a non-throwing control of the same shape, and the affected query shape is 44% faster at 2M rows because the CAST no longer runs on the rows the filter removes. Related: ClickHouse#121909 Co-Authored-By: Claude Opus 5 <[email protected]>
…s filter Covers the ClickHouse#121909 reproducer: a subquery whose SELECT list computes CAST(c3, 'Array(String)') while its own WHERE c4 excludes the only row for which that CAST is invalid, read as the probe side of an INNER JOIN that builds a runtime filter. join_runtime_filter_min_probe_rows = 0 is set explicitly rather than relying on a large fixture, because the threshold is compared against the planner's ESTIMATED probe rows and not the actual ones: with 2001 rows the estimate for t1 FINAL WHERE c4 comes out at 660, below the default 1000, so the runtime filter is planted but never applied and every assertion passes vacuously. I hit exactly that while writing this test, and the first draft produced byte-identical output with and without the fix. join_algorithm, query_plan_join_swap_table, query_plan_optimize_join_order_limit and query_plan_optimize_join_order_randomize are pinned in every statement's own SETTINGS clause, because the Stress job injects all four as client options (ci/jobs/scripts/stress/stress.py:418-439 and :541-547) and each one can silence the test in a different way. supportsRuntimeFilter (joinRuntimeFilter.cpp:206-212) accepts only hash, parallel_hash and grace_hash, so a subset such as ['partial_merge'] plants no runtime filter at all; and the apply step is planted on children[0] only (joinRuntimeFilter.cpp:347, :632-639), so with the orientation reversed the guarded subquery becomes the build side and the defect is unreachable. A query-level SETTINGS clause outranks a client option, which is why the pins are there rather than in a leading SET. tests/clickhouse-test does not randomize any of the four, which is why a 50/50 run cannot see this. The last two assertions are what keep the first two honest, and they cover different failure modes. The EXPLAIN check fails if the runtime filter is absent from the plan. The probe-side counter check fails if the filter is present but applied to the other side: a bare RuntimeFilterRowsChecked > 0 would not detect that, because with the orientation reversed the filter is applied to t2 and the counter reads 5 instead of 2001, so the threshold has to separate the two. Verified by stripping the orientation pin and forcing query_plan_join_swap_table = true: that assertion then emits 0 against a reference of 1, so a configuration in which the test cannot witness the bug reddens instead of passing. Substituting partial_merge for the pinned algorithm reddens both assertions the same way. The Random settings limits line pins enable_join_runtime_filters, which tests/clickhouse-test randomizes to false in about 5% of runs. Inverting that clamp to (0, 0) fails 5 of 5 randomized runs, so the line is parsed and applied rather than silently ignored. join_runtime_filter_min_probe_rows is deliberately not clamped: its own default is the pathological value, so a clamp could not help a run with randomization disabled. Co-Authored-By: Claude Opus 5 <[email protected]>
Every client option ci/jobs/scripts/stress/stress.py appends was swept against this test, and three more of them land on axes it asserts on. use_query_cache is the one that can actually break the test today. settingDoesNotAffectQueryResultCache (Interpreters/Cache/QueryResultCache.cpp:276) treats log_comment as not affecting the result, and RemoveQueryResultCacheSettingsMatcher strips it from the AST before the cache key is computed, so the first assertion's statement and the probe statement differ by nothing that reaches the key. query_cache_min_query_runs and query_cache_min_query_duration both default to 0, so the first execution is stored immediately, and stress.py:450 turns the cache on in 1 of 15 workers together with the two 'ignore' handlings that would otherwise keep the result out. The probe statement is then served from the cache with no pipeline built, no ProfileEvents raised, and the final assertion emits 0 against a reference of 1. Confirmed by removing the pin and re-running under that injection: 5 of 5 runs redden on that line alone. enable_parallel_replicas and query_plan_optimize_join_order_algorithm are pinned for uniformity with the tests that already do so (05210_join_runtime_filter_float_nan.sql:6,11, and 03777_join_runtime_filter_unsupported_type.sql:3-5), not because either can silence this test as written. Measured, so that the next reader does not have to: parallel replicas never engages here at all, because Planner.cpp:2739 forces allow_experimental_parallel_reading_from_replicas to 0 whenever a table expression carries FINAL, and this test reads t1 FINAL; ParallelReplicasUsedCount is 0 on every probe row under the full stress shape. The join-order algorithm has nothing left to choose either: with the pin removed the plan is byte-identical across greedy, dpsize,greedy and greedy,dpsize, because query_plan_join_swap_table = 0 already fixes the orientation this test asserts on. Both pins become load-bearing the moment the test loses FINAL, which is the reason to add them now rather than rediscover this. The no-parallel-replicas tag is the half that survives a dedicated --no-parallel-replicas run, where the whole job runs under parallel replicas: clickhouse-test emits --enable_parallel_replicas 0 last for a tagged test, explicitly so it beats an externally supplied client option. It does not disturb the Random settings limits line above it, because find_tag_line and find_random_settings_limits_line are independent scans over the whole file; re-inverting that clamp to (0, 0) with the tag in place still reddens 5 of 5. None of this weakens the test: with all three pins in place it still fails on the pre-fix binary with CANNOT_READ_ARRAY_FROM_TEXT, raised from a statement whose text contains them. Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the narration of why the rerun applies trySplitFilter again; keep the two properties of the pre-existing helpers that the guard and the call rest on.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds, 4 gate findings + 5 of my
Three further test hazards were refused with source citations rather than pinned: Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260925-020200 |
|
Workflow [PR], commit [b8b5279] Summary: ❌
AI ReviewSummaryThis PR fixes a real optimizer correctness gap in the runtime-filter second pass: after Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit b8b5279.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - b8b5279Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 173 check runs completed (133 pass, 39 not selected, 1 red), Master merge deliberately not pushed now, and the reason is measured rather than a preference. Session id: cron:our-pr-ci-monitor:20260925-080056 |
f05f2a7
Related: #121909
Related: #111954
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query failing with an error such as
CANNOT_READ_ARRAY_FROM_TEXTwhen a subquery'sSELECTlist computes an expression that the same subquery'sWHEREguards against, and that subquery is the probe side of aJOINfor which a runtime join filter is built (enable_join_runtime_filters = 1, enabled by default). The guarded expression was evaluated on rows that theWHEREhad already removed.Description
On 26.6.1.2207 at default settings,
SELECT a.c1, a.s, b.c2 FROM (SELECT c1, c2, CAST(c3, 'Array(String)') AS s FROM t1 FINAL WHERE c4) AS a INNER JOIN t2 AS b ON b.c1 = a.c2 ORDER BY a.c1fails withCode: 130 CANNOT_READ_ARRAY_FROM_TEXT: theCASTruns on the rowWHERE c4removes. Reported in #121909; reproduces on master too.Root cause: with
enable_join_runtime_filters = 1the optimizer re-runstryMergeExpressions,tryMergeFiltersandtryPushDownFiltertop-down. The first fuses the subquery's projection into the probe-side filter step, making theSELECT-list expressions required outputs of that step, so they run on every row read and are filtered only afterwards. The first pass prevents exactly this withtrySplitFilter, which keeps a filter minimal and lifts the rest into anExpressionStepabove it; the re-run omitted that one rewrite.Fix: re-run
trySplitFilterafter that loop converges, under the same setting gate as its siblings. The resulting plan is the one the first pass already produces, and the one atenable_join_runtime_filters = 0.MergeTreeSplitPrewhereIntoReadSteps.cppstates the same invariant for PREWHERE and accepts redundant reads to keep it (#107988).Not covered: if that
SELECTlist also computes a stateful function such asrowNumberInBlock,trySplitFilterdeclines to split, since moving evaluation across a stateful function would change results. That shape still fails, as today; preventing the merge is a different change.Validation: same-base debug A/B, distinct Build-IDs. Red on base, green with the fix, for both scalings, six guard type wrappers, eight throwing-expression shapes, and through
remote()+FINAL. The runtime filter is still built and applied, with identicalRuntimeFilter*profile events. No perf regression; the affected shape is 44% faster at 2M rows.#121909 also carries an independent
CANNOT_PARSE_DATETIMEreproducer needing no tables, which this change measurably does not fix, so the PR references the issue rather than closing it.Workflow [PR]
Sync PR [sync-upstream/pr/122143]
Version info
26.10.1.1079-master(included in26.10and later)