Skip to content

Cherry pick #110292 to 26.3: Refresh S3Queue bucket locks so the TTL cleanup does not remove them mid-processing - #112059

Merged
robot-clickhouse-ci-1 merged 24 commits into
backport/26.3/110292from
cherrypick/26.3/110292
Jul 27, 2026
Merged

robot-clickhouse-ci-1 merged 24 commits into
backport/26.3/110292from
cherrypick/26.3/110292

Conversation

@robot-ch-test-poll3

Copy link
Copy Markdown
Contributor

Original pull-request #110292

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

kssenii and others added 23 commits July 13, 2026 18:38
…oViews by it

Change the default of `persistent_processing_node_ttl_seconds` from 6 hours
to 24 hours. Log elapsed time of the whole `streamToViews` execution and stop
starting new iterations once elapsed time reaches half of the TTL, so that
the execution finishes before processing nodes and the bucket lock could be
cleaned up as abandoned.

Co-Authored-By: Claude Fable 5 <[email protected]>
When streamToViews breaks out of the loop because elapsed time reached
half of persistent_processing_node_ttl_seconds, drop the shared file
iterator instead of keeping it cached. releaseFinishedBuckets keeps the
last non-finished bucket holder, so a cached iterator would keep holding
the bucket lock with a stale mtime - the exact situation the early stop
is meant to avoid. Dropping the iterator releases all held buckets (via
BucketHolder destructors) once the last streaming task stops using it,
and the next execution re-acquires bucket locks with a fresh iterator.

Co-Authored-By: Claude Fable 5 <[email protected]>
…user

Add a force_release_unfinished flag to releaseFinishedBuckets which allows
to release also the last non-finished bucket holder. When streamToViews
stops on reaching half of persistent_processing_node_ttl_seconds and no
other streaming task uses the shared file iterator (checked via use_count
under streaming_mutex, which prevents new copies), release all buckets
explicitly and keep the iterator cached, so the next execution reuses its
listing state and re-acquires buckets with fresh lock nodes. If other
streaming tasks still use the iterator (parallel_inserts), force release
is not safe - they can have in-flight files from the non-finished bucket -
so keep dropping the shared iterator and let the buckets be released when
the last task stops using it.

Co-Authored-By: Claude Fable 5 <[email protected]>
The previous stop condition measured each streamToViews execution
separately, but bucket locks are held by the shared file iterator, which
outlives a single execution: with parallel_inserts, a task which adopted
the iterator just before another task dropped it could keep streaming for
another half TTL on its own clock, so in the worst case the bucket lock
hold time approached the full persistent_processing_node_ttl_seconds and
cleanup could remove a lock still in use.

Base the stop condition on the iterator age instead (no bucket lock can
be held longer than the iterator which acquired it), so all streaming
tasks sharing the iterator stop within their current iteration once the
age reaches half of the TTL. The task which stops last (use_count == 1
after the shared pointer is dropped, when no new user can appear) force
releases all buckets explicitly; BucketHolder destructors remain as
a backstop in case of a race between the last two users.

Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the file iterator age clock with the age of the oldest currently
held bucket lock (a stopwatch on BucketHolder started at acquisition),
which is the resource the TTL cleanup actually applies to. With no locks
held (e.g. unordered mode) the check never fires, so the iterator is not
pointlessly dropped and re-listed every half TTL, and a lock acquired
late in the iterator lifetime gets its full half-TTL of work.

Since releasing the locks resets this clock, the sole-user case no longer
needs to stop streaming at all: release the buckets under streaming_mutex
(so no other task can adopt the iterator mid-release) and continue with
the same iterator, re-acquiring locks as needed. With concurrent streaming
tasks the behavior is as before: drop the shared iterator, all tasks stop
on the shared clock, the last one releases the buckets.

Co-Authored-By: Claude Fable 5 <[email protected]>
Instead of stopping streaming and releasing bucket locks before
persistent_processing_node_ttl_seconds passes, keep the locks alive from
inside the file iterator: BucketHolder::refresh rewrites the lock node
data with a version-guarded set, updating its mtime, and the iterator
refreshes every held lock older than half of the TTL on each iterator
step. The TTL cleanup already removes nodes with a version check, so
a refreshed lock cannot be removed by a cleanup which read a stale stat,
and the TTL now only reaps locks of genuinely dead servers - its original
purpose.

