Skip to content

Keep the stable task distribution of object storage files when replicas are balanced - #128433

Merged
alexey-milovidov merged 4 commits into
masterfrom
stable-task-distributor-no-steal-from-busy
Nov 6, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
stable-task-distributor-no-steal-from-busy

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

With parallel replicas for object storage and *Cluster table functions, StorageObjectStorageStableTaskDistributor assigns every file to a replica by rendezvous hashing, so that the same file is read by the same replica, and from its cache, in every query. But once the iterator was exhausted, a replica that asked for a task immediately took a file of the replica with the most remaining bytes, among the replicas that had already asked for tasks. Those replicas keep asking until they receive an empty task, so their files would be processed anyway. Taking them only moved them to random replicas depending on the timing of the requests. This was common with slow iterators like Iceberg's, where most replicas become idle and ask at the same moment, and repeated queries kept reading 20-40% of their bytes from S3 instead of the filesystem cache.

Now, once the iterator is exhausted:

  • a replica first takes its own queued files;
  • it takes the files of a replica that has asked for tasks only when that replica has more than twice the average remaining bytes of the other replicas, i.e. only to balance the work. Otherwise it receives an empty task;
  • the files of replicas that haven't asked for tasks yet are handled as before (cluster_function_wait_for_replica_ms);
  • the files of replicas that have received an empty task can always be taken. They can only appear because of a race with threads that took them from the iterator before it was exhausted.

This implements the second option from the issue. The first option would wait since the owner's last request. It isn't used because the read task requests are served synchronously by the initiator's pipeline threads. Many idle replicas waiting there could block the threads that serve the owner's own requests, and the owner's files would then be taken anyway.

Trade-off: if a replica fails in the middle of the query after it has asked for tasks, its queued files are no longer taken by others. The result in that case was already incomplete, because the files the replica was reading are lost.

Closes: #128403

Changelog category (leave one):

  • Performance Improvement

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

With parallel replicas for object storage and *Cluster table functions, an idle replica no longer takes the files assigned to another replica that is still processing its own files, unless that replica has much more work left than the others. This keeps the assignment of files to replicas stable across queries and improves the hit rate of the filesystem and page caches.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1559-master (included in 26.11 and later)

…istributor`

Once the iterator was exhausted, a replica that asked for a task took a file
of the replica with the most remaining bytes among the replicas that had
already asked for tasks, immediately. These replicas keep asking until they
receive an empty task, so their files would be processed anyway, and taking
them only moved them to random replicas depending on the timing of the
requests, breaking the cache locality of the rendezvous hashing.

Now a replica first takes its own queued files, and takes the files of a
replica that has asked for tasks only when that replica has more than twice
the average remaining bytes of the other replicas. Otherwise it receives an
empty task. The files of replicas that haven't asked yet are handled as before
(`cluster_function_wait_for_replica_ms`), and the files of replicas that have
received an empty task can always be taken.

The decision doesn't wait, because the requests are served synchronously by
the threads of the initiator, and waiting could block the requests of the
replica whose files are waited for.

#128403

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

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [60a7b83]

Summary: ✅


AI Review

Summary

The PR aims to preserve object-storage cache locality by preferring each replica's queued files and limiting stealing from connected replicas to queues exceeding twice the other replicas' average remaining bytes. Review of head 60a7b83d33f4e8e727661d9fa4fa8b800d14bd24 retains one existing concern about missing performance evidence. Request changes pending measurements of the cache benefit and query duration.

Findings

⚠️ Majors

Tests
  • ⚠️ Provide a focused before/after comparison of repeated queries on a fixed replica set with per-node filesystem caches, covering uniform and skewed file sizes. Report CachedReadBufferReadFromCacheBytes, ReadBufferFromS3Bytes, and elapsed time. Measurements in the PR description are sufficient; a new integration test is not required.
Final Verdict

Status: ⚠️ Request changes. Supply the cache and elapsed-time comparison above to validate the material performance claim. No new inline findings were identified.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 1, 2026
Comment on lines +304 to +305
if (!should_wait)
break;

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.

[P2] Validate the cache benefit and latency cost of early completion

This now ends a replica's participation while other replicas still have queued files. The added unit tests prove the selection rule for a fixed queue snapshot, but do not establish the claimed performance improvement with real readers: remaining_bytes excludes files already handed out, and an idle replica that exits here cannot help if the remaining readers subsequently fall behind. The linked issue contains measurements only for the old implementation.

Please add a small before/after comparison of repeated queries over a fixed replica set, reporting filesystem-cache bytes, S3 bytes, and elapsed time. Include a skewed-file workload so the cache-locality gain is evaluated alongside the cost of retiring readers. A focused benchmark or measurements in the PR description would close this gap.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Agreed that the unit tests only pin the selection rule, not the end-to-end effect. A meaningful before/after measurement needs a real multi-node cluster reading from S3 with a filesystem cache on each node (the effect depends on the request timing of the replicas, which a single-host setup with MinIO doesn't reproduce), and that is not available in this automated environment, so I am leaving this thread open for a human to provide numbers.

Notes on the two risks raised:

  • Cache benefit: with the change, after the iterator is exhausted a file goes to a replica other than its rendezvous owner only when the owner has not asked for tasks within cluster_function_wait_for_replica_ms, when the owner has already finished, or when the owner has more than twice the average remaining queued bytes of the other replicas. In the balanced case, the assignment is therefore the same in every query, which is what keeps the cache hits; the issue (Parallel replicas for object storage: work stealing breaks the cache locality of the stable task distribution #128403) shows 20-40% of bytes being re-read from S3 with the old timing-dependent assignment.
  • Latency cost of retiring readers: an idle replica stops only when no replica has more than 2x the average remaining queued bytes, so the worst-case extra tail is bounded by roughly the skew allowed by that threshold. You are right that remaining_bytes does not include files already handed out, so a replica slowed down by one huge in-flight file is not detected. Skewed workloads where one file dominates are better handled by splitting the file into tasks (row groups / buckets) than by stealing whole files, which also breaks cache locality.

A benchmark with repeated queries over a fixed replica set (uniform and skewed file sizes, reporting CachedReadBufferReadFromCacheBytes, ReadBufferFromS3Bytes and elapsed time) would close this; I'll leave it to the author/reviewer to run it on a real cluster.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Nov 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 60a7b83d3 with master c8383042c (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128433&sha=13a08d58c8964f2b59da12ec2f28b027c99b7780&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%205%2F6%29 (long_primary_key query 0, +16.5% on amd_release; this PR only changes StorageObjectStorageStableTaskDistributor, which a MergeTree primary-key test doesn't use) and provide a fix in a separate PR. If the fix is already in progress, link it here. Possibly related: #127480

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

This run had no performance reference build: job.log line 144, WARNING: no performance reference build, the reference is the official build. MasterCI had skipped the reference builds at base c189bd99, because the source change of that push was in an earlier commit of the same push, so the PR build was compared with the official build. On amd these two builds differ by about 16% on all three long_primary_key queries, independent of the diff (the same red appeared on other PRs based on c189bd99).

The fix is #128453, merged 2026-11-01 22:14Z, after this run (04:28Z). The current head 31c76b92 is based on master 1df150ba, where both reference builds ran, so the next run has a reference build. Nothing to change in this PR. #127480 is the ARM-only instability and has a different cause.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128433&sha=31c76b92c4891b1691d1e5dce13e80ce01f960ea&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 (TLP WHERE oracle mismatch for SELECT id FROM tab WHERE hasToken(str, 'hello'): the NOT hasToken / isNull(hasToken) partitions contain extra rows; this PR only changes StorageObjectStorageStableTaskDistributor) and provide a fix in a separate PR. If the fix is already in progress, link it here. Possibly related: #106922

Thanks for the analysis of the earlier long_primary_key perf result. I merged the latest master (ef9d991f) so CI runs again with a performance reference build.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #113332 (open, closes #106922; no updates since 2026-10-15). Not related to this PR.

Cause: with a text index on a Nullable column, direct read from the index replaces hasToken(str, 'hello') with a UInt8 virtual column, so the NULL rows are read as 0 and not(...) keeps them. Reproduced on master e6c0a8e3 with the fuzzer's table (first section of 02346_text_index_nullable.sql): not(hasToken(str, 'hello')) returns ids 2, 3, 4 instead of 3, while the isNull(...) leg is correct (2, 4), so the three legs sum to 7 vs count() = 5. With query_plan_direct_read_from_text_index = 0, not(...) returns only 3.

#113332 adds these exact queries on the same table to 02346_text_index_nullable.sql (NOT hasToken(str, 'hello') -> 3 in WHERE and PREWHERE, isNull(hasToken(str, 'hello')) -> 2, 4), so I'm not opening a separate PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128433&sha=ef9d991fdb713d4a4d9102986f8f4dd5d8ed803f&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29 (Server shutdown: node0 had to be force-killed). In gdb.log, the main thread is blocked in Context::waitAllBackupsAndRestores -> BackupsWorker::waitAll. Meanwhile a BackupAsync thread is still in ZooKeeperRetriesControl::retryLoop inside BackupCoordinationStageSync::setError, called from RestoreCoordinationOnCluster::setError <- BackupsWorker::RestoreStarter::onException. So a failed RESTORE ON CLUSTER keeps retrying Keeper during shutdown. This PR only changes StorageObjectStorageStableTaskDistributor. Please provide a fix in a separate PR. If the fix is already in progress, link it here. Possibly related: #124334, #115377.

I merged the latest master (60a7b83d) so CI runs again.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

This run is from before #128774. The workflow started on 2026-11-03 at 08:44 UTC and #128774 was merged at 09:28 UTC, so the tested merge commit does not contain it: effective_config0.xml has no shutdown_wait_backups_and_restores, which defaults to 1 (wait for backups and restores without a time limit).

The setError loop is not cancellable on purpose: for WithRetries::kErrorHandling the retries get no process_list_element (src/Backups/WithRetries.cpp, "the error handling can't be cancellable"), since the error node is how the other hosts learn about the failure. It is bounded by backup_restore_keeper_max_retries_while_handling_error (20 retries, backoff up to 5 s, so about 76 s of sleeping while Keeper keeps failing), which is longer than the harness' 30 s. With #128774 the setting is 0: shutdown calls cancelAllBackupsAndRestores with a shutdown_wait_unfinished deadline (now at most 10 s in properties.py), and an operation still unfinished after that sends the server to Will shutdown forcefully with exit code 0, which dolor.py accepts.

CI agrees. Since #128774 was merged, La Casa Del Dolor Server shutdown failed 16 times: all 9 with BackupsWorker::waitAll in gdb.log ran without shutdown_wait_backups_and_restores in the config, and none of the 6 with it set to 0 is in BackupsWorker. The current head 60a7b83 contains #128774, so I don't think a separate PR is needed for this one.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, agreed: the tested merge commit predates #128774, and the current head 60a7b83d contains it. The rerun on 60a7b83d is green, so nothing to change here for the La Casa Del Dolor shutdown failure.

The remaining open review thread asks for a before/after benchmark on a real multi-node cluster with per-node filesystem caches, which needs a human to run.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Nov 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
Merged via the queue into master with commit 515c309 Nov 6, 2026
186 checks passed
@alexey-milovidov
alexey-milovidov deleted the stable-task-distributor-no-steal-from-busy branch November 6, 2026 20:49
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-performance Pull request with some performance improvements 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.

Parallel replicas for object storage: work stealing breaks the cache locality of the stable task distribution

3 participants