Skip to content

Let a merge shrink a table that is over max_table_size_rows - #117229

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-max-table-size-rows-shrinking-merge
Sep 18, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-max-table-size-rows-shrinking-merge

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117101

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

Fix a table that exceeds max_table_size_rows never being able to come back under the limit: every
merge threw TABLE_SIZE_LIMIT_EXCEEDED, so the table could not be compacted and its part count grew
until inserts started failing.

Description

throwIfTableSizeLimitsExceeded was asymmetric. The byte limits have an explicit shrinking-
replacement carve-out ("so that a table that has already crossed a limit can be brought back under
it by a size-reducing merge or mutation, and not only by dropping whole parts"), the row limit had
none: it computed current.rows - covered.rows and threw whenever that still exceeded the limit, so
a merge that covers a handful of small parts in an untouched partition was rejected even though it
does not increase the row count.

Since the background scheduler works by merging subsets of parts, that made an over-limit table
uncompactable — part count grows until parts_to_throw_insert, and on ReplicatedMergeTree the
already-logged MERGE_PARTS entry is retried forever, wedging the replication queue and hanging
SYSTEM SYNC REPLICA.

An operation that replaces the covered parts with a part holding no more rows than they had is now
allowed. A patch part carries a mutation of existing rows rather than new table rows, so it never
counts as growth. Inserts, which have no covered parts, are still rejected.

Test 05063_max_table_size_rows_shrinking_merge, which also asserts that an insert into the
over-limit table still throws and that a deleting mutation brings the table back under the limit.


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

Version info

  • Merged into: 26.10.1.115 (included in 26.10 and later)
  • Backported to: 26.9.1.1608

The row limit had no equivalent of the byte limits' shrinking-replacement carve-out, so
every partial merge of an over-limit table threw `TABLE_SIZE_LIMIT_EXCEEDED` at commit -
even a size-preserving compaction of a few small parts in an untouched partition. The table
could then not be compacted at all: the part count grew until `parts_to_throw_insert` made
every insert fail, and on `ReplicatedMergeTree` the already-logged `MERGE_PARTS` entry was
retried forever, wedging the replication queue.

An operation that replaces the covered parts with a part holding no more rows is now
allowed, mirroring the byte limits. Growing operations - inserts - are still rejected.

Closes: #117101
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cfe2133]

Summary: ✅


AI Review

Summary

This PR fixes the max_table_size_rows row-limit check so that an already over-limit MergeTree table can still be compacted or shrunk by a row-neutral / shrinking merge or mutation. The core logic and the updated regression test look correct, and the earlier test-shape review points appear addressed; I found one remaining documentation gap in the user-visible setting contract.

Findings

💡 Nits

  • [src/Storages/MergeTree/MergeTreeData.cpp:7828] The behavior change is not reflected in the structured max_table_size_rows setting docs. src/Storages/MergeTree/MergeTreeSettings.cpp:1128-1139 still says only empty parts are always allowed on an over-limit table, and that text feeds both system.merge_tree_settings and the autogenerated docs/reference/settings/merge-tree-settings/max.mdx. Update the source DECLARE doc string to mention that row-neutral or shrinking merges and mutations are allowed too.
Final Verdict

✅ The code change itself looks correct. I would merge it after updating the max_table_size_rows setting documentation.

LLVM Coverage Report

Measured on commit cfe2133.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cfe2133b5 with master 930ccf281 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 01b8f1c9f; 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

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

Job report

The previous `ALTER TABLE ... DELETE WHERE p = 0` dropped the whole 5000-row part, so the
table fell back under `max_table_size_rows` and the pre-patch check would have accepted it
too - the case did not exercise the new carve-out at all.

Delete only a part of the big partition first: the table stays at 3100 rows, far above the
limit of 1000, and the commit is allowed only because the mutated part holds fewer rows than
the part it replaces. The full delete and the follow-up insert are kept, so the test still
covers the return under the limit.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the AI review (the mutation case now stays over max_table_size_rows, so it actually exercises the new carve-out).

On the reds of the previous run — none of them touch this change, which only relaxes throwIfTableSizeLimitsExceeded for a shrinking replacement:

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Investigated. Pre-existing trunk defect, not related to this change. The reason no open issue turns up is that the issue which tracked it is closed: #115057 reported the identical got 3 and 1 and was closed as completed by your own #115352 ("Keep one output port per shard when a JOIN side reads nothing"), merged 2026-08-19T22:15:36Z.

That fix does not cover this abort. Its merge commit 0a03d0a8d6f6aca931dd67146fee16ec87adde61 is an ancestor of the tree this job built (3d5424696a1f342aec81c006a7e9a4fea8db8e47, behind_by: 0), so #115352 was present and it still aborted. Frames taken from the job's own fatal.log rather than the STID bucket:

13. src/QueryPipeline/QueryPipelineBuilder.cpp:373  DB::QueryPipelineBuilder::joinPipelinesYShaped
14. src/Processors/QueryPlan/JoinStep.cpp:159        DB::JoinStep::updatePipeline
15. src/Processors/QueryPlan/QueryPlan.cpp:273       DB::QueryPlan::buildQueryPipeline
20. src/Interpreters/executeQuery.cpp:3581           DB::executeASTFuzzerQueries

Frame 20 is the in-stress AST fuzzer, which is why the report carries no stable query.

The surviving route is in the optimizer, downstream of the port count #115352 corrected. optimizeParallelFullSortingMergeJoin scatters both sides (optimizeJoinByShards.cpp:585-586, convertToScatteredFullSort) and then enables layers, but the merge-back in SortingStep.cpp:552 is evaluated per side:

if (pipeline.getNumStreams() > 1 && (partition_by_description.empty() || pipeline.getNumThreads() == 1))

getNumThreads() is min(pipe.maxParallelStreams(), max_threads) for that one side, so a side already down to a single stream merges back to one port while the other keeps its shards. JoinStep::updatePipeline then sees unequal counts, drops use_sharding, and falls into joinPipelinesYShaped, which accepts only one port per side. I measured earlier on this family that this route still reproduces with query_plan_join_shard_by_pk_ranges = 0, so it is independent of the PK-range sharding that #115057 and #115352 were about. Separately, getNumStreamsWhenNothingToRead pads only a ReadFromMergeTree read, so a non-MergeTree side that yields a single port is not covered either.

Breadth over 30 days, keyed on the message text: 63 rows across 55 distinct carrier PRs. 15 of those rows, across 15 distinct PRs, are after #115352 merged, the latest today at 18:55Z. The 3 true-master rows all predate that merge; there is also one row on release branch 26.7 (2026-08-29, sub-STID 4488-4a91).

A fix is in progress in #109393, but not in a shape I would ask you to merge as it stands: it merges the streams at the joinPipelinesYShaped call site, which @ vdimir declined on 2026-08-10 in favour of repairing the invariant where it is broken, and #115352 is that repair for the read side. I will take the remaining asymmetry at the optimizer layer instead of the call-site merge, and post the PR here.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Fix: #117826

Two corrections to my comment above, both from reading the failing tree rather than the stack:

  • The trigger is the per-side thread BUDGET, not maxParallelStreams: the scatter raises the latter
    to scatter_partitions first. A single-table subquery with a trivial LIMIT is planned with one
    thread (PlannerJoinTree.cpp:1747-1751) while a UNION ALL side is re-budgeted to the sum of its
    branches (QueryPipelineBuilder.cpp:250,265-268), so the port pair is always 1 versus
    max_threads, in both orientations.
  • The getNumStreamsWhenNothingToRead gap I mentioned is not reachable, so no work is owed there:
    the primary-key-range route only matches sides whose reading step is a ReadFromMergeTree
    (optimizeJoinByShards.cpp:25-28,224).

The same line had a second effect worth recording: when both sides were limited to one thread the
merge fired on both, the counts stayed equal, and the sharded join the optimizer had asked for was
silently replaced by a single merge join.

Reproduced on master with two system.numbers subqueries and no tables; on released 26.8.2.7 the
query fails with Code: 49. Nothing in this pull request is involved.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 02:18
… exercises the over-limit merge

Without `max_bytes_to_merge_at_max_space_in_pool = 1` the five small parts of partition 1 could be
compacted by a regular background merge before `OPTIMIZE TABLE ... PARTITION 1 FINAL` runs, in which
case the part-count check still prints 1 while the new carve-out in `throwIfTableSizeLimitsExceeded`
is never taken. Also assert the part count before `OPTIMIZE`, as `04910_max_table_size_merge` does.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~3700 commits behind) and addressed the remaining review thread: 05063_max_table_size_rows_shrinking_merge now pins background merges off with max_bytes_to_merge_at_max_space_in_pool = 1 and asserts the part count of partition 1 before OPTIMIZE, so the test cannot pass on the background merge path without taking the new carve-out in throwIfTableSizeLimitsExceeded. Verified locally against a server built from this branch: both 05063_max_table_size_rows_shrinking_merge and 04910_max_table_size_merge match their references.

The single red on the previous run was Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), and it reports no failed test: the job hit its 9000 s wall clock at 13293 of 13459 tests (WARNING: Job timed out ... exit code [-15]), which is a job-level timeout on the coverage build, unrelated to a change that only relaxes one condition in throwIfTableSizeLimitsExceeded. The arm_msan red from the run before that is being fixed in #117826 (thanks @groeneai), and merging master keeps this branch current for it.

alexey-milovidov and others added 3 commits September 10, 2026 18:33
… needs the row carve-out

The previous mutation case deleted rows from the single 5000-row part of partition 0.
`throwIfTableSizeLimitsExceeded` computes the row count outside the replaced parts first
(`5100 - 5000 = 100`), which is already under `max_table_size_rows = 1000`, so the old code
would have accepted that commit without the new `added_rows <= covered.rows` branch.

Add a `DELETE IN PARTITION 1` of the 100-row part first: the rows outside the replaced part
stay at 5000, over the limit, so the commit is possible only through the carve-out for a
replacement that does not add rows. The partition-0 mutation is kept afterwards.

Also renumber the test to `05227` because `05063` collided with tests added on master.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~3900 commits behind) and addressed the remaining review thread: the mutation case in the test now mutates the small partition alone, so the rows outside the replaced part stay over max_table_size_rows and the commit really depends on the new carve-out in throwIfTableSizeLimitsExceeded. The test was renumbered to 05227_max_table_size_rows_shrinking_merge. Both it and 04910_max_table_size_merge pass locally against a server built from this branch.

The only red of the previous run, Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6), failed in test_storage_iceberg_with_spark partition pruning tests, which this change does not touch. The fix #119302 is on master since 2026-09-17 and is pulled in by this merge.

const UInt64 total_rows = current.rows - std::min(current.rows, covered.rows);

if (total_rows > max_rows)
/// An operation that replaces the covered parts with a part that has no more rows than they

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This changes the user-visible contract of max_table_size_rows, but the structured setting docs still describe only empty parts as the escape hatch (src/Storages/MergeTree/MergeTreeSettings.cpp:1128-1139, which also feeds the autogenerated docs/reference/settings/merge-tree-settings/max.mdx). After this lands, users reading the setting docs will still be told that recovering an over-limit table requires dropping data, even though row-neutral or shrinking merges and mutations are now allowed. Please update the DECLARE doc string rather than the generated .mdx page.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 18, 2026
Merged via the queue into master with commit f034a6f Sep 18, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-max-table-size-rows-shrinking-merge branch September 18, 2026 16:47
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 20, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 15, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 10, 2026
`optimizeParallelFullSortingMergeJoin` converts both pre-join sorts with
`convertToScatteredFullSort`, whose contract is one sorted stream per shard
with no final merge, so that the two sides present the same number of ports.
`JoinStep::updatePipeline` relies on that, because it pairs the shards of the
two sides positionally.

`SortingStep::fullSort` decided its final merge from `pipeline.getNumThreads`,
which is a per-side budget rather than a property of the shared plan: a
single-table subquery with a trivial `LIMIT` is planned with one thread, while
a `UNION ALL` side is re-budgeted to the sum of its branches. The one-thread
side therefore merged its shards back into a single port while the other kept
them, the counts diverged, `use_sharding` was dropped, and the single-port
fallback `joinPipelinesYShaped` threw `Join is supported only for pipelines
with one output port`. On a release build the query fails with `Code: 49`;
in debug and sanitizer builds the server aborts. Reachable on the released
26.8.

The same line had a second effect: when both sides were limited to one thread
the merge fired on both, the counts stayed equal, and the sharded join the
optimizer had asked for was silently replaced by a single merge join.

Skip the merge when the sort is a fixed-shard-count scatter. This completes
49c7604, which changed the scatter width from the thread count to
`scatter_partitions` but left the merge-back condition consulting the thread
count. A plain sort and a window-frame partitioned sort are unaffected, since
both have `scatter_partitions` equal to zero.

Found by the in-stress AST fuzzer on the `Stress test (arm_msan)` run of
ClickHouse#117229.

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

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.9-must-backport

Projects

None yet

5 participants