Skip to content

Make logTrace not suitable for constant folding - #110188

Closed
alexey-milovidov wants to merge 56 commits into
masterfrom
logtrace-no-constant-folding
Closed

alexey-milovidov wants to merge 56 commits into
masterfrom
logtrace-no-constant-folding

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

The function logTrace is 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 literal 0. It therefore never ran in the execution pipeline, max_block_size and 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 = 1 logged the message once instead of three times.

This makes logTrace opt out of constant folding, mirroring sleep, so it runs for every block during execution. It also overrides executeImplDryRun so the message is not emitted 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 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:

  • logTrace is marked non-deterministic, so the query result cache refuses to cache queries containing it (under the default query_cache_nondeterministic_function_handling = 'throw').
  • logTrace is marked stateful, so filter splitting and filter pushdown do not evaluate the other conjuncts first and feed it only the surviving blocks.
  • The sort-lifting optimization (liftUpFunctions) and lazy materialization now keep expressions containing stateful functions below a same-level ORDER 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 as runningAccumulate see the rows in pre-sort order when the ORDER BY is at the same query level; the existing test 04218_running_accumulate_state_uaf was adjusted to sort in a subquery (the documented usage pattern), so the accumulation order is pinned regardless of where the expression is evaluated.
  • The default top-K ORDER BY ... LIMIT optimizations (optimizeTopK dynamic filtering and skip-index pruning, and topKThroughJoin) no longer prune source rows below an expression containing stateful functions.
  • The in-order aggregation limit push-down (optimizeLimitForAggregationInOrder, default-on via optimize_aggregation_in_order_limit) no longer pushes the outer LIMIT into AggregatingStep's early termination across an expression containing a stateful function: isTransparentStep treated any row-count-preserving ExpressionStep as safe to cross, so a query such as SELECT neighbor(key, 1) FROM t GROUP BY key ORDER BY key LIMIT 1 (with optimize_aggregation_in_order = 1, optimize_aggregation_in_order_limit = 1) stopped the in-order aggregation after the first group and returned the default 0 instead of the next key, and logTrace in the same spot would fire only for the limited groups. The arrayJoin case was already rejected because it does not preserve the row count (mirroring the reader-side and top-K fences above).
  • The vector-search ORDER BY <distance> LIMIT rewrites (useVectorSearch over a vector similarity index, and useVectorSearchWithQuantizedCodes, 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 as SELECT logTrace('x'), id FROM t ORDER BY cosineDistance(vec, [..]) LIMIT 1 still evaluates the stateful function on every pre-sort block. The same rewrites also bail out on a row-changing arrayJoin below the sort (in the projection, the WHERE/PREWHERE chain, and - for the quantized-codes rewrite - the intervening Expression/Filter chain), mirroring optimizeTopK, so a query such as SELECT arrayJoin(tags) FROM t ORDER BY cosineDistance(vec, [..]) LIMIT 1 is not shortlisted to the nearest base row only (whose expansion may be empty).
  • The same fences now cover reader-side filters: a stateful predicate inside an explicit PREWHERE (or a row-level policy filter) executes inside the reader, below the plan steps the visible-chain guards inspect. optimizePrimaryKeyConditionAndLimit no 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 < 16 previously logged for 1 block instead of 8) - and stops the plan walk at a FilterStep containing a stateful function or arrayJoin, so neither its conjuncts nor the outer LIMIT are pushed below it. tryOptimizeTopK (whose skip-index pruning would drop marks before an explicit stateful PREWHERE runs), the useVectorSearch first pass (whose index shortlist would feed the prewhere only the candidate granules), and useVectorSearchWithQuantizedCodes (which runs after optimizePrewhere, so a stateful WHERE can already be hidden inside the reader) all bail out to the exact scan when the reader carries a stateful PREWHERE or row-level filter. Complementarily, MergeTreeWhereOptimizer (which implements the automatic WHERE -> PREWHERE move under the default optimize_move_to_prewhere = 1) no longer moves any conjunct of a stateful WHERE into PREWHERE, on both the planner optimizePrewhere and the old-analyzer try_move_to_prewhere paths: it previously rejected only arrayJoin / GLOBAL IN per conjunct, so a deterministic sibling condition (e.g. key % 2 = 0 in WHERE key % 2 = 0 AND neighbor(v, 1) = v + 1) could be moved to the reader-side PREWHERE, evaluated first, and drop rows before the stateful predicate runs, making neighbor observe the wrong adjacent rows (the count collapsed from 50 to 0). Non-stateful WHERE filters still move to PREWHERE as before.
  • A deterministic row-level policy must also take the same filtered-query path as a visible WHERE / PREWHERE, not only the stateful bailout above. tryOptimizeTopK gated perform_top_k_optimization on where_clause = filter_step || getPrewhereInfo(), and useVectorSearch gated additional_filters_present the 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 (so SELECT key FROM t ORDER BY key LIMIT 3 under USING key >= 100 could return nothing), and vector search skipped the vector_search_filter_strategy = 'prefilter' bailout and fetched only LIMIT neighbors without the vector_search_index_fetch_multiplier compensation (so USING id != 0 could make ORDER BY cosineDistance(...) LIMIT 1 miss the next allowed neighbor). Both now count any non-null getRowLevelFilter() as a filter, matching the visible-filter path.
  • Projection selection no longer substitutes a projection read or projection index for a query whose DAG contains a stateful function or a stateful reader-side filter. QueryDAG::build (used by both optimizeUseNormalProjections and optimizeUseAggregateProjections) previously rejected only arrayJoin, 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 by k and a projection ordered by v, SELECT count() FROM t WHERE neighbor(v, 1) = v + 1 counts differently through the projection than through the base read. The stateful-function bailout is now applied in QueryDAG::buildImpl to ExpressionStep, FilterStep, explicit PREWHERE, and row-level filters (mirroring the existing arrayJoin bailouts), so both projection optimizers leave stateful queries on the base-table read. Non-stateful queries still use projections as before.
  • The planner-side stateful / arrayJoin fences (mainQueryNodeBlockSizeByLimit, pushOrderByIntoView) now also descend into correlated subqueries in the projection. hasStatefulFunctionNode / hasArrayJoinFunctionNode previously stopped at every QUERY / UNION child, so a correlated scalar subquery such as SELECT (SELECT logTrace('x') FROM ... WHERE inner.k = outer.k) FROM t LIMIT 1 looked stateful-free. A non-correlated subquery is evaluated independently of the outer query, so a LIMIT below 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 (via isCorrelated). 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-LIMIT cap is already neutralized), and a correlated subquery cannot run at all without decorrelation.
  • Join reordering (optimizeJoin, under the default query_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 example SELECT 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.k evaluated neighbor on only the rows surviving the outer join. A hasStatefulFunctions() bailout is now applied alongside the existing hasArrayJoin checks in addChildQueryGraph and the sibling flattening check in buildQueryGraph. Non-stateful expressions are still merged into joins as before.
  • Merging stacked filters (tryMergeFilters, under the default query_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 single and(...) filter. The merged filter evaluated the stateful predicate on the inner filter's input instead of its output, so a query such as SELECT count() FROM (SELECT * FROM t WHERE k % 2 = 0) WHERE neighbor(v, 1) = v + 2 ran neighbor on the unfiltered stream (the count collapsed from 4 to 0 on ten sequential rows), and logTrace logged 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.
  • The Limit -> Distinct fast path of tryPushDownLimit no longer sets the DistinctStep limit 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 final LIMIT cancellation in the per-stream preliminary distinct. The check inspects reader-side filters (an explicit PREWHERE, a row-level security policy) on SourceStepWithFilterBase as well, not only visible ExpressionStep / FilterStep nodes. For non-stateful queries the hint is still applied as before.
  • The lazy FINAL optimization (optimizeLazyFinal, under query_plan_optimize_lazy_final) now bails out when the WHERE filter, the PREWHERE, or the row-level filter contains a stateful function, keeping the regular FINAL read. The rewrite clones these filters into a hidden non-FINAL set-building read (and the non-intersecting split replays them on a plain non-FINAL read) and then evaluates them again on the result branch, so a stateful predicate executed twice and observed the pre-FINAL duplicate stream: SELECT count() FROM t FINAL WHERE neighbor(v, 1) = 101 on a ReplacingMergeTree with an old and a new part built the key set from the pre-FINAL rows, narrowed the read to the wrong key set, and returned 0 instead of 1, and PREWHERE logTrace('x') = 0 logged its message additionally for each block of the hidden read. The bailout also covers a stateful function in the projection (an ExpressionStep above the FINAL read): the rewrite replaces the regular FINAL read with the InputSelector branches 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, so SELECT neighbor(v, 1) FROM t FINAL WHERE k > 0 returned non-deterministic results under max_threads > 1. For non-stateful queries the optimization is applied as before.
  • The AST-side stateful / arrayJoin detectors (the trivial-LIMIT fast paths in InterpreterSelectQuery and numbersLikeUtils, and the WHERE -> PREWHERE fence in MergeTreeWhereOptimizer) now descend into SQL UDF bodies (UserDefinedSQLFunctionFactory) with cycle protection, mirroring expressionContainsArrayJoin in RowPolicy.cpp, so a wrapper such as CREATE FUNCTION f AS x -> neighbor(x, 1) or CREATE 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::normalize on 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.
  • Plain LIMIT no 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-LIMIT source fast paths do not cap the source block size or row count for stateful projections (previously SELECT neighbor(number, 1) FROM system.numbers LIMIT 1 returned 0 instead of 1 because neighbor ran on a single-row block), ORDER BY/LIMIT is 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 or WHERE/PREWHERE chain: 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 the ORDER BY (previously SELECT neighbor(v, 1) FROM mt ORDER BY pk LIMIT 1 returned 0 because 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-changing arrayJoin function in the select list (getLimitForSorting only rejects the ARRAY JOIN clause form), matching the actions.hasArrayJoin() fence in the query-plan buildSortingDAG and the sibling maxBlockSizeByLimit, so a query such as SELECT arrayJoin(a) FROM mt ORDER BY pk LIMIT 1 does not push the limit into the storage read. The numbers-source limit pushdown (numbersLikeUtils::shouldPushdownLimit) now also inspects the WHERE/PREWHERE filter, not only the SELECT list, for arrayJoin and stateful functions, so a query such as SELECT number FROM numbers(100) WHERE arrayJoin(if(number < 3, [], [number])) >= 0 LIMIT 3 (the shape of a WITH alias referenced only in WHERE) is not hard-capped to the first LIMIT rows before the filter runs. All of these arrayJoin guards canonicalize the function name (via getFunctionCanonicalNameIfAny), so the case-insensitive alias unnest is treated the same as arrayJoin regardless of normalize_function_names. The legacy old-analyzer window read-in-order shortcut (tryReuseStorageOrderingForWindowFunctions, enabled by query_plan_reuse_storage_ordering_for_window_functions) likewise no longer pushes the outer LIMIT into the storage read when the pre-window expression contains a stateful function or arrayJoin. Both legacy old-analyzer read-in-order paths (InterpreterSelectQuery::executeFetchColumns and tryReuseStorageOrderingForWindowFunctions) also gate the limit pushdown on hidden reader-side filters collected into query_info.filter_asts (a row policy, an additional table filter, or a parallel-replicas custom-key filter), not only the AST-visible WHERE/PREWHERE, matching the filter_asts.empty() check in maxBlockSizeByLimit; so a query with a row policy such as USING logTrace('x') = 0 or USING neighbor(v, 1) = 20 does not have the outer LIMIT pushed past the filter before the reader-side filter runs. The existing test 04201_too_many_optimizations_window_array_join generated its data via generateRandom(...) LIMIT 20 under a stateful rowNumberInAllBlocks projection, 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.
  • The simple-LIMIT source 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, a generateRandom-backed source seeds each parallel stream independently, so an unordered LIMIT above a stateful function became nondeterministic across runs, picking up whichever stream's rows happened to arrive first. This surfaced as result differs with reference failures (only on this PR's CI runs) in 01710_projections, 02771_parallel_replicas_analyzer, and 02731_parallel_replicas_join_subquery, which all insert fixture data via rowNumberInAllBlocks() ... FROM generateRandom(...) LIMIT N. 01710_projections and 02731_parallel_replicas_join_subquery also pin max_block_size to the LIMIT on the affected inserts, since they read back non-first generateRandom columns, whose values are still block-size-dependent (generateRandom fills each block's columns sequentially from one RNG stream).
  • Parallel replicas are disabled for a stateful trivial-LIMIT query, on both the planner (PlannerJoinTree) and the old-analyzer InterpreterSelectQuery::adjustParallelReplicasAfterAnalysis. Forcing a single local stream (above) is not sufficient when parallel replicas are enabled: the read could still be replaced with ReadFromParallelRemoteReplicasStep, splitting and re-interleaving the rows the stateful expression observes, so a query such as SELECT neighbor(v, 1) FROM mt LIMIT 1 SETTINGS enable_parallel_replicas = 1 would 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 make maxBlockSizeByLimit short-circuit at its filter_asts.empty() gate (and PlannerJoinTree's has_additional_filters skip the mainQueryNodeBlockSizeByLimit call) before the stateful flag was set, so SELECT neighbor(v, 1) FROM mt LIMIT 1 under 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-side has_additional_filters check now also treats the parallel-replicas custom-key filter (appended to the reader-side where_filters later by buildCustomKeyFilterIfNeeded) as a hidden reader-side filter, matching the old-analyzer treatment (the custom-key AST lands in query_info.filter_asts, which maxBlockSizeByLimit already checks): a replica planning a trivial-LIMIT query under custom-key parallel replicas (parallel_replicas_count > 1 with a non-empty parallel_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 collapsed max_block_size to the LIMIT, forced a single stream, and fed a wrong row estimate to the progress and limits checks; the result rows on MergeTree were 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 an additional_table_filters predicate such as neighbor(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 trivial LIMIT query under such a policy kept several local read streams and kept parallel replicas enabled, so the logTrace side 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, pushOrderByIntoView no longer pushes ORDER BY/LIMIT into a view on a replica that appends a custom-key filter above the view subquery, mirroring its row-policy and additional_table_filters guards (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):

  • 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):

Function logTrace now 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 as runningAccumulate or neighbor) are no longer moved past a same-level ORDER BY by the sort-lifting and lazy-materialization optimizations, so they observe the rows in pre-sort order, and LIMIT-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

  • Documentation is written (mandatory for new features)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46f1067]

Summary: ✅


AI Review

Summary

This PR fixes logTrace and extends the stateful-function fences across a large set of plan optimizations. The overall direction looks right, but the pushOrderByIntoView rewrite still misses one important boundary: it only checks the outer projection, so it can still push ORDER BY/LIMIT into a view whose own query contains a stateful expression and change the row/block stream that expression observes.

Findings

❌ Blockers

  • [src/Planner/PlannerJoinTree.cpp:1256] pushOrderByIntoView still assumes the view definition itself is transparent once the outer projection is clean. A view like SELECT neighbor(v, 1) AS n, k FROM dist can therefore receive an injected inner ORDER BY k LIMIT 1, which moves the ordering/limit semantics across the view boundary and lets the stateful function run under a different read strategy than the original outer-sort plan.
    Suggested fix: reject the rewrite when the inner view query contains stateful functions in its projection or filter chain, and add a focused regression covering a stateful view queried with outer ORDER BY ... LIMIT.
Final Verdict

❌ Changes required: the stateful-function contract is still violated by ORDER BY/LIMIT pushdown into stateful view definitions.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 513/552 (92.93%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 12, 2026
Comment thread src/Functions/logTrace.cpp Resolved
alexey-milovidov and others added 2 commits July 13, 2026 03:54
…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]>
Comment thread src/Functions/logTrace.cpp Resolved
alexey-milovidov and others added 2 commits July 13, 2026 09:13
…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]>
Comment thread src/Functions/logTrace.cpp Resolved
alexey-milovidov and others added 2 commits July 13, 2026 12:28
`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]>
Comment thread src/Functions/logTrace.cpp Resolved
alexey-milovidov and others added 3 commits July 14, 2026 09:25
…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]>
Comment thread src/Functions/logTrace.cpp Resolved
…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]>
alexey-milovidov and others added 2 commits July 17, 2026 03:43
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`.
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 46f1067c5 with master 8cb46d93b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.65 MiB -3.00 MiB (-0.43%)

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 units

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

Translation units without a recent master baseline:

  • contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-s3/source/S3Client.cpp: 13.7 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/vm/plugin_modules.cpp: 13.3 s
  • contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-glue/source/GlueClient.cpp: 12.7 s
  • contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-glue/source/GlueClient1.cpp: 12.0 s
  • contrib/rocksdb-cmake/__/rocksdb/db/db_impl/db_impl.cc: 10.4 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/api/wasmedge.cpp: 10.1 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/host/wasi/wasimodule.cpp: 9.6 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/vm/vm.cpp: 9.3 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/host/wasi/wasifunc.cpp: 8.5 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/openai/openai_stream.cpp: 8.2 s
  • contrib/rocksdb-cmake/__/rocksdb/utilities/transactions/pessimistic_transaction_db.cc: 8.1 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/openai/openai_response_parser.cpp: 8.1 s
  • contrib/rocksdb-cmake/__/rocksdb/db/version_edit_handler.cc: 7.8 s
  • contrib/aws-cmake/__/aws/generated/src/aws-cpp-sdk-glue/source/GlueClient2.cpp: 7.8 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/anthropic/anthropic_response_parser.cpp: 7.6 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/plugin/plugin.cpp: 7.6 s
  • contrib/azure-cmake/__/azure/sdk/storage/azure-storage-blobs/src/rest_client.cpp: 7.5 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/base_provider_client.cpp: 7.4 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/openai/openai_request_builder.cpp: 7.3 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/engine/engine.cpp: 7.2 s
  • ... and 64 more

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole CI red on 5b0dd015 — test_dirty_pages_force_purge timing out waiting for the MemoryAllocatorPurge event in Integration tests (arm_binary, distributed plan, 4/4) — is unrelated to this PR: the same timeout hit unrelated PRs #111332, #113192, #107442, and #105056. Root cause is a machine-dependent threshold in the test (the query peaks at ~417 MiB while the purge threshold is 819 MiB, and jemalloc dirty-page reuse can keep pdirty below it); fix: #113811. Master has been merged into this branch for a fresh CI run.

… 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.
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
alexey-milovidov and others added 3 commits August 8, 2026 19:49
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for head 3818ccdc: the Stateless tests (arm_binary, parallel) red 04357_distributed_alias_same_expression (unmerged per-shard groups, 300 300 2 → two rows of 300 300 1) is unrelated to this PR — it flakes on master and across many PRs (10× on master in the last 30 days per CIDB). Tracked in #112987, fix in progress in #108855.

The amd_debug reds were this PR's own new test 04823_stateful_projection_lazy_final (flaky value-equality between two executions of the regular FINAL read, whose chunk order is not deterministic in debug builds) — fixed by comparing the plans instead, plus the two review Blockers (parallel-replicas custom-key filter) are addressed in the new commits.

…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the CI reds on 171e8cba, addressed in a3af03a83084..46f1067c50a9:

  • 04823_stateful_projection_lazy_final, 04824_parallel_replicas_stateful_custom_key_limit, 04825_custom_key_order_by_into_view (this PR's own tests) failed only in the old-analyzer and parallel-replicas configurations: enable_analyzer = 1 inside FROM (EXPLAIN ...) subqueries is rejected when the session default is 0 (INCORRECT_QUERY), 04823's control only optimizes with the analyzer plan shape, and 04825's control pushdown is legitimately suppressed by a session-enabled parallel-replicas plan. Fixed by pinning enable_analyzer at the session level and enable_parallel_replicas = 0 on the control — validated locally under default, old-analyzer, and parallel-replicas sessions (no-random + 4× randomized-settings runs).
  • Stress test (arm_tsan) Logical error: Not-ready Set is passed as the second argument for function (STID 0250-41a5) is the known open master issue, unrelated to this PR (every change here is gated on stateful functions, and the failing query family involves none). Investigation and fixes are already in progress there.
    Related: Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619
    Related: Preserve execution limits and resources in derived QueryPlans #109722

The remaining review thread (AST walkers descending into independent subqueries) was refuted empirically but the suggested explicit stop at ASTSubquery / ASTSelectWithUnionQuery is now in place anyway — see the thread reply for the probes.

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 9, 2026
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

I doubt this.

  1. Making logTrace run for each block will make it dangerous to give it to users. They could overwhelm monitoring and observability.
  2. Even if a function is stateless does not mean that we care about where it runs. It does not have to inhibit optimizations. We may let optimizations change the order of execution even if it contains stateless functions.

@alexey-milovidov alexey-milovidov added the wasted Discussion went in a wrong direction label Aug 9, 2026
github-actions Bot pushed a commit to Altinity/ClickHouse that referenced this pull request Aug 10, 2026
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)
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Aug 15, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default wasted Discussion went in a wrong direction

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants