Skip to content

Allow to change parallel_inserts of S3Queue/AzureQueue with ALTER - #130904

Open
azat wants to merge 14 commits into
ClickHouse:masterfrom
azat:s3queue-alter-parallel-inserts
Open

azat wants to merge 14 commits into
ClickHouse:masterfrom
azat:s3queue-alter-parallel-inserts

Conversation

@azat

@azat azat commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Blocked by #130864

Changelog category (leave one):

  • Improvement

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

Allow to change parallel_inserts of S3Queue/AzureQueue with ALTER

Previously the only way was to re-create the table, which is not trivial if you need to preserve the history of processed files in Keeper.

And apply ALTER of processing_threads_num with parallel_inserts without re-attaching the table.

It does not require detaching materialized views. ALTER asks the running streaming to stop, so it waits only for the in-flight INSERT (or interrupts it if deduplication is enabled), not for the whole backlog of files.


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

@azat
azat requested a review from NIKTONIKTO717 November 11, 2026 17:35
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a15a50]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR enables changing parallel_inserts and rebuilding S3Queue/AzureQueue streaming workers through ALTER, and includes batch-limit and polling fixes from its prerequisite. Reviewed head 2a15a500daec28747677aea3d81ad2e33ba33a12. Two correctness blockers remain: cancellation can duplicate destination rows, and independent ordered inserts can release another insert's bucket lock prematurely. There is also a polling regression and an existing test-coverage gap.

Findings

❌ Blockers

  • src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp:1181 — Reconfiguration can duplicate rows in destinations without deduplication. The cancellation callback treats deduplication_v2 and the query flag as proof that retries are safe, but ordinary MergeTree destinations default to non_replicated_deduplication_window = 0 (MergeTreeSink.cpp:83). Cancelling a multi-block file after a prefix is inserted resets the file for a complete retry without rolling back that prefix. Drain the current insert during ALTER unless every affected destination guarantees deduplication. Existing unresolved finding.

  • src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp:1095 — Independent ordered inserts can release each other's bucket locks before committing. All workers share a FileIterator; getNextKeyFromAcquiredBucket marks a bucket finished at source exhaustion (ObjectStorageQueueSource.cpp:896–900), but releaseFinishedBuckets scans every processor (:713–737). An unrelated successful or empty batch can release a lock while its owner's insert remains pending. A competing consumer can then skip the processing file and commit a later filename; if the original insert fails or is cancelled, its missing rows are below the watermark and permanently skipped. Release only buckets whose owning batches have committed or reset their files. New inline finding.

⚠️ Majors

  • src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp:1272–1273 — Disabling the file-count limit now inserts a polling delay between nonempty batches. processed_files increments only when max_processed_files_before_commit is nonzero (ObjectStorageQueueSource.cpp:1268–1270). With processing_threads_num = 1, max_processed_files_before_commit = 0, max_processed_rows_before_commit = 1, successful one-row files leave the counter zero and trigger this new exit. The default polling delay then permits roughly one file per second despite a backlog. Byte- and time-limited batches are affected too. Count acquired files independently of the configured limit before deciding that a batch was empty. New inline finding.

  • tests/queries/0_stateless/05618_s3queue_alter_parallel_inserts.sh:86–103 — The test still does not establish safe, effective reconfiguration during an active insert. Uploading 300 files provides a backlog but no synchronization with an active insert. Eventual counts and settings would still pass if createStreamingTasks were removed, and the test never selects deduplication_v2 = 0. Synchronize with active processing, verify the effective worker count after changing it, and cover cancellation and draining. Existing unresolved finding and follow-up.

Tests
  • ⚠️ Add a focused stateless case that changes topology after a prefix of a multi-block file becomes visible in a destination without deduplication, then verifies complete output without duplicates.
  • ⚠️ Cover ordered parallel ingestion with one insert pending while another batch finishes and a competing consumer attempts the same bucket. Verify that a later filename cannot advance the watermark past the pending file.
  • ⚠️ Cover successful batches with max_processed_files_before_commit = 0 and another commit limit enabled, preserving continuous backlog processing.
  • ⚠️ Strengthen 05618 as described above. These cases were assessed by source tracing; no local ClickHouse binary or configured build was available for reproductions.
Final Verdict

❌ Block. Make reconfiguration safe for destinations without deduplication, preserve bucket ownership through each owning insert's durable boundary, fix the zero-counter polling regression, and add focused coverage for those cases and effective worker reconfiguration.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-s3queue S3Queue/AzureQueue engines (queue-based ingestion from object storage). label Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a616a03bb with master cbd8a0ffb (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

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

Job report

@NIKTONIKTO717 NIKTONIKTO717 self-assigned this Nov 12, 2026

@NIKTONIKTO717 NIKTONIKTO717 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.

@ch-samuel-reviewer-1 open a PR with suggested change for this.

A possible change I suggest (on top of c83c685)
diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
index a8d9de6f434e..ebebe5129e1d 100644
--- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
+++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
@@ -1092,7 +1092,7 @@ bool StorageObjectStorageQueue::streamToViews(size_t streaming_tasks_index, UInt
     LOG_TEST(log, "Using {} processing threads (processing_threads_num: {}, parallel_inserts: {}, async deduplicate: {})",
         threads, processing_threads_num, use_parallel_inserts, is_deduplication_v2);
 
-    while (!shutdown_called && !file_iterator->isFinished() && !stream_control.isCancelRequested(cycle_epoch))
+    while (!shutdown_called && !file_iterator->isFinished() && !isStreamingCycleCancelled(cycle_epoch))
     {
         /// All tasks share a single batch size override so that the halving
         /// converges regardless of which task encounters the bad file.
@@ -1172,7 +1172,7 @@ bool StorageObjectStorageQueue::streamToViews(size_t streaming_tasks_index, UInt
                 executor.setCancelCallback(
                     [this, cycle_epoch, &cancelled_mid_insert]
                     {
-                        if (stream_control.isCancelRequested(cycle_epoch))
+                        if (isStreamingCycleCancelled(cycle_epoch))
                         {
                             cancelled_mid_insert = true;
                             return true;
@@ -1260,6 +1260,11 @@ bool StorageObjectStorageQueue::streamToViews(size_t streaming_tasks_index, UInt
     return total_rows > 0;
 }
 
+bool StorageObjectStorageQueue::isStreamingCycleCancelled(UInt64 cycle_epoch) const
+{
+    return stream_control.isCancelRequested(cycle_epoch) || restarting_streaming_tasks;
+}
+
 void StorageObjectStorageQueue::postProcess(
     const StoredObjects & successful_objects,
     UnorderedSetWithMemoryTracking<String> & post_processing_failed_paths,
@@ -1884,11 +1889,14 @@ void StorageObjectStorageQueue::alter(
         /// The number of streaming tasks changes, so they are re-created once the running ones finish.
         const bool recreate_streaming_tasks = parallel_inserts_changed || (processing_threads_num_changed && new_parallel_inserts);
         const bool restart_streaming = requires_detached_mv || recreate_streaming_tasks;
-        /// Otherwise the running tasks finish only once the whole backlog is processed.
-        if (recreate_streaming_tasks)
-            stream_control.requestCancel();
         if (restart_streaming)
         {
+            /// Otherwise the running tasks finish only once the whole backlog is processed.
+            if (recreate_streaming_tasks)
+                restarting_streaming_tasks = true;
+            /// No streaming cycle runs after the tasks are deactivated.
+            SCOPE_EXIT({ restarting_streaming_tasks = false; });
+
             std::lock_guard lock(streaming_tasks_mutex);
             LOG_TRACE(log, "Deactivating {} streaming tasks", streaming_tasks.size());
 
diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
index 977e702b6b57..8408acddfb81 100644
--- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
+++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
@@ -185,6 +185,9 @@ private:
     };
     mutable std::mutex streaming_tasks_mutex;
     std::vector<std::unique_ptr<StreamingTask>> streaming_tasks TSA_GUARDED_BY(streaming_tasks_mutex);
+    /// Set by `ALTER` while it waits for the running streaming cycles to finish before re-creating the
+    /// streaming tasks, so that the cycles stop early. Unlike `SYSTEM CANCEL`, it does not abort direct `SELECT`.
+    std::atomic<bool> restarting_streaming_tasks{false};
     std::atomic<size_t> max_files_override{0};
 
     LoggerPtr log;
@@ -226,6 +229,8 @@ private:
     void createStreamingTasks(size_t count);
     /// A subset of logic executed by threadFunc.
     bool streamToViews(size_t streaming_tasks_index, UInt64 cycle_epoch);
+    /// The streaming cycle started at `cycle_epoch` is cancelled by `SYSTEM STOP/CANCEL` or by `ALTER`.
+    bool isStreamingCycleCancelled(UInt64 cycle_epoch) const;
     /// Apply after_processing action to successfully processed files.
     void postProcess(
         const StoredObjects & successful_objects,

@ch-samuel-reviewer-1

Copy link
Copy Markdown
Contributor

@NIKTONIKTO717 Opened azat#1.

@azat
azat marked this pull request as draft November 13, 2026 15:28
@azat
azat marked this pull request as ready for review November 14, 2026 20:53
Previously the only way was to re-create the table, which is not trivial
if you need to preserve the history of processed files in Keeper.

And apply ALTER of `processing_threads_num` with `parallel_inserts`
without re-attaching the table.

It does not require detaching materialized views. ALTER asks the running
streaming to stop, so it waits only for the in-flight INSERT (or interrupts
it if deduplication is enabled), not for the whole backlog of files.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@azat
azat force-pushed the s3queue-alter-parallel-inserts branch from c83c685 to 75739a7 Compare November 14, 2026 21:14
azat added a commit to azat/ClickHouse that referenced this pull request Nov 14, 2026
Stop the running streaming cycles with a flag instead of
`stream_control.requestCancel()`: the latter only bumps the epoch, so a
cycle that started after it drained the whole backlog, and it aborted
direct `SELECT` with `QUERY_WAS_CANCELLED`.

ClickHouse#130904 (comment)
ClickHouse#130904 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Stop the running streaming cycles with a flag instead of
`stream_control.requestCancel()`: the latter only bumps the epoch, so a
cycle that started after it drained the whole backlog, and it aborted
direct `SELECT` with `QUERY_WAS_CANCELLED`.

ClickHouse#130904 (comment)
ClickHouse#130904 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Samuel Krempaský <[email protected]>
@azat
azat force-pushed the s3queue-alter-parallel-inserts branch from 75739a7 to c8b5134 Compare November 14, 2026 21:15

# Changes the number of streaming tasks
$CLICKHOUSE_CLIENT -q "
ALTER TABLE queue MODIFY SETTING processing_threads_num = 8;

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.

[Major] Verify reconfiguration with an active background insert

Each topology change follows wait_rows, and new files are uploaded only after the ALTER returns. There is therefore no intentional backlog or guaranteed active insert to exercise the new stop flag and deduplication cancellation callback. The separate direct-SELECT test has no materialized view and cannot cover those background paths. Also, checking system.s3_queue_settings and eventual row counts does not verify the effective worker count: removing the createStreamingTasks call would still satisfy these assertions. Please add a focused stateless case that alters the topology with an attached view while an insert is active and more files remain, covering deduplication enabled and disabled. Assert complete, nonduplicated output and that the effective streaming parallelism changes, so the promised safe reconfiguration is actually tested.

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.

🕵 Done in e66e1d6: 05618 now uploads 300 files right before each ALTER that changes the number of streaming tasks (processing_threads_num = 8 and parallel_inserts = 0), so background inserts are running while the tasks are stopped and re-created, and after each step it checks count() = uniqExact(x) = <expected>, i.e. every file is inserted exactly once.

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.

[Major] The backlog and uniqueness checks improve coverage, but the original issue is still partly present at tests/queries/0_stateless/05618_s3queue_alter_parallel_inserts.sh:86-95: there is no synchronization proving an insert is active when ALTER starts, and the assertions still observe only the setting and eventual rows. Removing the createStreamingTasks call at StorageObjectStorageQueue.cpp:1996 would still satisfy them with the old workers. The test also never selects deduplication_v2 = 0, so it cannot verify the branch that must finish the in-flight insert instead of cancelling it. Please synchronize with active processing and assert the effective streaming task count after reconfiguration, with coverage for both cancellation and draining.

alexey-milovidov and others added 3 commits November 14, 2026 21:50
After ClickHouse#130864, `parallel_inserts=1` runs one streaming task per processing
thread. Every successful commit, including commits of empty batches by idle
tasks, reset the shared `max_files_override` to 0, undoing the halving done
by the task that hit a failing INSERT. The bad file then never ended up alone
in a batch, its retry count was never reduced, and good files batched together
with it were never processed.

Reset the override only after a batch which committed files, and only if no
other task changed it since this iteration started.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=83b6da0324076eb3a1c8f1ea58fee8c57e24e757&name_0=MasterCI&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 7 commits November 15, 2026 01:57
A numeric compare-exchange could not tell that a failure happened after a
batch started if the halved limit came back to the same value, so an older
successful batch could clear a newer reduction. Move the shared limit into
`ObjectStorageQueueBatchSizeOverride`, which pairs it with a generation that
every failure increments; a success resets the limit only if the generation
is unchanged since its batch started.

Review: ClickHouse#131689 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
…Queue`/`AzureQueue`

Table creation already refuses zero, but `ALTER ... MODIFY SETTING
processing_threads_num = 0` was accepted, stored in keeper, and with
`parallel_inserts` replaced the streaming tasks with none. Check it while
validating the changed settings, before any task is deactivated or keeper
is updated.

Review: ClickHouse#130904

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s processed in 05618

Upload 300 files right before each `ALTER` that changes the number of
streaming tasks, so that background inserts are running while the tasks are
stopped and re-created, and check that every file is inserted exactly once.
Also check that `processing_threads_num = 0` is rejected.

Review: ClickHouse#130904

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `parallel_inserts` there is one streaming task per processing thread,
but they shared one `reschedule_processing_interval_ms`. Every task that
found no files added `polling_backoff_ms` to it, so N idle tasks grew the
backoff N times faster (e.g. 4 tasks reached 121 s after one idle poll), and
a reset by the task which found files did not shorten the wait of the
others, which were already scheduled far out. New files then waited for
minutes. Keep the interval per task, as it was with the single task.

Found from `05618_s3queue_alter_parallel_inserts` timing out in
ClickHouse#130904:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130904&sha=c8b5134c4293785f35c7ed755b32af690c093a0b&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
The test waits for new files after each `ALTER`, and with the default
`polling_backoff_ms = 30000` an idle poll right after re-creating the
streaming tasks delays processing by at least 31 s per step, which made the
test exceed the 180 s limit in every sanitizer job:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130904&sha=c8b5134c4293785f35c7ed755b32af690c093a0b&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

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

Copy link
Copy Markdown
Member

🕵 Continued this PR (pushed a616a03bbf9c):

Only syntax-checked locally; CI will run the tests.

[this, cycle_epoch, &cancelled_mid_insert]
{
if (stream_control.isCancelRequested(cycle_epoch))
if (stream_control.isCancelRequested(cycle_epoch) || restarting_streaming_tasks)

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.

[Blocker] Drain the insert when a destination does not deduplicate

is_deduplication_v2 only checks the queue and query flags (line 1072); it does not establish that the materialized-view targets deduplicate. For example, a plain MergeTree target has non_replicated_deduplication_window = 0 by default, so MergeTreeSink ignores these tokens. With a file spanning multiple output blocks, let some blocks commit, then run ALTER TABLE queue MODIFY SETTING parallel_inserts = 1 while the file is still being inserted. This new condition cancels the pipeline; commit(false, ...) resets the file for retry without rolling back the target's committed parts. The replacement worker rereads the file from the beginning and duplicates the committed prefix. The same issue applies to AzureQueue and to a view chain containing a non-deduplicating destination.

For ALTER, let the current insert finish unless every affected destination is known to deduplicate retries. Keeping the restart flag in the outer loop, without using it to cancel the executor, would still stop at the current insert boundary. Add a focused stateless case that alters after a prefix of a multi-block file becomes visible in a non-deduplicating target and checks the final count and unique count.

alexey-milovidov and others added 2 commits November 15, 2026 16:12
With one source per streaming task, a task can get no files while the
shared iterator is not finished, e.g. in ordered mode when the remaining
cached paths belong to buckets held by other tasks. It then committed empty
batches and rebuilt the insert pipeline in a loop, never reaching its
polling backoff. End the cycle instead.

Review: ClickHouse#131689 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const bool parallel_inserts = table_metadata.parallel_inserts;
const size_t threads = parallel_inserts ? 1 : processing_threads_num;
const bool use_parallel_inserts = parallel_inserts;
const size_t threads = use_parallel_inserts ? 1 : processing_threads_num;

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.

[Blocker] Keep ordered bucket locks until their owning insert commits

With mode = 'ordered', buckets > 1 and parallel_inserts = 1, these independent inserts share one FileIterator. getNextKeyFromAcquiredBucket marks a holder finished when its source reaches the end of its bucket (ObjectStorageQueueSource.cpp:896–900), before the insert commits. However, both cleanup calls in streamToViews invoke releaseFinishedBuckets, which scans every processor's holders (ObjectStorageQueueSource.cpp:713–737). An unrelated task, including one committing an empty batch, can therefore release that bucket while its owning insert is still pending.

Another consumer can acquire the bucket, skip the still-processing file and commit a later filename. If the original insert fails or is cancelled by ALTER, its retry is now below the processed watermark, so its missing rows are permanently skipped. Keep the lock until the owning batch has committed or reset its files; scope releases to processors whose batches have completed, or track outstanding batches explicitly. Please cover ordered parallel ingestion with an unfinished insert and a competing consumer.

Comment on lines +1272 to +1273
if (processing_progress->processed_files.load() == 0)
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.

[Major] Count acquired files independently of the configured file limit

ProcessingProgress::processed_files is incremented only inside if (commit_settings.max_processed_files_before_commit) in ObjectStorageQueueSource::generateImpl (ObjectStorageQueueSource.cpp:1268–1270). Thus a valid configuration such as processing_threads_num = 1, max_processed_files_before_commit = 0, max_processed_rows_before_commit = 1 leaves this counter at zero after every successful one-row file. This new condition exits despite a remaining backlog, and threadFunc waits polling_min_timeout_ms before processing the next batch. With the default polling timeout this limits ingestion to roughly one such file per second; previously it continued immediately after each commit. Byte- and time-limited batches have the same problem when the file-count limit is disabled.

Use an unconditional acquired-file count, with consistent decrement handling, or another measure that distinguishes an empty batch from a successful batch with no file-count limit. Add a focused case with the file limit disabled and another commit limit enabled.

This branch has not been deployed

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

Labels

comp-s3queue S3Queue/AzureQueue engines (queue-based ingestion from object storage). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants