Skip to content

Evaluate the PARTITION BY expression of file and object storage writes once per INSERT, not once per block - #128217

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-partition-by-stateful-function-spans-chunks
Nov 6, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-partition-by-stateful-function-spans-chunks

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128211
Related: #92844

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

Fixed PARTITION BY of file, url and object storage writes (table functions and table engines) evaluating stateful and non-deterministic functions anew for every block since 26.1: PARTITION BY intDiv(rowNumberInAllBlocks(), N) restarted its counter on every block and wrote rows into the wrong files, and now64() produced one file per block instead of one per INSERT. Closes #128211.

Description

On 26.3 and 26.8, INSERT INTO FUNCTION file('bad_{_partition_id}.parquet') PARTITION BY intDiv(rowNumberInAllBlocks(), 1000) SELECT number FROM numbers(5000) SETTINGS max_block_size = 1000, max_insert_threads = 1 writes all 5000 rows into bad_0.parquet instead of five 1000-row files (correct on 25.3, 25.8 and 25.12, wrong since 26.1).

Root cause: #92844 stopped caching the partition-key actions of a non-deterministic expression, so that now64() is not frozen for the lifetime of an S3 table, and rebuilt them for every chunk instead. A fresh rowNumberInAllBlocks then starts at 0 on every chunk, and now64() is re-captured per chunk.

Change: PartitionedSink, the only caller and the one object that lives exactly one INSERT for file, url and object storage, gets the actions once from the strategy (getPartitionKeyActions) and applies them to all its chunks. Deterministic actions stay cached in the strategy. A non-deterministic expression gets fresh actions per INSERT: now64() gives one value per INSERT, and the counter restarts with every INSERT, also for an S3 table (on 25.8 it continued across the table's INSERTs until a restart), so concurrent INSERTs do not share it. No partitioned storage supports parallel insert, so an INSERT has one such sink.

Validation: the new test 05459_partition_by_stateful_function_spans_chunks (file(), S3 engine with two INSERTs, now64(9)) fails on master (10/10) and passes with the fix (50/50 randomized). The #92844 test test_s3_non_deterministic_partition_by and 15 existing partitioned-write stateless tests pass on both binaries. The reporter's 200000-row MergeTree shape gives 4 x 50000 rows with the fix (2 x 100000 on master).


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

Version info

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

groeneai and others added 2 commits October 30, 2026 11:07
…s once per INSERT

Since ClickHouse#92844 the partition-key actions of a non-deterministic expression were
rebuilt for every chunk, so a stateful function such as `rowNumberInAllBlocks()`
restarted its counter at 0 on every chunk and `now64()` was re-captured per
chunk: `INSERT INTO FUNCTION file(...) PARTITION BY intDiv(rowNumberInAllBlocks(), N)`
put every row of 1000-row chunks into partition 0 (regression in 26.1).

Before ClickHouse#92844 the actions were built once in the strategy constructor, which is
per INSERT for table functions but per TABLE for object-storage engines, so
`now64()` was frozen for the table's lifetime. The right lifetime for both is
one INSERT: `PartitionedSink` now gets the actions once from the strategy
(`getPartitionKeyActions`) and applies them to all its chunks. Deterministic
actions stay cached in the strategy; a non-deterministic expression gets fresh
actions per sink, i.e. per INSERT, so concurrent INSERTs into one engine table
do not share a counter. None of the partitioned storages supports parallel
insert, so an INSERT has exactly one `PartitionedSink`.

Closes ClickHouse#128211

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the getPartitionKeyActions contract: the actions are rebuilt per call, not the function evaluated once per INSERT.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ❌ Separate async INSERTs batched into one flush share one counter (PartitionedSink.cpp:35) DISAGREE An async flush is one INSERT: one InterpreterInsertQuery and one Chunk for the whole batch (AsynchronousInsertQueue.cpp:1445-1452, :1655-1657). Master evaluates that chunk with one actions instance too, so the output is identical with and without this PR; per-entry evaluation was never the behaviour. No change.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261030-111200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The reporter's clickhouse local query (PARTITION BY intDiv(rowNumberInAllBlocks(), 1000), max_block_size = 1000) writes 1 file of 5000 rows on master every run, 5 x 1000 with the fix.
b Root cause explained? #92844 rebuilds the partition-key actions of a non-deterministic expression for every chunk, so every chunk gets a new rowNumberInAllBlocks object whose counter starts at 0 (and now64() is re-captured per chunk).
c Fix matches root cause? Yes. PartitionedSink, which lives exactly one INSERT, gets the actions once and applies them to all its chunks; deterministic actions stay cached in the strategy. No setting, no guard.
d Test intent preserved / new tests added? New 05459_partition_by_stateful_function_spans_chunks: file() counter across chunks, S3 engine with two INSERTs (spans chunks, restarts per INSERT), now64(9) one file per INSERT. The #92844 integration test is kept and passes.
e Both directions demonstrated? Yes. 05459 fails on master 10/10 (all three blocks differ), passes with the fix 50/50 with randomized settings.
f Fix is general across code paths? PartitionedSink::consume is the only caller; the file, url and object storage partitioned sinks all derive from it, and both strategies (wildcard, hive) are changed. DeltaLakePartitionedSink already builds its actions once per sink.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not type-dependent. Checked: table function and engine, file and S3, rowNumberInAllBlocks and now64, one and two INSERTs, max_insert_threads 1 and 8, an 8-stream MergeTree source (4 x 50000), 8 concurrent INSERTs into one table (each its own counter).
h Backward compatible? (maintainer-approved exception only) No setting or format change. For object storage engines a stateful function's state is now per INSERT (it was per table before 26.1), the same as for table functions; now64() stays per INSERT.
i Invariants and contracts preserved? One INSERT's partition expression is evaluated by one ExpressionActions for all its chunks, and a non-deterministic one is never shared across INSERTs. getPartitionKeyActions is const and reads the constructor-written cache, as the per-chunk call did.

Session id: cron:clickhouse-impl-slot-4:20261030-102000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @mstetsyuk @kssenii, could you review this and add the can be tested label so CI runs? Since #92844 the partition-key actions of a non-deterministic PARTITION BY are rebuilt for every chunk, so rowNumberInAllBlocks() restarts on every block; PartitionedSink now gets the actions once per INSERT, which keeps now64() per INSERT as #92844 intended.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b8153d]

Summary: ✅


AI Review

Summary

PR #128217 fixes partitioned writes through file, url, and object storage by retaining partition-expression actions for the lifetime of PartitionedSink. This preserves state across blocks while rebuilding non-deterministic actions for subsequent inserts. No actionable findings in head 5b8153d143926fb0ee198ddcb829d8cf2b2ea257.

Missing context / blind spots
  • ⚠️ No runnable ClickHouse binary is available locally, and the current CI reports contain no results for the new regression test. Runtime evidence is the author's reported before/after validation. Completed targeted stateless and retained S3 regression tests would close this verification gap.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). labels Oct 30, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5b8153d14 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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@mstetsyuk can you review this? It seems to fix a regression from #92844

virtual ~IPartitionStrategy() = default;

virtual ColumnPtr computePartitionKey(const Chunk & chunk) const = 0;
/// Rebuilt on every call if non-deterministic. A sink calls it once and reuses the result for all its chunks,

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.

Yes, this is reasonable.

And about non-determinism... This means a partition key that depends on a dictionary that could change. So it's not like randomness.

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Nov 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 690d3be Nov 6, 2026
528 of 532 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

A user on #128211 asks for this fix in 26.8. The regression came with #92844 (first released in 26.1), so all supported release branches have it: 26.3, 26.8, 26.9 and 26.10, and this fix is in none of them.

Cherry-pick check against the current branch heads: clean on 26.10. On 26.8 and 26.9, one hunk in IPartitionStrategy.h conflicts only in its context lines (a constructor argument those branches lack). 26.3 still has the code from before #99400 and needs a manual resolution.

A backport needs v26.8-must-backport (and the matching labels for the other branches, if wanted), which I can't add.

zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Stable 26.8 Backport of ClickHouse#128217 - Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Antalya 26.6 Backport of ClickHouse#128217 - Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Antalya 26.8 Backport of ClickHouse#128217 - Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Stable 26.3 Backport of ClickHouse#128217 - Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Antalya 26.3 Backport of ClickHouse#128217 - Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Nov 23, 2026
…tateful-function-spans-chunks

Evaluate the `PARTITION BY` expression of file and object storage writes once per INSERT, not once per block

Conflicts committed as-is; the next commit resolves them:
- src/Storages/IPartitionStrategy.cpp (both modified)
- src/Storages/IPartitionStrategy.h (both modified)
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Nov 23, 2026
Kept antalya's `computePartitionKey(Block&)` overrides, added the new `getPartitionKeyActions()` overrides, and left out upstream's `getPathForRead`/`getPathForWrite` context lines.
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-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-bugfix Pull request with bugfix, not backported by default 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.

rowNumberInAllBlocks() resets per chunk in S3/file PARTITION BY after #92844

4 participants