This removes the whole stop/release machinery from streamToViews: the
iterator drop, the use_count checks and the force_release_unfinished flag
of releaseFinishedBuckets. Streaming is never interrupted, and lock
refresh works during long iterations too, since it happens on every
iterator step rather than between them.

Co-Authored-By: Claude Fable 5 <[email protected]>
If the lock node is gone or owned by another server when refreshing,
throw LOGICAL_ERROR instead of logging a warning, failing the current
streaming execution. The holder is marked released first, so that
release() and the destructor do not remove someone else's lock node.

Co-Authored-By: Claude Fable 5 <[email protected]>
Scanning bucket holders on every iterator step is too often. Scan them
at most once per quarter of persistent_processing_node_ttl_seconds, so
each lock is still refreshed before 3/4 of the TTL passes.

Co-Authored-By: Claude Fable 5 <[email protected]>
A commit can take a long time (Keeper retries with backoff), during
which no thread calls `next` on the file iterator, so bucket locks
could age past the TTL and be removed as abandoned by the cleanup.
Refresh the locks right after each commit in `streamToViews`, so that
the locks which survive into the next batch enter it with most of the
TTL budget left.

Also consolidate the refresh into a single `refreshExpiringBucketLocks`
method with a single threshold (a quarter of the TTL) and drop the scan
throttle: the scan itself is an in-memory walk over a handful of
holders, and Keeper is only touched for locks that actually aged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Previously, when BucketHolder::refresh detected lost lock ownership,
the released holder stayed in bucket_holders and the iterator stayed
cached: the iterator kept draining keys cached for a bucket possibly
owned by another server, with no ownership check on the hot path in
release builds.

Lost bucket lock ownership must never happen: it means the lock was
removed as abandoned by the TTL cleanup and possibly acquired by
another server, which can lead to duplicates on the client side. If it
happens, either persistent_processing_node_ttl_seconds is too small
for the workload or there is a bug. Make it visible: a logical error
(aborting debug and sanitizer builds) and the new
ObjectStorageQueueBucketLockLostOwnership profile event, whether the
loss is detected by refresh or at release time.

In release builds fail closed and recover: the file iterator sets
bucket_lock_refresh_failed (from both refresh and release detection)
and rethrows, after which no thread drains cached keys (threads
observing the flag stop the iterator gracefully; the flag is checked
under the iterator mutex to close the race with a thread already
waiting on it), isFinished returns true, and the next streaming
execution creates a fresh iterator, re-listing and re-acquiring bucket
locks. In-flight files are marked failed and retried under
loading_retries.

To never remove a lock node re-created by another server, release
removes the node with a version check (the holder tracks the version:
0 at creation, then from the set response of every refresh), still a
single Keeper request in the common path. ZNONODE or ZBADVERSION on
the first attempt is the ownership loss; on ZBADVERSION the node is
re-read first, because the tracked version is stale if a refresh
succeeded without confirmation; on retries the ownership is checked
with a read, because a re-created node could collide with a
never-refreshed lock on version 0.

Add a test provoking the ownership loss: it steals a held bucket lock
mid-processing via Keeper (an atomic set of foreign owner data), checks
the loss is detected exactly once (log and profile event), and checks
streaming recovers with a fresh file iterator, processing all the
files. The test is skipped in debug and sanitizer builds, which abort
on the provoked logical error.

Addresses: #110292 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
…h scan

A thread which read a stale false before taking the mutex could call
refresh on the released holder of the just lost lock, tripping the
released assert in debug builds (unreachable today only because the
detecting thread aborts first on the logical error). Now every gate
reading bucket_lock_refresh_failed is checked under the iterator
mutex, which the flag is written under; the remaining lock-free read
in isFinished is a harmless early exit, since the flag is monotonic.

Also shorten the comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
ObjectStorageQueueBucketLockRefreshes complements
ObjectStorageQueueBucketLockLostOwnership: together they show whether
the refresh cadence is healthy relative to
persistent_processing_node_ttl_seconds.

