Skip to content

Add leader election for non-replicated MergeTree on shared storage - #101039

Open
alexey-milovidov wants to merge 468 commits into
masterfrom
leader-election-mergetree
Open

alexey-milovidov wants to merge 468 commits into
masterfrom
leader-election-mergetree

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 28, 2026 •

Copy link
Copy Markdown
Member

Add leader election for non-replicated MergeTree tables on shared object storage (currently S3; Azure is implemented but not yet enabled, pending test coverage), enabling active/standby failover without external coordination (no Keeper).

Uses conditional writes (If-Match / If-None-Match) on object storage to maintain a lease file with JSON content {"version":1,"leader_id":"...","timestamp":...}. The leader renews its lease periodically; followers monitor and claim leadership when the lease expires.

New MergeTree settings:

  • leader_election (Bool, default false) — enable leader election
  • leader_election_heartbeat_interval (Seconds, default 10) — lease renewal interval
  • leader_election_session_timeout (Seconds, default 30) — lease expiry threshold; must be at least 3x the heartbeat interval

When not the leader, inserts, merges, and DDL are blocked; background data processing is skipped. Heavy mutations (ALTER TABLE ... UPDATE / DELETE) are unsupported on the currently enabled S3 plain_rewritable metadata layout, including on the leader, because that layout provides no hard links. Lightweight updates do run on the leader: they write patch parts, need no hard links, and are admission-fenced by the leadership epoch like an INSERT. MOVE PARTITION ... TO TABLE from a leader_election table into a table without leader_election is rejected.

Every disk of the storage policy must be a writable S3 disk with metadata_type = plain_rewritable, enable_hard_links = false (the link counts of shared blobs are not coordinated between nodes) and metadata_snapshot_enabled = false (every node that writes to the disk would publish the snapshot of the whole disk without coordination). Other disks are rejected at table creation.

Wall-clock synchronization between the nodes is not required: a follower considers the lease expired only after it has observed the same version of the lease file for leader_election_session_timeout on its own monotonic clock, and the leader stops accepting writes no later than that, measured on its own monotonic clock from the moment before it wrote the lease. Only the rates of the clocks are assumed to be equal.

Queries on followers are coordinated with the cleanup on the leader. Every node that is not the leader keeps a small reader object next to the lease (<lease>_readers/<node>) and rewrites it at every heartbeat. It names the latest write of the lease that the node had read before it listed the storage for its current set of parts, and the outdated parts that its queries still read. The leader removes an outdated part only after every node with an unexpired reader object has refreshed its parts past the replacement of that part and does not list it, so a query on a follower can run longer than old_parts_lifetime. A reader object expires after leader_election_session_timeout, like the lease. If a part is removed anyway (the node stalled) and its name is reused, a query that still holds the old part fails with DATA_PART_CHANGED_ON_SHARED_STORAGE instead of reading the files of the new part. DETACH PARTITION, MOVE PARTITION and moves between disks still change the storage at once.

The same binding of a part to its directory guards the operations that take the files of a part by the name of its directory. A part of a leader_election table that is cloned into another table (ATTACH PARTITION ... FROM, REPLACE PARTITION) is checked after the copy, and the command fails with DATA_PART_CHANGED_ON_SHARED_STORAGE if the directory was replaced meanwhile. DETACH PART / DETACH PARTITION first writes the copy as detached/clone_<part>, which ATTACH PARTITION does not take, and renames it to detached/<part> only after the source and the leadership epoch are checked; if a check fails, the clone_ copy is left in place. A missing checksums.txt or columns.txt is not rewritten for such tables, neither while a part is loaded nor by CHECK TABLE: the values are recomputed in memory, and CHECK TABLE reports the missing file.

Closes #91613

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add leader_election setting for non-replicated MergeTree tables on shared object storage, enabling active/standby failover using conditional writes without external coordination.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Three new MergeTree-level settings are added:

  • leader_election (Bool) — When enabled on a non-replicated MergeTree table stored on an S3 object storage disk (Azure is implemented but rejected at table creation until it has test coverage), multiple ClickHouse instances sharing the same data path will elect a single leader. Only the leader performs writes and merges. Followers act as read-only replicas and automatically claim leadership when the current leader's lease expires. Heavy mutations (ALTER TABLE ... UPDATE / DELETE) are unsupported on the currently enabled S3 plain_rewritable metadata layout, including on the leader; lightweight updates are supported on the leader.
  • leader_election_heartbeat_interval (Seconds, default 10) — How often the leader renews its lease and followers check for an expired lease.
  • leader_election_session_timeout (Seconds, default 30) — How long a lease remains valid without renewal. Must be at least 3x leader_election_heartbeat_interval.

Example, using the same UUID and shared S3 storage policy on each node:

CREATE TABLE shared_table UUID '12345678-abcd-abcd-abcd-123456789abc' (x UInt64)
ENGINE = MergeTree ORDER BY x
SETTINGS
    storage_policy = 's3',
    leader_election = true,
    leader_election_heartbeat_interval = 10,
    leader_election_session_timeout = 30;

-- On every follower, attach the same table definition with the same UUID.
ATTACH TABLE shared_table UUID '12345678-abcd-abcd-abcd-123456789abc' (x UInt64)
ENGINE = MergeTree ORDER BY x
SETTINGS
    storage_policy = 's3',
    leader_election = true,
    leader_election_heartbeat_interval = 10,
    leader_election_session_timeout = 30;

Note

High Risk
High risk because it introduces new leader-election coordination and modifies core MergeTree write/DDL/drop and catalog cleanup paths; bugs could cause write unavailability or accidental deletion/incorrect visibility on shared storage.

Overview
Adds a Beta leader_election mode for non-replicated MergeTree tables on shared S3/Azure, using a conditional-write lease file to ensure only one instance performs inserts/merges/mutations while followers remain read-only and can take over on failure.

Introduces new MergeTree settings (leader_election, leader_election_heartbeat_interval, leader_election_session_timeout) with validation, new MergeTreeLeaderElection* metrics/events, and follower part-refresh + leader takeover sync to load new parts and advance block counters before enabling writes.

Hardens destructive operations for shared-storage tables: blocks most ALTER/partition-mutation operations and RENAME under leader election, gates background processing on leadership, and updates drop/cleanup logic (dropSkipsDataDirectoryCleanup, DatabaseCatalog/StorageTableProxy fail-closed behavior) to avoid recursive deletion or hangs when tables are shared or cannot be materialized. Adds documentation and integration/stateless tests covering failover, metrics, validation, and rejection cases.

Reviewed by Cursor Bugbot for commit 78c1252. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@clickhouse-gh

clickhouse-gh Bot commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5951709]

Summary: ✅


AI Review

Summary

Adds experimental leader_election for non-replicated MergeTree tables on shared S3 storage, including takeover synchronization, follower reader registrations, and protections for shared-data cleanup. Reviewed head 5951709f91c4026e871c25dd4144aca20aec6948, the current diff and surrounding code, all 224 review threads with their replies, and the conversation. Most historical findings are addressed. Four previously discussed correctness concerns remain; these are retained here without duplicating or reopening inline threads.

Missing context / blind spots
  • ⚠️ The latest Praktika report lists no failed tests, but the targeted integration report exposes zero test results and no artifacts. Completed failover-suite results for this head would close that validation gap. No local binary was available, and no nested CI run was started; the failure sequences below were verified by tracing code.
Findings

❌ Blockers

  1. Stale part loaders can detach or delete acknowledged replacement data. src/Storages/MergeTree/MergeTreeData.cpp:5356 and :5364 check only current lease freshness before renameToDetached / remove. A background load can classify an old broken or duplicate directory, pause, and resume after another leader cleaned it up, restarted empty, and reused the name. If the loading node subsequently acquires leadership, these checks pass and the stale continuation mutates the healthy replacement by logical path. The expected-incarnation checks during loading do not protect this later mutation. Carry the load's ownership epoch and directory identity through cleanup, or suppress stale cleanup.

    [dismissed by author -- https://github.com/Add leader election for non-replicated MergeTree on shared storage #101039#discussion_r4658331430] The author explicitly deferred these sibling cleanup paths; they still permit a stale classification to remove current data. The original checksum-repair finding in that thread is fixed.

  2. A successful backup can contain files from different part incarnations. src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp:527 creates deferred BackupEntryFromImmutableFile entries from logical disk paths. src/Backups/BackupImpl.cpp:1762 later copies those paths without the part's pinned identity check or verification against the recorded checksum. Let a leader backup copy some files, stall through failover and reader expiry, then resume after an empty restart reused the part name and its local disk metadata refreshed. Remaining copies can read same-size replacement files while retaining the old checksum bookkeeping, and the backup can report success with inconsistent contents. Bind the actual deferred reads and native copies to their source objects/incarnation, or reject the backup when that binding is lost.

    [dismissed by author -- https://github.com/Add leader election for non-replicated MergeTree on shared storage #101039#discussion_r4100780108] The accepted limitation assumed names cannot be reused and backups would merely fail on missing files. Empty-table restart/name reuse invalidates that premise, so documenting possible failure does not cover this corruption risk.

  3. Takeover can enable writes while omitting acknowledged replacement rows. src/Storages/MergeTree/MergeTreeData.cpp:4544 reconciles only Active and Outdated parts, while the seeding lookup at :4731 also encounters retained Deleting records. Foreground cleanup on A can retain such a record across B's takeover, cleanup, empty restart, and same-name replacement. When A reacquires leadership, the old record suppresses loading the replacement. The delayed cleanup correctly rejects its old epoch and restores the record to Outdated, but A is now leader and does not run follower reconciliation: its queries omit the replacement until another takeover or restart. Reconcile these retained records before completing takeover, or arrange the required reconciliation when the old cleanup returns.

    [dismissed by author -- https://github.com/Add leader election for non-replicated MergeTree on shared storage #101039#discussion_r4389027159] The author acknowledges this limitation. It remains incorrect results on the writable leader, rather than ordinary follower refresh delay; the destructive-delete component of the original finding is fixed.

  4. Failed DETACH can leave neither live rows nor an attachable copy. src/Storages/StorageMergeTree.cpp:5252 durably commits covering empty parts before calling clonePartsToDetached at :5255; DETACH PARTITION follows the same ordering. A copy error or leadership rejection then returns an exception after retirement has committed. Cleanup can remove the source, while the new staging path may leave only an incomplete/non-attachable clone_ directory. Stage a recoverable copy before committing retirement, or link a separate issue tracking this pre-existing defect.

    [dismissed by author -- https://github.com/Add leader election for non-replicated MergeTree on shared storage #101039#discussion_r4207258952] The author deferred it because the ordering also exists on master. It remains reachable through this PR's supported DETACH paths; the later source-identity checks prevent mixed detached copies but do not restore failed-command recoverability.

Final Verdict

Status: ❌ Block

Fence stale loader cleanup, bind deferred backup copies, and reconcile retained Deleting records before completing takeover. Make failed DETACH recoverable or link a tracking issue for that pre-existing defect. Prior dismissals remain summary-only; no new inline review was submitted.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Mar 28, 2026
Comment thread src/Storages/StorageMergeTree.h Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

We should assert leadership before every transaction commit, e.g., renaming part for adding it to the working set.

Comment thread src/Storages/StorageMergeTree.cpp Resolved

@clickhouse-gh clickhouse-gh Bot left a comment

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.

Submitting pending automated review to unblock inline review comments.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@mohamed-essam

Copy link
Copy Markdown

Hi @alexey-milovidov this looks amazing, I was wondering if this would acquire a lease per configured table or one lease for all configured tables?
Also given that writes to non-leaders fail with an exception, do you have any recommendations on how to route writes to the current active leader efficiently?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@alexey-milovidov

alexey-milovidov commented Apr 10, 2026 •

Copy link
Copy Markdown
Member Author

@mohamed-essam,

I was wondering if this would acquire a lease per configured table or one lease for all configured tables?

One lease per table, which means all tables are independent.
This has a downside - high cost of PUT requests for a large number of tables. For example, if you have 10,000 tables and the heartbeat interval is 10 seconds, you have 1000 requests per second on a single replica, and you will spend $20 per hour, $480 per day, and more than $10,000 a month, which is impractical.

@alexey-milovidov

alexey-milovidov commented Apr 10, 2026 •

Copy link
Copy Markdown
Member Author

Also, given that writes to non-leaders fail with an exception, do you have any recommendations on how to route writes to the current active leader efficiently?

This task implements a small building block and does not solve this problem. I imagine that we will have partitioned tables, where the lease is per partition, and every replica acquires a subset of partitions mostly uniformly. If partitions are by a random function, writes can go to any active replica. The decision of which replica to choose for writes could be made by randomly selecting replicas until success and remembering the last successful one to use next time.

This allows infinitely scalable tables without Keeper, but only a small number of such tables per server.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
The test used the UUID of `test_takeover_refused_when_dedup_log_cannot_be_read`'s table. `DROP TABLE`
leaves the data of a `leader_election` table on the shared storage, so in a run of the whole file
the `CREATE TABLE` of this test found the parts of the other one and failed with `INCORRECT_DATA`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=5310197a5dd842a0199cfad45d5b93a875c88860&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20targeted%29
PR: #101039

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@stresshouse

stresshouse Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

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

no significant changes detected. K_source=4 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 06483c8b-57b8-41ef-bef1-a83c263be6c7
  • MIRAI run: a2e71f69-beb0-4dc3-bf02-7c5208bdf3f5
  • PR check IDs:
    • clickbench_899275_1795399343
    • clickbench_899289_1795399343
    • tpch_adapted_1_official_899297_1795399343
    • tpch_adapted_1_official_899340_1795399343

alexey-milovidov and others added 4 commits November 22, 2026 06:55
`DetachedNamespaceRollback::renameDirectory` moved the directory first and built the undo record
afterwards. Copying the paths and growing the journal allocate memory, so an allocation that
failed there (e.g. with `MEMORY_LIMIT_EXCEEDED`) left the move without a record, and a rejected
`ATTACH PARTITION` did not undo it. `removeFileIfExists` had the same order, and could lose the
content of the file it removed.

The record and its slot in the journal are now prepared before the storage is changed. After the
change, only the prepared record is moved into the reserved slot, which cannot throw.

The failpoint `merge_tree_leader_election_fail_recording_detached_change` fails the preparation
once, and `test_attach_partition_undoes_detached_changes_when_lease_goes_stale` checks that a
command rejected this way leaves `detached/` as it was.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t directory

A part of a `leader_election` table is bound to its directory on the shared storage: after a file
is opened by the name of the directory, the part storage checks that the name still refers to the
directory the part was loaded from (`IDataPartStorage::pinSharedStorageIdentity`). Four opens went
to the disk directly and skipped the check:

- `IMergeTreeDataPart::getStatisticsPackedReader` reads the index of `statistics.packed`;
- `IMergeTreeDataPart::loadStatisticsFile` opens a member of that archive;
- `DataPartStorageOnDiskBase::getSkipIndicesPackedReader` reads the index of `skp_idx.packed`;
- `DataPartStorageOnDiskPacked::getSkipIndicesPackedReader` reads the same index inside `data.packed`.

The column statistics are read on first use. A query on a follower that held a part whose name was
then reused by another directory loaded the statistics of the new part into the old one, and
`MergeTreeDataSelectExecutor::filterPartsByStatistics` dropped the old part by them: the query
returned no rows instead of its row or an error. No column file is opened in that case, so the
checks of the column streams did not help.

All four now check the directory after the open and before the result is used or remembered, and
fail with `DATA_PART_CHANGED_ON_SHARED_STORAGE` like the other opens. The other reads of a part go
through `IDataPartStorage::prepareRead` and `readFileIfExists`, which check already, and the caches
shared between tables are keyed by the identity of the directory.

The index of an archive is read before the check, so the message of the exception no longer says
that nothing was read from the other directory: it says that its data was not used.

`test_follower_query_does_not_read_reused_part_name` gets a third scenario, `statistics`. The query
stops while it is being planned, between taking the parts of the table and pruning them by
statistics, with the statistics of the part not loaded yet. Without the fix the query returns an
empty result; with it the query fails in `getStatisticsPackedReader`. The scenario does not reach
the check in `loadStatisticsFile`, which needs the index to be loaded before the name is reused.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… is built

`MergeTreeData::loadDataPart` built the part first and recorded the identity of its directory on
the shared storage afterwards. The builder already reads from the directory: it looks at its files
to tell the format of the part, and reads the index of the archive of a `Packed` part. If the
directory was replaced by another one with the same name between the two steps, the part was
bound to the new directory while it kept what the builder had read from the old one, and the
checks that followed compared the new directory with itself. The load of a valid part could then
fail on mismatched metadata and the part could be treated as broken.

The identity is now taken before the builder, the part is bound to it as soon as it is built, and
the directory is checked right there. An identity never comes back to a name, so this proves that
the builder read the directory the part is bound to. A mismatch fails the load with
`DATA_PART_CHANGED_ON_SHARED_STORAGE`, which is retried, or skips a request that was queued for
the previous directory.

No test is added: reaching the window needs a pause inside `loadDataPart`, a second table that
refreshes the disk of the follower meanwhile, and a truncate and a restart of the leader to reuse
the name.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… tests

`system.parts` stops showing a part when the cleanup takes it for removal, before its files are
removed: a query without the `_state` column gets only the active and outdated parts. Two tests
took an empty result as "the parts are gone from the storage".

`test_follower_query_keeps_outdated_parts` then looked at the storage once, and failed in a local
run with "The objects of part all_2_2_0 are left on the storage" while the leader was still
removing the batch of three parts. It now polls the storage.

`test_follower_query_does_not_read_reused_part_name` restarted the leader at that point. A leader
that is restarted in the middle of the removal loads what is left of the parts and does not reuse
the name, which would fail the test for a reason unrelated to what it checks. It now also waits
until no part directory of the table is left on the storage.

Polling the storage during the removal hit another race, in the helper itself:
`find_part_object_key_prefix` lists the `prefix.path` objects and then reads each of them, and the
leader removed a directory in between (`NoSuchKey`). The listing is now in one place,
`directory_paths_on_storage`, which skips a directory that disappeared.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
… a grabbed batch on failure

Two findings of the review in `StorageMergeTree`.

`CHECK TABLE` recomputes and writes `checksums.txt` for a part that has none. Under
`leader_election` the write was allowed on the writable leader, but the check of the lease said
nothing about the part: it was validated without any tie to the leadership, possibly while this
node was a follower. If another leader removed the part and reused its name for other data, and
this node took the lease over before the check finished, the checksums of the old part were
written into the directory of the new one, because `IMergeTreeDataPart::writeChecksums` opens the
directory by its name. The part is now only validated under `leader_election`, on the leader as
well, and the missing file is reported. `checksums.txt` is optional for a part.

`clearOldPartsFromFilesystem` takes a batch of parts with `grabOldParts`, which moves them to the
`Deleting` state, and then looks up the directories of the parts on the shared storage to tell
the replaced ones. An exception from these lookups or from the allocations around them (the
cleanup also runs in the query of a partition command, under its memory limit) left the batch in
`Deleting` forever, since nothing selects a part in that state again: the objects stayed on the
storage and the records could hide a part with the same name. Everything between `grabOldParts`
and `clearPartsFromFilesystemAndRollbackIfError` is now inside a `try`, and on an exception the
parts of the batch that are still `Deleting` return to `Outdated`.

Review threads:
#101039 (comment)
#101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…nder `leader_election`

A part that is loaded without `checksums.txt` recomputes the checksums and writes the file, a
part without `columns.txt` rebuilds the list and writes it, an empty `checksums.txt` is removed
before the rewrite, and a leftover `txn_version.txt.tmp` is removed. Under `leader_election`
these changes were allowed when the node held the lease (`MergeTreeData::mayMutateSharedStorage`).

The lease says nothing about the part. The loaders, the one of the outdated parts in particular,
keep running across the changes of the leadership, and all of these writes open the directory of
the part by its name. A follower could finish reading an old part, another leader could remove
that part and reuse its name for other data, and the follower could take the lease over before
the write: the check passed, and the checksums or the columns of the old part went into the
directory of the new one. The identity of the directory that the part is bound to protects only
the reads, and the check at the end of `loadDataPart` comes after the write.

Under `leader_election` a part no longer changes its files while it is loaded, whoever holds the
lease. The recomputed checksums and the rebuilt list of columns are used in memory, as they
already were on a follower. This matches `CHECK TABLE`, which stopped writing `checksums.txt`
for such tables in the previous commit.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov and others added 2 commits November 22, 2026 16:30
…ep the publish journal intact on failure

Two findings of the review about exceptions that are not what the code took them for.

`MergeTreeLeaderElection::parseLeaseContent` caught every exception and reported a parse error, and
the heartbeat takes a lease with a parse error over at once, without waiting for it to expire.
Reading the strings of a valid lease allocates, so a memory limit hit there was taken for a
corrupted lease: a follower tried to claim the lease of a healthy leader at once. The claim is a
conditional write against the version of the lease that was read, so it succeeds unless the leader
has renewed the lease in between, and then the leader keeps passing its own freshness checks until
its next heartbeat while both nodes accept writes. Only `JSONException`, the error of the parser,
is caught now. Anything else reaches the handler of the heartbeat, which keeps (or makes) the node
a follower and retries.

The failpoint `merge_tree_leader_election_fail_parsing_lease` fails the parsing once like such an
allocation, and `test_failure_to_read_lease_is_not_a_takeover` checks that the follower counts a
failed heartbeat, the lease stays with the leader, and the leader keeps renewing it. With the old
`catch (...)` the test fails at the first of these checks: the follower logs "Failed to parse lease
file content" and "expired or corrupted ..., trying to claim". In that run the claim itself was
rejected, because the leader had renewed the lease in between.

`MergeTreeData::Transaction::undoPublishedRenames` abandons the rest of its journal of published
parts once the node no longer owns the epoch of the publish. It moved the pointer out of every
entry in a loop and cleared the journal after the loop, so an exception in the middle (growing
the list of the abandoned parts, the log message) left entries with a moved-out pointer in the
journal. The transaction rollback calls the function again and dereferenced the null pointer.
The function also took an entry out of the journal before it compared the paths, which allocates,
so an exception there lost the entry, and the entries whose undo had failed were kept in a local
list that an exception dropped.

An entry now leaves the journal only in a step that cannot throw. Abandoning reserves the storage
first and then moves the pointer and removes the entry together (`abandonPublishedParts`, also
used by `abandonPublishedRenames`). The undo works on the entry in place and erases it once the
part is back at its source; the entries whose undo failed stay where they are, in the order of
the journal.

Review threads:
#101039 (comment)
#101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The pull request had a conflict with `master`, so its CI did not start.

Conflict in `src/Storages/MergeTree/MergeTreeDataWriter.cpp`: `master` moved the computation of the
name and of the temporary directory of a new part further down in `writeTempPartImpl`, and this
branch had renamed `MergeTreeData::getPostfixForTempInsertName` to `getPostfixForTempPartName` in
the lines that were moved. The block stays where `master` put it, and calls the renamed method.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
alexey-milovidov and others added 3 commits November 22, 2026 17:51
…it into another table

`MergeTreeData::cloneAndLoadDataPart` copies the files of a part of another table with `freeze`
or `freezeRemote`, which take the files by the name of the directory, one after another, and do
not go through the readers of the part. The source may be a part of a `leader_election` table
that this server only reads, e.g. in `ALTER TABLE dst ATTACH PARTITION ... FROM src`. If the
leader of `src` removed the part and reused its name for other data while the files were being
copied, the copy mixed the files of two parts, and it could still load: loading a part compares
the sizes of the files, not their contents. The destination then kept rows that never existed.

The storage of such a part is bound to its directory on the shared storage
(`IDataPartStorage::pinSharedStorageIdentity`), and an identity never comes back to a name. So
the directory of the source is checked once after everything is copied and before the copy
becomes a part: if the name still refers to it, every file was taken from it. Otherwise the
command fails with `DATA_PART_CHANGED_ON_SHARED_STORAGE`. The check is on the storage of the
source part, so it covers `freeze`, `freezeRemote`, and both `Full` and `Packed` sources. For a
part that is not bound it does nothing.

Only compiled locally: after the merge of `master` the local binary is out of date.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…s source is checked

`DETACH PART` / `DETACH PARTITION` copies the parts into `detached/` with `freeze`, which takes the
files of a part one after another by the name of its directory. Under `leader_election` the epoch
was checked before the copy of each part and nothing was checked after it. A leader that stalled in
the middle of a copy for longer than its lease could continue after another leader had removed the
part and reused its name for other data: the rest of the files came from the other part, and the
command succeeded with a directory in `detached/` that `ATTACH` accepts, because loading a part
compares the sizes of the files, not their contents.

Under `leader_election` the copy is now made in two steps. It is written under a `clone_` name,
which `ATTACH PARTITION` does not take. Then the directory of the source is checked (the storage of
the part is bound to it, and an identity never comes back to a name, so an unchanged directory
after the copy means that every file was taken from it), and the leadership epoch of the command is
checked again. Only then the copy is renamed to the name of a detached part. If a check fails, the
copy stays under the `clone_` name and the command fails: a node that may no longer be the leader
does not remove anything by name.

The other copies into `detached/` (`broken`, `covered-by-broken` and so on) already have names that
`ATTACH PARTITION` does not take. Tables without `leader_election` are not changed.

Review thread: #101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`Storage memory check` failed in this pull request: the scenario `07_many_parts.sql` (1000 parts)
used 128,040 bytes more than on `master`, 128 bytes per part.

The storage of a part (`DataPartStorageOnDiskBase`) got three members for the binding to its
directory on the shared storage (`pinSharedStorageIdentity`): a flag, a mutex and an optional
string, 72 bytes together. A storage is allocated for every part of every table, with or without
`leader_election`, and with the control block of the shared pointer the allocation went from 192
bytes, which is exactly a size class of the allocator, to 264 bytes, which is served from the 320
byte class: the measured 128 bytes per part.

The binding is now a single atomic pointer to an immutable identity, null for the storages that
are not bound. Reading it needs no lock. Binding a storage again publishes a new identity that
keeps the previous one alive until the storage is destroyed, for the threads that have just
loaded the pointer. `DataPartStorageOnDiskFull` is 176 bytes instead of 240 (168 without the
binding), and `DataPartStorageOnDiskPacked` is 600 instead of 664.

One pointer is still 8 bytes more than without the binding, where the allocation fills its size
class, so a part costs 32 bytes more than on `master` (the 224 byte class) instead of 128. That is 0.26% in the
failed scenario, below the 1% limit of the check.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=29e18188c9e2a75f36696ea8a270a64ef79fec3d&name_0=PR&name_1=Storage%20memory%20check
PR: #101039

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=9b975116cb61387dd409463fc09ddc8fdfc888e5&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Upgrade check (amd_release) found this error in the server log after the upgrade:

<Error> StoragePtr DB::create(const StorageFactory::Arguments &): Cannot parse projection p (SELECT count() GROUP BY 0) during server startup, skipping it.

The same message failed this check in four other pull requests in the last three days, according to the CI database:

This pull request does not change how projections are parsed. I did not find an open issue for it.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #128105.

The table comes from my test 04627_lwd_rebuild_normal_projection_no_where, which creates PROJECTION p (SELECT count() GROUP BY 0). With the default enable_positional_arguments_for_projections = 0 the 0 is a constant key. The test reached 26.10 with the backport #132956 (v26.10.8.34, published 2026-11-20), which matches when this started. upgrade_runner.sh enables the setting only for the upgraded server (compatibility.xml), so the upgraded server reads the 0 of the leftover table as a position and skips the projection.

#128105 writes the setting into users.d before the previous release starts, so both servers parse projections the same way. I checked on 26.10.2.103: with the setting on, this CREATE already fails with Positional argument number 0 is out of bounds, so no such table survives into the upgrade.

alexey-milovidov and others added 3 commits November 23, 2026 15:07
# Conflicts:
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
#	src/Storages/MergeTree/MergeTreeMarksLoader.cpp
`for (size_t i = n; i-- > 0;)` computes `0 - 1` in `size_t` on its last check. Master now
builds with UBSan's unsigned integer overflow check (#120906), which reports it and makes the
server die in the targeted stateless tests.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=fb1c7a976a34d6e3b45a92bdcdbe23bc07f95536&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#101039

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/checkDataPart.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=722ca7b09b5aec3db9e78c6136e992107ed36425&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

03634_autopr_output_bytes_estimation printed query_10 142097 362202 (the output estimate is off by more than the allowed ratio); all 97 reruns with the same randomized settings passed. It fails in other PRs too, about once a day since 2026-11-14 (CI DB, default.checks), after #131357 was closed. This PR does not touch aggregation or parallel replicas.

@alexey-milovidov

alexey-milovidov commented Nov 23, 2026 •

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=722ca7b09b5aec3db9e78c6136e992107ed36425&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

formats_columns_nullable query 88 (SELECT * FROM table_TabSeparatedWithNames_with_nullable_columns FORMAT Null, a File table read with max_threads = 1) is reported as a confirmed regression of +28% on arm_release. This PR changes nothing on that path (it is about MergeTree on shared object storage), and the same query was reported as a regression in #116757 on 2026-11-22 (master_head, 2/8). The shard is also labeled disk-almost-full.

Also, Upgrade check (amd_release) failed before running anything: Unable to request data from GH API: https://api.github.com/repos/ClickHouse/ClickHouse/releases/tags/v26.10.11.12-stable in download_release_packages (after the retries of get_gh_api): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=722ca7b09b5aec3db9e78c6136e992107ed36425&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

@groeneai

Copy link
Copy Markdown
Collaborator

The fix in progress is mine, #131697 (open, not reviewed yet).

It is the same query_10 under-estimate. Aggregator::estimateSizeOfCompressedState prices the 215-key uniqExact table from a sample of 100 states, and three states hold about 70% of the bytes, so the estimate depends on which states the sample picks. With the test's pinned prelude (serial merge, max_threads = 16), master gives 145K..150K on CI's test.hits in my runs, barely above the 2.5x bound of 144880.

Since #131358 pinned the serial merge (2026-11-13 21:11Z), CIDB has this diff in 8 PRs and 1 master run (a887b48c, 19:39Z today), always query_10: 141848..142149 in 7 of them, 134462 and 94442 in the other two.

#131697 prices a single-level table of at most 1000 states (1 MiB) from all of its states, so this estimate no longer depends on the sample: query_10 was 197.8K..204.6K in 60/60 runs across the serial merge, max_threads = 32 and the default merge.

@groeneai

Copy link
Copy Markdown
Collaborator
  1. formats_columns_nullable typo fix #88 (TabSeparatedWithNames over File): this entry is bimodal on ARM, about 0.41 s or about 0.52-0.56 s, and on the m8g hosts the PR jobs use, the mode follows the build, not the host. Both runs of this PR, on two different hosts, measured 0.55 s against 0.42-0.43 s. Today it flipped by 17% to 30% in 12 runs on 10 PRs, in both directions: most master baselines used between 08:00Z and 16:30Z were in the slow mode, so a PR build in the fast mode looked 18% to 27% faster against them (example), and four PR builds, this one included, landed in it. It is the same query as entry 0, which my Run the JSONEachRow and Avro queries of formats_columns_nullable on a quarter of the rows #132357 replaced with this verbatim copy on 2026-11-17, and entry 0 has flipped the same way since October. No fix exists yet; I'm investigating why this read path has two speed modes on ARM, and I'll follow up here with a PR or my findings.

  2. Upgrade check (amd_release): get_gh_api retries a 5xx with a flat 3 s sleep, so one read timeout and four 504 Gateway Time-out (20:45:51-20:46:13Z) used all five attempts in 22 s; the other seven runs of this job in that hour passed. The fix in progress is my Back off exponentially on transient GitHub API failures, in praktika #112974, which gives get_gh_api a capped exponential backoff on 5xx and timeouts. It merges cleanly and has been waiting for review since August.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Follow-up on formats_columns_nullable query 88: the CI rerun reported the same +28% on arm_release, so I measured it locally on aarch64. I built the merge base (0c4d2cc39271, the master this PR head merges) and the PR head (722ca7b09b5a) from the same build directory. Then I ran the query (SELECT * FROM file(<the test's 1M-row TSV>, TabSeparatedWithNames, <the test's structure>) FORMAT Null SETTINGS max_threads = 1) in clickhouse-local, 20 rounds alternating the two binaries, each run a fresh process:

  • merge base: median 0.336 s (min 0.329)
  • PR: median 0.324 s (min 0.317)

That is no slowdown (PR/base = 0.96). The other TSV queries of the test in the same CI run are within -2%..+4%. The same query measured -3.1% on the previous head 9b975116cb61, which has the same PR code apart from the master merges. The test itself notes that single-threaded text parsing "runs at a different speed in each server process on ARM". My conclusion is that the CI result is not caused by this PR.

The branch was 322 commits behind `master`. The merge has no conflicts.

The only failed check on the previous head was `Performance Comparison (arm_release, master_head, 1/6)`
with `formats_columns_nullable` query 88, which measures the same on a rerun of the same builds and
differs between builds:
#101039 (comment)
#101039 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator

Thanks for measuring it. The CI counters agree that this PR does not change the work, and they show where the +28% comes from: where the TabSeparatedWithNames parsing code landed in each CI binary.

  • Same work, slower instruction fetch. In this job's profiled run of typo fix #88 (prewarm rows of left-query-log.tsv and right-query-log.tsv in logs.tar.zst): 31.05G instructions in the PR build vs 31.06G in the reference, 13.09G vs 8.19G cycles, and 6.37G vs 1.75G front-end stall cycles, which is the whole difference. L1D and iTLB misses are equal, branch misses +2.4M.
  • The mode is fixed per binary, not per server process (the comment in the test is about the old single-threaded parse; this query parses in parallel). The perf servers start without ASLR, and the confirm restart reproduced +28.5% to +31.1% at all three stack placements. In the 81 arm perf jobs since 2026-11-22 that ran typo fix #88, 29 of 117 binaries were slow (0.39-0.45 cycles per instruction, 0.50-0.56 s) and 88 fast (0.25-0.30, 0.40-0.46 s), at the same instruction count, and no binary was seen in both modes. It switched on at master df93bed596, whose diff from the fast 3dfd20ff22 does not touch the TSV reader, the serializations or src/IO, and the official build of df93bed596 runs fast (0.41 s). A local build has its own layout, which is why your A/B shows no difference.
  • Only this parser flips: on the same binaries the CSVWithNames, JSONEachRow and ORC copies (more cmake fixes #89, FR: configurable set of supported languages #154, Common get_revision function. #90) keep the same cycles per instruction.

Neither this PR nor the test decides where the code lands, so I have no fix PR for this. The performance job leaves rows with the same work and a different code placement to the reviewer (ruling).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Stress test (arm_asan_ubsan, s3) failed on 5951709f91c4 with a UBSan report that comes from master, not from this pull request:

src/Functions/FunctionsConversion.cpp:3649:55: runtime error: unsigned integer overflow: 0 - 1 cannot be represented in type 'size_t'

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101039&sha=5951709f91c4026e871c25dd4144aca20aec6948&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

According to the CI database, the same report (STID 0993-9a84) has failed 32 checks on master since 2026-11-23 20:34 UTC and checks of nine other pull requests. This pull request does not change FunctionsConversion.cpp, and the failure appeared here only after master was merged into the branch.

The fix is in progress:

Related: #133910
Related: #133935

This branch was successfully deployed

1 active deployment
staging - docs — 5951709f Deployed Nov 24, 2026 by mintlify[bot]
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-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Leader election in non-replicated MergeTree tables on shared storage

5 participants