Skip to content

Do not rebuild the window function argument index for every batch - #128097

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:window-arguments-shared-block-index
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:window-arguments-shared-block-index

Conversation

@groeneai

@groeneai groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127659
Related: #127389

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not required: the slow path exists only on master since #127389 and is not in any release.

Description

Since #127389, WindowTransform::flushBatch rebuilds the argument block index for every batch: collectArgumentBlocks walks all retained blocks, and every function slot copies the result. A frame that starts at UNBOUNDED PRECEDING keeps the whole partition, so a partition of B blocks costs O(B^2) block visits.

Now the transform keeps one index: an entry is appended in addInputBlock and removed with its block in releaseUnusedBlocks, and every WindowArguments holds a reference to it. Positions are still counted from the start of the current partition, so the window functions are unchanged: startNextPartition renumbers the stored entries once and drops the per-argument block cache. The cache is checked in WindowArguments::at itself, so a cache hit costs no call. collectArgumentBlocks is removed.

SELECT lagInFrame(number) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM numbers(N) FORMAT Null SETTINGS max_block_size = 1, max_threads = 1, median of 3, local RelWithDebInfo build without LTO:

N master this PR
10000 0.544 s 0.052 s
20000 2.317 s 0.099 s
40000 10.103 s 0.212 s

I added a 1M-row max_block_size = 100 variant to window_functions_streaming.xml (1.045 s -> 0.105 s locally). At the default block size, the six lag/lead/nth_value/exponentialTimeDecayedSum/nonNegativeDerivative queries of the existing perf tests stay between 7% faster and 3% slower than master (median of 12 runs each). The index is kept for every window, so a window without argument functions pays 32 bytes per stored block (+8% peak memory for row_number() over 1M one-row blocks). The existing block-size tests (05293*, 05441-05446) pass 50 times each with random settings, and fail when the partition offset is shifted by one.


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

groeneai and others added 2 commits October 28, 2026 22:22
Since ClickHouse#127389 `WindowTransform::flushBatch` called `collectArgumentBlocks`
for every batch: it walked from the batch block back to the first retained
block and then built one `WindowArguments::Block` per retained block, and
every slot copied that vector. The positions in it were counted from the
partition start, so the vector could not be reused between batches. A frame
that starts at `UNBOUNDED PRECEDING` retains the whole partition, so a
partition of B blocks cost Theta(B^2) block visits.

Keep one index for the whole transform instead, next to `SlidingBlocks`:
an entry is appended in `addInputBlock` and popped together with its block
in `releaseUnusedBlocks`, and positions are counted from the first input row,
so an entry never changes while its block is retained. A batch now computes
only the transform-wide position of its partition start and points every
slot at the shared index; `WindowArguments::at` keeps taking
partition-relative positions and adds that offset. The per-argument block
cache stores a pointer to the entry and is checked in `at` itself, so a
lookup that hits it neither indexes the deque nor calls the binary search
(with the check inside an out-of-line `findBlock`, every lookup paid a call,
3-5% on the `nth_value`/`lag`/`lead` queries at the default block size).

`SELECT lagInFrame(number) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND
CURRENT ROW) FROM numbers(40000) FORMAT Null SETTINGS max_block_size = 1,
max_threads = 1`, median of 3: 9.958 s before, 0.191 s after (RelWithDebInfo
without LTO); 10.917 s before, 0.229 s after (debug; 0.217 s before ClickHouse#127389).

Closes ClickHouse#127659

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The shared argument index added one entry per retained block also for
windows whose functions take no arguments (aggregate-only windows,
`row_number`, `rank`, ...), which never read it. Master skipped all
argument work for them, so keep the index only when some general function
has arguments.

Peak memory with one-row blocks, 1M rows (`--memory-usage`):
`row_number() OVER ()` 357901880 on master, 387340944 before this change,
357901880 after; `sum(number) OVER (ROWS UNBOUNDED PRECEDING)` 376681663,
408749231, 376681703.

Also shorten the new perf query to 1M rows so it stays under the perf
report's single-run limit on the old server (1.047 s -> 0.101 s locally).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head 4ba3a43): 1 major + 1 nit agreed and fixed, nothing open
  • ⚠️ Round 1: the shared argument index was also kept for windows whose functions read no arguments (aggregate-only, row_number, rank, ...), about +8% peak memory with one-row blocks. AGREE, fixed: the index is kept only when some function reads arguments, as before. Peak memory of row_number() OVER () and sum(number) OVER (ROWS UNBOUNDED PRECEDING) over 1M one-row blocks now equals master's.
  • 💡 Round 1: the new perf query ran ~4.6 s on the old server, above the perf report's 2 s single-run limit. AGREE, fixed: 1M rows (1.047 s -> 0.101 s).
  • 💡 The block cache check lives in WindowArguments::at instead of findBlock. DISAGREE: intended, so that a cache hit costs no call.
  • Round 2: no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: lagInFrame(number) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) over numbers(N) with max_block_size = 1; master grows ~4.4x per doubling of N (9.96 s at N = 40000, RelWithDebInfo).
b Root cause explained? flushBatch rebuilt the argument block index over all retained blocks for every batch, with positions relative to the partition start; UNBOUNDED PRECEDING retains the whole partition, so B blocks cost O(B^2).
c Fix matches root cause? Yes: one index per transform, updated in O(1) per added/released block and kept only when some function reads arguments (as on master); a batch only computes its partition offset. No bound, tag or size change.
d Test intent preserved / new tests added? Behaviour-preserving, no test changed. Existing 05293*/05441-05446 cover block sizes 1-65505 and partitions starting inside a block; one query added to window_functions_streaming.xml.
e Both directions demonstrated? Yes: 9.958 s -> 0.191 s at N = 40000 (linear afterwards). Tests pass 50/50; shifting the offset by one or dropping the cache's upper bound makes 05442/05441 fail.
f Fix is general across code paths? flushBatch is the only producer of argument positions; the index is updated at the only SlidingBlocks::add and pop call sites. All WindowArguments::at callers are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change maps positions to blocks only; column types do not reach it. Covered over block sizes 1, 2, 3, 5, 8, 65505 and functions with 1-3 arguments, with random settings.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change.
i Invariants and contracts preserved? Index entries and retained blocks are pushed/popped together; at keeps partition-relative positions; cached entry pointers stay valid (deque push_back/pop_front keep other references, cache reset every batch). Argument-free windows keep no index: row_number/sum peak memory equals master's (357.9 MB / 376.7 MB with one-row blocks).

Session id: cron:clickhouse-impl-slot-4:20261028-224700

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3702271]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

The PR removes the per-batch retained-block scan from WindowTransform by sharing an incrementally maintained argument index. Partition transitions renumber the index and invalidate cached entries. No actionable findings remain after reviewing the current code, existing regression coverage, benchmark evidence, and all prior discussion.

Missing context / blind spots
  • ⚠️ Full functional and sanitizer CI for head 370227130e3b1b48dc7cda2f6e07d904fee983bc is still pending. Completed current-head CI results would close this verification gap; no local build was available to rerun the tests independently.
Final Verdict

Status: ✅ Approve. No requested code changes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd, could you review this and add the can be tested label so CI runs? Since #127389 every batch rebuilt the window argument block index over all retained blocks (O(B^2) block visits for an UNBOUNDED PRECEDING frame); this keeps one index per transform, appended and popped together with the retained blocks, and only offsets positions per batch.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 28, 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 29, 2026
@Michicosun Michicosun self-assigned this Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
Int64 end_position = 0;
};

using Blocks = std::deque<Block>;

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.

don't add this alias.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 3864c62, the type is spelled out now.

std::vector<size_t> column_indices;
std::vector<Block> blocks;
mutable std::vector<size_t> last_used_block_for_arg;
const Blocks * blocks = nullptr;

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.

I don't like raw ptrs here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 3864c62: WindowArguments now gets the index in its constructor and keeps a const std::deque<Block> & (like Frame::params), and the per-argument cache holds a copy of the last used Block instead of a pointer.

ArgumentValue at(size_t argument, Int64 position) const;

private:
const Block & findBlock(Int64 position) const;

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.

Why was it moved??

never unite private fields and methods.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It returned const Block &, which needs Block declared above it, so I moved it next to the fields. In 3864c62 it is back in its original place with its original parameters (it now refreshes the cache entry instead of returning an index).

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 370227130 with master 4e3df38e8 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

Review of ClickHouse#128097: no `Blocks` alias, no raw pointers, and private methods
stay separate from the fields.

`WindowArguments` now receives the transform's argument block index in its
constructor and keeps a reference to it (like `Frame::params`); per batch the
transform only sets the partition start. The per-argument cache holds a copy
of the last used `Block` instead of a pointer. `findBlock` is back in its
original place with its original parameters and refreshes that cache, so the
cache hit in `at` is unchanged: in a RelWithDebInfo build without LTO the six
default-block-size window queries of the existing perf tests are within 1% of
the previous commit (median of 12 runs, 1.1% on `nonNegativeDerivative`).

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3864c62

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched flaky on macOS, not from this PR: the test holds the lock with flock(1), which macOS does not have; it failed on 160 other PRs in 14 days, and this run (started before the fix merged) still ran the test on macOS #128088 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261029-180003

