Repository navigation
Fix unfiltered TRUNCATE ALL TABLES permanently cancelling merges - #119425
alexey-milovidov merged 1 commit into
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Workflow [PR], commit [22ca85f] Summary: ✅
AI ReviewSummaryThis PR reroutes unfiltered Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit 22ca85f.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
|
🕵 The only red check was The private-only integration test That expected error was a side effect of exactly the bug this PR fixes: the old path called I adapted the private test accordingly on the sync branch ( |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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
|
|
🕵 Follow-up on
I re-ran the failed private jobs. Public CI is green, the branch merges cleanly into master, and there are no unresolved review threads. |
|
🕵 Update on |
|
Thanks @alexey-milovidov and Alexey's robots! |
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]>
Unfiltered
TRUNCATE ALL TABLES FROM dbleaves retainedMergeTreetables unable to merge. The truncate itself succeeds and removes the old data, but subsequent merges fail:The final query fails with:
The unfiltered form used the database shutdown-preparation path before truncating each table.
StorageMergeTree::flushAndPrepareForShutdownpermanently 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 bareTRUNCATE DATABASEoperations continue to use shutdown preparation.This also makes the unfiltered form consistent with
… LIKE '%'in two less common cases:shouldBeEmptyOnDetachis false now enumerate and truncate supported tables instead of effectively doing nothing.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:TRUNCATE TABLE, and filteredLIKE '%'probes.26.2.1.1139-stable, whose source does not contain PR 98161, also passes.OPTIMIZE TABLE ... FINALreturns Code 236 and leaves both active parts unmerged, while the ordinary and filtered controls still pass.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
SYSTEMmerge-control commands.The new stateless regression test verifies that the old row is removed, two separately inserted parts remain readable,
OPTIMIZE TABLE ... FINALsucceeds, and the parts merge into one active part containing two rows.On the unpatched source build, the test fails at
OPTIMIZE TABLE ... FINALwith Code 236. It passes after the change. The relevant existing tests00623_truncate_all_tables,03403_truncate_all_tables_like,04070_truncate_all_tables_skip_views,04078_truncate_tables_like_format_space, and03984_truncate_database_sync_cancellationalso pass. The style checks andgit diff --checkpass.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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a bug where unfiltered
TRUNCATE ALL TABLES FROMqueries permanently disabled merges on retainedMergeTreetables, causing laterOPTIMIZE TABLE ... FINALqueries to fail withABORTED.Workflow [PR]
Sync PR [sync-upstream/pr/119425]