Skip to content

Cherry pick #103126 to 26.2: StorageObjectStorageQueue: fix shutdown blocking on stuck pipeline - #105407

Merged
robot-ch-test-poll merged 18 commits into
backport/26.2/103126from
cherrypick/26.2/103126
May 21, 2026
Merged

robot-ch-test-poll merged 18 commits into
backport/26.2/103126from
cherrypick/26.2/103126

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #103126

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

tuanpach and others added 17 commits May 9, 2026 01:17
…file

When `generateImpl` observed `shutdown_called` with an in-flight file, only
the `table_is_being_dropped` sub-case threw `QUERY_WAS_CANCELLED`; normal
shutdown logged "Will process the file fully and then shutdown" and let the
loop keep reading the file. For large files or slow object storage, this
made `shutdown` block until the entire remainder of the file was read,
which could be many minutes per task.

Throw `QUERY_WAS_CANCELLED` in both cases. Rows already returned from
previous `generateImpl` calls may have been written to the destination
table; the file is marked `Cancelled` (not `Processed`) so it is retried
on next start, which can lead to duplicates for those rows. That trade-off
is acceptable in exchange for bounded shutdown time.

Suggested by azat:
#103126 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The previous commit makes `generateImpl` throw `QUERY_WAS_CANCELLED` for
partially-processed files on shutdown. Downstream, the existing handling
treated this exception as a real failure: `prepareCommitRequests` saw an
unknown error code, computed `reduce_retry_count = true`, called
`prepareFailedRequests` with that flag, and the file's processing node
was replaced by a `failed_node` in Keeper. `finalizeCommit` then routed
through `finalizeFailed`, and `appendLogElement` recorded the file with
`status = Failed` in `system.s3queue_log`. After a few shutdown cycles a
file would exceed `max_loading_retries` and become permanently failed
without ever having had a real read or insert error.

`test_storage_s3_queue/test_5.py::test_shutdown_order` asserts that no
entries with `status = 'Failed'` appear in `system.s3queue_log` after a
restart-during-processing, and was failing with 10 such entries.

Two changes:

1. Add `QUERY_WAS_CANCELLED` to the `reduce_retry_count` exclusion list
   in `prepareCommitRequests`. Cancellation (shutdown or `KILL QUERY`)
   is never the file's fault, so files cancelled mid-batch take the
   reset-only path of `prepareFailedRequests`: the processing node is
   removed, no `failed_node` is created, and `processing_reset_without_failure`
   is set so `finalizeCommit` routes through `finalizeResetProcessing`.

2. Skip `appendLogElement` in `finalizeCommit` when
   `wasProcessingResetWithoutFailure()` is true. A file that was reset
   for retry did not produce a real outcome; it should not appear as
   `Failed` in `system.s3queue_log`. It will be logged on its next
   attempt with the actual outcome.

The second change also corrects the equivalent reset paths for
`TOO_MANY_PARTS`, `TABLE_IS_BEING_RESTARTED`, and `TABLE_IS_READ_ONLY`,
which were also producing misleading `status = Failed` log entries.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The previous shutdown-throw assumed deduplication would catch the
partial-write duplicates produced by retrying the file from offset 0 on
next start. That assumption holds for the default configuration, but
`S3Queue` users can disable either `deduplication_v2` (table setting) or
`deduplicate_blocks_in_dependent_materialized_views` (server setting); in
those configurations the retry produces real duplicates, regressing the
prior correctness contract that the old "process file fully" path was
designed to uphold.

Thread the effective dedup state (the same `is_deduplication_v2` already
computed in `streamToViews`) into `ObjectStorageQueueSource` and use it to
gate the throw in `generateImpl`. When dedup is on, behavior is unchanged
(throw, fast shutdown). When dedup is off, the source falls back to the
old contract of reading the in-flight file to EOF before exiting.

`table_is_being_dropped` still throws unconditionally because no retry
will occur — duplicates are not a concern for a dropped table.

Raised by clickhouse-gh[bot]:
#103126 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…e_processed path

The streaming path passes `getCurrentExceptionCode()` to `commit` so that
`prepareCommitRequests` can recognise `QUERY_WAS_CANCELLED` and route
shutdown-cancelled files through the reset-without-failure path. The
`commit_once_processed` path (used by SELECT queries with
`commit_on_select=1`) only forwarded the message, so `prepareCommitRequests`
saw `error_code=0`, kept `reduce_retry_count=true`, and cancelled files
still burned retries / eventually moved to `Failed` on normal shutdown.

