Skip to content

Introduce General Window Functions Batch Execution - #127389

Merged
Michicosun merged 22 commits into
masterfrom
general_window_functions_interface
Oct 28, 2026
Merged

Michicosun merged 22 commits into
masterfrom
general_window_functions_interface

Conversation

@Michicosun

@Michicosun Michicosun commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

This patch changes how WindowTransform executes window functions by introducing batched execution over sliding blocks. Also, a general window function interface will be introduced in this patch.


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

Version info

  • Merged into: 26.11.1.875-master (included in 26.11 and later)

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ac6d9a]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

The PR separates general window functions from aggregates and evaluates them in batches. At head 1ac6d9aa70f02a73ccfc692dd05d115aa6f19611, two previously reported performance and cancellation regressions remain. Both were deliberately accepted in discussion; they are retained below without new inline comments or reopening threads. No additional inline findings were identified.

Findings

❌ Blockers

  • src/Processors/Transforms/WindowTransform.cpp:291 — Argument indexing makes streaming windows quadratic in retained blocks. [dismissed by author -- https://github.com/Introduce General Window Functions Batch Execution #127389#discussion_r4348236622] collectArgumentBlocks still scans every retained block for every batch containing general-function arguments. With UNBOUNDED PRECEDING, a partition spanning B blocks therefore requires Θ(B²) block visits, even for a constant-offset lagInFrame whose previous implementation was linear. Small input blocks need not come only from explicitly setting max_block_size. Skipping aggregate-only and argument-free windows narrows the affected surface but does not remove this regression. Maintain the argument index incrementally or reuse it across batches. The accepted follow-up is tracked in Window functions batch execution (#127389): every batch walks all retained blocks #127659.

  • src/Processors/Transforms/WindowTransform.cpp:298 — Cancellation latency grows from one result row to an entire expensive batch. [dismissed by author -- https://github.com/Introduce General Window Functions Batch Execution #127389#discussion_r4348236630] The batch evaluators still have no cancellation check. For exponentialTimeDecayedMax over a whole-partition frame, a 65,505-row batch over a million-row partition can scan roughly 65 billion rows before observing cancellation, delaying resource release and KILL QUERY ... SYNC. The unconditional flushBatch at line 258 also evaluates pending work after the collection loop detects cancellation. This remains an operational concern despite the deliberate decision to check between blocks. Pass cancellation into evaluation, poll between result rows, and discard pending work after cancellation.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so runtime reproduction was not repeated. The current-head fast-test report passes 05442–05446 but skips 05441_window_functions_general_block_sizes; a full stateless result for that test would close the remaining block-size validation gap. CI report.
Final Verdict

❌ Block — The two dismissed concerns remain present in the current code. The minimum technical changes are incremental/reused argument indexing and cancellation checks during expensive evaluation, with focused scaling and cancellation validation. Existing dismissed threads were left unchanged; no new review batch was necessary.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 22, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). label Oct 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 1ac6d9aa70f02a73ccfc692dd05d115aa6f19611 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

@yariks5s yariks5s self-assigned this Oct 22, 2026

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the bot's performance findings, I think that's still a reasonable trade-off given the code complexity. At least now

@groeneai please validate whether these findings existed before, and create a separate issue and a fix for them.

@groeneai

Copy link
Copy Markdown
Collaborator

I checked both performance findings against master. Neither existed before; both come from the batch path in this PR.

  • Retained-block walk: master has no per-batch argument index, and general functions read blocks through blocks.blockAt. With one-row blocks and an UNBOUNDED PRECEDING frame, lagInFrame(number) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) is linear on master: 0.53 / 0.66 / 1.08 s for 40k / 80k / 160k rows. Here collectArgumentBlocks walks all retained blocks once per batch. Since ae08c116 that happens only when a general function has arguments.
  • Cancellation: master checks isCancelled() after every result row. exponentialTimeDecayedMax over a whole-partition frame on numbers(300000) stops at 1004.8 ms with max_execution_time = 1. Here evaluate runs a whole batch without a check, and the final flushBatch() also runs after cancellation.

Issue: #127659. I'll send the fix after this PR is merged, since both are in the new code.

@Michicosun
Michicosun enabled auto-merge October 24, 2026 10:15
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 28, 2026
…es without rabbitmqctl

`rabbitmqctl close_all_connections test` timed out after 300 s in 3 runs of
`Integration tests (arm_binary, 2/4)` (master 524a0c2, ClickHouse#127389, ClickHouse#126642). The
close never reached the broker: no `Closing connection ... because "test"` line
in its log, and ClickHouse's AMQP connection stayed open for 5 minutes until the
test dropped the database. The broker passed its `rabbitmq-diagnostics ping`
healthcheck 29/29 times in each window, so a new CLI process again never got to
its RPC, like the `list_queues` call before.

Bounding the call and asking again does not fit here: the drop must happen while
most of the backlog is still queued (`view_rows() < messages_num // 2`), which
leaves about 9 s after the 500-row trigger at ~490 rows/s, and a timed-out
`docker exec` leaves the CLI running in the container, where a late close would
force a second reconnect.

Close through the management API instead:
`DELETE /api/connections/username/root` with `X-Reason: test` reaches the same
`rabbit_networking:close_connection(Pid, "test")` for every connection of the
broker's only user, synchronously before the 204 reply, and starts no CLI process.

Validated: an injected never-returning close fails the unfixed test after 300 s
with the CI error; without the DELETE the test fails waiting for the reconnect;
the pre-ClickHouse#125105 binary still fails on the duplicates bound (9500, 9400); 50/50
runs pass with `204` (p50 0.1 s) and ClickHouse logs `CONNECTION_FORCED - test`
then `Connection restored`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Michicosun
Michicosun added this pull request to the merge queue Oct 28, 2026
Merged via the queue into master with commit 7a17809 Oct 28, 2026
178 of 180 checks passed
@Michicosun
Michicosun deleted the general_window_functions_interface branch October 28, 2026 20:12
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up to #127389 (comment): the fix for the retained-block walk (#127659) is #128097. It keeps one argument block index per transform instead of rebuilding it every batch (max_block_size = 1, 40000 rows: 9.96 s -> 0.19 s). Cancellation inside a batch is left as is, as agreed on #127659.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 29, 2026
…-rank-dense-rank-rows-frame-peers

Master's ClickHouse#125749 (Peers) and ClickHouse#127389 (general window functions batch
execution) removed IWindowFunction.h and made rank() and dense_rank()
read bounds.peers_start and bounds.peer_group_index.

Port of the same fix onto that interface:
- needsSeparateOrderByPeerGroups uses the function's getRequirements().peers
  (under ROWS only rank() and dense_rank() can require peers, cume_dist() and
  percent_rank() reject any frame but RANGE over the whole partition), so the
  needsOrderByPeerGroup virtual is dropped.
- The ORDER BY peer group start is tracked in WindowTransform as before and
  appendCurrentRow passes it as peers_start / peer_group_index, so the rank
  and dense_rank sources are master's again.
- SlidingIndexes is unchanged on master and merged cleanly.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Follow-up to #127389 (comment), where I left cancellation inside a batch as is: it now hangs master CI. Stress test (arm_tsan) on 5087d81 failed the hung check (report, hung_check.log) on a server-side AST fuzzer mutation of 02020_exponential_smoothing.sql:

SELECT ... exponentialTimeDecayedMax(100)(x, t) OVER w ... FROM numbers(1000000)
WINDOW w AS (ORDER BY 1 DESC GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)

ORDER BY 1 makes all rows one peer group, so every frame is the whole partition (130818 rows after max_rows_to_read = 100000, read_overflow_mode = 'break'). The query had max_execution_time = 10 and was still running after 574 s with is_cancelled: 1. Its pipeline thread was in WindowFunctionExponentialTimeDecayedMax::evaluate called from WindowTransform::flushBatch (c_stacktraces.log in the same job). One batch is one 65409-row block, and each row scans the whole frame, so one evaluate call does about 8.6 billion iterations.

Wall time with clickhouse local, on the CI amd_release binaries of the merge commit and its parent:

Query 6f2ed95 (parent) 7a17809 (#127389 merge)
the fuzzed query with its CI max_rows_to_read, read_overflow_mode, max_block_size, max_threads and max_execution_time = 10 10.4 s 65.1 s
exponentialTimeDecayedMax(1)(number, number) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM numbers(200000), max_execution_time = 1 1.3 s 87.2 s

Both binaries report Timeout exceeded: elapsed ~1005 ms for the second query: the limit is detected on time on both, and on the merge commit the work continues until the batch ends. Current master behaves the same.

@Michicosun which do you prefer: (a) I open a PR that passes the cancellation flag into IGeneralWindowFunction::evaluate and checks it every N rows, or (b) you handle it in your current WindowTransform rework (#128687, #128726)?

@Michicosun

Copy link
Copy Markdown
Member Author

@groeneai, I explicitly told you that this is not a problem.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Understood, sorry for raising it again. I will not open a PR for this.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 10, 2026
… right key twice

`buildJoinUsingCondition` casts the right `USING` column to the common
type as an alias with the input's own name, and `join_use_nulls` wraps it
in `toNullable`, so the right after-join action is
`ALIAS k -> toNullable -> ALIAS k -> _CAST -> INPUT k`.

For a prepared storage, `buildPhysicalJoinImpl` replaced that action with
`children(0)->children(0)`, assuming `toNullable` reads the input. With a
promoted column this is the already cast alias, so the right pre-join DAG
outputs `k` cast to the common type. For a key-value storage the whole
after-join chain is then merged into the same DAG, and
`ActionsDAG::mergeInplace` binds the chain's input `k` by name to that
cast alias. The second `_CAST` was prepared for a `LowCardinality`
argument and gets a plain column: `Bad cast ... to
DB::ColumnLowCardinality` (abort in debug). When the key needs no cast
(`String` x `LowCardinality(String)`), the DAG outputs the raw key and the
promoted alias, the merge binds the raw one, and two `k` columns of
different types remain: `Block structure mismatch`.

For a key-value storage, pass only the inputs of such an action, since
the whole action is merged into the DAG right after; the chain then runs
once over the stored column. The `Join` engine path does no merge and is
unchanged.

Found by the AST fuzzer (STID 4525-5f05) on PR ClickHouse#127389. Released 26.3 and
26.8 reject `String` x `LowCardinality(String)` with `Code: 49`; 25.8
returns the right rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants