Skip to content

OPTIMIZE TABLE ... FINAL on ReplacingMergeTree Can Spontaneously Fail with Code 236 ABORTED #115288

Closed

Description

@mbtolou

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

  1. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x000000001798f5ea
  2. DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000fbd9fce
  3. DB::Exception::Exception(PreformattedMessage&&, int) @ 0x000000000fbd9909
  4. DB::Exception::Exception<>(int, FormatStringHelperImpl<>) @ 0x000000001798dbf6
  5. DB::StorageMergeTree::merge(bool, String const&, bool, bool, std::vector<String, std::allocator> const&, bool, std::shared_ptrDB::MergeTreeTransaction const&, PreformattedMessage&, bool) @ 0x000000001d9903ae
  6. 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
  7. DB::InterpreterOptimizeQuery::execute() @ 0x000000001d0a55e2
  8. 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
  9. 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
  10. DB::HTTPHandler::processQuery(DB::HTTPServerRequest&, DB::HTMLForm&, DB::HTTPServerResponse&, DB::HTTPHandler::Output&, DB::QueryScope&, StrongTypedef<unsigned long, ProfileEvents::EventTag> const&) @ 0x000000001e84dc11
  11. DB::HTTPHandler::handleRequest(DB::HTTPServerRequest&, DB::HTTPServerResponse&, StrongTypedef<unsigned long, ProfileEvents::EventTag> const&) @ 0x000000001e852a64
  12. DB::HTTPServerConnection::run() @ 0x000000001e94a48a
  13. Poco::Net::TCPServerConnection::start() @ 0x000000002424be07
  14. Poco::Net::TCPServerDispatcher::run() @ 0x000000002424c382
  15. Poco::PooledThread::run() @ 0x00000000242094c5
  16. Poco::ThreadImpl::runnableEntry(void*) @ 0x0000000024207a4f
  17. start_thread @ 0x0000000000072464
  18. __GI___clone3 @ 0x00000000000f55ec
    (version 26.3.10.60 (official build))

Related issues and pull requests

No response

Additional context

No response

Activity

  1. added
    potential bug
    on Aug 18, 2026
  2. removed
    potential bug
    on Aug 18, 2026
  3. PedroTadim commented on Aug 18, 2026

    @PedroTadim
    Member

    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

  4. added
    close in a month if not active
    on Aug 18, 2026
  5. mbtolou commented on Aug 18, 2026

    @mbtolou
    Author

    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

  6. PedroTadim commented on Aug 18, 2026

    @PedroTadim
    Member

    Dear @mbtolou, I checked the script again.

    🕵️

    I re-checked this carefully. Your literal script, run strictly sequentially, does not fail:

    • 200 runs via clickhouse-client --multiquery: 0 failures
    • 100 runs over HTTP (your trace shows DynamicQueryHandler, i.e. the HTTP interface), one awaited request per statement: 0 failures

    I can, however, reproduce your exact symptom — the second OPTIMIZE failing with Code: 236. Cancelled merging parts (ABORTED) while CREATE OR REPLACE succeeds — whenever the OPTIMIZE is issued before the preceding CREATE OR REPLACE has fully completed. While the replace is still inserting into its temporary table, the name still resolves to the old table; the OPTIMIZE ... FINAL starts 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 the OPTIMIZE started 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 FINAL is exactly a query that executes a merge.

    You can verify this on your side with one failing run:

    SELECT type, query_start_time_microseconds AS start, event_time_microseconds AS finish, left(query, 60)
    FROM system.query_log
    WHERE query LIKE '%bug_report.test%' AND type != 'QueryStart'
    ORDER BY start;

    If the OPTIMIZE's start is earlier than the CREATE OR REPLACE's finish, 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.

  7. mbtolou commented on Aug 18, 2026

    @mbtolou
    Author

    Dear @PedroTadim ,

    Thank you for your detailed analysis.

    I have attached the system.query_log output for a failing run:

    QueryFinish    21:55:58.597 → 21:55:58.627    CREATE OR REPLACE (1st)     ✅
    QueryFinish    21:55:58.631 → 21:55:58.637    OPTIMIZE (1st)              ✅
    QueryFinish    21:55:58.643 → 21:55:58.674    CREATE OR REPLACE (2nd)     ✅
    ExceptionBeforeStart    21:55:58.682          OPTIMIZE (2nd)              ❌
    

    Observations:

    1. The second OPTIMIZE started at 21:55:58.682.
    2. The second CREATE OR REPLACE finished at 21:55:58.674.
    3. There is an 8ms gap between the completion of CREATE and the start of OPTIMIZE.
    4. There is no overlap between these two queries.

    Conclusion:

    Contrary to the scenario you described, in my execution OPTIMIZE ran after CREATE OR REPLACE had fully completed, yet the error Code: 236. Cancelled merging parts (ABORTED) still occurred.

    This indicates that although QueryFinish is recorded in system.query_log, the atomic table swap/drop operation had not yet been fully completed at that moment. As a result, OPTIMIZE attempted to merge parts of the old table which was still being dropped, causing the error.


    Additional points:

    • This error is reproducible with both dBeaver and the official C# driver (with await on each query).
    • The behavior has been tested on 12 separate servers with identical results.
    • This issue did not exist on version 25.3 and has only been observed in newer versions.
    • Since this issue occurs with two different tools, with strictly sequential execution, and across multiple servers, it cannot be attributed to client-side pipelining, retries, or server-specific problems.
    • This appears to be an inherent issue in ClickHouse's design, where QueryFinish does not guarantee that the atomic operation is fully complete.

    Notes:

    • I am not using SYSTEM SYNC REPLICA because Replication is not enabled.
    • Using a fixed sleep delay 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:

    1. An official solution or workaround for this issue.
    2. If you need any additional information (such as config.xml, users.xml, or any other settings), please let me know.
    3. If possible, please confirm whether this behavior has been reported as a known bug in recent ClickHouse versions.
  8. mbtolou commented on Aug 19, 2026

    @mbtolou
    Author

    I have also tested this using clickhouse-client --multiquery < /home/test.sql and it fails with the same error:

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

    This confirms the issue is reproducible even in a single batch execution.

  9. PedroTadim commented on Aug 19, 2026

    @PedroTadim
    Member

    🕵️
    Thank you — the query_log timeline 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 1000 CREATE OR REPLACE + OPTIMIZE FINAL pairs in a single clickhouse-client --multiquery session (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 the CREATE OR REPLACE query, before its QueryFinish is written — so a later OPTIMIZE resolves the new table, whose merges were never cancelled.

    That suggests a version-specific difference. Two things would pin it down:

    1. Tell which version are you using. I cannot reproduce this with the latest master.

    2. From one failing run, the server log lines around the error (grep "Cancelled merging" /var/log/clickhouse-server/clickhouse-server.log) together with SELECT 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, your OPTIMIZE still resolved the old table despite the replace's QueryFinish — 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.

  10. mbtolou commented on Aug 19, 2026

    @mbtolou
    Author

    Script-10.sql

    err.log

    Here is the information you requested:

    Version: 26.3.17.110

    UUID before CREATE OR REPLACE: 97f51dc8-849d-490a-a7fb-63e0fc1ca802
    UUID after CREATE OR REPLACE: 7fb4110d-a646-4d93-8b2a-06d2dedb4b4a

    Timeline from query_log:

    15:07:38.106 - CREATE OR REPLACE starts
    15:07:38.144 - CREATE OR REPLACE finishes (QueryFinish)
    15:07:38.146 - OPTIMIZE starts
    15:07:38.151 - OPTIMIZE finishes successfully
    15:07:41.324 - Second CREATE OR REPLACE starts
    15:07:41.381 - Second CREATE OR REPLACE finishes (QueryFinish)
    15:07:44.552 - Second OPTIMIZE fails with ExceptionBeforeStart (ABORTED)
    

    The second OPTIMIZE fails even though:

    • The previous CREATE OR REPLACE completed 3 seconds earlier
    • No concurrent queries were running
    • The table was successfully replaced (new UUID: 7fb4110d-a646-4d93-8b2a-06d2dedb4b4a)

    Since I couldn't find the specific "Cancelled merging" log line with UUID in the server log (it only shows the error without UUID context), but based on the timeline and UUID change, the OPTIMIZE should be resolving the new table. The merge is being wrongly cancelled on a brand-new table with no concurrent operations.

    This is a regression in version 26.3.17.110 - it worked correctly in older versions.

  11. removed
    close in a month if not active
    on Aug 19, 2026
  12. PedroTadim commented on Aug 19, 2026

    @PedroTadim
    Member

    🕵️ You were right, and my earlier analysis was wrong — thank you for pushing back with the version and the script.

    With 26.3.17.110 I reproduce it immediately: 283/300 consecutive CREATE OR REPLACE TABLE ... AS SELECT + OPTIMIZE ... FINAL pairs 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 SELECT creates 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 flushAndPrepareForShutdown on the new table instead of the old one, and that runs merger_mutator.merges_blocker.cancelForever().

    The server log shows it plainly (dd00aee2… is the new, live table):

    … bug_report.test (dd00aee2-…): Start preparing for shutdown
    … bug_report.test (dd00aee2-…): Finished preparing for shutdown
    … bug_report.test (dd00aee2-…): Start preparing for shutdown     <-- second call, on the live table
    

    and a debugger confirms the caller is the replace itself:

    DB::StorageMergeTree::flushAndPrepareForShutdown()
    DB::InterpreterDropQuery::executeToTableImpl(...)
    DB::InterpreterCreateQuery::doCreateOrReplaceTable(...)
    

    This is permanent, and worse than a failing OPTIMIZE

    cancelForever is not transient, so no sleep will ever help — the table can never merge again for the rest of its life:

    $ OPTIMIZE TABLE bug_report.test FINAL   -- 3s later, 60s later, always
    Code: 236. DB::Exception: Cancelled merging parts. (ABORTED)
    

    Because background merges are dead too, parts accumulate without bound. On a table with parts_to_throw_insert = 10, inserts start failing outright:

    Code: 252. DB::Exception: Too many parts (10 with average size of 413.00 B) …
    

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

    Version Result
    25.8.9.20 (LTS) 0/10 — not affected
    26.1.9.5 9/10
    26.3.16.16 19/20
    26.3.17.56 19/20
    26.3.17.110 (yours) 283/300
    26.6.3.62 19/20
    26.7.4.58 (latest stable) 0/300 — fixed

    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

    • Upgrade to 26.7+, where this is fixed; or
    • avoid 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 = … (no AS SELECT) followed by a separate INSERT INTO t SELECT … — 0/10 failures;
      • creating a differently-named table with AS SELECT, then EXCHANGE TABLES tmp AND t, then DROP 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.

  13. PedroTadim commented on Aug 19, 2026

    @PedroTadim
    Member

    This has been fixed on master, I am backporting the fix PR to close this issue.

  14. PedroTadim commented on Aug 20, 2026

    @PedroTadim
    Member

    Just backported the patch, you can test on latest 26.3 build

  15. mbtolou commented on Aug 21, 2026

    @mbtolou
    Author

    Just backported the patch, you can test on latest 26.3 build

    not work in version ClickHouse client version 26.3.20.7 (official build).

  16. PedroTadim commented on Aug 21, 2026

    @PedroTadim
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions