Repository navigation
Description
Company or project name
No response
Describe what's wrong
When running OPTIMIZE TABLE ... FINAL on a ReplacingMergeTree table, the merge operation can be canceled and fail with an ABORTED exception. This is a significant issue because OPTIMIZE ... FINAL is an explicit command to force a merge, and it should not be aborted arbitrarily without a clear, actionable reason .
The error appears to be non-deterministic and can occur even when the table is small and uncomplicated, making it difficult to predict or avoid in production systems.
This issue report aims to provide a straightforward and reliable test case to reproduce the problem, which is a key requirement for ClickHouse's bug bounty program .
Does it reproduce on the most recent release?
Yes
How to reproduce
Create a new atomic database.
Create a ReplacingMergeTree table populated with data.
Run OPTIMIZE TABLE ... FINAL.
Recreate the same table with the same data.
Run OPTIMIZE TABLE ... FINAL again.
Observe the error.
A complete and reproducible SQL script is provided below:
create database bug_report engine=Atomic;
CREATE OR REPLACE TABLE bug_report.test
(
nn Int32,
mm Int32,
no DATETIME,
col1 Int32,
col2 Int32,
col3 Int32,
col4 Int32,
col5 Int32
)
ENGINE = ReplacingMergeTree(no)
ORDER BY (nn, mm)
SETTINGS index_granularity = 8192 AS
SELECT
1 AS nn,
2 AS mm,
now() AS no,
number AS col1,
number + 1 AS col2,
number + 2 AS col3,
number + 3 AS col4,
number + 4 AS col5
FROM numbers(1000);
optimize table bug_report.test final;
CREATE OR REPLACE TABLE bug_report.test
(
nn Int32,
mm Int32,
no DATETIME,
col1 Int32,
col2 Int32,
col3 Int32,
col4 Int32,
col5 Int32
)
ENGINE = ReplacingMergeTree(no)
ORDER BY (nn, mm)
SETTINGS index_granularity = 8192 AS
SELECT
1 AS nn,
2 AS mm,
now() AS no,
number AS col1,
number + 1 AS col2,
number + 2 AS col3,
number + 3 AS col4,
number + 4 AS col5
FROM numbers(1000);
optimize table bug_report.test final;
Expected behavior
Both OPTIMIZE commands should complete successfully. The table data is small (1000 rows), and there is no discernible reason for the merge to be canceled. If there is a constraint or conflict, the system should return a more descriptive and actionable error message.
Error message and/or stacktrace
2026.08.17 09:19:48.910592 [ 1880510 ] {1eb0e529-5960-4180-b986-19805ae344fb} DynamicQueryHandler: Code: 236. DB::Exception: Cancelled merging parts. (ABORTED), Stack trace (when copying this message, always include the lines below):
- DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x000000001798f5ea
- DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000fbd9fce
- DB::Exception::Exception(PreformattedMessage&&, int) @ 0x000000000fbd9909
- DB::Exception::Exception<>(int, FormatStringHelperImpl<>) @ 0x000000001798dbf6
- DB::StorageMergeTree::merge(bool, String const&, bool, bool, std::vector<String, std::allocator> const&, bool, std::shared_ptrDB::MergeTreeTransaction const&, PreformattedMessage&, bool) @ 0x000000001d9903ae
- DB::StorageMergeTree::optimize(boost::intrusive_ptrDB::IAST const&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, boost::intrusive_ptrDB::IAST const&, bool, bool, std::vector<String, std::allocator> const&, bool, std::shared_ptr<DB::Context const>) @ 0x000000001d99ab57
- DB::InterpreterOptimizeQuery::execute() @ 0x000000001d0a55e2
- DB::executeQueryImpl(char const*, char const*, std::shared_ptrDB::Context, DB::QueryFlags, DB::QueryProcessingStage::Enum, std::unique_ptr<DB::ReadBuffer, std::default_deleteDB::ReadBuffer>&, boost::intrusive_ptrDB::IAST&, std::shared_ptrDB::ImplicitTransactionControlExecutor, std::function<void ()>, DB::QueryResultDetails&) @ 0x000000001d01c3fe
- DB::executeQuery(std::unique_ptr<DB::ReadBuffer, std::default_deleteDB::ReadBuffer>, DB::WriteBuffer&, std::shared_ptrDB::Context, std::function<void (DB::QueryResultDetails const&)>, DB::QueryFlags, std::optionalDB::FormatSettings const&, std::function<void (DB::IOutputFormat&, String const&, std::shared_ptr<DB::Context const> const&, std::optionalDB::FormatSettings const&)>, std::function<void ()>, std::function<void ()>) @ 0x000000001d024804
- DB::HTTPHandler::processQuery(DB::HTTPServerRequest&, DB::HTMLForm&, DB::HTTPServerResponse&, DB::HTTPHandler::Output&, DB::QueryScope&, StrongTypedef<unsigned long, ProfileEvents::EventTag> const&) @ 0x000000001e84dc11
- DB::HTTPHandler::handleRequest(DB::HTTPServerRequest&, DB::HTTPServerResponse&, StrongTypedef<unsigned long, ProfileEvents::EventTag> const&) @ 0x000000001e852a64
- DB::HTTPServerConnection::run() @ 0x000000001e94a48a
- Poco::Net::TCPServerConnection::start() @ 0x000000002424be07
- Poco::Net::TCPServerDispatcher::run() @ 0x000000002424c382
- Poco::PooledThread::run() @ 0x00000000242094c5
- Poco::ThreadImpl::runnableEntry(void*) @ 0x0000000024207a4f
- start_thread @ 0x0000000000072464
- __GI___clone3 @ 0x00000000000f55ec
(version 26.3.10.60 (official build))
Related issues and pull requests
No response
Additional context
No response
Activity
PedroTadim commentedon Aug 18, 2026
Not a bug: canceling an in-flight merge when its table is concurrently dropped or replaced is required behavior, not specific to CREATE OR REPLACE TABLE — a merge can't continue once the storage it targets is gone. Your literal script doesn't reproduce this sequentially; this needs the second statement to genuinely overlap the first OPTIMIZE ... FINAL
mbtolou commentedon Aug 18, 2026
With respect, your response is incorrect:
My script runs completely sequentially. There is no overlap between the OPTIMIZE and CREATE OR REPLACE statements. The first OPTIMIZE finishes completely before CREATE OR REPLACE is executed, and the second OPTIMIZE runs only after CREATE OR REPLACE has completed. Therefore, the claim that "this requires overlap" is irrelevant.
In a database with ENGINE=Atomic, the atomicity concept means that the new table atomically replaces the old one, and all new queries are executed on the new (active) table. The old table is only removed after all currently running queries on it have finished. (And to be clear, we have no concurrent queries running at all.)
Despite this, the second OPTIMIZE fails with the ABORTED error. This indicates a real bug in the merge cancellation mechanism or in how replaced tables are handled.
This functionality worked correctly in older versions of ClickHouse. This is a regression, not expected behavior.
Please re-examine the script carefully and accept this as a valid bug report.
@PedroTadim
PedroTadim commentedon Aug 18, 2026
Dear @mbtolou, I checked the script again.
🕵️
I re-checked this carefully. Your literal script, run strictly sequentially, does not fail:
clickhouse-client --multiquery: 0 failuresDynamicQueryHandler, i.e. the HTTP interface), one awaited request per statement: 0 failuresI can, however, reproduce your exact symptom — the second
OPTIMIZEfailing withCode: 236. Cancelled merging parts (ABORTED)whileCREATE OR REPLACEsucceeds — whenever theOPTIMIZEis issued before the precedingCREATE OR REPLACEhas fully completed. While the replace is still inserting into its temporary table, the name still resolves to the old table; theOPTIMIZE ... FINALstarts merging the old table; the replace then exchanges and drops it, cancelling the merge. In my run the cancelled merge belongs to the old table's UUID while the surviving table has a different one, which is only possible if theOPTIMIZEstarted before the replace finished.On Atomic semantics: "the old table is removed after running queries finish" applies to readers holding a snapshot (SELECTs). It deliberately does not apply to merges — DROP/replace cancels in-flight merges instead of waiting behind them, and
OPTIMIZE FINALis exactly a query that executes a merge.You can verify this on your side with one failing run:
If the
OPTIMIZE'sstartis earlier than theCREATE OR REPLACE'sfinish, the requests overlap — which tool/driver executes the script would also be useful to know, since HTTP clients that pipeline or retry produce exactly this pattern.mbtolou commentedon Aug 18, 2026
Dear @PedroTadim ,
Thank you for your detailed analysis.
I have attached the
system.query_logoutput for a failing run:Observations:
OPTIMIZEstarted at21:55:58.682.CREATE OR REPLACEfinished at21:55:58.674.Conclusion:
Contrary to the scenario you described, in my execution
OPTIMIZEran afterCREATE OR REPLACEhad fully completed, yet the errorCode: 236. Cancelled merging parts (ABORTED)still occurred.This indicates that although
QueryFinishis recorded insystem.query_log, the atomic table swap/drop operation had not yet been fully completed at that moment. As a result,OPTIMIZEattempted to merge parts of the old table which was still being dropped, causing the error.Additional points:
awaiton each query).QueryFinishdoes not guarantee that the atomic operation is fully complete.Notes:
SYSTEM SYNC REPLICAbecause Replication is not enabled.sleepdelay is not a viable solution, as the time required for the atomic operation to complete depends on data volume and system conditions, making a constant delay unreliable.Request:
Given the above, I kindly request:
config.xml,users.xml, or any other settings), please let me know.mbtolou commentedon Aug 19, 2026
I have also tested this using
clickhouse-client --multiquery < /home/test.sqland it fails with the same error:This confirms the issue is reproducible even in a single batch execution.
PedroTadim commentedon Aug 19, 2026
🕵️
Thank you — the
query_logtimeline is useful, and it rules out simple client pipelining if those rows are matched correctly. However, I cannot reconcile it with the current code, and I cannot reproduce it at any intensity: on top of the earlier runs, I executed 1000CREATE OR REPLACE+OPTIMIZE FINALpairs in a singleclickhouse-client --multiquerysession (your exact scenario, no gaps between statements) with 0 failures. In the current implementation the populate, the table exchange and the drop of the old table all complete inside theCREATE OR REPLACEquery, before itsQueryFinishis written — so a laterOPTIMIZEresolves the new table, whose merges were never cancelled.That suggests a version-specific difference. Two things would pin it down:
Tell which version are you using. I cannot reproduce this with the latest master.
From one failing run, the server log lines around the error (
grep "Cancelled merging" /var/log/clickhouse-server/clickhouse-server.log) together withSELECT uuid FROM system.tables WHERE database='bug_report' AND name='test'. The cancelled-merge log line contains the table UUID (e.g.{<uuid>::all_1_5_2}). If that UUID is the previous table's, yourOPTIMIZEstill resolved the old table despite the replace'sQueryFinish— an ordering bug in that version. If it is the current table's UUID, merges were wrongly cancelled on the brand-new table — a different bug. Either way that single line tells us which mechanism to chase.mbtolou commentedon Aug 19, 2026
Script-10.sql
err.log
PedroTadim commentedon Aug 19, 2026
🕵️ You were right, and my earlier analysis was wrong — thank you for pushing back with the version and the script.
With
26.3.17.110I reproduce it immediately: 283/300 consecutiveCREATE OR REPLACE TABLE ... AS SELECT+OPTIMIZE ... FINALpairs fail. It is not a race, not client pipelining, and not a timing artifact — the first pair succeeds and essentially every pair after it fails, deterministically.Your second hypothesis was the correct one: "the merge is being wrongly cancelled on a brand-new table".
Root cause
CREATE OR REPLACE TABLE ... AS SELECTcreates a temporary table, populates it,EXCHANGEs it with the target, then drops the old table under the temporary name. While populating, the temporary name is cached in the per-query storage cache (Context::getOrCacheStorage), which is keyed by qualified name only. After the exchange that name maps to a different table, but the cache still hands back the entry it stored — the brand-new, now-live table.So the final internal drop calls
flushAndPrepareForShutdownon the new table instead of the old one, and that runsmerger_mutator.merges_blocker.cancelForever().The server log shows it plainly (
dd00aee2…is the new, live table):and a debugger confirms the caller is the replace itself:
This is permanent, and worse than a failing OPTIMIZE
cancelForeveris not transient, so nosleepwill ever help — the table can never merge again for the rest of its life:Because background merges are dead too, parts accumulate without bound. On a table with
parts_to_throw_insert = 10, inserts start failing outright:An identical table created without a replace absorbed 30 inserts with no error. So on a busy table this eventually breaks writes, not just
OPTIMIZE.Affected versions
Tested with the same script (failures / attempts):
Bisecting master pins the fix to
0e0e86a7f6a(#108728, 2026-07-07), which makes the cache verify that a hit still resolves to the requested name/UUID and drops it otherwise. Its own comment describes this exact scenario. It landed after the 26.3 branch point, so 26.3 LTS does not have it — I will arrange a backport, and this issue tracks that.Until then
CREATE OR REPLACE ... AS SELECT— the bug is specific to the populate-and-swap path. Both of these are clean in my testing on 26.3.17.110:CREATE OR REPLACE TABLE t (...) ENGINE = …(noAS SELECT) followed by a separateINSERT INTO t SELECT …— 0/10 failures;AS SELECT, thenEXCHANGE TABLES tmp AND t, thenDROP TABLE tmp— 0/3 failures.Any table already poisoned stays poisoned; recreate it with one of the above to recover merging.
Sorry for the runaround on the earlier reproduction attempts — I was testing on master, which already had the fix.
PedroTadim commentedon Aug 19, 2026
This has been fixed on master, I am backporting the fix PR to close this issue.
Replace the MV tests with a table one that 26.3 can run
PedroTadim commentedon Aug 20, 2026
Just backported the patch, you can test on latest 26.3 build
mbtolou commentedon Aug 21, 2026
not work in version
ClickHouse client version 26.3.20.7 (official build).PedroTadim commentedon Aug 21, 2026
According to my research, the fix is in version
26.3.20.9. You can test it once it's out. If you can't wait, you can try the latest build from the release branch: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.3&sha=a3d10fb883377e5ebbfb5ca4b32ba749eeba62bc&name_0=ReleaseBranchCI, but be careful, as many backports are happening.