std::vector<Block> blocks;
mutable std::vector<size_t> last_used_block_for_arg;
const std::deque<Block> & blocks;
Int64 partition_start = 0;

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.

do not add this field

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 3702271. The index now counts positions from the start of the current partition, as collectArgumentBlocks did, so at needs no offset: startNextPartition renumbers the stored entries once and calls WindowArguments::resetPartition, which drops the cached block entries.

auto materialized_columns = materializeColumns(chunk.getColumns(), params.should_materialize);
auto index = indexes.calculate(materialized_columns, rows_count);
auto & block = blocks.add(std::move(chunk), std::move(materialized_columns), std::move(index));
if (has_arguments)

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.

do it unconditionally

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 3702271: has_arguments is gone, and the index is appended and popped for every window. For a window without argument functions this costs 32 bytes per stored block, +8% peak memory for row_number() over 1M one-row blocks.

Review of ClickHouse#128097: `WindowArguments` keeps no partition offset, and the
argument index is maintained for every window.

The shared index now numbers its positions from the start of the current
partition, as `collectArgumentBlocks` did before, so `WindowArguments::at`
reads positions as the window functions pass them. `startNextPartition`
renumbers the stored entries once and drops the per-argument block cache,
whose entries carry the old numbering. Blocks before the partition start get
negative positions, which keeps the index sorted. With no stored blocks left, a
new block starts at the current row, so its first position is that row's index
in the partition.

`has_arguments` is removed: the index is appended in `addInputBlock` and popped
in `releaseUnusedBlocks` unconditionally. For a window without argument
functions over one-row blocks this costs 32 bytes per stored block (peak
memory +8% for `row_number`/`sum` over 1M one-row blocks).

Release build, median of 12 runs: the six default-block-size lag/lead/
nth_value/exponentialTimeDecayedSum/nonNegativeDerivative queries are 0.934 to
1.025 of master and 0.978 to 1.014 of the previous head. The previous head's
inline cache check in `at` is kept: master's `findBlock` shape over the deque
measured +5% to +21%.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3702271

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 2/6) infra, not from this PR: the shard's own report has 0 slower queries (8 too long, 1 faster), but the performance dashboard answered HTTP 500 (Unknown table expression identifier 'perf_test_times_v1') at the end of its 600 s wait, and the harness treats that answer as a hard error, so the shard fails instead of being judged by its own report; the same error failed 3 other shards on 2 other PRs in the same minutes a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same task as the row above)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261030-150005

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 2/6) dashboard HTTP 500 failure: #128255

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 30, 2026
On 2026-10-30 the performance dashboard backend was switched to a new
CIDB (explained by egor-click on ClickHouse#128236). For about 3 minutes
(14:09:54Z to 14:13:05Z, measured from the polls of 6 shards) it
answered HTTP 500 with ClickHouse code 60 for the tables it reads:

  failed to resolve performance comparison run: code: 60, message:
  Unknown table expression identifier 'perf_test_times_v1'
  failed to load performance comparison rows: code: 60, message:
  Unknown table expression identifier 'query_metrics_v2'

`dashboard_did_not_answer` knew no signature for this message, so the
500 was a `PerfDashboardError`; the poll loop keeps the first hard
error, and `main` failed the shard instead of judging it by its own
report. Four `Performance Comparison (arm_release, master_head, N/6)`
jobs whose 600 s wait ended inside the window failed this way
(ClickHouse#126879 6/6, ClickHouse#128209 1/6 and 3/6, ClickHouse#128097 2/6), all with 0 slower
queries. Shards whose wait outlived the window got the same requests
answered with 200 and passed.

The request cannot cause this answer: the table names are the
backend's own storage, and identical requests (same run id and test)
were served after the window. It is the case the class documents,
"the dashboard, or the CIDB tables it reads, did not answer", so add
the measured signature next to the two existing ones. Only a 5xx with
an application envelope is affected; a 4xx with this text, a non-JSON
body, and every other 5xx keep their classification, and a real hard
error seen before or after it still wins.

Validated locally against a fake dashboard serving the logged bodies:
the incident replay fails on master and reaches the own-report
fallback with the fix.

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

Copy link
Copy Markdown
Member

will do it differently.

@Michicosun Michicosun closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-window-functions Window function execution + frame handling (ROW_NUMBER/RANK/LAG/LEAD, frames, partitions, order). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Window functions batch execution (#127389): every batch walks all retained blocks

3 participants