Skip to content

Fix unfiltered TRUNCATE ALL TABLES permanently cancelling merges - #119425

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
buildkite-forks:fix-unfiltered-bulk-truncate
Sep 13, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
buildkite-forks:fix-unfiltered-bulk-truncate

Conversation

@pda

@pda pda commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Unfiltered TRUNCATE ALL TABLES FROM db leaves retained MergeTree tables unable to merge. The truncate itself succeeds and removes the old data, but subsequent merges fail:

CREATE DATABASE truncate_test;
CREATE TABLE truncate_test.t (id UInt64) ENGINE = MergeTree ORDER BY id;

INSERT INTO truncate_test.t VALUES (100);
TRUNCATE ALL TABLES FROM truncate_test;

INSERT INTO truncate_test.t VALUES (7);
INSERT INTO truncate_test.t VALUES (16);
OPTIMIZE TABLE truncate_test.t FINAL;

The final query fails with:

Code: 236. DB::Exception: Cancelled merging parts. (ABORTED)

The unfiltered form used the database shutdown-preparation path before truncating each table. StorageMergeTree::flushAndPrepareForShutdown permanently cancels merges and moves and finishes its background assignees. That is appropriate before removing a storage, but not when the storage remains live after truncation.

Truncating all tables and then proceeding with writes is a common scenario in automated testing, where database contents is cleared between test cases but schema remains.

Filtered TRUNCATE TABLES FROM db LIKE '%' queries already avoid shutdown preparation and use the regular per-table truncate path with scoped merge blockers. This change uses that path for the unfiltered form as well. DROP, DETACH, and bare TRUNCATE DATABASE operations continue to use shutdown preparation.

This also makes the unfiltered form consistent with … LIKE '%' in two less common cases:

  • Databases where shouldBeEmptyOnDetach is false now enumerate and truncate supported tables instead of effectively doing nothing.
  • A read-only database metadata disk no longer changes the operation into per-table DETACH; normal per-table truncate checks and errors apply.

Existing supportsTruncate, static-storage, access, engine, and locking checks remain in place.

PR #98161 introduced the regression by moving permanent merge cancellation into StorageMergeTree::flushAndPrepareForShutdown. I built PR 98161’s first parent and merge commit under the same configuration and ran identical probes against both:

  • Without PR 98161,
    • a source build of its exact first parent, dc665af, passes minimal and instrumented unfiltered truncation, ordinary TRUNCATE TABLE, and filtered LIKE '%' probes.
    • Official release 26.2.1.1139-stable, whose source does not contain PR 98161, also passes.
  • With PR 98161,
    • a source build of its exact merge commit, 78a7f5f, fails only the two unfiltered probes. OPTIMIZE TABLE ... FINAL returns Code 236 and leaves both active parts unmerged, while the ordinary and filtered controls still pass.
    • Official release 26.3.1.896-lts, which contains PR 98161, reproduces the same result.

Across the eight probe runs on these two source builds, truncation succeeds, the table is empty afterward, and the exact newly inserted rows remain readable. Each successful merge reduces two active parts to one; both failing unfiltered probes leave the two parts unmerged. The minimal probe uses no SYSTEM merge-control commands.

The new stateless regression test verifies that the old row is removed, two separately inserted parts remain readable, OPTIMIZE TABLE ... FINAL succeeds, and the parts merge into one active part containing two rows.

On the unpatched source build, the test fails at OPTIMIZE TABLE ... FINAL with Code 236. It passes after the change. The relevant existing tests 00623_truncate_all_tables, 03403_truncate_all_tables_like, 04070_truncate_all_tables_skip_views, 04078_truncate_tables_like_format_space, and 03984_truncate_database_sync_cancellation also pass. The style checks and git diff --check pass.

The adjacent comparison and fix validation used focused Debug builds. Sanitizer, release, replicated, and full integration configurations were not run locally.

Related: #98161

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

Fixes a bug where unfiltered TRUNCATE ALL TABLES FROM queries permanently disabled merges on retained MergeTree tables, causing later OPTIMIZE TABLE ... FINAL queries to fail with ABORTED.


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

PR ClickHouse#98161 moved permanent `MergeTree` merge and move cancellation into
`flushAndPrepareForShutdown`. The unfiltered `TRUNCATE ALL TABLES FROM db`
form used this database shutdown-preparation path before truncating each
storage, leaving retained tables unable to merge and causing later
`OPTIMIZE TABLE ... FINAL` queries to fail with `ABORTED`.

Source-built probes at the exact PR boundary confirm the attribution. Its
first parent passes unfiltered, ordinary, and filtered truncate probes. The
merge commit fails only the unfiltered probes with Code 236, while the
ordinary and filtered controls continue to pass.

Route the unfiltered form through the existing per-table truncate path
already used by filtered `TRUNCATE TABLES ... LIKE` queries. Keep shutdown
preparation unchanged for `DROP`, `DETACH`, and `TRUNCATE DATABASE`.

This also aligns unfiltered truncation with `LIKE '%'` for databases where
`shouldBeEmptyOnDetach` is false and for read-only database metadata disks,
instead of retaining the previous no-op or per-table `DETACH` behavior.

Add a regression that truncates a `MergeTree`, inserts two new parts,
runs `OPTIMIZE FINAL`, and verifies that they merge into one active part.

Regression introduced by:
ClickHouse#98161
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-11T11:03:26.638743Z 22ca85f PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@maxknv maxknv removed the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). external Author is not a member of the ClickHouse organization labels Sep 11, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [22ca85f]

Summary: ✅


AI Review

Summary

This PR reroutes unfiltered TRUNCATE [ALL] TABLES FROM <db> through the existing per-table truncate path instead of the shutdown-preparation path, which avoids leaving retained MergeTree tables with merges permanently cancelled after truncation. I did not find a correctness, compatibility, or evidence gap that warrants an inline review comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit 22ca85f.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (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 Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 22ca85f4e with master 2497bf535 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c4bee2f83; 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, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red check was CH Inc sync ("tests failed"), and it was a real consequence of this change, not flakiness.

The private-only integration test test_refreshable_materialized_view_backup_with_shared_database::test_rmv_backup does:

BACKUP VIEW d4.v111 TO ...
TRUNCATE ALL TABLES FROM d4
-- expects: RESTORE VIEW d4.v111 fails with "The table was dropped or detached"

That expected error was a side effect of exactly the bug this PR fixes: the old path called IStorage::flushAndPrepareForShutdown on every table of the database, which for a refreshable materialized view runs RefreshTask::shutdown and clears its view pointer and its RefreshSet handle - leaving d4.v111 attached but permanently dead, so the later RESTORE threw TABLE_IS_DROPPED. With this PR the refresh task survives the truncate and the restore succeeds.

I adapted the private test accordingly on the sync branch (ClickHouse/clickhouse-private#74407): it now asserts that the view is still listed in system.view_refreshes right after TRUNCATE ALL TABLES - which is the property this PR guarantees - and that the RESTORE VIEW succeeds. Nothing was changed on the public side, so this branch is untouched.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR only adjusts TRUNCATE TABLES handling in InterpreterDropQuery (dropping the has_like condition so LIKE-less TRUNCATE ALL TABLES no longer prepares storages for shutdown), plus a new stateless test and an integration-test update. None of that touches the query-execution hot path any ClickBench SELECT exercises. The two flagged queries (Q28 +5.4%, Q34 +5.6%) are small deltas with no plausible mechanism tied to this diff: Q34 already sits inside master's current variance band and stays non-directional, and Q28 is downgraded to not_sure as run-to-run variance. No real performance impact expected from this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1052 1109 +5.4% <0.0001 This PR only changes TRUNCATE TABLES ... LIKE logic in DROP-query handling; a ClickBench SELECT never touches that path, so the +5.4% delta is run-to-run variance. The two tests disagree here anyway.
⚠️ 34 not_sure 1142 1207 +5.6% <0.0001 Envelope-suppressed and correctly left non-directional: median 1207 ms sits inside master's current variance band (1119.5-1378.0). The TRUNCATE-only DROP-query change cannot affect this SELECT, so this is variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e1daf588-7784-4d43-99d8-1a38d6b8ba9e
  • MIRAI run: 79f927e4-8e31-4648-8cf2-3b273ddd5610
  • PR check IDs:
    • clickbench_197708_1789233024
    • clickbench_197720_1789233024
    • clickbench_197726_1789233024
    • tpch_adapted_1_official_197736_1789233024
    • tpch_adapted_1_official_197765_1789233024
    • tpch_adapted_1_official_197779_1789233024

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Follow-up on CH Inc sync: after the private test adaptation from 2026-09-12, test_rmv_backup passes, and the remaining reds on the sync branch are unrelated to this change:

I re-ran the failed private jobs. Public CI is green, the branch merges cleanly into master, and there are no unresolved review threads.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Update on CH Inc sync: the re-run of the failed private jobs on ClickHouse/clickhouse-private#74407 completed successfully on 2026-09-13, so the three unrelated reds listed above are cleared. Both the public PR and the sync PR are fully green, the branch still merges cleanly into master, and there are no unresolved review threads. Nothing remains on the author's side; this is ready to be merged.

Merged via the queue into ClickHouse:master with commit ee927fc Sep 13, 2026
174 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 Sep 13, 2026
@pda

pda commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @alexey-milovidov and Alexey's robots!

clickgapai added a commit to clickgapai/ClickHouse that referenced this pull request Sep 17, 2026
pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 27, 2026
The pre-upgrade kill loop added in ClickHouse#120978 reds with "N mutations could not be killed before
the upgrade" on pull requests unrelated to mutations: 4 failures against 331 OK runs of the
counterpart assertion since it landed on 2026-09-20, on 4 unrelated pull requests, in 3 of
them the job's only red.

In the three occurrences whose job logs I read, the kill threw Code: 242 TABLE_IS_READ_ONLY
and the deliberate `||:` discarded it. The chain: 04070_truncate_all_tables_skip_views.sql
runs TRUNCATE ALL TABLES FROM currentDatabase(), which in stress mode is the runner's shared
test_N database, so it covers every table earlier tests left behind (--upgrade-check implies
--fake-drop, so their DROPs were no-ops). On the previous release the unfiltered form still
calls flushAndPrepareForShutdown() on every table in the database;
StorageReplicatedMergeTree::flushAndPrepareForShutdown does
restarting_thread.shutdown(part_of_full_shutdown = true), which sets need_stop, deactivates
the task and calls setReadonly(), so the replica is read-only permanently with no thread left
to re-activate it. The per-table truncate then throws, because truncate() begins with
assertNotReadonly(), so the tables are left read-only and un-truncated with their mutations
intact. Thirteen minutes later the kill loop reaches killMutation(), which also begins with
assertNotReadonly().

ClickHouse#119425 fixed the product half on master, the `if (!truncate || !query.has_tables)` guard in
InterpreterDropQuery, but it is not backported and the stress phase runs the previous
release's binary and queries, so only this script can act. Reproduced on v26.8.10.6-lts,
which find_previous_release picks today.

Three changes, all in the kill step:

- Each KILL MUTATION keeps its stderr in unkilled_mutation_errors.txt, and the FAIL line
  names it. Today the survivor is reported with an empty latest_fail_reason, so the artifact
  says nothing about why the kill did not happen, and attributing one occurrence cost a whole
  investigation.

- If a mutation survives, SYSTEM RESTART REPLICA the read-only replicas that still hold one,
  then run the same kill pass again. Re-attaching the table builds it from its metadata and
  starts a replica that can remove the mutation's ZooKeeper node. Waiting instead cannot work
  for this cause: the restarting thread is deactivated, so no session-expiry check
  re-activates the replica. The no-argument SYSTEM RESTART REPLICAS is unusable here because
  restartReplicas() passes throw_on_error = false, so a table it fails to restart is left
  detached and its mutation silently disappears from system.mutations.

- A restart that does not report success, that changes the number of rows in system.replicas,
  or that leaves its own replica read-only, writes its own FAIL row whatever the count says.
  Without this the change would be fail-open, which is worse than the red it removes, and it
  is fail-open in two distinct ways. doRestartReplica() detaches before rebuilding, so a
  failure after that point leaves the table detached; and because it re-creates the table with
  LoadingStrictnessLevel::ATTACH the storage always goes through
  ReplicatedMergeTreeAttachThread, whose startup() only waits for the first initialization
  attempt and never rethrows, so a restart whose first attempt fails returns success and
  leaves the replica read-only with a retry scheduled initialization_retry_period later.
  system.mutations reports only what an attached, initialized replica holds, because the
  mutation queue is filled by pullLogsToQueue(..., LOAD) on the same success path that later
  calls setNotReadonly(). Either state would otherwise drive the count to zero and report
  success for a mutation still in ZooKeeper. That load order is also why the per-replica check
  is race-free: is_readonly = 0 implies the mutations are already loaded.

Validated against a real v26.8.10.6-lts server, since no harness executes upgrade_runner.sh.
On one fixture of two bricked replicated tables the old block reports FAIL and the new one
OK; on a clean server it does nothing, leaves no artifact, and never enters the recovery
block. Both fail-open shapes were injected and both produce the new FAIL row while
system.mutations has already reached zero: the restart_replica_fail_after_detach failpoint for
the detached table, and a stopped Keeper for the replica that stays read-only, where the
unguarded block reported "The stress phase left no unfinished mutation to the upgrade" for a
mutation whose znode was still there and which executed as soon as the replica came back.
shellcheck reports the same findings as before.

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

can be tested Allows running workflows for external contributors comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). external Author is not a member of the ClickHouse organization 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.

4 participants