Skip to content

Do not report a concurrent backup when our own lock-file write committed - #116376

Merged
alexey-milovidov merged 27 commits into
masterfrom
fix-backup-lock-file-committed-write
Oct 12, 2026
Merged

alexey-milovidov merged 27 commits into
masterfrom
fix-backup-lock-file-committed-write

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

BACKUP claims its destination by writing its own UUID into the .lock file with a conditional write (writeFileIfNotExists, which is If-None-Match: * on S3). Such a write is not idempotent: a request that times out on the client can still have been applied, and its retry then fails the precondition against the object the first attempt wrote.

BackupImpl::createLockFile already re-read the lock file to disambiguate, but treated a contents match as proof of a concurrent writer and threw BACKUP_ALREADY_EXISTS, "A concurrent backup writing to the same destination detected". The lock contents identify a single attempt — open picks a fresh backup UUID for every retry, and a resumed attempt is continuing the very attempt that wrote them — so finding them in the destination means our own write went through and the lock is ours. This commit treats it as taken instead of failing an uncontended destination, and collapses the CLICKHOUSE_CLOUD special case that only existed to let a resumed attempt fall through.

The new backup_fail_lock_file_write_after_commit fail point throws right after the lock write commits, which reproduces the S3 shape deterministically. Without the fix the new test fails with the same createLockFile stack as the CI report below; with it the backup succeeds, restores, and a second backup to the same destination is still rejected.

Review follow-up: lock_file_contents are only proof of ownership if they are unique to a single attempt, and backup_uuid — although documented internal-only — was still accepted from user SETTINGS. An explicit backup_uuid on a non-internal query is now rejected with ACCESS_DENIED, the same way as the internal setting, so the contents cannot be spoofed by a second BACKUP reusing the UUID of one in progress.

Second review follow-up: once createLockFile has read the lock back and found this attempt's own contents in it, open no longer verifies it a second time. That immediate re-check could not make the ownership any more certain, but it could fail on its own, aborting an uncontended backup and leaving behind a lock that removeLockFile refuses to remove, because removal needs a readable lock too. The new fail point backup_fail_lock_file_check_after_creation fails exactly that post-creation verification, and 05052_backup_lock_file_verified_once.sh covers "write committed, first read matches, second verification read fails".

Archive follow-up: the post-creation verification is still skipped only for non-archive destinations. For an archive, openArchive truncates the archive before any checked write, and a lock created exclusively by File(...) can be written over through Disk(...) in rewrite mode, so open re-checks the lock before opening the archive (05359_backup_lock_file_archive_rechecked).

Seen on master, where a single BACKUP TABLE data TO S3(...) in 02803_backup_tmp_files failed after the PutObject of .lock timed out and was retried:

AWSClient: Failed to make request to: http://localhost:11111/test/backups/.../.lock:
           will be retried, Poco::TimeoutException
AWSClient: Retrying S3 request to: .../.lock, aws sdk attempt: 2, clickhouse attempt: 1, kind: Write
WriteBufferFromS3: S3Exception name PreconditionFailed ... key backups/.../.lock, object size 36
BackupsWorker: Failed to make backup ...: A concurrent backup writing to the same destination ... detected

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=20743c1ad6e66a06721db9130f8414abfa7469ff&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

Related: #115387

Review follow-up (2026-09-01). Taking the lock back on matching contents is only sound when the lock
write cannot replace an existing lock, so it is now gated on IBackupWriter::supportsAtomicCreateIfNotExists.
BackupWriterS3 and BackupWriterAzureBlobStorage write with If-None-Match: * and answer true;
BackupWriterFile now creates the lock with O_EXCL, which is atomic and non-destructive, and answers
true as well. Disk, Memory and the rest keep the overwriting writeFile fallback, answer false,
and keep reporting the destination as taken, so a backup that clobbered a foreign lock cannot take the
destination over. The new test 05055_backup_lock_file_non_atomic_backend pins that fail-closed
behaviour for Disk(...).