Co-Authored-By: Claude Fable 5 <[email protected]>
uniqExact on the destination table only proves at-least-once
processing. Prove exactly-once commits via the s3queue log: every file
must be set as processed exactly once. A duplicates check on the
destination table itself would be flaky by design: a file in flight
when the batch fails can legitimately re-insert an already inserted
row when it is retried.

Addresses: #110292 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
…aned

The version check alone cannot prove ownership when the holder was not
refreshed for longer than persistent_processing_node_ttl_seconds: the
cleanup could have removed the lock and another server could have
re-created it colliding on the version (e.g. both at the creation
version 0), so the versioned remove would delete the new owner's lock
and return ZOK instead of surfacing the lost ownership. Now release
checks ownership with a read first in that case, keeping the common
path (age below the TTL, when the cleanup cannot have touched the
node) at a single Keeper request.

Add a test for the release-time detection. It cannot be provoked with
a single stolen lock: every release site is preceded or accompanied by
a refresh scan which detects the loss first. Steal two bucket locks
while all the processing threads sleep inside the pipeline for longer
than the TTL (where nothing refreshes the locks): the refresh scan
detects the first one and throws immediately, invalidating the
iterator, so the second one is only discovered by release when the
invalidated iterator holders are destroyed. The test checks one
detection of each kind in the log, the profile event counting both,
and full exactly-once recovery afterwards. The recovery checks poll
the s3queue log instead of reading it once, because a file row reaches
the destination table before the file is committed as processed.

Also clarify that the after-commit refresh of bucket locks applies to
streaming, where the file iterator outlives the batch and sits idle
between batches. A direct select refreshes on every next call and its
iterator does not outlive the query.

Addresses: #110292 (comment)
Related: #110292 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
bucket_lock_refresh_failed is set on both failed refresh and failed
release, so rename it to iterator_invalidated, which describes the
state instead of one of the triggers and pairs with iterator_finished.

Restore the first-attempt debug assert on bucket lock ownership in
release, lost in the rework to the version-checked remove.

Also shorten a few comments.

Co-Authored-By: Claude Fable 5 <[email protected]>
The cleanup raced the tests: in CI with TTL = 2 sec it removed a live
processing node of a file which takes 2.5 sec due to the sleep
throttling (processing nodes are not refreshed during processing,
unlike bucket locks), the processed commit then failed on the missing
node, and later commits advanced the bucket watermark past the file,
leaving it without a processed commit in the s3queue log (the data was
already inserted). It could similarly remove bucket locks which stop
being refreshed after the provoked ownership loss. Set the cleanup
intervals beyond the test duration: both tests provoke ownership loss
manually and do not need the cleanup.

Also do not set the deprecated use_persistent_processing_nodes setting.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110292&sha=2eb4d16e15f363d054b21c05281eab2b2cfdf7d6&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%202%2F4%29
Related: #110292

Co-Authored-By: Claude Fable 5 <[email protected]>
persistent_processing_node_ttl_seconds is changeable at runtime, so
after an ALTER the cleanup starts using the new TTL immediately while
existing holders kept the value snapshotted at acquisition. Lowering
the TTL then reopened the fail-open release path: the cleanup could
remove a lock which release still considered too young for the
ownership check. Hold a reference to the atomic setting instead (the
holders never outlive the metadata which owns it).

Addresses: #110292 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
persistent_processing_node_ttl_seconds is changeable at runtime, while
the cleanup task gating flag is fixed at metadata creation. Altering
the TTL to zero on a table with the cleanup running made it treat every
processing node and bucket lock as stale and remove live ownership
state immediately.

The opposite direction stays a known pre-existing limitation: the
cleanup task is only created at startup, so a table created with a zero
TTL does not start it when the TTL is enabled later.

Addresses: #110292 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Refresh S3Queue bucket locks so the TTL cleanup does not remove them mid-processing
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Jul 27, 2026
@robot-clickhouse-ci-1
robot-clickhouse-ci-1 merged commit bb520be into backport/26.3/110292 Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants