Repository navigation
Make logTrace not suitable for constant folding - #110188
alexey-milovidov wants to merge 56 commits into
Conversation
Previously `logTrace` used the default `isSuitableForConstantFolding` (`true`). Because it only accepts a constant string argument, its call was always eligible for constant folding, so the analyzer executed it exactly once during query analysis and replaced it with the literal `0`. As a result it never ran in the execution pipeline and never emitted a message "for each Block" as documented - `max_block_size` and the number of rows had no effect on it. Make `logTrace` opt out of constant folding, mirroring `sleep`, so it runs for every block during execution. Also override `executeImplDryRun` to not emit the message during query analysis: `ActionsDAG::evaluatePartialResult` (used by `updateHeader`) executes functions with all-constant arguments via a dry run regardless of `isSuitableForConstantFolding`, which would otherwise log spuriously while computing the result header. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [46f1067] Summary: ✅
AI ReviewSummaryThis PR fixes Findings❌ Blockers
Final Verdict❌ Changes required: the stateful-function contract is still violated by LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 513/552 (92.93%) · Uncovered code |
…gging
`logTrace` now has an observable execution-time side effect (a trace message
per block), but it was still treated as deterministic. Deterministic-only
optimization paths could therefore preserve its constant `0` result while
silently dropping the logging:
- `QueryResultCache` only refuses to cache a query when it contains a function
with `isDeterministic() == false`. With `logTrace` deterministic, a query
such as `SELECT logTrace('x') FROM numbers(3) SETTINGS use_query_cache = 1`
was cached, and a later cache hit returned without executing `logTrace`, so
no per-block messages were emitted.
- `ActionsDAG` merges structurally equivalent deterministic function nodes.
Override `isDeterministic` and `isDeterministicInScopeOfQuery` to return
`false`, mirroring other per-block functions such as `blockNumber`,
`blockSize` and `nowInBlock`. Under the default
`query_cache_nondeterministic_function_handling = 'throw'`, using the query
cache with `logTrace` now throws instead of silently caching, guaranteeing the
per-block logging always runs.
Adds `04530_logtrace_not_cacheable` covering the query-cache case.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…logging `logTrace` has an observable per-block side effect but was neither deterministic (fixed earlier in this branch) nor stateful. Because `FilterStep::transformPipeline` splits a `WHERE a AND logTrace(...)` chain into separate filter transforms whenever the expression does not `hasStatefulFunctions()`, the leading conditions run first and `logTrace` is evaluated only on the blocks that survive them - logging fewer times than there are input blocks. The same `hasStatefulFunctions` gate protects `splitFilter`, `filterPushDown`, and redundant-sort removal, so a non-stateful `logTrace` could also be reordered by those. Override `isStateful` to return `true`, mirroring other functions with block-level semantics such as `neighbor`. This keeps the per-block trace message firing once per input block regardless of the surrounding filter conditions. Add a regression test: with `query_plan_merge_filters` enabled (the default) and one row per block, `SELECT count() FROM numbers(4) WHERE number % 2 = 0 AND logTrace(...) = 0` must emit four trace messages (one per input block). Without the fix it emitted only two (one per surviving block). Addresses review feedback on #110188 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`logTrace` is marked stateful so optimizations do not reduce how many blocks
reach it, but `tryExecuteFunctionsAfterSorting` (lift-up-after-sorting) and lazy
materialization did not consult `hasStatefulFunctions`.
`tryExecuteFunctionsAfterSorting` lifts projection expressions that are not
needed for sorting above the `SortingStep` (which can carry a pushed-down
`LIMIT`), and lazy materialization defers such expressions past the `LIMIT`.
Either would evaluate `logTrace` only on the post-sort/post-limit rows, so a
query like `SELECT logTrace('x'), payload FROM t ORDER BY key LIMIT 1` would log
fewer times than there are input blocks.
Add a `hasStatefulFunctions` guard to both, mirroring `splitFilter`,
`filterPushDown`, and `removeRedundantSorting`. This also removes an analogous
latent hazard for `neighbor`, whose result depends on row order and grouping.
Add regression test `04532_logtrace_order_by_limit_lift` (verified: without the
guard the query logs once instead of once per input block).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…on sort guard Since expressions with stateful functions are no longer moved past a same-level ORDER BY (`tryExecuteFunctionsAfterSorting` now keeps them below the sort), `runningAccumulate` in two of the test's queries saw the rows in `GROUP BY` output order, which is not deterministic with more than one thread. Sort the rows in a subquery before applying `runningAccumulate` — the same pattern the last query of the test already uses — so the accumulation order is pinned no matter on which side of the sort the expression runs. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=ef139096118347f188b8cb2c0598df203371558d&name_0=PR&name_1=Fast%20test PR: #110188 Co-Authored-By: Claude Fable 5 <[email protected]>
…e's per-block logging Marking `logTrace` stateful already fenced the filter-splitting, sort-lifting, and lazy-materialization paths, but the default top-K `ORDER BY ... LIMIT` optimizations still reduced the rows reaching the function before the sort: - `optimizeTopK` installs a `__topKFilter` prewhere (and, with a skip index, minmax granule pruning) on the `MergeTree` read that drops source rows as the sort threshold stabilizes, before they reach the `ExpressionStep` holding `logTrace`. - `topKThroughJoin` pushes the sort + limit below a `JOIN`, truncating the preserved side to its top-n rows, so the join emits fewer rows to the expression above it. Both are enabled by default (`use_top_k_dynamic_filtering`, `use_skip_indexes_for_top_k`, `query_plan_top_k_through_join`), so `logTrace` (and other stateful functions such as `neighbor` or `runningAccumulate`) would run on only the surviving candidate rows instead of once per input block. Add the `hasStatefulFunctions()` guard to both, mirroring the existing guards in `liftUpFunctions`, lazy materialization, `splitFilter`, and filter push-down. New test `04533_logtrace_top_k_optimization` covers both paths: the dynamic-filter path via a self-calibrating trace-message count over a partitioned (multi-block) table, and the through-join path via the plan shape (the sort must not be pushed below the join when a stateful function sits above it). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d settings Since stateful functions are now kept below a same-level `ORDER BY`, `runningAccumulate` observes the rows in pre-sort order. `runningAccumulate` resets its state per block and accumulates in receive order, so under the flaky check's randomized `max_threads` it ran on several parallel streams and produced nondeterministic running sums (the previous CI failure: result differs with reference). Pin these queries to a single thread and a single block so the accumulation order is fixed regardless of the harness's randomized settings, and add a value tiebreaker to the `-ForEach` query whose `arrayJoin` expands each row into two rows that tie on `number` (previously the sort-lifting optimization masked this by applying `arrayJoin` after the sort). This does not weaken the use-after-free coverage: the fault triggers when the result column is destroyed, independent of the thread count. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…functions A limit must not truncate or re-chunk the input of a stateful expression (`IFunctionBase::isStateful`, e.g. `neighbor`, `runningAccumulate`, `logTrace`): - `tryPushDownLimit` no longer moves `LimitStep` below an `ExpressionStep` containing stateful functions, and `pushLimitByIntoSort` keeps `LIMIT BY` above such an expression. - The simple-LIMIT source fast paths (`maxBlockSizeByLimit`, `mainQueryNodeBlockSizeByLimit`, `numbersLikeUtils::shouldPushdownLimit`) do not cap the source block size or row count for stateful projections. - `optimizePrimaryKeyConditionAndLimit` stops walking through stateful expression steps, so neither the outer limit nor filters from above them reduce the source rows. - Read-in-order does not propagate the limit into the storage read below a stateful expression: `buildSortingDAG` zeroes the read limit, the reading task size (`query_limit`) is not capped, and the old interpreter's `getInputOrder` call in `executeFetchColumns` passes no limit either. - `pushOrderByIntoView` does not push `ORDER BY`/`LIMIT` into a view when the outer projection is stateful. Adds `hasStatefulFunctionNode` to the analyzer utils and a regression test for both reviewed query shapes: a stateful projection under a plain top-level `LIMIT` over a numbers-like source, and under `ORDER BY <primary key> LIMIT` with read-in-order, in both analyzers. Addresses the review on #110188.
…endent of block chunking `generateRandom` fills the columns of each block sequentially from one RNG stream, so the values inserted by the test depended on how the `LIMIT 20` was chunked into blocks. `rowNumberInAllBlocks` is stateful, so the limit is no longer pushed into the source as a block size and row cap, which changed the chunking and thus the generated values. Use `numbers` with `intHash64` instead: the inserted data is now deterministic regardless of block sizes, thread count, and plan optimizations (verified identical output on binaries with and without the stateful-function guards). The test is a regression test for a query plan optimization loop, so the concrete values are incidental; the reference is regenerated.
…l function The `hasStatefulFunctionNode` guards added to `mainQueryNodeBlockSizeByLimit` and `InterpreterSelectQuery::maxBlockSizeByLimit` disabled the whole trivial-LIMIT optimization (block-size cap, `trivial_limit`, and reducing `max_streams` to 1) whenever the query's projection contains a stateful function such as `rowNumberInAllBlocks`. That correctly stops the block-size cap from starving `neighbor`-like functions of context, but it also let such a query run with the default number of parallel streams. For a source like `generateRandom`, each stream is seeded independently and an unordered multi-stream `LIMIT` keeps whichever rows happen to arrive first, so the query became non-deterministic across runs (reproduced locally: two back-to-back runs of the same `rowNumberInAllBlocks() ... FROM generateRandom(...) LIMIT 10` returned different rows). Decouple the two: still skip the block-size cap for a stateful projection, but keep forcing a single stream, matching the pre-existing behavior for such a trivial LIMIT before the stateful-function guard was added. This surfaced as CI failures on this branch in `01710_projections`, `02771_parallel_replicas_analyzer`, and `02731_parallel_replicas_join_subquery` (`result differs with reference`, only ever on this PR's runs per CIDB history). Two of the three insert non-first `generateRandom` columns that are still block-size-dependent (`generateRandom` fills each block's columns sequentially from one RNG stream), so `01710_projections` and `02731_parallel_replicas_join_subquery` also get an explicit `max_block_size` pin (matching their `LIMIT`) to keep reproducing the existing `.reference` values regardless of the block-size cap being skipped; `02771_parallel_replicas_analyzer`'s insert only surfaces the first column, which is block-size-independent, so it only needed the single-stream fix (pinned `max_threads`/`max_block_size` anyway for clarity). Co-Authored-By: Claude Sonnet 5 <[email protected]>
Address review: extend the `hasStatefulFunctions()` fence to the vector-search
`ORDER BY <distance> LIMIT` rewrites, which were the remaining row-reducing
optimizations that bypassed it.
`useVectorSearch` (vector similarity index) and
`useVectorSearchWithQuantizedCodes` (quantized codes shortlist + rescore) both
match `Limit -> Sorting -> Expression -> [Filter] -> ReadFromMergeTree` and
prune the row stream below the expression / filter chain. A stateful function
such as `logTrace`, `neighbor`, or `runningAccumulate` in the projection or the
WHERE chain would therefore observe only the shortlisted rows instead of every
pre-sort block, e.g. `SELECT logTrace('x'), id FROM t ORDER BY
cosineDistance(vec, [..]) LIMIT 1`.
Add the same bailout used in `optimizeTopK`, `liftUpFunctions`, and lazy
materialization: `useVectorSearch` bails in its first pass (which sets the
vector-search parameters that gate the whole optimization) when the
`ExpressionStep` or the optional `FilterStep` contains a stateful function, and
`useVectorSearchWithQuantizedCodes` bails when the rescore expression or any
intervening Expression/Filter step in the chain does.
New test `04535_logtrace_vector_search` checks, for both paths, that the
optimization fires for a non-stateful query but is disabled when a stateful
function sits in the projection or the WHERE chain, and that `logTrace` still
fires for every block when the index is available.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `hasStatefulFunctions()` fences added for `logTrace`/`neighbor` do not cover row-changing `arrayJoin` below the `ORDER BY <distance> LIMIT`. `useVectorSearch` never rejected `arrayJoin` in the pre-sort `ExpressionStep` or the optional `FilterStep`, and `useVectorSearchWithQuantizedCodes` only checked `hasArrayJoin` on the rescore expression, not on the intervening `Expression`/`Filter` chain it already walks for stateful functions. For example `SELECT arrayJoin(tags) FROM t ORDER BY cosineDistance(vec, [..]) LIMIT 1` could shortlist only the nearest base row and then drop it when its `tags` array is empty, returning too few rows even though a later base row should satisfy the `LIMIT`. Add the same `hasArrayJoin` bailouts these passes now mirror for `hasStatefulFunctions`, matching `optimizeTopK`, including the intervening chain in the quantized-codes rewrite. New test `04536_vector_search_array_join`.
…functions The main read-in-order path (`buildInputOrderInfo` / `buildSortingDAG`) now zeroes the pushed limit when a stateful function or `arrayJoin` sits below the `ORDER BY`, but the legacy `tryReuseStorageOrderingForWindowFunctions` shortcut still fed `getLimitForSorting` straight into `requestReadingInOrder` after peeling an optional `ExpressionStep`. In old-analyzer window queries, `expressions.before_window` can put `neighbor` or `runningAccumulate` in that `ExpressionStep`, so `SELECT neighbor(v, 1), row_number() OVER (ORDER BY k) FROM t ORDER BY k LIMIT 1 SETTINGS allow_experimental_analyzer = 0, query_plan_reuse_storage_ordering_for_window_functions = 1` stopped the `MergeTree` read after the first row and returned the default value instead of the next row. Suppress the limit pushdown in that shortcut when the peeled expression contains `arrayJoin` or a stateful function, mirroring the main path. New test `04539_window_read_in_order_stateful`.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units3820 translation units recompiled, 4385 s compile time in total, 126 of them have a recent master baseline. Translation units without a recent master baseline:
|
|
🕵 The sole CI red on |
… a stateful function The bailout only covered stateful predicates in the visible filter, the prewhere, and the row-level filter, but a stateful expression (`neighbor`, `runningAccumulate`, `logTrace`) in an `ExpressionStep` above the `FINAL` read still observed the rewritten stream: the `InputSelector` branches and, with mixed intersecting/non-intersecting parts, the union with the split-off non-intersecting parts produce the same rows in a different row/block stream. Verified empirically: with mixed parts and `max_threads = 4`, `neighbor` over `query_plan_optimize_lazy_final = 1` returned four distinct results across eight runs, while the unoptimized query was stable. Now the walk over the steps above the read bails out of the whole optimization when an `ExpressionStep` or `FilterStep` contains a stateful function, which also subsumes the previous immediate-parent filter check.
The last check compared `groupArray(neighbor(v, 1))` between two independent executions of the same regular `FINAL` read. That read emits the merged intersecting stream and the split-off non-intersecting stream as separate chunks whose order is not deterministic run-to-run (the amd_debug CI rerun failed 102/185 times with identical settings), and `neighbor` is sensitive to chunk boundaries, so the equality was flaky even though both subqueries run the identical plan. Compare the `EXPLAIN` output of the two queries instead: plan equality is exactly what the `optimizeLazyFinal` stateful guard guarantees, and it is deterministic. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=3818ccdc9ebdf54f49d985e45f891407a1ce8f85&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 #110188 Co-Authored-By: Claude Fable 5 <[email protected]>
…rivial-LIMIT fence The trivial-`LIMIT` stateful fence in `buildQueryPlanForTableExpression` treated the parallel-replicas custom-key filter only as a deterministic hidden filter (it suppressed the source cap), on the assumption that the generated filter is a plain range predicate. But `parseCustomKeyForTable` accepts an arbitrary expression and `getCustomKeyFilterForParallelReplica` embeds it verbatim into the generated modulo / range comparisons, so a custom key such as `neighbor(k, 1)` becomes a stateful reader-side filter later in the same function, and a trivial-`LIMIT` query would still evaluate it on split / interleaved streams. Parse the key expression and scan it for stateful functions like the other hidden filters (a row policy, `additional_table_filters`), so such a query forces a single deterministic stream and disables parallel replicas. Addresses a review Blocker on #110188 Co-Authored-By: Claude Fable 5 <[email protected]>
… filter `pushOrderByIntoView` blocked the pushdown for a row policy and for `additional_table_filters`, but not for the parallel-replicas custom-key filter, which is likewise appended as a planner `where_filter` above the view subquery later in `buildQueryPlanForTableExpression`. Pushing `ORDER BY`/ `LIMIT` into the view truncates to the globally top rows before the filter discards the rows outside this replica's share of the key space. (For a plain view over a table exposing the key column the values currently stay correct, because the custom-key filter is also applied to the storage read inside the view, below the pushed sort - but the pushdown must not rely on that, so this mirrors the row-policy / additional-filter guards.) Addresses a review Blocker on #110188 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 CI triage for head The |
…rations `04824` and `04825` set `enable_analyzer = 1` inside `FROM (EXPLAIN ...)` subqueries, which the old-analyzer configuration rejects with "Setting 'enable_analyzer' is changed in the subquery" (`INCORRECT_QUERY`); pin the analyzer at the session level too. `04823`'s control query only optimizes with the analyzer plan shape, so pin it there as well. `04825`'s control query must also pin `enable_parallel_replicas = 0`, because a session-enabled parallel-replicas plan legitimately suppresses the view pushdown. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=171e8cba3ff602412810018536f076cdc4e407d9&name_0=PR #110188
…ries
The walkers already never scanned an independent subquery's expressions: every
select ultimately hangs off an `ASTSelectQuery` child, which the recursion skips.
Make the scope boundary explicit by also stopping at the wrapper nodes
`ASTSubquery` and `ASTSelectWithUnionQuery`, so the intent is visible and the
pointless descent through the wrappers is skipped. No behavior change: verified
that `SELECT (SELECT logTrace('x')) FROM numbers_mt(1000000) LIMIT 5` keeps the
trivial-`LIMIT` source cap (`max_rows_to_read = 1000` does not throw) and
`WHERE k IN (SELECT ... WHERE logTrace('z') = 0)` keeps the `PREWHERE` move,
while direct and SQL-UDF-wrapped stateful calls still trip the fences.
|
🕵 Triage of the CI reds on
The remaining review thread (AST walkers descending into independent subqueries) was refuted empirically but the suggested explicit stop at |
The test query peaks at ~417 MiB, but the purge was triggered only when jemalloc dirty pages exceeded 4 GiB * 0.2 = 819 MiB. Since jemalloc reuses dirty pages within the same arenas across iterations, `pdirty` can plateau below the threshold when few arenas are touched (e.g. when the number of query threads is lowered by `MemoryTrackerUtils` on a constrained CI machine), so the `MemoryAllocatorPurge` event never fired and the test timed out. Lower the ratio to 0.05 (~205 MiB) so a single iteration of the test query reliably exceeds the threshold. Seen in: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=5b0dd0156a543c7e72ceb73c0ebb890d53cb1f83&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29 PR: ClickHouse#110188 Co-Authored-By: Claude Fable 5 <[email protected]>
|
I doubt this.
|
The test query peaks at ~417 MiB, but the purge was triggered only when jemalloc dirty pages exceeded 4 GiB * 0.2 = 819 MiB. Since jemalloc reuses dirty pages within the same arenas across iterations, `pdirty` can plateau below the threshold when few arenas are touched (e.g. when the number of query threads is lowered by `MemoryTrackerUtils` on a constrained CI machine), so the `MemoryAllocatorPurge` event never fired and the test timed out. Lower the ratio to 0.05 (~205 MiB) so a single iteration of the test query reliably exceeds the threshold. Seen in: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=5b0dd0156a543c7e72ceb73c0ebb890d53cb1f83&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29 PR: ClickHouse#110188 Co-Authored-By: Claude Fable 5 <[email protected]> (cherry picked from commit b87486d)
… stage With `inject_random_order_for_select_without_order_by = 1`, `InjectRandomOrderIfNoOrderByPass` wrapped every top-level query into `SELECT * FROM (...) ORDER BY rand()`, including queries that are planned only up to an intermediate stage. For a `Merge` table with a `Distributed` child, the other children are planned to `WithMergeableState`; the wrapper made such a child plan complete its aggregation, so blocks without `AggregatedChunkInfo` reached `MergingAggregatedTransform`, failing with a logical error (exception) "Chunk info was not set for chunk in MergingAggregatedTransform". Now the pass is only added when the query is processed to stage `Complete`. Found by BuzzHouse: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=cdc23648d36878b136bf2c8d87ee9b0a29651412&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29 On: ClickHouse#110188 Co-Authored-By: Claude Fable 5 <[email protected]>
The function
logTraceis documented to emit a trace log message for each processed block. In practice it never did: because it only accepts a constant string argument, its call was always eligible for constant folding, so the analyzer executed it exactly once during query analysis and replaced it with the literal0. It therefore never ran in the execution pipeline,max_block_sizeand the number of rows had no effect on it, and it produced a single message at analysis time rather than one per block.For example,
SELECT logTrace('Hello') FROM numbers(3) SETTINGS max_block_size = 1logged the message once instead of three times.This makes
logTraceopt out of constant folding, mirroringsleep, so it runs for every block during execution. It also overridesexecuteImplDryRunso the message is not emitted during query analysis:ActionsDAG::evaluatePartialResult(used byupdateHeader) executes functions with all-constant arguments via a dry run regardless ofisSuitableForConstantFolding, which would otherwise log the message spuriously while computing the result header.Review follow-ups extend this so that the per-block behavior survives the rest of the plan pipeline:
logTraceis marked non-deterministic, so the query result cache refuses to cache queries containing it (under the defaultquery_cache_nondeterministic_function_handling = 'throw').logTraceis marked stateful, so filter splitting and filter pushdown do not evaluate the other conjuncts first and feed it only the surviving blocks.liftUpFunctions) and lazy materialization now keep expressions containing stateful functions below a same-levelORDER BY, matching the pre-existing stateful-function checks in the other plan optimizations (splitFilter, filter pushdown, redundant-sort removal). As a consequence, stateful functions such asrunningAccumulatesee the rows in pre-sort order when theORDER BYis at the same query level; the existing test04218_running_accumulate_state_uafwas adjusted to sort in a subquery (the documented usage pattern), so the accumulation order is pinned regardless of where the expression is evaluated.ORDER BY ... LIMIToptimizations (optimizeTopKdynamic filtering and skip-index pruning, andtopKThroughJoin) no longer prune source rows below an expression containing stateful functions.optimizeLimitForAggregationInOrder, default-on viaoptimize_aggregation_in_order_limit) no longer pushes the outerLIMITintoAggregatingStep's early termination across an expression containing a stateful function:isTransparentSteptreated any row-count-preservingExpressionStepas safe to cross, so a query such asSELECT neighbor(key, 1) FROM t GROUP BY key ORDER BY key LIMIT 1(withoptimize_aggregation_in_order = 1, optimize_aggregation_in_order_limit = 1) stopped the in-order aggregation after the first group and returned the default0instead of the next key, andlogTracein the same spot would fire only for the limited groups. ThearrayJoincase was already rejected because it does not preserve the row count (mirroring the reader-side and top-K fences above).ORDER BY <distance> LIMITrewrites (useVectorSearchover a vector similarity index, anduseVectorSearchWithQuantizedCodes, which shortlists over the quantized codes subcolumn and rescores the survivors) no longer shortlist source rows below an expression or filter chain containing stateful functions, so a query such asSELECT logTrace('x'), id FROM t ORDER BY cosineDistance(vec, [..]) LIMIT 1still evaluates the stateful function on every pre-sort block. The same rewrites also bail out on a row-changingarrayJoinbelow the sort (in the projection, theWHERE/PREWHEREchain, and - for the quantized-codes rewrite - the interveningExpression/Filterchain), mirroringoptimizeTopK, so a query such asSELECT arrayJoin(tags) FROM t ORDER BY cosineDistance(vec, [..]) LIMIT 1is not shortlisted to the nearest base row only (whose expansion may be empty).PREWHERE(or a row-level policy filter) executes inside the reader, below the plan steps the visible-chain guards inspect.optimizePrimaryKeyConditionAndLimitno longer composes such filters into the index analysis - whose partition/primary-key pruning would drop granules by the deterministic conjuncts before the stateful part runs (e.g.PREWHERE logTrace('x') = 0 AND key < 16previously logged for 1 block instead of 8) - and stops the plan walk at aFilterStepcontaining a stateful function orarrayJoin, so neither its conjuncts nor the outerLIMITare pushed below it.tryOptimizeTopK(whose skip-index pruning would drop marks before an explicit statefulPREWHEREruns), theuseVectorSearchfirst pass (whose index shortlist would feed the prewhere only the candidate granules), anduseVectorSearchWithQuantizedCodes(which runs afteroptimizePrewhere, so a statefulWHEREcan already be hidden inside the reader) all bail out to the exact scan when the reader carries a statefulPREWHEREor row-level filter. Complementarily,MergeTreeWhereOptimizer(which implements the automaticWHERE->PREWHEREmove under the defaultoptimize_move_to_prewhere = 1) no longer moves any conjunct of a statefulWHEREintoPREWHERE, on both the planneroptimizePrewhereand the old-analyzertry_move_to_prewherepaths: it previously rejected onlyarrayJoin/GLOBAL INper conjunct, so a deterministic sibling condition (e.g.key % 2 = 0inWHERE key % 2 = 0 AND neighbor(v, 1) = v + 1) could be moved to the reader-sidePREWHERE, evaluated first, and drop rows before the stateful predicate runs, makingneighborobserve the wrong adjacent rows (the count collapsed from 50 to 0). Non-statefulWHEREfilters still move toPREWHEREas before.WHERE/PREWHERE, not only the stateful bailout above.tryOptimizeTopKgatedperform_top_k_optimizationonwhere_clause = filter_step || getPrewhereInfo(), anduseVectorSearchgatedadditional_filters_presentthe same way - neither saw a hidden row policy. A query filtered only by a policy therefore stayed on the unfiltered fast path: top-K narrowed the read to the top-K marks before the policy ran (soSELECT key FROM t ORDER BY key LIMIT 3underUSING key >= 100could return nothing), and vector search skipped thevector_search_filter_strategy = 'prefilter'bailout and fetched onlyLIMITneighbors without thevector_search_index_fetch_multipliercompensation (soUSING id != 0could makeORDER BY cosineDistance(...) LIMIT 1miss the next allowed neighbor). Both now count any non-nullgetRowLevelFilter()as a filter, matching the visible-filter path.QueryDAG::build(used by bothoptimizeUseNormalProjectionsandoptimizeUseAggregateProjections) previously rejected onlyarrayJoin, so a projection - which is free to have a different sort key and granularity than the base table - could replace the base-table read and change the rows and blocks the stateful function observes. For example, with a base table ordered bykand a projection ordered byv,SELECT count() FROM t WHERE neighbor(v, 1) = v + 1counts differently through the projection than through the base read. The stateful-function bailout is now applied inQueryDAG::buildImpltoExpressionStep,FilterStep, explicitPREWHERE, and row-level filters (mirroring the existingarrayJoinbailouts), so both projection optimizers leave stateful queries on the base-table read. Non-stateful queries still use projections as before.arrayJoinfences (mainQueryNodeBlockSizeByLimit,pushOrderByIntoView) now also descend into correlated subqueries in the projection.hasStatefulFunctionNode/hasArrayJoinFunctionNodepreviously stopped at everyQUERY/UNIONchild, so a correlated scalar subquery such asSELECT (SELECT logTrace('x') FROM ... WHERE inner.k = outer.k) FROM t LIMIT 1looked stateful-free. A non-correlated subquery is evaluated independently of the outer query, so aLIMITbelow the outer projection does not change how many times it runs (the visitors still stop there); a correlated subquery is an execution-time expression evaluated in the context of the outer rows, so the visitors now descend into it (viaisCorrelated). In the current regime this is a defense-in-depth guard: correlated subqueries are decorrelated into a set-based join that reads all outer rows regardless (so the trivial-LIMITcap is already neutralized), and a correlated subquery cannot run at all without decorrelation.optimizeJoin, under the defaultquery_plan_merge_expression_into_join) no longer flattens an expression that wraps a child join into the global join graph when the expression contains a stateful function. Merging such an expression lets the optimizer reattach it at the final reordered join, so a stateful function in a subquery's projection would observe different rows and blocks than in the query as written - for exampleSELECT groupArray(n) FROM (SELECT neighbor(v, 1) AS n, l.k AS k FROM l INNER JOIN m ON l.k = m.k) lm INNER JOIN r ON lm.k = r.kevaluatedneighboron only the rows surviving the outer join. AhasStatefulFunctions()bailout is now applied alongside the existinghasArrayJoinchecks inaddChildQueryGraphand the sibling flattening check inbuildQueryGraph. Non-stateful expressions are still merged into joins as before.tryMergeFilters, under the defaultquery_plan_merge_filters) no longer collapses a stateful outer filter together with an inner filter (e.g. from a subquery or view boundary) into a singleand(...)filter. The merged filter evaluated the stateful predicate on the inner filter's input instead of its output, so a query such asSELECT count() FROM (SELECT * FROM t WHERE k % 2 = 0) WHERE neighbor(v, 1) = v + 2ranneighboron the unfiltered stream (the count collapsed from 4 to 0 on ten sequential rows), andlogTracelogged for the unfiltered blocks. A stateful inner filter observes the same input rows whether or not the merge happens, so it does not prevent the merge, and non-stateful stacked filters are still merged as before.Limit -> Distinctfast path oftryPushDownLimitno longer sets theDistinctSteplimit hint when the plan subtree below the distinct contains a stateful expression. The distinct transforms stop reading input once the hint is reached (DistinctTransform,DistinctSorted*Transform), which truncates the rows and blocks a stateful expression below the distinct observes - independently of the finalLIMITcancellation in the per-stream preliminary distinct. The check inspects reader-side filters (an explicitPREWHERE, a row-level security policy) onSourceStepWithFilterBaseas well, not only visibleExpressionStep/FilterStepnodes. For non-stateful queries the hint is still applied as before.FINALoptimization (optimizeLazyFinal, underquery_plan_optimize_lazy_final) now bails out when theWHEREfilter, thePREWHERE, or the row-level filter contains a stateful function, keeping the regularFINALread. The rewrite clones these filters into a hidden non-FINALset-building read (and the non-intersecting split replays them on a plain non-FINALread) and then evaluates them again on the result branch, so a stateful predicate executed twice and observed the pre-FINALduplicate stream:SELECT count() FROM t FINAL WHERE neighbor(v, 1) = 101on aReplacingMergeTreewith an old and a new part built the key set from the pre-FINALrows, narrowed the read to the wrong key set, and returned0instead of1, andPREWHERE logTrace('x') = 0logged its message additionally for each block of the hidden read. The bailout also covers a stateful function in the projection (anExpressionStepabove theFINALread): the rewrite replaces the regularFINALread with theInputSelectorbranches and, with mixed intersecting/non-intersecting parts, unions the split-off non-intersecting parts with the result, which produces the same rows in a different row/block stream, soSELECT neighbor(v, 1) FROM t FINAL WHERE k > 0returned non-deterministic results undermax_threads > 1. For non-stateful queries the optimization is applied as before.arrayJoindetectors (the trivial-LIMITfast paths inInterpreterSelectQueryandnumbersLikeUtils, and theWHERE->PREWHEREfence inMergeTreeWhereOptimizer) now descend into SQL UDF bodies (UserDefinedSQLFunctionFactory) with cycle protection, mirroringexpressionContainsArrayJoininRowPolicy.cpp, so a wrapper such asCREATE FUNCTION f AS x -> neighbor(x, 1)orCREATE FUNCTION explode AS a -> arrayJoin(a)cannot bypass the fences. This is defense in depth: both analyzer paths already inline SQL UDFs before these checks run (TreeRewriter::normalizeon the AST path, function resolution on the analyzer path), and a controlled experiment confirmed no wrong result was reachable through the wrappers at the previous head.LIMITno longer truncates or re-chunks the input of a stateful expression: the generic limit pushdown (tryPushDownLimit,optimizePrimaryKeyConditionAndLimit,pushLimitByIntoSort) keeps the limit above such expressions, the simple-LIMITsource fast paths do not cap the source block size or row count for stateful projections (previouslySELECT neighbor(number, 1) FROM system.numbers LIMIT 1returned0instead of1becauseneighborran on a single-row block),ORDER BY/LIMITis not pushed into a view below a stateful outer projection (and not into a view whose own query contains a stateful function in its projection orWHERE/PREWHEREchain: injecting the sort and truncation into the view definition would let the stateful expression run under an ordered top-N read strategy instead of the full view read), and the read-in-order optimization does not stop the storage read early because of the limit when a stateful expression is below theORDER BY(previouslySELECT neighbor(v, 1) FROM mt ORDER BY pk LIMIT 1returned0because the read stopped after the first row). The legacy old-analyzer interpreter path (InterpreterSelectQuery::executeFetchColumns) applies the same read-in-order guard to a row-changingarrayJoinfunction in the select list (getLimitForSortingonly rejects theARRAY JOINclause form), matching theactions.hasArrayJoin()fence in the query-planbuildSortingDAGand the siblingmaxBlockSizeByLimit, so a query such asSELECT arrayJoin(a) FROM mt ORDER BY pk LIMIT 1does not push the limit into the storage read. The numbers-source limit pushdown (numbersLikeUtils::shouldPushdownLimit) now also inspects theWHERE/PREWHEREfilter, not only the SELECT list, forarrayJoinand stateful functions, so a query such asSELECT number FROM numbers(100) WHERE arrayJoin(if(number < 3, [], [number])) >= 0 LIMIT 3(the shape of aWITHalias referenced only inWHERE) is not hard-capped to the firstLIMITrows before the filter runs. All of thesearrayJoinguards canonicalize the function name (viagetFunctionCanonicalNameIfAny), so the case-insensitive aliasunnestis treated the same asarrayJoinregardless ofnormalize_function_names. The legacy old-analyzer window read-in-order shortcut (tryReuseStorageOrderingForWindowFunctions, enabled byquery_plan_reuse_storage_ordering_for_window_functions) likewise no longer pushes the outerLIMITinto the storage read when the pre-window expression contains a stateful function orarrayJoin. Both legacy old-analyzer read-in-order paths (InterpreterSelectQuery::executeFetchColumnsandtryReuseStorageOrderingForWindowFunctions) also gate the limit pushdown on hidden reader-side filters collected intoquery_info.filter_asts(a row policy, an additional table filter, or a parallel-replicas custom-key filter), not only the AST-visibleWHERE/PREWHERE, matching thefilter_asts.empty()check inmaxBlockSizeByLimit; so a query with a row policy such asUSING logTrace('x') = 0orUSING neighbor(v, 1) = 20does not have the outerLIMITpushed past the filter before the reader-side filter runs. The existing test04201_too_many_optimizations_window_array_joingenerated its data viagenerateRandom(...) LIMIT 20under a statefulrowNumberInAllBlocksprojection, and the generated values silently depended on the limit being pushed into the source as a block size cap; it now uses a deterministic source that does not depend on chunking.LIMITsource fast paths (mainQueryNodeBlockSizeByLimit,InterpreterSelectQuery::maxBlockSizeByLimit) still force a single stream for a stateful projection even though they no longer cap the block size: without a block-size cap, agenerateRandom-backed source seeds each parallel stream independently, so an unorderedLIMITabove a stateful function became nondeterministic across runs, picking up whichever stream's rows happened to arrive first. This surfaced asresult differs with referencefailures (only on this PR's CI runs) in01710_projections,02771_parallel_replicas_analyzer, and02731_parallel_replicas_join_subquery, which all insert fixture data viarowNumberInAllBlocks() ... FROM generateRandom(...) LIMIT N.01710_projectionsand02731_parallel_replicas_join_subqueryalso pinmax_block_sizeto theLIMITon the affected inserts, since they read back non-firstgenerateRandomcolumns, whose values are still block-size-dependent (generateRandomfills each block's columns sequentially from one RNG stream).LIMITquery, on both the planner (PlannerJoinTree) and the old-analyzerInterpreterSelectQuery::adjustParallelReplicasAfterAnalysis. Forcing a single local stream (above) is not sufficient when parallel replicas are enabled: the read could still be replaced withReadFromParallelRemoteReplicasStep, splitting and re-interleaving the rows the stateful expression observes, so a query such asSELECT neighbor(v, 1) FROM mt LIMIT 1 SETTINGS enable_parallel_replicas = 1would otherwise not see a single deterministic input stream. This single-deterministic-stream requirement (force one stream, disable parallel replicas) is a separate concern from the source-cap decision, so it must not be conflated with the hidden-reader-side-filter bailout: a row policy / additional table filter used to makemaxBlockSizeByLimitshort-circuit at itsfilter_asts.empty()gate (andPlannerJoinTree'shas_additional_filtersskip themainQueryNodeBlockSizeByLimitcall) before the stateful flag was set, soSELECT neighbor(v, 1) FROM mt LIMIT 1under a row policy could still run multi-stream / parallel-replica. The hidden-filter check now suppresses only the source cap (moved after the stateful-function check in both functions); the stateful projection still forces a single stream and disables parallel replicas on both analyzers even under a hidden filter. The planner-sidehas_additional_filterscheck now also treats the parallel-replicas custom-key filter (appended to the reader-sidewhere_filterslater bybuildCustomKeyFilterIfNeeded) as a hidden reader-side filter, matching the old-analyzer treatment (the custom-key AST lands inquery_info.filter_asts, whichmaxBlockSizeByLimitalready checks): a replica planning a trivial-LIMITquery under custom-key parallel replicas (parallel_replicas_count > 1with a non-emptyparallel_replicas_custom_key) no longer announces the source cap in front of the filter that discards the rows outside its share of the key space (the cap collapsedmax_block_sizeto theLIMIT, forced a single stream, and fed a wrong row estimate to the progress and limits checks; the result rows onMergeTreewere still correct because the read is pulled lazily). Finally, the hidden reader-side filter can itself contain a stateful function (CREATE ROW POLICY ... USING logTrace('x') = 0, or anadditional_table_filterspredicate such asneighbor(v, 1) = 20); such a filter runs on the read side, so both functions now scan the hidden filters for stateful functions as well and raise the same single-deterministic-stream requirement even when the SELECT list is free of them - previously a trivialLIMITquery under such a policy kept several local read streams and kept parallel replicas enabled, so thelogTraceside effect could disappear on the remote replicas and an order-dependent filter could keep different rows. The parallel-replicas custom key is such a filter too: the key expression is arbitrary (parallel_replicas_custom_key = 'neighbor(k, 1)') and is embedded verbatim into the generated modulo/range comparisons, so the planner now parses the key expression and scans it for stateful functions like the other hidden filters. Similarly,pushOrderByIntoViewno longer pushesORDER BY/LIMITinto a view on a replica that appends a custom-key filter above the view subquery, mirroring its row-policy andadditional_table_filtersguards (for a plain view over a table exposing the key column the values currently stay correct either way, because the custom-key filter is also applied to the storage read inside the view, below the pushed sort - the pushdown must not rely on that).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Function
logTracenow emits its message for each processed block during query execution, as documented. Previously it was constant-folded during query analysis and logged the message only once. Additionally, expressions containing stateful functions (such asrunningAccumulateorneighbor) are no longer moved past a same-levelORDER BYby the sort-lifting and lazy-materialization optimizations, so they observe the rows in pre-sort order, andLIMIT-related optimizations (limit pushdown into the source, read-in-order early termination, and top-K filtering) no longer truncate or re-chunk their input rows.Documentation entry for user-facing changes