Thread the code through the second commit path so both behave the same.

Raised by clickhouse-gh[bot]:
#103126 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Covers the `ObjectStorageQueueSource::commit` path (used when
`commit_on_select=1`). Verifies that a shutdown interrupting an
in-progress SELECT does not record the cancelled attempt as Failed in
`system.s3queue_log` and does not burn the file's retry budget.

Mirrors the structure of `test_shutdown_order` for the streaming path.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ession

The previous version used `restart_clickhouse()`, which SIGKILLs the
server before `ObjectStorageQueueSource::commit` can run. With no
`commit()` call, the buggy error-code-dropping path is never exercised,
so the test passed on master too (caught by Bugfix validation).

Switch to `KILL QUERY`: the executor is cancelled gracefully,
`generateImpl` observes `isCancelled() == true` and throws
`QUERY_WAS_CANCELLED`, the catch in `generate()` calls
`commit(false, ..., QUERY_WAS_CANCELLED)`. Without the fix the error
code is dropped and the file ends up logged as Failed; with the fix
it propagates and the processing node is reset for retry instead.

Also: 1 processing thread + larger files so the SELECT is reliably
mid-file when KILL arrives, and poll `system.processes` instead of
`time.sleep(1)` so the timing is robust on slow runners.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…_select

The KILL QUERY / sleepEachRow approach to triggering an in-progress SELECT
cancellation is fragile: count(*) over a small CSV completes in
~85 milliseconds on local MinIO, and timing-based polling/kill loops
either miss the running query entirely or fire after it has already
finished.

Add a one-shot failpoint `object_storage_queue_cancel_in_generate` that
sits at the top of the per-file processing block in
`ObjectStorageQueueSource::generateImpl`. When triggered, it marks the
in-flight file `FileState::Cancelled` and throws `QUERY_WAS_CANCELLED`,
mirroring the real `isCancelled()` branch a few lines above. The throw
must happen outside the inner pull-error try-catch so it bubbles up to
`generate()`'s catch rather than being converted to
`FileState::ErrorOnRead`.

Rewrite `test_cancel_during_commit_on_select` to enable the failpoint,
run a SELECT, and verify no `status='Failed'` rows in
`system.s3queue_log`. The test is now fully deterministic and exercises
the same code path the bug-fix touches (error code propagation through
`commit_once_processed`).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The dedup-off path in `generateImpl` (`if (!table_is_being_dropped &&
!is_deduplication_v2)`) preserves the old "process file fully on
shutdown" contract for users who have explicitly disabled
`deduplication_v2` or `deduplicate_blocks_in_dependent_materialized_views`.
Without that gate, the source would throw `QUERY_WAS_CANCELLED` mid-file,
the file would be marked Cancelled and retried on restart, and the
partial-write rows already inserted into the destination would arrive
twice on the retry — a silent duplicate regression for users who opted
out of dedup.

Add a new `object_storage_queue_sleep_in_generate` failpoint (ONCE)
that parks `generateImpl` for 5 seconds after at least one row has been
read from the current file. The test enables the failpoint, starts
streaming with `deduplication_v2=0`, sleeps briefly, and calls
`restart_clickhouse()` so `shutdown_called` is set while the source is
parked. After the sleep, the next loop iteration enters the
shutdown-handling branch with the current file in `Processing` state —
the dedup-off gate must continue reading to EOF.

Assertion: destination row count == files * rows_per_file (exact, no
duplicates). With the gate removed, the same file would be partially
inserted before shutdown and fully reinserted on retry, failing the
assertion.

Uses `sleepForSeconds()` (canonical pattern from `rmt_delay_commit_part`,
`rmt_delay_execute_drop_range`, etc.) gated behind a failpoint — not
production logic.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The flaky-check job hit a `checkProcessingOwnership` chassert in
`~ObjectStorageQueueIFileMetadata` once out of three repetitions. Stack
trace shows the chassert fires from `FileIterator::~FileIterator`
destroying its pre-fetched `vector<FileMetadataPtr>`: with default
`enable_hash_ring_filtering=1`, the iterator stages a batch of files
and creates their Keeper processing nodes up front. When the failpoint
throws `QUERY_WAS_CANCELLED`, only the one file currently being
processed runs through `commit()`/`finalizeResetProcessing()`. The
remaining pre-fetched files have `created_processing_node=true` but
never went through any finalize-method, so their destructors fire the
chassert as the iterator's vector unwinds.

Set `enable_hash_ring_filtering=0` so the iterator pulls files one at
a time on demand. No pre-fetched batch means no orphaned processing
nodes at iterator destruction time. Same workaround
`test_failed_commit_after_success_select` already uses for the same
reason, with the same comment.

Verified locally: `--count 3` runs all pass cleanly.

The underlying destructor cleanup bug — not finalizing pre-fetched
files when the source unwinds — is real but out of scope for this PR.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
`test_cancel_during_commit_on_select`: replace the broad `except Exception: pass`
with `query_and_get_error` + assertion that the message contains
`QUERY_WAS_CANCELLED`, so the test fails (instead of trivially passing the
`Failed count == 0` assertion) if the `object_storage_queue_cancel_in_generate`
failpoint silently does not fire.

`test_shutdown_dedup_off_no_duplicates`: replace the fixed `time.sleep(1)` before
`restart_clickhouse()` with a 30s polling loop on `system.s3queue_metadata_cache`
for `status = 'Processing' AND rows_processed > 0`. The
`object_storage_queue_sleep_in_generate` failpoint fires after the first chunk
is pulled, so this is the deterministic signal that the source is currently
parked at the failpoint. Without the wait, on a loaded runner the restart can
fire before streaming has scheduled, never exercising the dedup-off shutdown
branch this PR protects.

Addresses bot review comments:
- #103126 (comment)
- #103126 (comment)
CI of d50271e broke `test_cancel_during_commit_on_select` under
`amd_asan_ubsan` because Keeper fault injection (probability 0.05 on the
default `instance`) fired inside `ZooKeeperWithFaultInjection::tryMulti`
during `ObjectStorageQueueSource::commit`. The `KEEPER_EXCEPTION` thrown
by the fault path supersedes the in-flight `QUERY_WAS_CANCELLED` from
the `object_storage_queue_cancel_in_generate` failpoint (the catch in
`generate()` invokes `commit(false, ...)` and its own throw replaces
the original exception before the trailing `throw;` rethrows it).

The new strict assertion that the SELECT errors with `QUERY_WAS_CANCELLED`
is what the bot review asked for, but it is incompatible with a cluster
where unrelated Keeper faults can manifest as the visible error. Switch
both review-comment tests to `instance_without_keeper_fault_injection`
(same approach as `test_max_set_age`) so the cancellation signal — and,
for the dedup-off test, the exact `actual_rows == expected_rows` row count
that is its regression signal — is no longer masked by fault injection.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103126&sha=d50271eef194de4b7230d192685a22c9ca7db1c0&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20targeted%29
`object_storage_queue_sleep_in_generate` is a `ONCE` failpoint: it fires
at most once after being enabled, but if the test's `parked` polling
times out before the failpoint has fired (e.g. streaming never gets
scheduled), the failpoint stays in the "enabled, not yet fired" state
and a later test in the module can unexpectedly consume the pending
trigger and sleep for 5 seconds inside `generateImpl`.

After a successful `restart_clickhouse()` the failpoint state is wiped
with the server process, so the `finally`-block disable is a no-op on
the happy path; the value is the recovery line on the assertion-failure
path the bot review flagged.

Matches the existing pattern in `test_cancel_during_commit_on_select`
which already wraps its failpoint enable in try/finally.

Addresses bot review comment:
#103126 (comment)
…ipeline

StorageObjectStorageQueue: fix shutdown blocking on stuck pipeline
@robot-ch-test-poll robot-ch-test-poll 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 May 20, 2026
…rrypick/26.2/103126

# Conflicts:
#	src/Common/FailPoint.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
@robot-ch-test-poll
robot-ch-test-poll merged commit e746f71 into backport/26.2/103126 May 21, 2026
1 check passed
@robot-ch-test-poll
robot-ch-test-poll deleted the cherrypick/26.2/103126 branch May 21, 2026 11:19
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.

3 participants