Review follow-up (2026-09-17). The cleanup of a failed open no longer depends on the backend. On
Disk/Memory the lock write runs in rewrite mode, so a backup B can write its .lock over the lock of
a backup A that got there first; a previous follow-up left that lock in place after a late write error,
so as not to unfence A. But A has already lost its lock the moment it was written over and fails at its
next checkLockFile either way, so the lock B left behind fenced a destination nobody owned any more,
against every later BACKUP, until it was removed by hand. After a failed lock write
created_own_lock_file is now set as on master, and removeLockFile re-reads the lock and removes it
only while it still holds this attempt's contents. B is still rejected with BACKUP_ALREADY_EXISTS on such
backends: the ownership proof keeps gating own_write_committed. New pause fail point
backup_pause_after_lock_file_creation; 05055 now asserts the next backup to the same destination
goes through, and 05227_backup_lock_file_overwritten_owner_no_orphan covers the contended ordering (B
passes the existence check and pauses, A writes and verifies its lock and pauses, B writes over it and
fails, A fails because its lock is gone, a third backup C completes).

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed BACKUP failing with A concurrent backup writing to the same destination ... detected when nothing else was writing there. The lock file is claimed with a conditional write, and a retry of a request that had already been applied made the backup mistake its own lock for someone else's.


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

Version info

  • Merged into: 26.10.1.2168-master (included in 26.10 and later)

`BACKUP` claims its destination by writing its own UUID into the `.lock` file
with a conditional write (`writeFileIfNotExists`, which is `If-None-Match: *`
on S3). Such a write is not idempotent: a request that times out on the client
can still have been applied, and its retry then fails the precondition against
the object the first attempt wrote.

`createLockFile` already re-read the lock file to disambiguate, but treated a
contents *match* as proof of a concurrent writer and threw
`BACKUP_ALREADY_EXISTS`, "A concurrent backup writing to the same destination
detected". The lock contents identify a single attempt - `open` picks a fresh
backup UUID for every retry, and a resumed attempt is continuing the very
attempt that wrote them - so finding them in the destination means our write
went through and the lock is ours. Treat it as taken instead of failing an
uncontended destination.

This also collapses the `CLICKHOUSE_CLOUD` special case, which only existed to
let a resumed attempt fall through; now both paths do.

The new `backup_fail_lock_file_write_after_commit` fail point throws right
after the lock write commits, which reproduces the S3 shape deterministically.

Seen on master, where a single `BACKUP TABLE data TO S3(...)` in
`02803_backup_tmp_files` failed after the `PutObject` of `.lock` timed out and
was retried:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=20743c1ad6e66a06721db9130f8414abfa7469ff&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09337f7]

Summary: ✅


AI Review

Summary

I reviewed the current PR diff, the current code on the touched paths, all prior inline review threads, and the top-level PR discussion. On the reviewed OSS code, I do not see any remaining correctness or safety issue in the lock-file handling changes: the earlier ownership, cleanup, exclusive-create, and archive-truncation races raised in prior threads are addressed in the current BackupImpl / writer capability logic and are covered by focused stateless tests.

Missing context / blind spots
  • ⚠️ The CLICKHOUSE_CLOUD && USE_SSL path is only partially reviewable from this checkout: BackupImpl references BackupEncryptionSidecar, but that implementation is not present here. I therefore could not independently verify whether the new lock_file_verified_on_create shortcut leaves any cloud-only pre-check destination write on the non-archive path. Seeing the sidecar implementation would close that gap.
  • ⚠️ The cloud resumable path is only partially reviewable from this checkout as well: BackupImpl contains params.resume handling and references BackupResumer, but the corresponding implementation is not present here. The visible changes around resumed ownership look consistent, but I could not validate the full end-to-end resume flow locally.
Final Verdict

✅ No new inline findings for the reviewed OSS diff.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
Comment thread src/Backups/BackupImpl.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09337f72b with master 5fbccc970 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 73c48370f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

19 translation units recompiled, 59 s compile time in total, 19 of them have a recent master baseline.

Job report

`backup_uuid` is documented internal-only, but `BackupsWorker` only auto-generated it
when absent and rejected only `internal`. With the new "matching lock contents means the
lock is ours" path in `createLockFile`, a second `BACKUP ... SETTINGS backup_uuid =
<victim UUID>` could spoof the live `.lock` contents and proceed into a destination another
backup owns instead of getting `BACKUP_ALREADY_EXISTS`. Reject an explicit `backup_uuid`
the same way as `internal`: only queries initiated by another query may carry it.

#116376 (comment)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two failures in Stateless tests (amd_debug, parallel) are unrelated to this PR (which only touches Backups and a fail point):

  • 04612_forwarded_for_invalid_address failed with CANNOT_SCHEDULE_TASK: "Cannot schedule a task: no free thread (timeout=60000000) (threads=3, jobs=3)" while reading system.text_log; the CI harness re-ran it 33 times with the same randomized settings and all passed, labeling it transient.
  • 01119_session_log has 50 failures across PRs in the last 60 days in CIDB — a long-standing flaky test with no open tracking issue.

@groeneai, investigate these failures and provide fixes in separate PRs. If fixes are already in progress, link them here. I merged current master into the branch, so the next CI run will re-check both.

Comment thread src/Backups/BackupImpl.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

04612_forwarded_for_invalid_address (Code 439)

I root-caused this exact signature for you on PR 112803: #112803 (comment). No fixing PR exists, ours or external, so I am opening one.

MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes builds a private pool of min(num_streams, parts) threads and schedules one job per part with scheduleOrThrow. Each job's index analysis then blocks inside MergeTreeMarksLoader on a future served by the server-wide marks pool (load_marks_threadpool_pool_size, default 50). When that pool has a backlog, every slot of the private pool is held by a thread blocked downstream, so the next part's scheduleOrThrow waits out lock_acquire_timeout and throws 439. In the run I analysed the marks pool was pinned at 50/50 with a draining backlog, while the global pool stayed flat with spare capacity.

That is not the case the comment above scheduleOrThrow guards against: it is there to avoid saturating max_thread_pool_size, but here the global pool has room and the private workers are merely blocked. I plan to make the timed-out schedule fall back to running that part inline on the calling thread, which is the path this function already takes when num_threads <= 1, instead of rejecting a valid query after 60 s. No additional global-pool thread is requested, so the anti-deadlock property the comment cares about is preserved. I will build a deterministic repro first and link the PR here.

Breadth for the exact signature over 120 days: 4 incidents, 4 unrelated PRs, 0 true-master rows, 0 release-branch rows.

01119_session_log

Neither half of this is a session_log defect.

The row in the report you linked is the same incident as 04612, not an independent failure: Code 439, same job, same instant, same 60 s timeout, raised on select ... from system.session_log. One thread-pool incident with two victims.

The 60-day history splits as follows. 45 of the 50 rows are PR 110144's own pre-merge regression (TCP_Interserver auth_type becoming NO_PASSWORD), confined to that single branch between 08-15 and 08-18 and fixed inside it before it merged on 08-26. 4 rows are the fleet-wide Code: 241 event of 2026-07-15, which produced 13,299 failing rows across 6,320 distinct tests and 159 PRs on that one day. The remaining row is the 439 above. On true master over the last 30 days the test is 0 failures against 11,379 passes across 1,051 commits, the latest earlier today.

So there is no residual flakiness here to fix, and I am not opening a PR or a tracking issue for it. If you would rather also have the 439 case covered by a test-side pin, tell me and I will add it.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR for the 04612_forwarded_for_invalid_address failure: #116822

Root cause: filterPartsByPrimaryKeyAndSkipIndexes builds its private pool with the four-argument ThreadPool constructor, which sets queue_size equal to max_threads, i.e. to min(num_streams, parts), and then submits one job per part. With more parts than streams the loop submits more jobs than its own queue can hold, so the submitter blocks on a full queue rather than on threads, waits out lock_acquire_timeout, and reports no free thread. The in-flight jobs are slow because index analysis blocks on the server-wide marks pool.

Correcting what I wrote earlier in this thread: the shipped mechanism is removing that self-inflicted queue bound, not the inline fallback I floated. The fallback would still pay the full timeout per part and would do nothing when the marks pool is starved.

The repro is deterministic. With an injected per-part delay the new test fails 20 out of 20 runs with the exact error above, and passes 20 out of 20 with the change.

…ready verified it

`open` called `checkLockFile(true)` right after `createLockFile`, including on the path where
`createLockFile` had already read the lock back and found this attempt's own contents in it. That
second read adds nothing to the proof of ownership and can fail on its own, which aborts an
uncontended backup and leaves behind a lock that `removeLockFile` cannot remove, because it bails
out when the lock is unreadable.

`createLockFile` now records that it verified the lock, and `open` skips the immediate re-check in
that case. New failpoint `backup_fail_lock_file_check_after_creation` and test
`05046_backup_lock_file_verified_once.sh` cover "write committed, first read matches, second
verification read fails".
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review's "Changes requested" verdict (the only remaining unresolved thread) and merged current master.

The two stress failures on the previous head 995cc568 are unrelated to this PR, which touches only Backups and fail points:

@groeneai, investigate https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116376&sha=995cc56853a0e872374d2e16b778a2358c94e801&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 and provide a fix for the Not-ready Set failure in a separate PR. If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The Not-ready Set failure is the object-storage _path filtering route, so the fix already in progress for it is your own #112968.

fatal.log on 995cc568, thread 5898, globalNotIn:

src/Functions/in.cpp:128                                       FunctionIn::executeImpl
src/Storages/VirtualColumnUtils.cpp:163                        filterBlockWithExpression
src/Storages/VirtualColumnUtils.cpp:417                        getFilterByPathAndFileIndexes
src/Storages/VirtualColumnUtils.h:135                          filterByPathOrFile<String>
src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:555   createFileIterator
src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp:179      createIterator

Fuzzed query: SELECT count() FROM azureBlobStorage(..., '/slashed.csv', ...) WHERE _path GLOBAL NOT IN (SELECT _path FROM azureBlobStorage(..., '/slashed.csv', 'CSV', 'auto', 'x UInt64')) LIMIT 960. The key has no globs, so this is the explicit-keys branch, and line 555 of the tree CI built (7fc428ef) is the eager buildSetsForDAG plus filterByPathOrFile pair that #112968 replaces with a filter deferred into KeysIterator when a set is reported not ready. ReadFromObjectStorageStep::applyFilters leaves globalNotIn sets unbuilt on purpose, so that call runs against an unbuilt set for every such query today.

One detail worth knowing: the carrier is azureBlobStorage, not s3, which is the same shared createFileIterator, while 04669_object_storage_path_filter_global_in.sql in #112968 exercises s3 only.

So I am not opening a separate PR for this one. The same route produced both Not-ready Set reds I looked at on #115680 yesterday. Until #112968 is merged the mutation can still appear on the fresh run here, and I will follow up if it comes back with a different frame chain.

Comment thread src/Backups/BackupImpl.cpp Resolved
…l create

`createLockFile` treated a lock file holding this attempt's own contents as proof that this attempt
wrote it. That holds only when the lock write cannot replace an existing lock. `IBackupWriter::writeFileIfNotExists`
falls back to `writeFile` for `Disk` and `Memory`, which write in rewrite mode, so a second backup could
clobber the lock of the backup that got to the destination first, read its own contents back, and take
over a destination that was already taken.

Two changes:

- `IBackupWriter::supportsAtomicCreateIfNotExists` states whether `writeFileIfNotExists` is a real
  conditional create. `BackupWriterS3` and `BackupWriterAzureBlobStorage` write with `If-None-Match: *`,
  so they answer `true`. `BackupWriterFile` now creates the file with `O_EXCL`, which is atomic and
  non-destructive, and answers `true` as well. Everything else keeps the overwriting fallback and
  answers `false`.
- The "the write committed" branch in `createLockFile` is active only for writers that answer `true`.
  On the others the destination stays reported as taken, which is the safe answer.

Tests: `05043_backup_lock_file_committed_write` and `05052_backup_lock_file_verified_once` now back up
to a `File(...)` destination, whose lock write is a real conditional create. The new
`05055_backup_lock_file_non_atomic_backend` pins the fail-closed behaviour of `Disk(...)`: the same
post-commit write failure reports `BACKUP_ALREADY_EXISTS`, and the lock is still cleaned up, so the
next backup to the same destination goes through.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review's "Changes requested" verdict (the only unresolved thread, discussion_r3875759824's successor) and merged current master (the branch was ~1045 commits behind).

The lock-ownership rule is now gated on the writer really having conditional-create semantics: IBackupWriter::supportsAtomicCreateIfNotExists is true for S3/AzureBlobStorage (If-None-Match: *) and for File, whose writeFileIfNotExists now creates the lock with O_EXCL. Disk, Memory and the rest keep the overwriting fallback and keep reporting the destination as taken, so an attempt that clobbered a foreign lock cannot take the destination over. New test 05055_backup_lock_file_non_atomic_backend pins that; 05043 and 05052 moved to a File(...) destination. All verified locally, together with the File(...)-based backup tests 02973, 03276, 03784, 04149, 04801.

The single red on the previous head 7be3f437 was Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) failing at the job level with Timeout and no test results, which is unrelated to a change confined to Backups and fail points; the fresh run on the merged head re-evaluates it.

Comment thread src/Backups/BackupImpl.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-backup Backup/restore infrastructure and backup formats. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 9, 2026 18:32
… non-atomic backend

After a failed lock write, `createLockFile` marked the lock as this attempt's own regardless of
the backend, so `tryRemoveOwnLockFile` removed a `.lock` holding the attempt's contents on the
way out of a failed `open`. On a backend without conditional create (`Disk`, `Memory`) the write
runs in rewrite mode, so such a lock may have been written over the lock of the backup that got
to the destination first; removing it unfenced that backup while it was still writing, and a
third backup could then take the destination.

Now `created_own_lock_file` is set on the failure path only when
`IBackupWriter::supportsAtomicCreateIfNotExists` holds, the same proof the "our write committed"
continuation relies on. Elsewhere the lock stays and the destination remains fenced.

Test `05055_backup_lock_file_non_atomic_backend` now asserts the fence survives the failed
attempt; new test `05153_backup_lock_file_cleanup_keeps_foreign_fence` covers the contended
case: a paused backup A, a backup B failing after its lock write committed, and a backup C that
must still be rejected before A resumes and completes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Backups/BackupImpl.cpp Resolved
alexey-milovidov and others added 2 commits September 17, 2026 15:22
… lock back

On `Disk`/`Memory` the lock write runs in rewrite mode, so a backup B can write its
`.lock` over the lock of a backup A that got to the destination first. The previous
follow-up left the lock in place when B then hit a late write error, so as not to unfence
A -- but A has already lost its lock the moment it was written over, and it fails at its
next `checkLockFile` whether the lock still holds B's contents or nothing at all. The lock
B left behind therefore fenced a destination nobody owned any more, against every later
`BACKUP`, until somebody removed it by hand.

`createLockFile` now sets `created_own_lock_file` on the failure path regardless of
`supportsAtomicCreateIfNotExists`, as `master` does; `removeLockFile` still re-reads the
lock and removes it only while it holds this attempt's contents. The ownership proof still
gates `own_write_committed`, so B is still rejected with `BACKUP_ALREADY_EXISTS` on such
backends.

New pause fail point `backup_pause_after_lock_file_creation`, right after `open` has
created and verified the lock. `05055_backup_lock_file_non_atomic_backend` now asserts the
next backup to the same destination goes through, and the new
`05227_backup_lock_file_overwritten_owner_no_orphan` covers the contended ordering from the
review: B passes the existence check and pauses, A writes and verifies its lock and pauses,
B writes over it and fails, A fails because its lock is gone, and a third backup C
completes. `05153_backup_lock_file_cleanup_keeps_foreign_fence` pinned the orphaned lock
and is removed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@jkartseva jkartseva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Addresses review: `05052_backup_lock_file_verified_once` only covers the late-failure
recovery path. The new test enables only `backup_fail_lock_file_check_after_creation` and
proves that a `File(...)` backup, whose lock is created with `O_EXCL`, skips the
verification read after a normal lock creation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Backups/BackupImpl.cpp Resolved
alexey-milovidov and others added 2 commits October 8, 2026 13:05
…reate

`BackupWriterFile::writeFileIfNotExists` creates the `.lock` with `O_EXCL` already
when it opens the file, before the contents are written. If the write fails
afterwards (`ENOSPC`, `EIO`, a failed `finalize`), the file left behind is this
attempt's own, but `createLockFile` treated it as a concurrent backup's and threw
`BACKUP_ALREADY_EXISTS`, and `removeLockFile` could not take it back because its
contents did not match. Carry an explicit "created exclusively on open" bit into
the failure path, remove the lock there, and rethrow the original write error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116376&sha=3b039aedffdb8305aac0bc243b48dabb8cd9ec48&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 (Logical error: Coordination mode mismatch for stream test_7.t_mt_index_rp: got Default, expected WithOrder, STID 6117-68e9) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR: CIDB shows it on more than 10 other PRs and on master in the last 30 days, and #106039 was closed but the failure still happens.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Investigated. This run's fatal.log names SELECT id, department FROM t_mt_index_rp ORDER BY id from 04891_mergetree_index_respects_row_policy (log_comment), with serialize_query_plan = 1 and parallel replicas over a non-replicated MergeTree. It is the row-policy route of #112891, the same one as on #118536: the initiator applies the policy, which fixes the first sorting key column, so it reads in order and creates the coordinator as WithOrder; the replicas plan the shipped serialized plan without the policy and announce Default. #106039 is the CI matcher for this message on any stream; its fix #114916 covered a different route.

The fix is in progress: #114955 (mine, open). It applies the policy on the executing server, so all replicas plan the same read. Its current head is green and mergeable and waits for review (requested from @ davenger and @ yariks5s). It is not merged, so this run's tree could not contain it.

CIDB, last 30 days, this message: 14 Stress runs on 13 PRs and master.

Since 2026-09-27 only t_mt_index_rp remains. The same route also aborts with unknown stream on t_mt_index_rp (STID 5217-505b, 5217-5b3d): 47 more Stress runs in those 30 days, one of them on master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai — noted that the Coordination mode mismatch failure is tracked by #114955.

I merged current master again (015a00a, the branch was 429 commits behind); the merged tree builds and 05043, 05045, 05052, 05055, 05227, 05325, 05339 pass locally. The two reds on the previous head 80337e1c are unrelated to this PR, which touches only Backups and fail points:

@groeneai, investigate the timeseries_group_to_sampling_key perf instability: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116376&sha=80337e1c215f1a92c2e16388312d22bc54b6e444&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

This is the same report you sent me on #98708 (#98708 (comment)), so one investigation covers both. The two builds ran against the same master c9d4edb564 six minutes apart and both were slow on query 0: 112.4 -> 139.2 ms here, 112.6 -> 142.9 ms there. The other 8 PR builds against that master stayed within 4.2%. In this run's CPU stacks most of the extra time is in arrayElement reading the constant groups array (143 -> 203 samples), not in timeSeriesGroupToSamplingKey itself.

There is no fix PR yet. I'll post its link here when it opens.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

The fix is open: #124809 (test-only). The slowdown was in the benchmark's constant-array lookup groups[number % 4096 + 1], not in this PR; the query now passes the group ids directly.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai: the timeseries_group_to_sampling_key perf noise is addressed by #124809.

The only red on the previous head 015a00aa, Build (arm_fuzzers), was serialization_dynamic_fuzzer.cpp:125: no member named object_and_dynamic_read_statistics, a master breakage unrelated to this PR, already fixed on master by d22e861333a ("Fix fuzzers build"). I merged current master (e466938), which pulls that fix in; the merged tree builds and 05043, 05045, 05052, 05055, 05227, 05325, 05339 pass locally.

Comment thread src/Backups/BackupImpl.cpp Resolved
Bartok9 pushed a commit to Bartok9/ClickHouse that referenced this pull request Oct 9, 2026
The benchmark looked each row's group up in a constant array,
`groups[number % 4096 + 1]`. About half of its CPU went to that lookup
(`arrayElement` over a constant array copies row by row through a virtual
`insertFrom`), not to the sampling-key code the test measures. On arm some
builds run that loop about twice as slow in every server process: in the
job profiles of the slow runs on ClickHouse#98708, ClickHouse#116376, ClickHouse#117754, ClickHouse#123545 and
ClickHouse#123188 only that frame grew (x1.4 to x2.2) while every other frame stayed
flat, so the query moved 20-27% and the confirmation restart reproduced it.

The per-query tags collector numbers groups 0, 1, 2, ... with 0 reserved for
the empty tag set (`ContextTimeSeriesTagsCollector.h`), so the 4096 groups
the subquery creates are 1..4096 and the query can pass
`number % length(groups) + 1` directly. `length(groups)` keeps the scalar
subquery referenced: without it the analyzer drops the subquery, no group is
registered and the function throws `Group 1 is out of bounds`.

Checked on x86 with an official master build: the same keys over the 20M
rows (`sum` and `groupBitXor` equal, 0 rows differ), 84 -> 52 ms, and the
per-process medians of 24 processes span 79-91 ms before and 52-53 ms after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 10, 2026 06:57
… an `O_EXCL` create

`File(...)` and `Disk(...)` can address the same local directory, and the
`Disk` writer opens the lock in rewrite mode. So after the `O_EXCL` open of
`BackupWriterFile::writeFileIfNotExists` succeeds and the content write
fails, the file may by then hold another backup's lock. Remove it only while
it still holds a prefix of this attempt's own contents (nothing, or a short
write); foreign contents or an unreadable lock stay on the fail-closed path
and are reported as a concurrent backup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Backups/BackupImpl.cpp Resolved
alexey-milovidov and others added 2 commits October 11, 2026 00:53
`openArchive` truncates the archive with `writeFile` right away, before any
checked write. A lock created exclusively by `File(...)` can still be
written over through `Disk(...)`, whose writer opens `.lock` in rewrite
mode, so skipping the immediate `checkLockFile` let a backup that had lost
its lock truncate the archive of the backup that took it. Keep the check
for archive destinations; the new test `05359_backup_lock_file_archive_rechecked`
pins it and checks that the failed attempt takes its lock back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 1af17caa-9082-4392-bec5-cd379064e4b1
  • MIRAI run: 20f16161-46a9-49d0-bd52-0d0fcc7a651a
  • PR check IDs:
    • clickbench_941937_1791758790
    • clickbench_941943_1791758791
    • clickbench_941949_1791758790
    • tpch_adapted_1_official_941961_1791758790
    • tpch_adapted_1_official_941995_1791758791
    • tpch_adapted_1_official_942009_1791758791

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into master with commit b469f4c Oct 12, 2026
164 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-backup-lock-file-committed-write branch October 12, 2026 02:25
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-backup Backup/restore infrastructure and backup formats. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants