diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 2b9bd3ac4370..c4faa4bf49ff 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -460,6 +460,26 @@ Source: `ServerSettings.cpp`. This setting is process-wide rather than scoped to |---|---|---| | `cas_blob_upload_pool_size` | `64` | Size of the dedicated server-wide thread pool used to upload blobs in parallel when committing a `CAS` part. Zero is rejected: the pool must have at least one thread | +## Write bandwidth limits {#write-bandwidth-limits} + +These limits pace blob bodies and part files staged in the object store with `cas_staging_backend = s3`: + +| Setting | Paces | +|---|---| +| `max_remote_write_network_bandwidth` | The uploads of the query | +| `max_remote_write_network_bandwidth_for_server` | Every upload of the server, also merges, mutations and moves | +| `max_network_bandwidth_for_user`, `max_network_bandwidth_for_all_users` | Uploads that run under a query, together with the query's other network traffic that these limits count | + +Part manifests, refs, the catalog, the mount lease, the GC state and deletes are never paced by these limits. + +A request that the S3 client sends by itself during an upload may be throttled with the upload. Two such requests +are a token request with `http_client = gcp_oauth` and the bucket region lookup of a client that has not sent a +request yet. + +After an upgrade, a server that already has one of these limits set starts to pace `CAS` uploads. A low server-wide +limit makes merges and mutations hold their queue slots longer while they upload. A stop ends such an upload; see +[stopping `CAS` work](/antalya/cas/operations/troubleshooting#stopping-cas-work). + ## `SYSTEM CAS` commands {#system-commands} `SYSTEM CAS GC RUN`, `SYSTEM CAS GC STOP`, `SYSTEM CAS GC START`, `SYSTEM CAS GC REBUILD`, diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index dc37b19025b8..15faf620d5a1 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -141,7 +141,7 @@ A query that is killed with `KILL QUERY` or hits its time limit stops `CAS` work - A retry after a failed request. The retry is not sent. When a read or a blob upload failed before the stop, the query fails with that request's error, or with a retry-later `NETWORK_ERROR` (210) that names a credential refusal, not with the stop's own error. That request's error can itself be `TIMEOUT_EXCEEDED` (159), when the failed attempt timed out. When a metadata write failed before the stop, the query fails with a retry-later `NETWORK_ERROR` (210) that says the write is unresolved and what a read of the key found; it does not carry the store's error. A metadata write that the store refused, with no earlier attempt left unanswered, keeps the store's error. When such a write was refused for its credentials and the stop cancels its resend with fresh credentials, it fails with a retry-later `NETWORK_ERROR` (210) that names the refusal. When the request fails after the stop, the S3 client reports the stop itself (see below). The pause before a retry notices the stop within 200 ms. A pause inside cleanup that the operation owes after a send runs to its end, and the request is sent once more unless the mount fence, the mount lease or a deadline stops it; if that attempt fails after the stop, it is not retried. - The next step of work that `CAS` can resume later: the catalog cleanup of a manual `SYSTEM CAS GC RUN`, the drain of `SYSTEM CAS DROP POOL MEMBER`, and the upload of a blob body the writer has to publish, because the store does not hold the blob or holds one the writer cannot reuse. The query fails with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. When an earlier upload attempt of the same blob failed, the check before the next upload fails the query with that attempt's error instead. The drain checks the stop before each of the member's namespaces, before the listing of its manifests and after each page of that listing arrives, before each group of its manifests and before each key it deletes. A `SYSTEM CAS DROP POOL MEMBER` stopped after its drain began leaves the member retired; rerun it to finish. Stopped before that, it can leave the member as it was. -Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk. This covers the first attempt of every request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. +Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk, except the upload of a part that is being built (see below). This covers the first attempt of every other request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. The S3 client reports a stopped query's error in place of any failed answer from the store, as on a plain S3 disk. This includes an expected answer of a healthy store, such as `404` for a key that does not exist. So the query can still fail with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` when the store answers with an error after the stop. A bulk delete that the store answers successfully, with an error for one of its keys, keeps that key's error. Writes of several queries to one table's metadata can be sent together by one of them. When that query is stopped, such a failed answer can fail the other queries' writes in the same request too. @@ -154,12 +154,72 @@ Two background owners stop `CAS` work at its next step, with their own error: A `GC` round that `SYSTEM CAS GC STOP` ends is recorded as `Stopped` in `system.cas_gc_log`. A manual round whose query is killed or timed out is recorded as `Stopped` when it ends with `QUERY_WAS_CANCELLED`, or with one of the transient errors `S3_ERROR`, `NETWORK_ERROR`, `SOCKET_TIMEOUT`, `TIMEOUT_EXCEEDED`, `ABORTED` or `MEMORY_LIMIT_EXCEEDED`. It is recorded as `Error` when it ends with any other error, for example `READONLY`. A stop that comes after the round's last check leaves the round's own outcome. +A stop also ends the upload of a part that is being built: + +- The `INSERT` ends with `QUERY_WAS_CANCELLED` after `KILL QUERY`, or with `TIMEOUT_EXCEEDED` when it reaches + `max_execution_time` with `timeout_overflow_mode = 'throw'`. It may be retried unchanged. +- The stop is noticed while a blob body is being sent, usually within a second. A bandwidth limit can add its own + wait. No time is promised. +- With `cas_staging_backend = s3` the write to the staging object is what is stopped, also for a data file written + into an existing part. +- A blob body that was cut may still have reached the store. Cleanup is best effort, and the rest is left to GC. The + next mount start removes a staging object. +- The server aborts the incomplete multipart upload of a cut body. If the abort fails, the upload stays until the + bucket's lifecycle rule removes it. +- A stopped upload may log an error line for each cancelled request of a multipart upload. +- A fetch or a move that a query runs itself (`ALTER TABLE ... FETCH PARTITION`, `ALTER TABLE ... MOVE PARTITION`) + is stopped with that query. + +The upload of the result of a merge or a mutation, of a fetched part and of a moved part is stopped too. The stop +reaches the body being sent at its next check. On a test stand the upload stopped within seconds. That is a measured +time, not a bound. + +| What stops the upload | What does not | +|---|---| +| `SYSTEM STOP MERGES`, `SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES` for the table | `KILL QUERY` on a foreground `OPTIMIZE`: the merge runs under its own task. `OPTIMIZE ... DRY RUN PARTS` runs inside the query and stops with it | +| `KILL MUTATION` | A shutdown while a client connection is still open: it waits for the connection first | +| `DROP TABLE`, `DETACH TABLE` | Another replica that is already uploading the same result | +| Server shutdown | `SYSTEM STOP MERGES ... ON VOLUME`: it changes selection and does not cancel a running merge | +| | A server-side copy: no body is streamed | + +What you see after such a stop: + +- A cancelled merge or mutation is expected after a stop, not a failure. A `MergeTree` table usually logs an error + line "Cancelled merging parts" or "Cancelled mutating parts" with code `ABORTED`. A cut that lands at the final + commit can log it at a lower level. A `ReplicatedMergeTree` table logs the cancellation at information level and + leaves `last_exception` of the queue entry as it was. +- A cut with local staging may leave no failed row in `system.part_log`. +- The source parts of a merge or mutation stay active, as long as the table exists. `DROP TABLE` removes its data. +- After `SYSTEM STOP MERGES`, `SYSTEM STOP FETCHES` or `SYSTEM STOP MOVES`, work that is still eligible can be + selected again after the matching `SYSTEM START`. A `MergeTree` table selects afresh, so an insert made while + merges were stopped can change which parts are merged. After a restart, the work is scheduled again. This holds while the table and the work + still exist: a killed mutation is gone. +- A running fetch has a row in `system.replicated_fetches`, also a fetch by relink. A running move has a row in + `system.moves`. + +A stop can leave: + +- The objects of a cancelled merge or mutation whose result part goes to a plain S3 disk of the same storage policy. +- The objects that a stopped byte fetch onto a plain S3 disk had already written. +- A `tmp-fetch_` directory or a `moving/` directory, when the stop coincides with a failed request. A later byte fetch of the same part removes + a `tmp-fetch_` directory only when it uses the same disk and the same temporary path; a retry can choose another disk. The startup + cleanup does not look under `detached/`: there, `ALTER TABLE ... DROP DETACHED PART` removes a named leftover, and it needs the + setting `allow_drop_detached`. A `moving/` directory is + removed when the table is loaded again, if removal of stale moving parts is enabled (the default). + +Known limits: + +- A `SYSTEM STOP` followed by a `SYSTEM START` in quick succession can be missed by an upload that is running. +- Other work can still hold a shutdown, for example a fetch blocked in a read that does not return. +- A running step of an `EXPORT PART` is not cancelled by a shutdown. It is waited for and can hold the shutdown. +- Cleanup after a cut retries its requests. A shutdown with the object store unreachable waits for those retries. + No stop interrupts: -- A request already in flight. +- Any other request already in flight. - The first attempt of a read, and a read that only waits for another reader's result. - A recovery walk that is already running. On S3 the walk of a stopped query still fails at the first error answer. A walk that looks for a record after its last one ends with such an answer, the `404` for that key; a walk that ends at the table's final removal record looks for none. The failed read is not retried. When the stop cuts short the read that follows a refused write of the walk, the walk ends with a retry-later `NETWORK_ERROR` (210) instead of starting again. -- Cleanup that the operation owes after a send, and merges. +- Cleanup that the operation owes after a send. If the stop lands after a metadata write whose outcome is unknown, the error is the retry-later `NETWORK_ERROR` (210), and its message says the write is unresolved or its outcome is unknown. Check the table before you repeat the write. diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 533218442c58..25b9a3f00bd5 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -43,6 +43,9 @@ static struct InitFiu REGULAR(rmt_dedup_conflict_part_name_missing) \ REGULAR(smt_dedup_conflict_part_name_missing) \ REGULAR(merge_tree_sink_on_start_random_sleep) \ + REGULAR(merge_tree_sequential_source_sleep_before_read) \ + REGULAR(replicated_sends_sleep_before_file_send) \ + PAUSEABLE_ONCE(replicated_fetch_pause_after_projections) \ REGULAR(use_delayed_remote_source) \ ONCE(remote_query_executor_cancel_before_send) \ PAUSEABLE_ONCE(remote_query_executor_receive_packet_pause) \ @@ -405,6 +408,7 @@ static struct InitFiu REGULAR(smt_takeover_fake_hardware_error_after_set) \ REGULAR(cas_relink_receiver_force_mechanism_failure) \ PAUSEABLE_ONCE(cas_relink_receiver_pause_before_confirm) \ + REGULAR(cas_relink_receiver_cancel_fetches_in_preparation) \ REGULAR(cas_relink_sender_omit_pool_cookie) \ REGULAR(cas_relink_receiver_drop_forced_disk) \ ONCE(cas_gc_scheduler_fail_before_heartbeat_worker_start) \ diff --git a/src/Common/OOMCanary/OOMCanary.cpp b/src/Common/OOMCanary/OOMCanary.cpp index 69f795a2ba0e..40087318c04d 100644 --- a/src/Common/OOMCanary/OOMCanary.cpp +++ b/src/Common/OOMCanary/OOMCanary.cpp @@ -438,8 +438,8 @@ void OOMCanary::onCanaryOOM() /// Cancel all merges and mutations try { - context->getMergeList().cancelAll(); - LOG_INFO(log, "Cancelled all running merges"); + context->getMergeList().cancelCurrent(); + LOG_INFO(log, "Cancelled currently running merges"); } catch (...) { diff --git a/src/Common/ThreadPool.cpp b/src/Common/ThreadPool.cpp index 40e24478ffa6..37d3a0ea3431 100644 --- a/src/Common/ThreadPool.cpp +++ b/src/Common/ThreadPool.cpp @@ -238,6 +238,9 @@ class JobWithPriority DB::OpenTelemetry::TracingContextOnThread thread_trace_context; + /// Propagated like the tracing context: a job scheduled under `QueryCancellationBlocker` runs under one. + bool query_cancellation_blocked = false; + /// Call stacks of all jobs' schedulings leading to this one std::vector frame_pointers; bool enable_job_stack_trace = false; @@ -253,11 +256,12 @@ class JobWithPriority JobWithPriority( Job job_, Priority priority_, CurrentMetrics::Metric metric, - const DB::OpenTelemetry::TracingContextOnThread & thread_trace_context_, + const DB::OpenTelemetry::TracingContextOnThread & thread_trace_context_, bool query_cancellation_blocked_, bool capture_frame_pointers, ScopedDecrement available_threads_decrement_) : job(job_), priority(priority_), metric_increment(metric), available_threads_decrement(std::move(available_threads_decrement_)), - thread_trace_context(thread_trace_context_), enable_job_stack_trace(capture_frame_pointers) + thread_trace_context(thread_trace_context_), query_cancellation_blocked(query_cancellation_blocked_), + enable_job_stack_trace(capture_frame_pointers) { if (!capture_frame_pointers) return; @@ -542,6 +546,8 @@ ReturnType ThreadPoolImpl::scheduleImpl(Job job, Priority priority, std: metric_scheduled_jobs, /// Tracing context on this thread is used as parent context for the sub-thread that runs the job propagate_opentelemetry_tracing_context ? DB::OpenTelemetry::CurrentContext() : DB::OpenTelemetry::TracingContextOnThread(), + /// Not for pool worker threads (created without propagation), which outlive the scheduling scope + propagate_opentelemetry_tracing_context && DB::ThreadStatus::QueryCancellationBlocker::isActive(), /// capture_frame_pointers DB::Exception::enable_job_stack_trace, std::move(available_threads_decrement)); @@ -1108,6 +1114,11 @@ void ThreadPoolImpl::ThreadFromThreadPool::worker() /// Set up tracing context for this thread by its parent context. DB::OpenTelemetry::TracingContextHolder thread_trace_context("ThreadPool::worker()", job_data->thread_trace_context); + /// The job may attach to the thread group of the scheduling thread and inherit its cancellation predicates. + std::optional cancellation_blocker; + if (job_data->query_cancellation_blocked) + cancellation_blocker.emplace(); + DB::Exception::enable_job_stack_trace = job_data->enable_job_stack_trace; if (DB::Exception::enable_job_stack_trace) DB::Exception::setThreadFramePointers(std::move(job_data->frame_pointers)); diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 419a52981100..adf00011c70e 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -267,9 +267,29 @@ void ThreadStatus::flushUntrackedMemory() memory_tracker.adjustWithUntrackedMemory(current_untracked_memory); } +namespace +{ +thread_local bool query_cancellation_blocked = false; +} + +ThreadStatus::QueryCancellationBlocker::QueryCancellationBlocker() + : previous(std::exchange(query_cancellation_blocked, true)) +{ +} + +ThreadStatus::QueryCancellationBlocker::~QueryCancellationBlocker() +{ + query_cancellation_blocked = previous; +} + +bool ThreadStatus::QueryCancellationBlocker::isActive() +{ + return query_cancellation_blocked; +} + bool ThreadStatus::isQueryCanceled() const { - if (!thread_group) + if (!thread_group || query_cancellation_blocked) return false; if (local_data.query_is_canceled_predicate) @@ -279,7 +299,7 @@ bool ThreadStatus::isQueryCanceled() const void ThreadStatus::throwIfQueryCanceled() const { - if (!thread_group) + if (!thread_group || query_cancellation_blocked) return; if (local_data.throw_if_query_canceled_predicate) diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index c8f60bcd18d5..86018eafe746 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -92,6 +92,10 @@ class ThreadGroup const ContextWeakPtr query_context; const ContextWeakPtr global_context; + /// False for a group from `createWithoutQueryContext` and the groups nested in it: attaching them does not set up + /// query profilers, so detaching keeps the profilers of the thread (e.g. the global profiler of a pool thread). + const bool with_query_context = true; + const FatalErrorCallback fatal_error_callback; const Int32 os_threads_nice_value; @@ -119,13 +123,16 @@ class ThreadGroup ThrowIfQueryCanceledPredicate throw_if_query_canceled_predicate = {}; }; - SharedData getSharedData() + SharedData getSharedData() const { /// Critical section for making the copy of shared_data std::lock_guard lock(mutex); return shared_data; } + /// Must be called before any thread attaches to the group: threads copy the predicates on attach. + void setQueryCancellationPredicates(QueryIsCanceledPredicate is_canceled, ThrowIfQueryCanceledPredicate throw_if_canceled); + /// Mutation shared data void attachInternalTextLogsQueue(const InternalTextLogsQueuePtr & logs_queue, LogsLevel logs_level); void attachQueryForLog(const String & query_, UInt64 normalized_hash = 0); @@ -152,6 +159,16 @@ class ThreadGroup static ThreadGroupPtr createForFlushAsyncInsertQueue(ContextPtr context, ThreadGroupPtr parent_thread_group); static ThreadGroupPtr createForExplainAnalyze(ThreadGroupPtr parent_thread_group); + /// For background work outside of any query (e.g. a system log flush): the threads of the group share its memory + /// tracker, but get no query context and so none of the query settings (e.g. the profilers). + static ThreadGroupPtr createWithoutQueryContext(ContextPtr global_context_); + + /// For a background operation that owns its cancellation (e.g. a replication fetch or a part move): the group of + /// its own, nested in `parent` if there is one (it inherits the predicates of the parent), else without a query + /// context. It is not `createForMergeMutate`: the memory of a fetch or move must not count against the merges and +/// mutations tracker, unless `parent` is a merge's group. + static ThreadGroupPtr createForBackgroundOperation(ContextPtr global_context_, ThreadGroupPtr parent_thread_group); + std::vector getInvolvedThreadIds() const; size_t getPeakThreadsUsage() const; UInt64 getGroupElapsedMs() const; @@ -181,6 +198,7 @@ class ThreadGroup explicit ThreadGroup(ThreadGroupPtr parent_thread_group); ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent_thread_group); + explicit ThreadGroup(const ContextWeakPtr & global_context_); }; /** Encapsulates all per-thread info (ProfileEvents, MemoryTracker, query_id, query context, etc.). @@ -316,6 +334,21 @@ class ThreadStatus : public boost::noncopyable /// Throws the real cancellation cause if the query has been cancelled. No-op if not attached to a query. void throwIfQueryCanceled() const; + /// While alive, `isQueryCanceled` returns false and `throwIfQueryCanceled` does nothing in the current thread. + /// For code that must not be interrupted, like the finalization of a committed transaction. + class QueryCancellationBlocker : private boost::noncopyable + { + public: + QueryCancellationBlocker(); + ~QueryCancellationBlocker(); + + /// Whether a blocker is alive in the current thread. `ThreadPool` carries it into the jobs scheduled under it. + static bool isActive(); + + private: + bool previous; + }; + /// Proper cal for fatal_error_callback void onFatalError(); diff --git a/src/Common/tests/gtest_thread_group_switcher.cpp b/src/Common/tests/gtest_thread_group_switcher.cpp index 6ea889809c7c..93f72864ec94 100644 --- a/src/Common/tests/gtest_thread_group_switcher.cpp +++ b/src/Common/tests/gtest_thread_group_switcher.cpp @@ -130,4 +130,49 @@ TEST(ThreadGroupSwitcher, RestoresBorrowedThreadName) t.join(); } +/// A group without a query context, and a child of it, attach and detach like any other group: +/// the original group and name come back. +TEST(ThreadGroupSwitcher, WithoutQueryContextRestoresGroupAndName) +{ + std::thread t([&] + { + ThreadStatus ts; + auto context = getContext().context; + auto G0 = std::make_shared(context, 0); + auto contextless = ThreadGroup::createWithoutQueryContext(context); + auto child = ThreadGroup::createForExplainAnalyze(contextless); + + EXPECT_TRUE(G0->with_query_context); + EXPECT_FALSE(contextless->with_query_context); + EXPECT_FALSE(child->with_query_context); + EXPECT_TRUE(ThreadGroup::createForExplainAnalyze(G0)->with_query_context); + + /// Starting detached. + for (const auto & group : {contextless, child}) + { + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE); + EXPECT_EQ(getCurrentThreadGroup(), group); + } + EXPECT_EQ(getCurrentThreadGroup(), nullptr); + } + + /// Starting attached to G0 and named. + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(G0); + for (const auto & group : {contextless, child}) + { + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + EXPECT_EQ(getCurrentThreadGroup(), group); + EXPECT_EQ(getThreadName(), ThreadName::MERGE_MUTATE); + } + EXPECT_EQ(getCurrentThreadGroup(), G0); + EXPECT_EQ(getThreadName(), ThreadName::TCP_HANDLER); + } + CurrentThread::detachFromGroupIfNotDetached(); + }); + t.join(); +} + } // namespace DB diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp b/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp index 57b9633c53a9..039fbc4729a6 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp +++ b/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -824,6 +825,9 @@ TransactionCommitOutcomeVariant DiskObjectStorageTransaction::tryCommit(const Tr void DiskObjectStorageTransaction::undo() noexcept { + /// Keep the retries of this cleanup when the query or merge is cancelled: nothing removes orphaned blobs later. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + for (const auto & [location, blobs] : written_blobs) { try diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp index ad32d87eeda5..00fc726d7ec4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -928,12 +929,14 @@ void ObjectStorageBackend::publish(const BlobPublishRequest & request, Transport /// Unconditional rewrite: default request mode and multipart policy, so generation stores are /// not restricted by the conditional single-PUT cap. + WriteSettings write_settings = blobPublicationWriteSettings(); + write_settings.remote_throttler = BodyGuardScope::forKey(request.destination_key); auto out = object_storage->writeObject( StoredObject(request.destination_key), WriteMode::Rewrite, /*attributes=*/std::nullopt, blob_publication_detail::blobWriteBufferSize(streaming->fresh_envelope.size() + streaming->payload_size), - blobPublicationWriteSettings()); + write_settings); out->write(streaming->fresh_envelope.data(), streaming->fresh_envelope.size()); blob_publication_detail::copyVerifiedPayloadAndFinalize(*payload, *out, *streaming, request.destination_key, "ObjectStorageBackend::publish: source yielded {}{} payload bytes for {}, declared {} -- upload aborted, nothing published"); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 7fe8fde5bf08..161837ec81cb 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -235,4 +235,43 @@ std::function OwnerScope::effectiveCheck() return current.background; } +namespace +{ + +thread_local std::function upload_stop; + +} + +std::function uploadStopCheck() +{ + const auto & owner = OwnerScope::current; + /// The returned callable invokes the group's predicate directly, bypassing the blocker check of + /// `throwIfQueryCanceled`, and runs on pool threads that do not see this thread's blocker. So the blocker is + /// honoured here, when the stop is captured. + if (owner.owed || owner.shared || ThreadStatus::QueryCancellationBlocker::isActive()) + return {}; + ThreadGroupPtr thread_group = CurrentThread::getGroup(); + if (!thread_group) + return {}; + auto predicate = thread_group->getSharedData().throw_if_query_canceled_predicate; + if (!predicate) + return {}; + return [keep_group = std::move(thread_group), stop = std::move(predicate)] { stop(); }; +} + +UploadStopScope::UploadStopScope(std::function stop) + : saved(std::exchange(upload_stop, std::move(stop))) +{ +} + +UploadStopScope::~UploadStopScope() +{ + upload_stop = std::move(saved); +} + +const std::function & UploadStopScope::current() +{ + return upload_stop; +} + } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h index fab5f4478f5f..70ac37dcd572 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -59,13 +59,15 @@ namespace DB::Cas /// except that a vetoed resend with refreshed credentials ends as a retry-later `NETWORK_ERROR` carrying the /// refusal. A scan head throws the query's verdict. /// - A killed query's conditional write that loses a race can end as `ABORTED` "conflict": the S3 client replaces the -/// 412 with the query's exception, and the settling read shows the other writer's object. +/// 412 with the query's exception, and the settling read shows the other writer's object. Where the thread's +/// cancellation is masked (`shared` held with a `ThreadStatus::QueryCancellationBlocker`), the 412 stays a conflict. /// - An unresolved sent write keeps its "outcome unknown" exit; a later owner verdict does not overwrite it. /// - `OwnerScope::owed` removes the checks before work and the query's cut of a pause: the pause runs to its end, and /// the next attempt is sent unless the fence, the lease or a deadline refuses it after the pause. A failure after a /// stop is still not retried, and a background owner's verdict still replaces it. `OwnerScope::shared` removes the -/// owner. Neither hides a query from the S3 client, which replaces a failed request's answer with the query's -/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. +/// owner. `owed` does not hide a query from the S3 client, which replaces a failed request's answer with the query's +/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. Where the thread's +/// cancellation is masked, such as `owed` nested under `shared` held with the blocker, nothing is replaced. /// - Code above the engine may still do follow-up work its own counts bound, such as another recovery walk. With a /// lease loss or a credential refusal at the same time, the error can be the less specific of the two. @@ -78,7 +80,8 @@ std::exception_ptr ownerStopRequested(); /// True when the thread's query, not a background owner, asked to stop. False inside `shared`. /// The S3 client throws the query's verdict in place of a failed request's answer, but not of one key's error in a -/// bulk delete that succeeded, and it cannot see a background owner. +/// bulk delete that succeeded, and it cannot see a background owner. It sees no query where the thread's cancellation +/// is masked by a `ThreadStatus::QueryCancellationBlocker`. bool queryStopRequested(); /// Rethrows the verdict of the background owners in scope, except inside `owed` or `shared`. Ignores the query. @@ -96,7 +99,8 @@ std::exception_ptr backgroundStopRequested(); /// True when `e` is the query's stored cancellation cause, the one verdict rethrown as the same object to every thread /// the query stops; false inside `shared`. A kill or timeout without a stored cause and every background owner's verdict /// are built anew on each check, so they never match. Such a cause is neither a store answer nor a local fault, -/// whatever its code or type. +/// whatever its code or type. The cause is recognized only while the thread's cancellation check is enabled: under a +/// `QueryCancellationBlocker` the check does not throw and the answer is false. bool isQueryStoredCause(const std::exception_ptr & e); /// Adds `message` to `e`, the exception being handled, unless `e` is the query's stored cause, whatever the scope: @@ -136,8 +140,9 @@ class OwnerScope static OwnerScope background(std::function throw_if_stopped); /// Work owed to a possibly-sent write, a failed commit or a claimed resource: no throwing check. static OwnerScope owed(); - /// Work for several callers: CAS owner checks see no owner. The S3 client still replaces a failed answer with the - /// exception of the thread's query. + /// Work for several callers: CAS owner checks see no owner. The caller must also hold a + /// `ThreadStatus::QueryCancellationBlocker` for the scope's lifetime. Without it the S3 client replaces a failed + /// answer with the thread's query exception, and nothing inside this scope recognizes that as no store answer. static OwnerScope shared(); /// This thread's background owner check, to keep calling inside a later `shared` scope. Valid only while the @@ -164,10 +169,38 @@ class OwnerScope friend void throwIfQueryStopped(); friend std::exception_ptr backgroundStopRequested(); friend bool isQueryStoredCause(const std::exception_ptr & e); + friend std::function uploadStopCheck(); static thread_local State current; State saved; bool active = true; }; +/// The check an upload of a new build runs while it sends, built on the publishing thread; the callable may run on any +/// thread. Empty inside `owed` or `shared`, on a thread with no thread group, and while the calling thread holds a +/// `QueryCancellationBlocker`. The blocker is read when the stop is captured; the callable runs on pool threads and +/// does not read it again, so a stop captured outside a blocker stays live. Otherwise it runs the group's throwing +/// cancellation predicate. It holds the thread group, so it may outlive the scope that built it, but not the +/// operation that installed the group's inherited predicates (a merge's list entry). Background owners are not part +/// of it. +std::function uploadStopCheck(); + +/// Carries the stop check of the build being published from the publishing thread to the code that builds each +/// body's throttler. Scopes nest; destruction restores the enclosing value. +class UploadStopScope +{ +public: + explicit UploadStopScope(std::function stop); + ~UploadStopScope(); + + UploadStopScope(const UploadStopScope &) = delete; + UploadStopScope & operator=(const UploadStopScope &) = delete; + + /// Empty outside a scope. + static const std::function & current(); + +private: + std::function saved; +}; + } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp new file mode 100644 index 000000000000..854bff8c697c --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp @@ -0,0 +1,67 @@ +#include + +#include +#include + +namespace DB::Cas +{ + +namespace +{ + +class UploadGuard final : public IThrottler +{ +public: + UploadGuard(ThrottlerPtr bandwidth_, std::function stop_) + : bandwidth(std::move(bandwidth_)) + , stop(std::move(stop_)) + { + } + + bool throttle(size_t amount, size_t max_block_ns) override + { + stop(); + const bool blocked = bandwidth && bandwidth->throttle(amount, max_block_ns); + stop(); + return blocked; + } + + bool isThrottling() const override { return bandwidth && bandwidth->isThrottling(); } + Int64 getAvailable() override { return bandwidth ? bandwidth->getAvailable() : std::numeric_limits::max(); } + UInt64 getMaxSpeed() const override { return bandwidth ? bandwidth->getMaxSpeed() : 0; } + UInt64 getMaxBurst() const override { return bandwidth ? bandwidth->getMaxBurst() : 0; } + +private: + ThrottlerPtr bandwidth; + std::function stop; +}; + +thread_local String bound_key; +thread_local ThrottlerPtr bound_throttler; + +} + +ThrottlerPtr makeUploadGuard(ThrottlerPtr bandwidth, std::function stop) +{ + if (!stop) + return bandwidth; + return std::make_shared(std::move(bandwidth), std::move(stop)); +} + +BodyGuardScope::BodyGuardScope(String key, ThrottlerPtr throttler) + : saved{std::exchange(bound_key, std::move(key)), std::exchange(bound_throttler, std::move(throttler))} +{ +} + +BodyGuardScope::~BodyGuardScope() +{ + bound_key = std::move(saved.key); + bound_throttler = std::move(saved.throttler); +} + +ThrottlerPtr BodyGuardScope::forKey(const String & key) +{ + return bound_throttler && bound_key == key ? bound_throttler : nullptr; +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h new file mode 100644 index 000000000000..a9a0ac1796af --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h @@ -0,0 +1,40 @@ +#pragma once +#include +#include + +#include + +namespace DB::Cas +{ + +/// A throttler for one request body that also runs `stop` around every `throttle` call, so the sender notices a +/// stopped owner at each send-budget refill. The amount and `max_block_ns` reach `bandwidth` unchanged. +/// Returns `bandwidth` itself, possibly null, when `stop` is empty. With a stop and no `bandwidth`, `throttle` +/// runs the stop and returns false, and the limits report as absent. +ThrottlerPtr makeUploadGuard(ThrottlerPtr bandwidth, std::function stop); + +/// Binds one object key to the throttler of its body on this thread, for backend code that builds the write settings +/// of that body and has no parameter to receive it. Scopes nest: the innermost binding is the only one visible. +class BodyGuardScope +{ +public: + BodyGuardScope(String key, ThrottlerPtr throttler); + ~BodyGuardScope(); + + BodyGuardScope(const BodyGuardScope &) = delete; + BodyGuardScope & operator=(const BodyGuardScope &) = delete; + + /// The throttler bound to exactly `key` on this thread, null for any other key or outside a scope. + static ThrottlerPtr forKey(const String & key); + +private: + struct Binding + { + String key; + ThrottlerPtr throttler; + }; + + Binding saved; +}; + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 02d8803be693..e92692915508 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -503,6 +504,7 @@ void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st Cas::BlobSource source; source.size = pb.size; source.publication_attempted = pb.publication_attempted; + source.remote_throttler = pb.remote_throttler; if (pb.backend == Cas::StagingBackend::S3) { source.server_side_copy_from = pb.staging_key; @@ -687,8 +689,13 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, throw Exception(ErrorCodes::LOGICAL_ERROR, "ContentAddressedTransaction: staged entries or removal marks for {}/{} without a Build", ns.string(), ref); - /// Promote is an atomic owner move that validates every blob dependency proof. - const Cas::ManifestId manifest_id = precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); + /// Promote is an atomic owner move that validates every blob dependency proof. Only the uploads of a new build may + /// be stopped: nothing names it yet, and the promote itself must not be cut. + const Cas::ManifestId manifest_id = [&] + { + Cas::UploadStopScope upload_stop(Cas::uploadStopCheck()); + return precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); + }(); /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` right /// before the durable promote call. A no-op in production (nothing ever arms it). @@ -987,14 +994,16 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const void ContentAddressedTransaction::stageBlobPartFile( const ContentAddressedMetadataStorage::Route & route, - const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend) + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend, + ThrottlerPtr remote_throttler) { /// Do not upload here. Record the pending blob for post-precommit publication; dependency state /// remains absent until the upload succeeds and its result is merged. /// The staging bytes are kept (the transaction owns them) — a local temp file for /// `Cas::StagingBackend::Local`, or an S3 staging object for `Cas::StagingBackend::S3`. auto & st = stagingFor(route); - st.pending_blobs.push_back({ref, staging_key, size, backend}); + st.pending_blobs.push_back( + {ref, staging_key, size, backend, std::make_shared>(false), std::move(remote_throttler)}); (void)buildFor(route, st); Cas::ManifestEntry entry; @@ -1181,8 +1190,11 @@ std::unique_ptr ContentAddressedTransaction::writeFile( const Cas::PoolPtr pool = metadata_storage.store(); const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); - - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); + /// Only the throttler travels: the caller's other settings describe its own buffer, not this upload. + WriteSettings sink_settings; + sink_settings.remote_throttler = Cas::makeUploadGuard(settings.remote_throttler, Cas::uploadStopCheck()); + auto object_sink = metadata_storage.objectStorage()->writeObject( + StoredObject(staging_key), WriteMode::Rewrite, /*attributes=*/std::nullopt, DBMS_DEFAULT_BUFFER_SIZE, sink_settings); return std::make_unique( std::move(object_sink), @@ -1192,16 +1204,17 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) + [this, route = *r, hash_algo, throttler = settings.remote_throttler]( + const std::string & hash_hex, size_t size, const std::string & key) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); + stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3, throttler); }, [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); } /// Oversized inline candidates use local staging even on disks with S3 staging enabled. - auto create_local_blob_writer = [this, route = *r, hash_algo, buf_size, + auto create_local_blob_writer = [this, route = *r, hash_algo, buf_size, throttler = settings.remote_throttler, adaptive = settings.use_adaptive_write_buffer, initial_size = settings.adaptive_write_buffer_initial_size] { return std::make_unique( @@ -1210,10 +1223,10 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, adaptive, initial_size, - [this, route, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) + [this, route, hash_algo, throttler](const std::string & hash_hex, size_t size, const std::string & temp_path) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local); + stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local, throttler); }); }; @@ -1257,6 +1270,21 @@ void ContentAddressedTransaction::createDirectoryRecursive(const std::string &) metadata_storage.checkOpAdmitted(CasOpClass::Write); } +void ContentAddressedTransaction::discardStagingOf(const ContentAddressedMetadataStorage::Route & r) +{ + auto * st = findStaging(r); + if (!st) + return; + st->content_removed.clear(); + clearEntries(*st); + st->base_manifest_ref.reset(); + if (st->build) + { + st->build->abandon(); + st->build.reset(); + } +} + void ContentAddressedTransaction::removeDirectory(const std::string & path) { /// CONTRACT: `removeDirectory`/`moveDirectory` mutate durable refs at CALL TIME, not at commit — @@ -1279,22 +1307,7 @@ void ContentAddressedTransaction::removeDirectory(const std::string & path) if (auto r = routeOf(path); r && !r->ref.empty() && r->file.empty()) { metadata_storage.partAccess()->dropRefIfPresent(r->refKey()); - /// This transaction's staged removal marks for the same ref (content_removed, populated by - /// unlinkFile's per-file unlinks that the MergeTree fast-removal path issues right before this - /// call) are superseded by the whole-part ref-drop just performed above — discard them so - /// publishStaging's committed-ref repoint branch never chases an already-dropped ref, and the - /// dominant removal path pays zero repoints (one ref-drop only). - if (auto * st = findStaging(*r)) - { - st->content_removed.clear(); - clearEntries(*st); - st->base_manifest_ref.reset(); - if (st->build) - { - st->build->abandon(); - st->build.reset(); - } - } + discardStagingOf(*r); return; } } @@ -1390,6 +1403,7 @@ void ContentAddressedTransaction::removeRecursive(const std::string & path, cons if (r && !r->ref.empty() && r->file.empty()) { metadata_storage.partAccess()->dropRefIfPresent(r->refKey()); + discardStagingOf(*r); return; } /// A projection subdir: virtual (nested in the parent tree) - removal is a no-op; the @@ -2089,6 +2103,8 @@ void fanOutBlobUploads( /// `waitForAllToFinish` only waits (never throws), so it is safe on the unwinding path (the B90 /// lesson, `threadPoolCallbackRunner.h:68`). SCOPE_EXIT_SAFE({ ThreadPoolCallbackRunnerLocal::waitForAllToFinish(handles); }); + /// Read on the publishing thread, so every worker is stopped, or not, as its publisher would be. + const std::function upload_stop = UploadStopScope::current(); size_t idx = 0; for (const auto & [ref, req] : grouped) { @@ -2103,8 +2119,9 @@ void fanOutBlobUploads( /// task is now runnable) and the pre-reserved `emplace_back` records it without allocating, so /// there is no window in which a scheduled task is untracked. handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks, - group = CurrentThread::getGroup()] + group = CurrentThread::getGroup(), upload_stop] { + UploadStopScope adopted_stop(upload_stop); throwUnlessInThreadGroup(group, "CAS blob upload worker"); if (task_hooks && task_hooks->in_task) task_hooks->in_task(req_by_value.ref); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 8d9271f112fe..dd9d1ec2756e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -176,6 +176,8 @@ class ContentAddressedTransaction : public IMetadataTransaction /// record into another part, and the copy shares the flag, so the parts together copy /// the staged envelope at most once. std::shared_ptr> publication_attempted = std::make_shared>(false); + /// The `remote_throttler` of the settings the file was written with; a hardlink or a move keeps it. + ThrottlerPtr remote_throttler; }; std::vector pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted. }; @@ -202,7 +204,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, - Cas::StagingBackend backend); + Cas::StagingBackend backend, ThrottlerPtr remote_throttler); /// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`, /// so the S3 staging object holds `[header][payload]` and the promote @@ -235,6 +237,10 @@ class ContentAddressedTransaction : public IMetadataTransaction PartStaging & stagingFor(const ContentAddressedMetadataStorage::Route & r); /// Finds existing staging state without creating an entry; returns nullptr when untouched. PartStaging * findStaging(const ContentAddressedMetadataStorage::Route & r); + /// A whole-part removal supersedes what this transaction staged for the same ref: files written, + /// per-file removal marks and an open build. Without the discard the commit would publish a part the + /// caller just removed, or chase a ref that is already dropped. + void discardStagingOf(const ContentAddressedMetadataStorage::Route & r); /// Finds the staged manifest entry for a routed file without consulting committed storage. const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const; /// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index d1f799b2a8e6..744036270fb2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -525,6 +526,9 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// each iteration of this loop builds one. The verbatim staged copy is additionally /// once-only per staging object: `beginPublication` spends a flag that the caller shares /// among every source over that object. + std::optional body_guard; + if (transport == BlobPublicationTransport::Streaming) + body_guard.emplace(key, makeUploadGuard(source.remote_throttler, UploadStopScope::current())); op.publish(BlobPublishRequest{key, std::move(publication)}, Retry::once()); } catch (...) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index 0329981a3449..e9d1b75debdb 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -33,6 +34,8 @@ struct BlobSource std::optional server_side_copy_from; std::shared_ptr> publication_attempted = std::make_shared>(false); + /// The bandwidth limit of the writer that produced the bytes; null for none. + ThrottlerPtr remote_throttler; /// Atomically consume the logical source's first-publication privilege -- the verbatim staged copy /// is available to exactly one physical publication of this source, whichever one gets here first. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index b7b9374a8572..074fa3c0ce1c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -1830,8 +1831,11 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( bool unresolved_sent = false; try { - /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk still - /// fails at its first error answer, the `404` that ends every walk included. + /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk fails at + /// its first failed request, because the client replaces that failure with the query's exception + /// (the `404` that ends an ordinary walk is such a failure). A walk that ends on a successful read, + /// or whose failed write is settled by a successful read, is not affected. Nothing is replaced + /// while the thread's cancellation is masked. const auto owed = Cas::OwnerScope::owed(); walked = runRecoveryWalkOnce( ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, unresolved_sent, token); @@ -2650,6 +2654,9 @@ void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared const std::function owner_check = Cas::OwnerScope::effectiveCheck(); /// One caller's owner must not decide work done for several callers. const auto shared = Cas::OwnerScope::shared(); + /// The S3 client replaces a failed request's result with the thread's cancellation cause, which says nothing + /// about the store. Work done for several callers must be judged by the store's answer. + const ThreadStatus::QueryCancellationBlocker no_query_cancellation; /// Fairness baton pass: serve flushes only until the caller's OWN item is done, then hand off to a /// woken waiter. diff --git a/src/Disks/tests/cas_fake_generation_object_storage.h b/src/Disks/tests/cas_fake_generation_object_storage.h new file mode 100644 index 000000000000..b7dbb8233692 --- /dev/null +++ b/src/Disks/tests/cas_fake_generation_object_storage.h @@ -0,0 +1,440 @@ +#pragma once + +#include "config.h" + +#if USE_AWS_S3 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ +extern const int BAD_ARGUMENTS; +} + +namespace DB::Cas::tests +{ + +/// A `LocalObjectStorage` that reports the GCS generation dialect +/// (`conditionalOpsUseGenerationTokens() == true`) and a non-`Local` `getType()`, so +/// `ContentAddressedMetadataStorage::openPoolView` builds its backend in `Mode::Native` with +/// `native_token_type == Dialect::Generation`. The fake also advertises native copy so generation +/// token mode can exercise explicit S3 staging without endpoint/provider heuristics. +/// +/// Holds every object entirely in memory, keyed by the BARE CAS key exactly as `Backend` hands it to +/// `object_storage` (e.g. `"pool/_probe//token"`). Native mode never asks `object_storage` to +/// resolve that key against anything (`ContentAddressedMetadataStorage::physicalKey` is a documented +/// no-op for Native, since a real S3 client resolves a bucket-relative key against its own bucket/prefix +/// configuration internally) -- so this fake never needs a notion of "resolve a key to a location" at +/// all, unlike a real filesystem-backed object storage would. That sidesteps the class of bug a +/// resolve-then-strip round trip through the real `LocalObjectStorage` file/list implementation is prone +/// to (a key is a key, with no round trip to get wrong), and it never touches the real filesystem, so it +/// cannot leak files into the test process's working directory either. +/// +/// A writable Native-mode mount always runs the mandatory capability battery (`CasProbe.cpp`), which +/// requires REAL conditional-write enforcement: the precondition is evaluated when a write completes, +/// signaled by an `S3Exception` carrying the canonical `PreconditionFailed` name (see +/// `ObjectStorageBackend::finalizeConditionalWrite`). `writeObject` therefore buffers bytes in memory and +/// defers both the precondition check and the commit to `finalize`, mirroring how a real object store +/// only commits -- and only then can reject -- on PUT completion. +class FakeGenerationObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + /// Report the S3 ETag dialect instead: a token is a digest of the object's bytes, so the same bytes + /// written or copied again carry the same token, as on S3 without KMS. Set before `startup`. + bool content_derived_etags = false; + + DB::ObjectStorageType getType() const override { return DB::ObjectStorageType::S3; } + bool conditionalOpsUseGenerationTokens() const override { return !content_derived_etags; } + std::optional isBucketVersioningEnabled(const DB::ObjectStorageControlRequest &) const override { return false; } + bool supportsRetryProfile(DB::ObjectStorageRetryProfile) const override { return true; } + bool supportsCopyMode(DB::ObjectStorageCopyMode mode) const override + { + return mode == DB::ObjectStorageCopyMode::Default || mode == DB::ObjectStorageCopyMode::NativeOnly; + } + + /// One `writeObject` or `copyObject` as the store received it. + struct WriteRecord + { + std::string key; + DB::WriteSettings settings; + bool copy = false; + bool throttled = false; + std::exception_ptr throttle_error; + }; + + /// Keys whose write calls its `remote_throttler->throttle(32768, 0)` once before the store takes the bytes, as a + /// socket does at a send-budget refill. What that call throws fails the write. Set before the writes start. + std::function throttle_while_writing; + /// Runs on the writing thread right before that call. + std::function before_throttle; + + /// Every write and copy so far, in the order the store received them. + std::vector> records() const + { + std::lock_guard lock(mutex); + return {recorded.begin(), recorded.end()}; + } + + std::unique_ptr writeObject( + const DB::StoredObject & object, + DB::WriteMode mode, + std::optional /*attributes*/, + size_t /*buf_size*/, + const DB::WriteSettings & write_settings) override + { + if (mode != DB::WriteMode::Rewrite) + throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "FakeGenerationObjectStorage only supports Rewrite"); + auto record = std::make_shared(); + record->key = object.remote_path; + record->settings = write_settings; + { + std::lock_guard lock(mutex); + recorded.push_back(record); + } + return std::make_unique( + *this, object.remote_path, write_settings.object_storage_write_if_none_match, + write_settings.object_storage_write_if_match, std::move(record)); + } + + bool exists(const DB::StoredObject & object) const override + { + std::lock_guard lock(mutex); + return objects.contains(object.remote_path); + } + + std::unique_ptr readObject( + const DB::StoredObject & object, + const DB::ReadSettings & /*read_settings*/, + std::optional /*read_hint*/, + bool /*use_external_buffer*/, + bool /*restrict_seek*/) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(object.remote_path); + if (it == objects.end()) + /// `RESOURCE_NOT_FOUND`, not a plain `DB::Exception`: `Backend::probeSentinelRaw`'s Native + /// path (`CasObjectStorageBackend.cpp`) classifies absence ONLY from a caught `S3Exception` + /// carrying `NO_SUCH_KEY`/`RESOURCE_NOT_FOUND` (or the matching exception name) -- anything + /// else, including an unrecognized exception TYPE, falls through to `ProbeOutcome:: + /// Indeterminate` (fail-closed). A bodyless HEAD on a real absent S3 key throws exactly this + /// code, since the SDK cannot parse a `` from a body that was never sent. + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + /// Copies the bytes, matching a real remote read (no shared ownership with the stored entry, so + /// a later overwrite of this key cannot mutate bytes a caller is still reading). + return std::make_unique(object.remote_path, it->second.bytes); + } + + DB::ObjectMetadata getObjectMetadata(const std::string & path, bool with_tags) const override + { + auto metadata = tryGetObjectMetadata(path, with_tags); + if (!metadata) + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + return *metadata; + } + + std::optional tryGetObjectMetadata(const std::string & path, bool /*with_tags*/) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(path); + if (it == objects.end()) + return std::nullopt; + DB::ObjectMetadata metadata; + metadata.size_bytes = it->second.bytes.size(); + metadata.etag = tokenOf(it->second); + return metadata; + } + + std::optional tryGetObjectMetadataWithNativeToken(const std::string & path, bool with_tags) const override + { + return tryGetObjectMetadata(path, with_tags); + } + + /// This fake advertises every retry profile, and an in-memory store has no retry behaviour to + /// vary, so the profile-aware overloads simply forward. A storage that claimed the capability + /// without implementing them would refuse every control-plane request of a writable mount. + std::optional tryGetObjectMetadataWithNativeToken( + const std::string & path, bool with_tags, const DB::ObjectStorageControlRequest &) const override + { + return tryGetObjectMetadata(path, with_tags); + } + + DB::ObjectStorageIteratorPtr iterate( + const std::string & path_prefix, size_t max_keys, bool with_tags, const std::optional & start_after, + const DB::ObjectStorageControlRequest &) const override + { + return DB::LocalObjectStorage::iterate(path_prefix, max_keys, with_tags, start_after); + } + + DB::ConditionalRemoveResult removeObjectIfTokenMatches( + const DB::StoredObject & object, const std::string & etag, const DB::ObjectStorageControlRequest &) override + { + return removeObjectIfTokenMatches(object, etag); + } + using DB::LocalObjectStorage::removeObjectIfTokenMatches; + + /// A real S3 GET answers with the object's incarnation, which is what the backend reads its + /// bytes AND its generation from in one request. Quoted, the way the SDK's ETag field carries a + /// generation across the HTTP boundary. + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(object.remote_path); + if (it == objects.end()) + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + DB::SmallObjectDataWithMetadata result; + result.data = it->second.bytes; + result.metadata.size_bytes = it->second.bytes.size(); + result.metadata.etag = transportTokenOf(it->second); + return result; + } + + void removeObjectIfExists(const DB::StoredObject & object) override + { + std::lock_guard lock(mutex); + objects.erase(object.remote_path); + } + + void removeObjectsIfExist(const DB::StoredObjects & objects_to_remove) override + { + std::lock_guard lock(mutex); + for (const auto & object : objects_to_remove) + objects.erase(object.remote_path); + } + + /// S3 sends an unconditional delete under every retry profile; the intent probe and GC use it. + void removeObjectsIfExistUnderProfile(const DB::StoredObjects & objects_to_remove, const DB::ObjectStorageControlRequest &) override + { + removeObjectsIfExist(objects_to_remove); + } + + /// `path` is a bare CAS-relative prefix (e.g. `"pool/"` or `"pool/_probe/"`) -- exactly what + /// `Backend::list`'s Native-mode path passes through unchanged (it applies no prefix stripping of + /// its own there) and expects back on every listed key. A plain string-prefix scan over the + /// in-memory keys already IS that key space, so there is no separate "physical" representation to + /// resolve to or strip back off. + void listObjects(const std::string & path, DB::RelativePathsWithMetadata & children, size_t max_keys) const override + { + std::lock_guard lock(mutex); + for (const auto & [key, entry] : objects) + { + if (!key.starts_with(path)) + continue; + DB::ObjectMetadata metadata; + metadata.size_bytes = entry.bytes.size(); + metadata.etag = tokenOf(entry); + children.push_back(std::make_shared(key, std::move(metadata))); + if (max_keys != 0 && children.size() >= max_keys) + break; + } + } + + DB::ConditionalRemoveResult removeObjectIfTokenMatches(const DB::StoredObject & object, const std::string & etag) override + { + std::lock_guard lock(mutex); + DB::ConditionalRemoveResult result; + auto it = objects.find(object.remote_path); + if (it == objects.end()) + { + result.outcome = DB::ConditionalRemoveOutcome::NotFound; + return result; + } + if (tokenOf(it->second) != etag) + { + result.outcome = DB::ConditionalRemoveOutcome::TokenMismatch; + return result; + } + objects.erase(it); + result.outcome = DB::ConditionalRemoveOutcome::Removed; + return result; + } + + /// Checks the write-once/exact-token precondition against the current generation and, on success, + /// stores `bytes` and mints the next generation. Throws an `S3Exception` naming `PreconditionFailed` + /// on a lost condition -- the one signal `finalizeConditionalWrite` classifies as + /// `ConditionalWriteOutcome::PreconditionLost` rather than an ordinary failure. + /// Returns the new object's token as a real store returns it in the write response: the backend + /// attributes the write to that token and nothing reads it back. + std::string commitConditionalWrite(const std::string & key, const std::string & bytes, + const std::string & if_none_match, const std::string & if_match) + { + std::lock_guard lock(mutex); + auto it = objects.find(key); + const bool exists_now = it != objects.end(); + if (!if_none_match.empty() && exists_now) + throw DB::S3Exception("FakeGenerationObjectStorage: if-none-match precondition failed", + Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + if (!if_match.empty() && (!exists_now || tokenOf(it->second) != if_match)) + throw DB::S3Exception("FakeGenerationObjectStorage: if-match precondition failed", + Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + + Entry & entry = objects[key]; + entry = Entry{bytes, next_generation++}; + return transportTokenOf(entry); + } + + /// A same-store copy of the stored bytes, counted per destination key. + void copyObject( /// NOLINT + const DB::StoredObject & object_from, + const DB::StoredObject & object_to, + const DB::ReadSettings & /*read_settings*/, + const DB::WriteSettings & write_settings, + std::optional /*object_to_attributes*/ = {}) override + { + std::lock_guard lock(mutex); + auto record = std::make_shared(); + record->key = object_to.remote_path; + record->settings = write_settings; + record->copy = true; + recorded.push_back(std::move(record)); + auto it = objects.find(object_from.remote_path); + if (it == objects.end()) + throw DB::S3Exception("FakeGenerationObjectStorage: copy source does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + Entry copy{it->second.bytes, next_generation++}; + objects[object_to.remote_path] = std::move(copy); + ++copies_to[object_to.remote_path]; + } + + std::map copiesByDestination() const + { + std::lock_guard lock(mutex); + return copies_to; + } + +private: + struct Entry + { + std::string bytes; + uint64_t generation; + }; + + std::string tokenOf(const Entry & entry) const + { + if (content_derived_etags) + return getHexUIntLowercase(sipHash128(entry.bytes.data(), entry.bytes.size())); + return std::to_string(entry.generation); + } + + /// The token as the SDK's ETag field carries it: quoted for a GCS generation. + std::string transportTokenOf(const Entry & entry) const + { + return content_derived_etags ? tokenOf(entry) : "\"" + tokenOf(entry) + "\""; + } + + /// Buffers the whole body in memory so the entry is committed exactly once, at `finalize`, and only after the + /// precondition has been checked. + class ConditionalWriteBuffer final : public DB::WriteBufferFromFileBase + { + public: + ConditionalWriteBuffer(FakeGenerationObjectStorage & storage_, std::string key_, + std::string if_none_match_, std::string if_match_, std::shared_ptr record_) + : DB::WriteBufferFromFileBase(/*buf_size=*/8192, nullptr, 0) + , storage(storage_), key(std::move(key_)) + , if_none_match(std::move(if_none_match_)), if_match(std::move(if_match_)) + , record(std::move(record_)) + { + } + + void sync() override {} + std::string getFileName() const override { return key; } + + /// The write response's own incarnation, quoted the way the SDK's ETag field carries a GCS + /// generation across the HTTP boundary -- the backend is what strips that transport syntax. + std::optional getResultObjectETag() const override { return committed_generation; } + + protected: + void nextImpl() override + { + if (!offset()) + return; + buffered.append(working_buffer.begin(), offset()); + } + + void finalizeImpl() override + { + next(); + const auto & throttler = record->settings.remote_throttler; + if (throttler && storage.throttle_while_writing && storage.throttle_while_writing(key)) + throttleOnce(*throttler); + committed_generation = storage.commitConditionalWrite(key, buffered, if_none_match, if_match); + } + + void throttleOnce(DB::IThrottler & throttler) + { + if (storage.before_throttle) + storage.before_throttle(key); + record->throttled = true; + try + { + throttler.throttle(32768, 0); + } + catch (...) + { + record->throttle_error = std::current_exception(); + throw; + } + } + + private: + FakeGenerationObjectStorage & storage; + std::string key; + std::string if_none_match; + std::string if_match; + std::string buffered; + std::optional committed_generation; + std::shared_ptr record; + }; + + mutable std::mutex mutex; + std::map objects; + std::map copies_to; + std::vector> recorded; + uint64_t next_generation = 1; +}; + +inline std::shared_ptr makeFakeGenerationObjectStorageForTest() +{ + static std::atomic counter{0}; + const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); + const auto root = (std::filesystem::temp_directory_path() / ("cas_s3_staging_generation_" + unique)).string(); + + std::error_code ec; + std::filesystem::remove_all(root, ec); + std::filesystem::create_directories(root, ec); + + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +} + +#endif diff --git a/src/Disks/tests/cas_killable_query.h b/src/Disks/tests/cas_killable_query.h index a4b3157ce5ec..cd7029261326 100644 --- a/src/Disks/tests/cas_killable_query.h +++ b/src/Disks/tests/cas_killable_query.h @@ -154,7 +154,7 @@ auto checkedUnless(Call && call, Succeeded && succeeded) /// Forwards to `inner` and, as the S3 client does after every unsuccessful response, checks the current /// thread's query on each miss, conflict or failure before answering. Success is never checked. The /// sentinel probe stays the base default, which goes through the decorated `head` and `read`. -class CasClientLikeBackend final : public Backend +class CasClientLikeBackend : public Backend { public: explicit CasClientLikeBackend(BackendPtr inner_) : inner(std::move(inner_)) {} diff --git a/src/Disks/tests/gtest_ca_transaction.cpp b/src/Disks/tests/gtest_ca_transaction.cpp index c45e8cbf6502..456c73d13a60 100644 --- a/src/Disks/tests/gtest_ca_transaction.cpp +++ b/src/Disks/tests/gtest_ca_transaction.cpp @@ -811,6 +811,52 @@ TEST(CASTransactionRemove, CreateThenDirDropDoesNotPublish) EXPECT_FALSE(storage->existsDirectory("b08/b08b08b0-0808-4808-8808-080808080808/all_1_1_0")); } +/// The stopped-fetch cleanup (`DataPartsExchange`, `ABORTED` branch) removes a half-downloaded +/// `tmp-fetch_*` part with `removeSharedRecursive` and then commits the SAME transaction that staged +/// its files. The removal must leave nothing behind, whichever removal call the storage issues. +namespace +{ + +void stageHalfFetchedPartThenRemoveAndCommit( + DB::ContentAddressedMetadataStorage & storage, + const std::string & table_dir, + const std::function & remove) +{ + const std::string part_dir = table_dir + "/tmp-fetch_all_1_1_0"; + auto tx = storage.createTransaction(); + writeFileTx(*tx, part_dir + "/checksums.txt", "cs-bytes"); + writeFileTx(*tx, part_dir + "/data.bin", "half-downloaded"); + remove(*tx, part_dir); + tx->commit(DB::NoCommitOptions{}); +} + +} + +TEST(CASTransactionRemove, FetchCleanupWithRemoveDirectoryLeavesNothing) +{ + auto storage = openTxStorage(); + const std::string table_dir = "b10/b10b10b0-1010-4010-8010-101010101010"; + stageHalfFetchedPartThenRemoveAndCommit( + *storage, table_dir, [](DB::IMetadataTransaction & tx, const std::string & dir) { tx.removeDirectory(dir); }); + + EXPECT_FALSE(storage->existsDirectory(table_dir + "/tmp-fetch_all_1_1_0")); + EXPECT_FALSE(storage->existsFile(table_dir + "/tmp-fetch_all_1_1_0/data.bin")); +} + +TEST(CASTransactionRemove, FetchCleanupWithRemoveRecursiveLeavesNothing) +{ + auto storage = openTxStorage(); + const std::string table_dir = "b11/b11b11b0-1111-4111-8111-111111111111"; + stageHalfFetchedPartThenRemoveAndCommit( + *storage, + table_dir, + [](DB::IMetadataTransaction & tx, const std::string & dir) { tx.removeRecursive(dir, /*should_remove_objects=*/nullptr); }); + + EXPECT_FALSE(storage->existsDirectory(table_dir + "/tmp-fetch_all_1_1_0")) + << "removeRecursive on a part directory dropped the committed ref only; the staged files were published by commit"; + EXPECT_FALSE(storage->existsFile(table_dir + "/tmp-fetch_all_1_1_0/data.bin")); +} + /// [Task 3] `startup()` publishes `cas_store`/`part_access`/`gc_scheduler` (and sets /// `pool_uuid`) atomically as its LAST action. Everything /// before that point -- opening the pool, building the part-folder facade, the capability probe, diff --git a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp index 34295f407978..1a965e9fc53c 100644 --- a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp +++ b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp @@ -10,9 +10,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include #include @@ -22,6 +26,8 @@ #include #include +#include +#include #include @@ -32,12 +38,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include namespace DB::ErrorCodes @@ -47,6 +55,8 @@ extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; extern const int LOGICAL_ERROR; extern const int ABORTED; +extern const int READONLY; +extern const int BAD_ARGUMENTS; } namespace ProfileEvents @@ -225,11 +235,12 @@ void waitEntered(const std::shared_ptr & sync) sync->cv.wait_for(lk, std::chrono::seconds(10), [&] { return sync->entered; }); } -void waitPendingAtLeast(const PoolPtr & store, const RootNamespace & ns, size_t n) +bool waitPendingAtLeast(const PoolPtr & store, const RootNamespace & ns, size_t n) { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); while (store->refQueuePendingForTest(ns) < n && std::chrono::steady_clock::now() < deadline) std::this_thread::yield(); + return store->refQueuePendingForTest(ns) >= n; } /// Asserts `err` is non-null and carries EXACTLY `expected_code` -- distinguishes the new counts-only @@ -1170,6 +1181,10 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend std::function before_answer; std::atomic armed{false}; std::atomic fired{false}; + /// Runs right after the armed create landed, before its reply is lost or returned. + std::function after_landed; + /// The armed create lands, and its reply is lost. + bool lose_reply = false; std::expected write(const String & key, const String & bytes, const std::optional & expected_value, @@ -1178,6 +1193,10 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend if (!expected_value && key.starts_with(log_prefix) && armed.exchange(false)) { fired = true; + if (lose_reply) + injectAmbiguousLandedWrite(key); + if (after_landed) + onWriteCommitted(key, after_landed); if (before_answer) before_answer(); } @@ -1185,9 +1204,52 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend } }; +/// Records the first exception of a ref-log create that leaves the client-like layer, which is what the request engine +/// sees. +class RecordingClientLikeBackend final : public CasClientLikeBackend +{ +public: + RecordingClientLikeBackend(std::shared_ptr faults_) + : CasClientLikeBackend(faults_), faults(std::move(faults_)) + { + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + try + { + return CasClientLikeBackend::write(key, bytes, expected_value, access); + } + catch (...) + { + if (key.starts_with(faults->log_prefix)) + { + std::lock_guard lock(mutex); + if (!first_log_write_failure) + first_log_write_failure = std::current_exception(); + } + throw; + } + } + + std::exception_ptr firstLogWriteFailure() const + { + std::lock_guard lock(mutex); + return first_log_write_failure; + } + +private: + std::shared_ptr faults; + mutable std::mutex mutex; + std::exception_ptr first_log_write_failure; +}; + struct KilledLeaderFixture { std::shared_ptr faults = std::make_shared(); + std::shared_ptr client = std::make_shared(faults); PoolPtr store; std::shared_ptr clock; RootNamespace ns; @@ -1195,7 +1257,7 @@ struct KilledLeaderFixture explicit KilledLeaderFixture(const String & ns_suffix) : ns(String("srv1/") + ns_suffix) { - store = openPoolWith(std::make_shared(faults), PoolConfig{}); + store = openPoolWith(client, PoolConfig{}); clock = VirtualRetryClock::installOn(store); publishEmptyPart(store, ns, "seed"); faults->log_prefix = store->layout().namespaceStreamPrefix(DB::Cas::tests::fixture::fixtureLife(ns)) + "_log/"; @@ -1220,6 +1282,22 @@ int exceptionCode(const std::exception_ptr & e) } } +bool isTransportTimeout(const std::exception_ptr & e) +{ + try + { + std::rethrow_exception(e); + } + catch (const Poco::TimeoutException &) + { + return true; + } + catch (...) + { + return false; + } +} + /// The leader's side of a killed-leader case, run on a raw thread with its own `ThreadStatus` and a /// query registered in the process list. `body` gets the query and returns the append's result. struct LeaderRun @@ -1255,18 +1333,79 @@ struct KilledLeaderOutcome LeaderRun leader; AppendResult neighbor; int neighbor_builds = 0; + /// The neighbor's item was queued before the blocked leader was released to carve. + bool neighbor_queued_before_release = false; +}; + +/// What the leader thread does around its append: `before_answer` runs before the chunk's create is answered, +/// `after_landed` right after a lost-reply create landed, and `finish` after the append returned or threw. +struct LeaderArm +{ + std::function before_answer; + std::function after_landed; + std::function finish; +}; + +/// What a direct cancellation check on the calling thread does. +struct CancellationProbe +{ + bool threw = false; + bool same_cause = false; + int code = 0; }; -KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) +CancellationProbe probeCancellation(const std::exception_ptr & cause) +{ + CancellationProbe probe; + try + { + DB::CurrentThread::checkIfNotCancelled(); + } + catch (...) + { + const std::exception_ptr thrown = std::current_exception(); + probe.threw = true; + probe.same_cause = thrown == cause; + probe.code = exceptionCode(thrown); + } + return probe; +} + +enum class KillAt : uint8_t { BeforeAnswer, AfterLanded }; + +/// Kills the leader's query at `at`; with `probe`, checks the cancellation again once the append ended. +LeaderArm killLeaderWith( + CasKillableQuery & query, std::exception_ptr cause = nullptr, KillAt at = KillAt::BeforeAnswer, CancellationProbe * probe = nullptr) +{ + LeaderArm arm; + auto kill = [&query, cause] { query.kill(cause); }; + (at == KillAt::BeforeAnswer ? arm.before_answer : arm.after_landed) = kill; + if (probe) + arm.finish = [probe, cause] { *probe = probeCancellation(cause); }; + return arm; +} + +std::exception_ptr storedCauseWithCode(int code) +{ + return std::make_exception_ptr(DB::Exception(code, "the query's stored cause")); +} + +KilledLeaderOutcome runKilledLeaderChunk( + KilledLeaderFixture & fx, + const std::function & arm = [](CasKillableQuery & query) { return killLeaderWith(query); }, + bool lose_reply = false) { auto sync = std::make_shared(); armPreCarveBlock(fx.store, fx.ns, sync, 2); auto neighbor_builds = std::make_shared>(0); std::thread leader_thread; - std::future leader = launchQueryLeader(leader_thread, [&fx](CasKillableQuery & query) + std::future leader = launchQueryLeader(leader_thread, [&fx, &arm, lose_reply](CasKillableQuery & query) { - fx.faults->before_answer = [&query] { query.kill(); }; + const LeaderArm leader_arm = arm(query); + fx.faults->before_answer = leader_arm.before_answer; + fx.faults->after_landed = leader_arm.after_landed; + fx.faults->lose_reply = lose_reply; fx.faults->armed = true; AppendResult r; try @@ -1279,15 +1418,18 @@ KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) { r.err = std::current_exception(); } + if (leader_arm.finish) + leader_arm.finish(); return r; }); waitEntered(sync); AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), addRemovePrecommitPairs("item_neighbor", 1, 910000002), neighbor_builds); - waitPendingAtLeast(fx.store, fx.ns, 2); + const bool neighbor_queued = waitPendingAtLeast(fx.store, fx.ns, 2); sync->cv.notify_all(); KilledLeaderOutcome out; + out.neighbor_queued_before_release = neighbor_queued; EXPECT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the killed leader must not hang"; EXPECT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; out.leader = leader.get(); @@ -1295,6 +1437,8 @@ KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) leader_thread.join(); neighbor.t.join(); fx.faults->before_answer = {}; + fx.faults->after_landed = {}; + fx.faults->lose_reply = false; fx.store->setRefPreCarveHookForTest(nullptr); out.neighbor_builds = neighbor_builds->load(); return out; @@ -1324,6 +1468,495 @@ TEST(CASRefWriterChunkedFlush, KilledLeaderOnHealthyStoreCommitsWithNeighbor) << "the chunk is durable exactly once"; } +namespace +{ + +size_t countRequests(const DB::Cas::tests::CountingBackend & backend, DB::Cas::tests::JournalVerb verb, const String & key) +{ + const auto journal = backend.journal(); + return static_cast(std::count_if(journal.begin(), journal.end(), [&](const DB::Cas::tests::JournalEntry & entry) + { + return entry.verb == verb && entry.keys.size() == 1 && entry.keys.front() == key; + })); +} + +/// The leader's query is killed with a stored cause right after the chunk's create landed and its reply was lost. The +/// store's answer, not the cause, decides: one settling read finds the chunk, both callers commit, and the lane is not +/// wedged, so the next distinct mutation takes the next id. +void expectLostReplyOfKilledLeaderIsSettled(int cause_code, const String & ns_suffix) +{ + KilledLeaderFixture fx(ns_suffix); + const std::exception_ptr cause = storedCauseWithCode(cause_code); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk( + fx, [&](CasKillableQuery & query) { return killLeaderWith(query, cause, KillAt::AfterLanded, &probe); }, true); + + ASSERT_TRUE(fx.faults->fired) << "the kill never ran after the chunk's create"; + EXPECT_TRUE(probe.threw) << "the kill took effect: the query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; + /// Fatal: a failed append leaves a zero id, which the key derivation below rejects. + ASSERT_EQ(exceptionCode(out.leader.result.err), 0) << "the killed leader's item is acknowledged"; + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor's item is acknowledged"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id) << "both items were in one chunk"; + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + + const String log_key = fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), out.neighbor.id); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Write, log_key), 1u) << "the chunk is sent once"; + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Read, log_key), 1u) << "one settling read"; + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1); + + /// Synchronous on the test thread: a failed assertion cannot leave a blocked thread to join. + AppendResult after; + try + { + after.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_next"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_next", 1, 910000003); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + after.err = std::current_exception(); + } + EXPECT_EQ(exceptionCode(after.err), 0) << "a distinct mutation appends after the settled chunk"; + EXPECT_EQ(after.id.writer_epoch, out.neighbor.id.writer_epoch); + EXPECT_EQ(after.id.ref_sequence, out.neighbor.id.ref_sequence + 1) << "the settled chunk's id is not reused"; + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); +} + +} + +/// The S3 client replaces a failed request's answer with the query's stored cause. A `READONLY` cause read as a store +/// refusal would declare the landed chunk's id free. +TEST(CASRefWriterChunkedFlush, KilledLeaderLostReplyWithReadonlyCauseIsSettledByRead) +{ + expectLostReplyOfKilledLeaderIsSettled(DB::ErrorCodes::READONLY, "killed_leader_lost_reply_readonly"); +} + +/// A `BAD_ARGUMENTS` cause read as a local fault would end the flush with no settling read and leave the lane wedged. +TEST(CASRefWriterChunkedFlush, KilledLeaderLostReplyWithBadArgumentsCauseIsSettledByRead) +{ + expectLostReplyOfKilledLeaderIsSettled(DB::ErrorCodes::BAD_ARGUMENTS, "killed_leader_lost_reply_bad_arguments"); +} + +/// After the leader's flush ended, the query's own cancellation is visible again on its thread: a direct check throws +/// the stored cause itself. +TEST(CASRefWriterChunkedFlush, KilledLeaderQueryIsCancelledAgainAfterAFlush) +{ + KilledLeaderFixture fx("killed_leader_visible_after_flush"); + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk( + fx, [&](CasKillableQuery & query) { return killLeaderWith(query, cause, KillAt::BeforeAnswer, &probe); }); + + ASSERT_TRUE(fx.faults->fired); + EXPECT_EQ(exceptionCode(out.leader.result.err), 0); + EXPECT_TRUE(probe.threw) << "the killed query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; +} + +/// An exception that leaves the leader's flush ends its tenure with the cancellation visible again: the query's +/// check throws the stored cause itself. The exception is the flush's own, not the cause, the check is masked while +/// the flush runs, and a queued neighbor takes the baton and commits. +TEST(CASRefWriterChunkedFlush, KilledLeaderQueryIsCancelledAgainAfterAThrowingFlush) +{ + KilledLeaderFixture fx("killed_leader_visible_after_throwing_flush"); + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + const String sentinel = "sentinel thrown from the carve plan"; + std::atomic thrown{false}; + bool masked_in_flush = false; + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx, [&](CasKillableQuery & query) + { + fx.store->setCarveHookForTest([&](CasRefLedger::CarvePhaseForTest phase) + { + if (phase != CasRefLedger::CarvePhaseForTest::PlanSeenRefs || thrown.exchange(true)) + return; + query.kill(cause); + masked_in_flush = !probeCancellation(cause).threw; + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", sentinel); + }); + LeaderArm arm; + arm.finish = [&] { probe = probeCancellation(cause); }; + return arm; + }); + fx.store->setCarveHookForTest(nullptr); + + ASSERT_TRUE(thrown) << "the exception never left the carve plan"; + ASSERT_TRUE(out.neighbor_queued_before_release) << "the neighbor's item was not queued before the leader's flush began"; + EXPECT_TRUE(masked_in_flush) << "a killed leader's cancellation is masked while its flush runs"; + ASSERT_EQ(exceptionCode(out.leader.result.err), DB::ErrorCodes::CORRUPTED_DATA) << "the leader gets the flush's own exception"; + try + { + std::rethrow_exception(out.leader.result.err); + } + catch (const DB::Exception & e) + { + EXPECT_NE(String(e.message()).find(sentinel), String::npos) << e.message(); + } + EXPECT_TRUE(probe.threw) << "the killed query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; + EXPECT_TRUE(out.leader.group_restored); + + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor takes the baton and commits"; + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); +} + +/// A leader running a background operation whose group has a throwing cancellation predicate (a cancelled merge) is +/// not a query. A lost reply inside its flush is still settled by a read, and the other callers' items are acknowledged. +/// The transport timeout, not the operation's `ABORTED`, is what leaves the client-like layer. +TEST(CASRefWriterChunkedFlush, LeaderOfACancelledBackgroundOperationSettlesALostReplyByRead) +{ + KilledLeaderFixture fx("cancelled_background_leader_lost_reply"); + auto cancelled = std::make_shared>(false); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx, [&](CasKillableQuery & query) + { + auto group = DB::ThreadGroup::createForMergeMutate(getContext().context); + group->setQueryCancellationPredicates( + [cancelled] { return cancelled->load(); }, + [cancelled] + { + if (cancelled->load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + DB::CurrentThread::detachFromGroupIfNotDetached(); + DB::CurrentThread::attachToGroup(group); + LeaderArm arm; + arm.before_answer = [cancelled] { *cancelled = true; }; + arm.finish = [&query, &probe] + { + /// Still attached to the operation's group: its predicate is live. + probe = probeCancellation(nullptr); + DB::CurrentThread::detachFromGroupIfNotDetached(); + query.attachCurrentThread(); + }; + return arm; + }, true); + + ASSERT_TRUE(fx.faults->fired); + EXPECT_TRUE(probe.threw) << "the operation's cancellation predicate is live once the leader returned"; + EXPECT_EQ(probe.code, DB::ErrorCodes::ABORTED); + const std::exception_ptr leaving_client = fx.client->firstLogWriteFailure(); + ASSERT_TRUE(leaving_client != nullptr); + EXPECT_TRUE(isTransportTimeout(leaving_client)) << "the lost reply leaves the client-like layer as the transport timeout"; + ASSERT_EQ(exceptionCode(out.leader.result.err), 0) << "the leader's item is acknowledged"; + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor's item is acknowledged"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + const String log_key = fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), out.neighbor.id); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Write, log_key), 1u); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Read, log_key), 1u) << "one settling read"; +} + +#if USE_AWS_S3 + +namespace +{ + +/// Where a request classified by the native object-storage backend runs after its query was killed with a stored +/// cause. `InsideLeaderFlush` is the production case. `SharedWithoutBlocker` is the control: the same scope the leader +/// holds, minus the cancellation blocker, which shows that `OwnerScope::shared` alone does not keep the S3 client from +/// substituting the query's cause. +enum class KilledQueryPlace : uint8_t { InsideLeaderFlush, SharedWithoutBlocker }; + +/// Kills a query with `cause` and runs `scenario` on its thread in `place`. +template +void runKilledQueryScenario(KilledQueryPlace place, const std::exception_ptr & cause, Scenario && scenario) +{ + if (place == KilledQueryPlace::SharedWithoutBlocker) + { + DB::Cas::tests::onKillableQueryThread([&](CasKillableQuery & query) + { + const auto shared = DB::Cas::OwnerScope::shared(); + query.kill(cause); + scenario(); + }); + return; + } + + KilledLeaderFixture fx("killed_leader_native_classifier"); + std::atomic ran{false}; + int append_code = -2; + DB::Cas::tests::onKillableQueryThread([&](CasKillableQuery & query) + { + fx.store->setRefPreCarveHookForTest([&] + { + if (ran.exchange(true)) + return; + query.kill(cause); + scenario(); + }); + try + { + fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 910000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + append_code = 0; + } + catch (...) + { + append_code = exceptionCode(std::current_exception()); + } + }); + fx.store->setRefPreCarveHookForTest(nullptr); + EXPECT_TRUE(ran) << "the scenario never ran inside the leader's flush"; + EXPECT_EQ(append_code, 0) << "the leader's own append commits"; +} + +/// A local object storage whose reads and conditional writes fail the way the S3 client fails a request: a failure +/// first asks the thread's query, so the query's cause replaces the failure. +class ClientLikeNativeStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic fail_next{false}; + mutable std::atomic miss_next{false}; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (fail_next.exchange(false)) + { + DB::CurrentThread::checkIfNotCancelled(); + throw Poco::TimeoutException("ClientLikeNativeStorage: the read timed out"); + } + if (miss_next.exchange(false)) + { + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered NoSuchKey for " + object.remote_path, Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"); + } + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } +}; + +/// Finalizes by asking the thread's query, as the S3 client does, then failing with the store's own `412`. +class PreconditionFailedNativeBuffer final : public DB::WriteBufferFromFileBase +{ +public: + PreconditionFailedNativeBuffer() : DB::WriteBufferFromFileBase(DB::DBMS_DEFAULT_BUFFER_SIZE, nullptr, 0) {} + + void sync() override { next(); } + std::string getFileName() const override { return "precondition-failed-native-buffer"; } + +private: + void nextImpl() override {} + + void finalizeImpl() override + { + next(); + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered 412", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + } +}; + +class PreconditionFailedNativeStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::atomic writes{0}; + + std::unique_ptr writeObject( + const DB::StoredObject &, DB::WriteMode, std::optional, size_t, const DB::WriteSettings &) override + { + ++writes; + return std::make_unique(); + } +}; + +template +std::shared_ptr makeNativeTestStorage() +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_flush_native_unit_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +struct NativeReadOutcome +{ + bool absent = false; + String bytes; + bool cause_thrown = false; + int code = 0; + int reads = 0; +}; + +/// One native read through the request engine of an object that is present, whose first read fails with a timeout. +NativeReadOutcome readWithFailedFirstGet(KilledQueryPlace place, const std::exception_ptr & cause) +{ + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + NativeReadOutcome out; + runKilledQueryScenario(place, cause, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + storage->reads = 0; + storage->fail_next = true; + try + { + const auto read = op.read(key, Retry::standard()); + out.absent = !read.has_value(); + if (read) + out.bytes = String(read->bytes); + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + } + out.reads = storage->reads.load(); + }); + return out; +} + +} + +/// A failed GET of a present key, while the thread carries a stored `NoSuchKey`: the leader's masked cancellation lets +/// the timeout be retried and the original bytes come back. Without the blocker the stored cause replaces the timeout +/// and is read as the key's absence. +TEST(CASRefWriterChunkedFlush, FailedGetOfAPresentKeyUnderAKilledLeaderIsRetried) +{ + const std::exception_ptr cause + = std::make_exception_ptr(DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey")); + const NativeReadOutcome in_leader = readWithFailedFirstGet(KilledQueryPlace::InsideLeaderFlush, cause); + EXPECT_EQ(in_leader.code, 0); + EXPECT_FALSE(in_leader.absent) << "a failed GET of a present key is not absence"; + EXPECT_EQ(in_leader.bytes, "body") << "the retry returns the original bytes"; + EXPECT_EQ(in_leader.reads, 2) << "the timeout was retried once"; + + const NativeReadOutcome without_blocker = readWithFailedFirstGet(KilledQueryPlace::SharedWithoutBlocker, cause); + EXPECT_TRUE(without_blocker.absent) << "control: shared alone lets the stored NoSuchKey be read as absence; code " + << without_blocker.code; +} + +/// A genuine `412` on a conditional write, while the thread carries a distinct stored cause: a clean conflict. +/// Without the blocker the stored cause replaces the `412`, which is then not a conflict. +TEST(CASRefWriterChunkedFlush, GenuinePreconditionFailedUnderAKilledLeaderIsAConflict) +{ + struct Outcome + { + bool conflict = false; + bool any_ambiguous = false; + bool refused = false; + int refused_code = 0; + int code = 0; + int writes = 0; + }; + const auto run = [](KilledQueryPlace place) + { + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + Outcome out; + runKilledQueryScenario(place, storedCauseWithCode(DB::ErrorCodes::READONLY), [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + const WriteResult written = op.create(key, "bytes", Retry::standard()); + if (const auto * conflict = std::get_if(&written)) + { + out.conflict = true; + out.any_ambiguous = conflict->any_ambiguous; + } + else if (const auto * refused = std::get_if(&written)) + { + out.refused = true; + out.refused_code = refused->store_error; + } + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + } + }); + out.writes = storage->writes.load(); + return out; + }; + + const Outcome in_leader = run(KilledQueryPlace::InsideLeaderFlush); + EXPECT_EQ(in_leader.code, 0); + EXPECT_TRUE(in_leader.conflict) << "the store's own 412 is a conflict"; + EXPECT_FALSE(in_leader.any_ambiguous); + EXPECT_EQ(in_leader.writes, 1); + + const Outcome without_blocker = run(KilledQueryPlace::SharedWithoutBlocker); + EXPECT_FALSE(without_blocker.conflict) << "control: shared alone lets the stored cause replace the 412"; + EXPECT_EQ(without_blocker.code, 0) << "control: the 412 is refused, not thrown"; + EXPECT_TRUE(without_blocker.refused) << "control: the stored cause is read as a store refusal"; + EXPECT_EQ(without_blocker.refused_code, DB::ErrorCodes::READONLY); + EXPECT_EQ(without_blocker.writes, 1) << "control: exactly one attempt was sent"; +} + +/// A genuine miss, which the fake checks the cancellation before emitting as the S3 client does: absence under the +/// leader's masked cancellation. Without the blocker the stored cause replaces the miss. +TEST(CASRefWriterChunkedFlush, GenuineMissUnderAKilledLeaderIsAbsence) +{ + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + const auto run = [&cause](KilledQueryPlace place) + { + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + NativeReadOutcome out; + runKilledQueryScenario(place, cause, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + storage->reads = 0; + storage->miss_next = true; + try + { + out.absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + out.cause_thrown = std::current_exception() == cause; + } + out.reads = storage->reads.load(); + }); + return out; + }; + + const NativeReadOutcome in_leader = run(KilledQueryPlace::InsideLeaderFlush); + EXPECT_EQ(in_leader.code, 0); + EXPECT_TRUE(in_leader.absent) << "the store's own miss is absence"; + EXPECT_EQ(in_leader.reads, 1); + + const NativeReadOutcome without_blocker = run(KilledQueryPlace::SharedWithoutBlocker); + EXPECT_FALSE(without_blocker.absent) << "control: shared alone lets the stored cause replace the miss"; + EXPECT_EQ(without_blocker.code, DB::ErrorCodes::READONLY) << "control: the read throws the stored cause"; + EXPECT_TRUE(without_blocker.cause_thrown) << "control: the exception is the stored cause itself"; + EXPECT_EQ(without_blocker.reads, 1) << "control: exactly one attempt was sent"; +} + +#endif + /// Leaving a query's thread group finalizes the thread's counters and writes a `system.query_thread_log` row, so a /// leader must flush in its caller's group: the same group before the append, inside the flush and after it. TEST(CASRefWriterChunkedFlush, LeaderFlushesInItsCallersThreadGroup) diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index 1437f7f9f0ca..f96a1c3f5aec 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -1,6 +1,7 @@ #include #include "cas_test_helpers.h" #include "cas_publication_test_support.h" +#include "cas_fake_generation_object_storage.h" #include #include #include @@ -1154,351 +1155,8 @@ TEST(CASS3Staging, MountStartSweepsALostAbortDelete) #if USE_AWS_S3 -namespace -{ - -/// A `LocalObjectStorage` that reports the GCS generation dialect -/// (`conditionalOpsUseGenerationTokens() == true`) and a non-`Local` `getType()`, so -/// `ContentAddressedMetadataStorage::openPoolView` builds its backend in `Mode::Native` with -/// `native_token_type == Dialect::Generation`. The fake also advertises native copy so generation -/// token mode can exercise explicit S3 staging without endpoint/provider heuristics. -/// -/// Holds every object entirely in memory, keyed by the BARE CAS key exactly as `Backend` hands it to -/// `object_storage` (e.g. `"pool/_probe//token"`). Native mode never asks `object_storage` to -/// resolve that key against anything (`ContentAddressedMetadataStorage::physicalKey` is a documented -/// no-op for Native, since a real S3 client resolves a bucket-relative key against its own bucket/prefix -/// configuration internally) -- so this fake never needs a notion of "resolve a key to a location" at -/// all, unlike a real filesystem-backed object storage would. That sidesteps the class of bug a -/// resolve-then-strip round trip through the real `LocalObjectStorage` file/list implementation is prone -/// to (a key is a key, with no round trip to get wrong), and it never touches the real filesystem, so it -/// cannot leak files into the test process's working directory either. -/// -/// A writable Native-mode mount always runs the mandatory capability battery (`CasProbe.cpp`), which -/// requires REAL conditional-write enforcement: the precondition is evaluated when a write completes, -/// signaled by an `S3Exception` carrying the canonical `PreconditionFailed` name (see -/// `ObjectStorageBackend::finalizeConditionalWrite`). `writeObject` therefore buffers bytes in memory and -/// defers both the precondition check and the commit to `finalize`, mirroring how a real object store -/// only commits -- and only then can reject -- on PUT completion. -class FakeGenerationObjectStorage final : public DB::LocalObjectStorage -{ -public: - using DB::LocalObjectStorage::LocalObjectStorage; - - /// Report the S3 ETag dialect instead: a token is a digest of the object's bytes, so the same bytes - /// written or copied again carry the same token, as on S3 without KMS. Set before `startup`. - bool content_derived_etags = false; - - DB::ObjectStorageType getType() const override { return DB::ObjectStorageType::S3; } - bool conditionalOpsUseGenerationTokens() const override { return !content_derived_etags; } - std::optional isBucketVersioningEnabled(const DB::ObjectStorageControlRequest &) const override { return false; } - bool supportsRetryProfile(DB::ObjectStorageRetryProfile) const override { return true; } - bool supportsCopyMode(DB::ObjectStorageCopyMode mode) const override - { - return mode == DB::ObjectStorageCopyMode::Default || mode == DB::ObjectStorageCopyMode::NativeOnly; - } - - std::unique_ptr writeObject( - const DB::StoredObject & object, - DB::WriteMode mode, - std::optional /*attributes*/, - size_t /*buf_size*/, - const DB::WriteSettings & write_settings) override - { - if (mode != DB::WriteMode::Rewrite) - throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "FakeGenerationObjectStorage only supports Rewrite"); - return std::make_unique( - *this, object.remote_path, write_settings.object_storage_write_if_none_match, - write_settings.object_storage_write_if_match); - } - - bool exists(const DB::StoredObject & object) const override - { - std::lock_guard lock(mutex); - return objects.contains(object.remote_path); - } - - std::unique_ptr readObject( - const DB::StoredObject & object, - const DB::ReadSettings & /*read_settings*/, - std::optional /*read_hint*/, - bool /*use_external_buffer*/, - bool /*restrict_seek*/) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(object.remote_path); - if (it == objects.end()) - /// `RESOURCE_NOT_FOUND`, not a plain `DB::Exception`: `Backend::probeSentinelRaw`'s Native - /// path (`CasObjectStorageBackend.cpp`) classifies absence ONLY from a caught `S3Exception` - /// carrying `NO_SUCH_KEY`/`RESOURCE_NOT_FOUND` (or the matching exception name) -- anything - /// else, including an unrecognized exception TYPE, falls through to `ProbeOutcome:: - /// Indeterminate` (fail-closed). A bodyless HEAD on a real absent S3 key throws exactly this - /// code, since the SDK cannot parse a `` from a body that was never sent. - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - /// Copies the bytes, matching a real remote read (no shared ownership with the stored entry, so - /// a later overwrite of this key cannot mutate bytes a caller is still reading). - return std::make_unique(object.remote_path, it->second.bytes); - } - - DB::ObjectMetadata getObjectMetadata(const std::string & path, bool with_tags) const override - { - auto metadata = tryGetObjectMetadata(path, with_tags); - if (!metadata) - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - return *metadata; - } - - std::optional tryGetObjectMetadata(const std::string & path, bool /*with_tags*/) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(path); - if (it == objects.end()) - return std::nullopt; - DB::ObjectMetadata metadata; - metadata.size_bytes = it->second.bytes.size(); - metadata.etag = tokenOf(it->second); - return metadata; - } - - std::optional tryGetObjectMetadataWithNativeToken(const std::string & path, bool with_tags) const override - { - return tryGetObjectMetadata(path, with_tags); - } - - /// This fake advertises every retry profile, and an in-memory store has no retry behaviour to - /// vary, so the profile-aware overloads simply forward. A storage that claimed the capability - /// without implementing them would refuse every control-plane request of a writable mount. - std::optional tryGetObjectMetadataWithNativeToken( - const std::string & path, bool with_tags, const DB::ObjectStorageControlRequest &) const override - { - return tryGetObjectMetadata(path, with_tags); - } - - DB::ObjectStorageIteratorPtr iterate( - const std::string & path_prefix, size_t max_keys, bool with_tags, const std::optional & start_after, - const DB::ObjectStorageControlRequest &) const override - { - return DB::LocalObjectStorage::iterate(path_prefix, max_keys, with_tags, start_after); - } - - DB::ConditionalRemoveResult removeObjectIfTokenMatches( - const DB::StoredObject & object, const std::string & etag, const DB::ObjectStorageControlRequest &) override - { - return removeObjectIfTokenMatches(object, etag); - } - using DB::LocalObjectStorage::removeObjectIfTokenMatches; - - /// A real S3 GET answers with the object's incarnation, which is what the backend reads its - /// bytes AND its generation from in one request. Quoted, the way the SDK's ETag field carries a - /// generation across the HTTP boundary. - DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( - const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(object.remote_path); - if (it == objects.end()) - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - DB::SmallObjectDataWithMetadata result; - result.data = it->second.bytes; - result.metadata.size_bytes = it->second.bytes.size(); - result.metadata.etag = transportTokenOf(it->second); - return result; - } - - void removeObjectIfExists(const DB::StoredObject & object) override - { - std::lock_guard lock(mutex); - objects.erase(object.remote_path); - } - - void removeObjectsIfExist(const DB::StoredObjects & objects_to_remove) override - { - std::lock_guard lock(mutex); - for (const auto & object : objects_to_remove) - objects.erase(object.remote_path); - } - - /// S3 sends an unconditional delete under every retry profile; the intent probe and GC use it. - void removeObjectsIfExistUnderProfile(const DB::StoredObjects & objects_to_remove, const DB::ObjectStorageControlRequest &) override - { - removeObjectsIfExist(objects_to_remove); - } - - /// `path` is a bare CAS-relative prefix (e.g. `"pool/"` or `"pool/_probe/"`) -- exactly what - /// `Backend::list`'s Native-mode path passes through unchanged (it applies no prefix stripping of - /// its own there) and expects back on every listed key. A plain string-prefix scan over the - /// in-memory keys already IS that key space, so there is no separate "physical" representation to - /// resolve to or strip back off. - void listObjects(const std::string & path, DB::RelativePathsWithMetadata & children, size_t max_keys) const override - { - std::lock_guard lock(mutex); - for (const auto & [key, entry] : objects) - { - if (!key.starts_with(path)) - continue; - DB::ObjectMetadata metadata; - metadata.size_bytes = entry.bytes.size(); - metadata.etag = tokenOf(entry); - children.push_back(std::make_shared(key, std::move(metadata))); - if (max_keys != 0 && children.size() >= max_keys) - break; - } - } - - DB::ConditionalRemoveResult removeObjectIfTokenMatches(const DB::StoredObject & object, const std::string & etag) override - { - std::lock_guard lock(mutex); - DB::ConditionalRemoveResult result; - auto it = objects.find(object.remote_path); - if (it == objects.end()) - { - result.outcome = DB::ConditionalRemoveOutcome::NotFound; - return result; - } - if (tokenOf(it->second) != etag) - { - result.outcome = DB::ConditionalRemoveOutcome::TokenMismatch; - return result; - } - objects.erase(it); - result.outcome = DB::ConditionalRemoveOutcome::Removed; - return result; - } - - /// Checks the write-once/exact-token precondition against the current generation and, on success, - /// stores `bytes` and mints the next generation. Throws an `S3Exception` naming `PreconditionFailed` - /// on a lost condition -- the one signal `finalizeConditionalWrite` classifies as - /// `ConditionalWriteOutcome::PreconditionLost` rather than an ordinary failure. - /// Returns the new object's token as a real store returns it in the write response: the backend - /// attributes the write to that token and nothing reads it back. - std::string commitConditionalWrite(const std::string & key, const std::string & bytes, - const std::string & if_none_match, const std::string & if_match) - { - std::lock_guard lock(mutex); - auto it = objects.find(key); - const bool exists_now = it != objects.end(); - if (!if_none_match.empty() && exists_now) - throw DB::S3Exception("FakeGenerationObjectStorage: if-none-match precondition failed", - Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); - if (!if_match.empty() && (!exists_now || tokenOf(it->second) != if_match)) - throw DB::S3Exception("FakeGenerationObjectStorage: if-match precondition failed", - Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); - - Entry & entry = objects[key]; - entry = Entry{bytes, next_generation++}; - return transportTokenOf(entry); - } - - /// A same-store copy of the stored bytes, counted per destination key. - void copyObject( /// NOLINT - const DB::StoredObject & object_from, - const DB::StoredObject & object_to, - const DB::ReadSettings & /*read_settings*/, - const DB::WriteSettings & /*write_settings*/, - std::optional /*object_to_attributes*/ = {}) override - { - std::lock_guard lock(mutex); - auto it = objects.find(object_from.remote_path); - if (it == objects.end()) - throw DB::S3Exception("FakeGenerationObjectStorage: copy source does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - Entry copy{it->second.bytes, next_generation++}; - objects[object_to.remote_path] = std::move(copy); - ++copies_to[object_to.remote_path]; - } - - std::map copiesByDestination() const - { - std::lock_guard lock(mutex); - return copies_to; - } - -private: - struct Entry - { - std::string bytes; - uint64_t generation; - }; - - std::string tokenOf(const Entry & entry) const - { - if (content_derived_etags) - return getHexUIntLowercase(sipHash128(entry.bytes.data(), entry.bytes.size())); - return std::to_string(entry.generation); - } - - /// The token as the SDK's ETag field carries it: quoted for a GCS generation. - std::string transportTokenOf(const Entry & entry) const - { - return content_derived_etags ? tokenOf(entry) : "\"" + tokenOf(entry) + "\""; - } - - /// Buffers the whole body in memory (like `FakeStagingSink` above) so the entry is committed exactly - /// once, at `finalize`, and only after the precondition has been checked. - class ConditionalWriteBuffer final : public DB::WriteBufferFromFileBase - { - public: - ConditionalWriteBuffer(FakeGenerationObjectStorage & storage_, std::string key_, - std::string if_none_match_, std::string if_match_) - : DB::WriteBufferFromFileBase(/*buf_size=*/8192, nullptr, 0) - , storage(storage_), key(std::move(key_)) - , if_none_match(std::move(if_none_match_)), if_match(std::move(if_match_)) - { - } - - void sync() override {} - std::string getFileName() const override { return key; } - - /// The write response's own incarnation, quoted the way the SDK's ETag field carries a GCS - /// generation across the HTTP boundary -- the backend is what strips that transport syntax. - std::optional getResultObjectETag() const override { return committed_generation; } - - protected: - void nextImpl() override - { - if (!offset()) - return; - buffered.append(working_buffer.begin(), offset()); - } - - void finalizeImpl() override - { - next(); - committed_generation = storage.commitConditionalWrite(key, buffered, if_none_match, if_match); - } - - private: - FakeGenerationObjectStorage & storage; - std::string key; - std::string if_none_match; - std::string if_match; - std::string buffered; - std::optional committed_generation; - }; - - mutable std::mutex mutex; - std::map objects; - std::map copies_to; - uint64_t next_generation = 1; -}; - -std::shared_ptr makeFakeGenerationObjectStorageForTest() -{ - static std::atomic counter{0}; - const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); - const auto root = (std::filesystem::temp_directory_path() / ("cas_s3_staging_generation_" + unique)).string(); - - std::error_code ec; - std::filesystem::remove_all(root, ec); - std::filesystem::create_directories(root, ec); - - DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); - return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); -} - -} +using DB::Cas::tests::FakeGenerationObjectStorage; +using DB::Cas::tests::makeFakeGenerationObjectStorageForTest; /// A store whose iterator does not page (the fallback `IObjectStorage::iterate` lists `max_keys` keys /// once and ends) must still let a page-sized list report that more keys follow. A page that ended diff --git a/src/Disks/tests/gtest_cas_upload_guard.cpp b/src/Disks/tests/gtest_cas_upload_guard.cpp new file mode 100644 index 000000000000..45b59c7339d1 --- /dev/null +++ b/src/Disks/tests/gtest_cas_upload_guard.cpp @@ -0,0 +1,810 @@ +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "config.h" +#if USE_AWS_S3 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace DB::ErrorCodes +{ + extern const int ABORTED; + extern const int QUERY_WAS_CANCELLED; +} + +using namespace DB; +using namespace DB::Cas; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::onKillableQueryThread; +using DB::Cas::tests::onThread; + +namespace +{ + +/// Records what reaches it and reports fixed limits. +class RecordingThrottler final : public IThrottler +{ +public: + bool throttle(size_t amount_, size_t max_block_ns_) override + { + amount += amount_; + max_block_ns = max_block_ns_; + ++calls; + return true; + } + + bool isThrottling() const override { return true; } + Int64 getAvailable() override { return 123; } + UInt64 getMaxSpeed() const override { return 456; } + UInt64 getMaxBurst() const override { return 789; } + + size_t amount = 0; + size_t max_block_ns = 0; + size_t calls = 0; +}; + +int codeOf(const std::function & call) +{ + try + { + call(); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; +} + +} + +TEST(CASUploadGuard, GuardForwardsAndStops) +{ + auto limiter = std::make_shared(); + + EXPECT_EQ(makeUploadGuard(limiter, {}), limiter); + EXPECT_EQ(makeUploadGuard(nullptr, {}), nullptr); + + std::vector inner_calls_at_stop; + auto guard = makeUploadGuard(limiter, [&] { inner_calls_at_stop.push_back(limiter->calls); }); + ASSERT_NE(guard, limiter); + EXPECT_TRUE(guard->throttle(32768, 20'000'000'000)); + EXPECT_EQ(limiter->amount, 32768u); + EXPECT_EQ(limiter->max_block_ns, 20'000'000'000u); + EXPECT_EQ(inner_calls_at_stop, (std::vector{0, 1})); + EXPECT_TRUE(guard->isThrottling()); + EXPECT_EQ(guard->getAvailable(), 123); + EXPECT_EQ(guard->getMaxSpeed(), 456u); + EXPECT_EQ(guard->getMaxBurst(), 789u); + + std::atomic stopped{false}; + auto stopping = makeUploadGuard(limiter, [&] + { + if (stopped) + throw Exception(ErrorCodes::QUERY_WAS_CANCELLED, "stopped"); + }); + stopped = true; + const size_t calls_before = limiter->calls; + EXPECT_EQ(codeOf([&] { stopping->throttle(1, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(limiter->calls, calls_before) << "the stop before the inner call must keep the bytes from the limiter"; + + stopped = false; + auto stop_after = makeUploadGuard(limiter, [&, first = true]() mutable + { + if (!std::exchange(first, false)) + throw Exception(ErrorCodes::QUERY_WAS_CANCELLED, "stopped"); + }); + EXPECT_EQ(codeOf([&] { stop_after->throttle(1, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(limiter->calls, calls_before + 1) << "the stop after the inner call runs once the limiter was charged"; +} + +TEST(CASUploadGuard, AStopOnlyGuardStopsAndReportsNoLimit) +{ + onKillableQueryThread([](CasKillableQuery & query) + { + auto guard = makeUploadGuard(nullptr, uploadStopCheck()); + ASSERT_NE(guard, nullptr); + EXPECT_FALSE(guard->throttle(32768, 1)); + EXPECT_FALSE(guard->isThrottling()); + EXPECT_EQ(guard->getAvailable(), std::numeric_limits::max()); + EXPECT_EQ(guard->getMaxSpeed(), 0u); + EXPECT_EQ(guard->getMaxBurst(), 0u); + + query.kill(); + EXPECT_EQ(codeOf([&] { guard->throttle(32768, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + +TEST(CASUploadGuard, StopCheckIsEmptyWhereWorkMustFinish) +{ + onKillableQueryThread([](CasKillableQuery &) + { + EXPECT_TRUE(uploadStopCheck()); + { + auto owed = OwnerScope::owed(); + EXPECT_FALSE(uploadStopCheck()); + } + { + auto shared = OwnerScope::shared(); + EXPECT_FALSE(uploadStopCheck()); + } + EXPECT_TRUE(uploadStopCheck()); + }); + + onThread(true, [] { EXPECT_FALSE(uploadStopCheck()) << "a thread with no group has no query to stop"; }); + onThread(false, [] { EXPECT_FALSE(uploadStopCheck()); }); +} + +TEST(CASUploadGuard, StopIsEmptyUnderACancellationBlocker) +{ + onKillableQueryThread([](CasKillableQuery & query) + { + query.kill(); + { + ThreadStatus::QueryCancellationBlocker blocker; + EXPECT_FALSE(uploadStopCheck()); + } + const std::function stop = uploadStopCheck(); + ASSERT_TRUE(stop); + EXPECT_EQ(codeOf(stop), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + +TEST(CASUploadGuard, StopCheckCarriesTheQueryVerdictAndKeepsTheGroup) +{ + std::function check; + std::weak_ptr group; + + onKillableQueryThread([&](CasKillableQuery & query) + { + check = uploadStopCheck(); + ASSERT_TRUE(check); + group = query.group; + + onThread(false, [&] { EXPECT_EQ(codeOf(check), 0); }); + query.kill(); + onThread(false, [&] { EXPECT_EQ(codeOf(check), ErrorCodes::QUERY_WAS_CANCELLED); }); + }); + + EXPECT_FALSE(group.expired()) << "the check keeps the group after the fixture released its references"; + check = nullptr; + EXPECT_TRUE(group.expired()); +} + +TEST(CASUploadGuard, AMergeThreadGroupWithNoTaskPredicateInstalledGetsAStopThatNeverThrows) +{ + onThread(true, [] + { + CurrentThread::attachToGroup(ThreadGroup::createForMergeMutate(getContext().context)); + const std::function stop = uploadStopCheck(); + if (stop) + EXPECT_NO_THROW(stop()); + + auto limiter = std::make_shared(); + auto guard = makeUploadGuard(limiter, stop); + EXPECT_NO_THROW(guard->throttle(32768, 0)); + EXPECT_EQ(limiter->amount, 32768u); + }); +} + +TEST(CASUploadGuard, AGroupWithATaskPredicateThrowsThroughTheGuard) +{ + onThread(true, [] + { + auto group = ThreadGroup::createForMergeMutate(getContext().context); + auto cancelled = std::make_shared>(false); + group->setQueryCancellationPredicates( + [cancelled] { return cancelled->load(); }, + [cancelled] + { + if (cancelled->load()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + CurrentThread::attachToGroup(group); + + auto limiter = std::make_shared(); + auto guard = makeUploadGuard(limiter, uploadStopCheck()); + EXPECT_NO_THROW(guard->throttle(32768, 0)); + + *cancelled = true; + EXPECT_EQ(codeOf([&] { guard->throttle(32768, 0); }), ErrorCodes::ABORTED); + }); +} + +TEST(CASUploadGuard, BodyGuardScopeMatchesTheExactKeyOnly) +{ + auto outer = std::make_shared(); + auto inner = std::make_shared(); + + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + { + BodyGuardScope scope("a", outer); + EXPECT_EQ(BodyGuardScope::forKey("a"), outer); + EXPECT_EQ(BodyGuardScope::forKey("b"), nullptr); + EXPECT_EQ(BodyGuardScope::forKey("a/"), nullptr); + EXPECT_EQ(BodyGuardScope::forKey(""), nullptr); + { + BodyGuardScope nested("b", inner); + EXPECT_EQ(BodyGuardScope::forKey("b"), inner); + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + } + EXPECT_EQ(BodyGuardScope::forKey("a"), outer); + EXPECT_EQ(BodyGuardScope::forKey("b"), nullptr); + } + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + + onThread(false, [&] + { + BodyGuardScope scope("a", outer); + }); + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); +} + +TEST(CASUploadGuard, UploadStopScopeRestoresItsPredecessor) +{ + EXPECT_FALSE(UploadStopScope::current()); + int outer_calls = 0; + int inner_calls = 0; + { + UploadStopScope outer([&] { ++outer_calls; }); + UploadStopScope::current()(); + { + UploadStopScope inner([&] { ++inner_calls; }); + UploadStopScope::current()(); + } + UploadStopScope::current()(); + { + UploadStopScope empty({}); + EXPECT_FALSE(UploadStopScope::current()); + } + EXPECT_TRUE(UploadStopScope::current()); + } + EXPECT_FALSE(UploadStopScope::current()); + EXPECT_EQ(outer_calls, 2); + EXPECT_EQ(inner_calls, 1); + + UploadStopScope here([] {}); + onThread(false, [] { EXPECT_FALSE(UploadStopScope::current()) << "the marker is thread-scoped"; }); +} + +#if USE_AWS_S3 + +namespace DB::ContentAddressedSetting +{ + extern const ContentAddressedSettingsString staging_backend; +} + +namespace CurrentMetrics +{ + extern const Metric LocalThread; + extern const Metric LocalThreadActive; + extern const Metric LocalThreadScheduled; +} + +namespace +{ + +using DB::Cas::tests::FakeGenerationObjectStorage; +using DB::Cas::tests::makeFakeGenerationObjectStorageForTest; +using WriteRecords = std::vector>; + +const String kTable = "a11/a11a11a1-1111-4111-8111-111111111111/"; + +/// A mount of `object_storage` that stages blob bodies in local files, so each body is streamed through `writeObject` +/// at publication; with `s3_staging` it stages them in the store and publishes them by a server-side copy. +std::shared_ptr mountOver( + const ObjectStoragePtr & object_storage, const String & server_root_id, bool s3_staging = false) +{ + static std::atomic counter{0}; + const auto scratch = std::filesystem::temp_directory_path() + / ("cas_upload_guard_" + server_root_id + "_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1))); + auto settings = DB::Cas::tests::makeSettingsForTest(server_root_id, scratch); + if (s3_staging) + { + settings[ContentAddressedSetting::staging_backend] = "s3"; + settings.validate(); + } + auto mount = DB::Cas::tests::ownedByDirectory( + std::make_shared(object_storage, "pool", "srv1", /*disk_name_=*/"", /*context_=*/nullptr, settings), + scratch); + mount->startup(); + return mount; +} + +void writeWith(IMetadataTransaction & tx, const String & path, const String & bytes, ThrottlerPtr limiter) +{ + WriteSettings settings; + settings.remote_throttler = std::move(limiter); + auto buf = dynamic_cast(tx).writeFile(path, 65536, WriteMode::Rewrite, settings); + buf->write(bytes.data(), bytes.size()); + buf->finalize(); +} + +String bodyKeyOf(const PoolPtr & pool, const String & payload) +{ + return pool->layout().blobKey(poolContentHash(pool->writeAlgo(), payload)); +} + +/// The streamed writes of `key`, copies excluded. +WriteRecords writesOf(const FakeGenerationObjectStorage & storage, const String & key) +{ + WriteRecords result; + for (const auto & record : storage.records()) + if (record->key == key && !record->copy) + result.push_back(record); + return result; +} + +/// The throttler of the one streamed body of `payload`. +ThrottlerPtr bodyThrottlerOf(const FakeGenerationObjectStorage & storage, const PoolPtr & pool, const String & payload) +{ + const auto writes = writesOf(storage, bodyKeyOf(pool, payload)); + if (writes.size() != 1) + throw std::runtime_error(fmt::format("expected one body write of {}, got {}", bodyKeyOf(pool, payload), writes.size())); + return writes.front()->settings.remote_throttler; +} + +/// Calls `throttler` as a socket does at a refill and checks that `target` alone among `limiters` was charged. +void expectReachesOnly(const ThrottlerPtr & throttler, const RecordingThrottler & target, const std::vector & limiters) +{ + ASSERT_NE(throttler, nullptr) << "the body carries no throttler"; + std::vector before; + for (const auto * limiter : limiters) + before.push_back(limiter->amount); + EXPECT_EQ(codeOf([&] { throttler->throttle(32768, 0); }), 0); + for (size_t i = 0; i < limiters.size(); ++i) + EXPECT_EQ(limiters[i]->amount - before[i], limiters[i] == &target ? 32768u : 0u) << "limiter #" << i; +} + +/// Sets the query's `max_remote_write_network_bandwidth` to one byte per second and returns the limiter that the +/// calling thread's writes get from it. +ThrottlerPtr limitQueryRemoteWrites(CasKillableQuery & query) +{ + query.context->setSetting("max_remote_write_network_bandwidth", Field(UInt64{1})); + return DB::getWriteSettings().remote_throttler; +} + +bool isManifestKey(const PoolPtr & pool, const String & key) +{ + return key.starts_with(pool->layout().casManifestsPrefix()); +} + +struct BoundedEvent +{ + std::mutex mutex; + std::condition_variable cv; + bool fired = false; + + void fire() + { + { + std::lock_guard lock(mutex); + fired = true; + } + cv.notify_all(); + } + + bool wait(std::chrono::seconds bound) + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, bound, [&] { return fired; }); + } +}; + +/// A precommitted build of `part_path`'s part, which every publication of `uploadBlobDetached` requires. +PartWriteTxnPtr precommittedBuild(ContentAddressedMetadataStorage & mount, const String & part_path) +{ + const auto route = mount.route(*parsePartFilePath(part_path + "data.bin")); + PartWriteInfo info; + info.intended_ref = route->ns.string() + "/" + route->ref; + PartWriteTxnPtr build = mount.poolForTest()->beginPartWrite(std::move(info)); + const String seed = "seed-manifest-" + part_path; + const ManifestId id = build->stageManifest({DB::Cas::tests::blobEntryFor("seed.bin", DB::Cas::tests::u128Of(seed), seed.size())}); + build->precommitAdd(route->ns, route->ref, id); + return build; +} + +BlobUploadRequest requestFor(const PoolPtr & pool, const String & payload, ThrottlerPtr limiter) +{ + BlobUploadRequest request{poolContentHash(pool->writeAlgo(), payload), BlobSource::fromString(payload), payload.size()}; + request.source.remote_throttler = std::move(limiter); + return request; +} + +std::unique_ptr makeWorkers(size_t size) +{ + return std::make_unique( + CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, CurrentMetrics::LocalThreadScheduled, size); +} + +} + +TEST(CASUploadGuard, EachBodyCarriesItsOwnLimiterAndTheStopOnlyInANewBuild) +{ + enum class Arm : uint8_t { NewBuild, CommittedPart, Owed, Shared }; + for (const Arm arm : {Arm::NewBuild, Arm::CommittedPart, Arm::Owed, Arm::Shared}) + { + const char * name = arm == Arm::NewBuild ? "new build" + : arm == Arm::CommittedPart ? "write onto a committed part" + : arm == Arm::Owed ? "inside owed" + : "inside shared"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardBodies{}", static_cast(arm))); + const String part = kTable + "all_1_1_0/"; + if (arm == Arm::CommittedPart) + { + auto tx = mount->createTransaction(); + writeWith(*tx, part + "count.txt", "1", nullptr); + tx->commit(NoCommitOptions{}); + } + + const String payload_a = fmt::format("guard bodies {}: the first file", name); + const String payload_b = fmt::format("guard bodies {}: the second file", name); + auto limiter_a = std::make_shared(); + auto limiter_b = std::make_shared(); + const std::vector limiters{limiter_a.get(), limiter_b.get()}; + const size_t records_before_query = storage->records().size(); + std::set manifests; + + onKillableQueryThread([&](CasKillableQuery & query) + { + SCOPED_TRACE(name); + ASSERT_NE(limitQueryRemoteWrites(query), nullptr) << "the query has no remote write limiter"; + { + std::optional owner; + if (arm == Arm::Owed) + owner.emplace(OwnerScope::owed()); + if (arm == Arm::Shared) + owner.emplace(OwnerScope::shared()); + auto tx = mount->createTransaction(); + writeWith(*tx, part + "a.bin", payload_a, limiter_a); + writeWith(*tx, part + "b.bin", payload_b, limiter_b); + tx->commit(NoCommitOptions{}); + } + + const ThrottlerPtr body_a = bodyThrottlerOf(*storage, mount->poolForTest(), payload_a); + const ThrottlerPtr body_b = bodyThrottlerOf(*storage, mount->poolForTest(), payload_b); + expectReachesOnly(body_a, *limiter_a, limiters); + expectReachesOnly(body_b, *limiter_b, limiters); + + const auto records = storage->records(); + for (size_t i = records_before_query; i < records.size(); ++i) + if (!records[i]->copy && isManifestKey(mount->poolForTest(), records[i]->key)) + manifests.insert(records[i].get()); + ASSERT_FALSE(manifests.empty()) << "the commit wrote no manifest"; + for (const auto * manifest : manifests) + EXPECT_EQ(manifest->settings.remote_throttler, nullptr) << "the manifest " << manifest->key << " carries a throttler"; + + query.kill(); + const int expected = arm == Arm::NewBuild ? ErrorCodes::QUERY_WAS_CANCELLED : 0; + ASSERT_NE(body_a, nullptr); + ASSERT_NE(body_b, nullptr); + EXPECT_EQ(codeOf([&] { body_a->throttle(32768, 0); }), expected); + EXPECT_EQ(codeOf([&] { body_b->throttle(32768, 0); }), expected); + }); + + const auto pool = mount->poolForTest(); + const std::set bodies{bodyKeyOf(pool, payload_a), bodyKeyOf(pool, payload_b)}; + size_t others = 0; + for (const auto & record : storage->records()) + { + if (record->copy || bodies.contains(record->key) || manifests.contains(record.get())) + continue; + ++others; + EXPECT_EQ(record->settings.remote_throttler, nullptr) << "a write of " << record->key << " carries a throttler"; + } + EXPECT_GT(others, 0u) << "the commit's other writes were not recorded"; + } +} + +TEST(CASUploadGuard, AServerSideCopyOfAStagedBodyCarriesNoThrottler) +{ + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardCopy", /*s3_staging=*/true); + const String payload = "guard copy: a staged body"; + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, kTable + "all_1_1_0/data.bin", payload, limiter); + tx->commit(NoCommitOptions{}); + }); + + const String body = bodyKeyOf(mount->poolForTest(), payload); + size_t copies = 0; + for (const auto & record : storage->records()) + { + if (!record->copy || record->key != body) + continue; + ++copies; + EXPECT_EQ(record->settings.remote_throttler, nullptr); + } + EXPECT_EQ(copies, 1u) << "the publication of a staged body was not a server-side copy"; +} + +TEST(CASUploadGuard, TheFanOutCarriesTheStopToItsWorkers) +{ + constexpr auto watchdog = std::chrono::seconds(30); + { + SCOPED_TRACE("a query killed while a worker sends a body"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFanoutStop"); + const auto pool = mount->poolForTest(); + const std::vector payloads{"guard fan-out stop: one", "guard fan-out stop: two", "guard fan-out stop: three"}; + const String stopped = bodyKeyOf(pool, payloads.front()); + + /// The hooks live in the storage, which the mount's teardown still writes through after this scope's locals + /// are gone, so they hold what they use. + auto in_body = std::make_shared(); + auto killed = std::make_shared(); + storage->throttle_while_writing = [stopped](const String & key) { return key == stopped; }; + storage->before_throttle = [in_body, killed, watchdog](const String &) + { + in_body->fire(); + EXPECT_TRUE(killed->wait(watchdog)); + }; + + std::atomic query_ptr{nullptr}; + int code = 0; + std::exception_ptr setup_error; + std::thread publisher([&] + { + try + { + ThreadStatus thread_status; + CasKillableQuery query(getContext().context); + query_ptr = &query; + auto build = precommittedBuild(*mount, kTable + "all_2_2_0/"); + std::vector requests; + for (const auto & payload : payloads) + requests.push_back(requestFor(pool, payload, std::make_shared())); + auto workers = makeWorkers(requests.size()); + UploadStopScope scope(uploadStopCheck()); + code = codeOf([&] { fanOutBlobUploads(*build, requests, *workers); }); + } + catch (...) + { + setup_error = std::current_exception(); + } + }); + + const bool entered = in_body->wait(watchdog); + EXPECT_TRUE(entered) << "no worker sent the body of the stopped blob"; + if (entered) + query_ptr.load()->kill(); + killed->fire(); + publisher.join(); + ASSERT_FALSE(setup_error) << "the publisher failed: " << getExceptionMessage(setup_error, false); + + const auto writes = writesOf(*storage, stopped); + ASSERT_EQ(writes.size(), 1u) << "the stopped blob was published again"; + ASSERT_TRUE(writes.front()->throttled) << "the stopped body carries no throttler"; + const std::exception_ptr throttle_error = writes.front()->throttle_error; + EXPECT_EQ(codeOf([&] { if (throttle_error) std::rethrow_exception(throttle_error); }), ErrorCodes::QUERY_WAS_CANCELLED) + << "the worker's body did not carry the query's stop"; + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + } +} + +TEST(CASUploadGuard, TheLimiterFollowsTheFile) +{ + const String source = kTable + "all_1_1_0/"; + const String destination = kTable + "all_2_2_0/"; + enum class Arm : uint8_t { Hardlink, Move }; + for (const Arm arm : {Arm::Hardlink, Arm::Move}) + { + const char * name = arm == Arm::Hardlink ? "hardlink" : "move"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardFollows{}", static_cast(arm))); + const String payload = fmt::format("guard follows the file: {}", name); + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "data.bin", payload, limiter); + writeWith(*tx, source + "count.txt", "1", nullptr); + if (arm == Arm::Hardlink) + { + tx->createHardLink(source + "data.bin", destination + "data.bin"); + tx->unlinkFile(source + "data.bin", /*if_exists=*/false, /*should_remove_objects=*/false); + } + else + tx->moveFile(source + "data.bin", destination + "data.bin"); + tx->commit(NoCommitOptions{}); + }); + + ASSERT_FALSE(mount->existsFile(source + "data.bin")) << "the source part still names the body"; + ASSERT_TRUE(mount->existsFile(destination + "data.bin")); + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter, {limiter.get()}); + } + + { + SCOPED_TRACE("equal bytes written twice into one part"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFollowsTwice"); + const String payload = "guard follows the file: equal bytes"; + auto limiter_a = std::make_shared(); + auto limiter_b = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "a.bin", payload, limiter_a); + writeWith(*tx, source + "b.bin", payload, limiter_b); + tx->commit(NoCommitOptions{}); + }); + + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter_a, {limiter_a.get(), limiter_b.get()}); + } + + { + SCOPED_TRACE("an inline candidate above the inline cap"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFollowsOversizedInline"); + /// One byte above `INLINE_CAP` of `ContentAddressedTransaction.cpp`, so the file spills to a blob. + const String payload(1024 * 1024 + 1, 'c'); + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "columns.txt", payload, limiter); + tx->commit(NoCommitOptions{}); + }); + + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter, {limiter.get()}); + } +} + +TEST(CASUploadGuard, TheStagingSinkCarriesTheGuardAndKeepsItsDefaults) +{ + enum class Arm : uint8_t { NewBuild, CommittedPart }; + for (const Arm arm : {Arm::NewBuild, Arm::CommittedPart}) + { + const char * name = arm == Arm::NewBuild ? "new build" : "data file written into a committed part"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardSink{}", static_cast(arm)), /*s3_staging=*/true); + const String part = kTable + "all_1_1_0/"; + if (arm == Arm::CommittedPart) + { + auto tx = mount->createTransaction(); + writeWith(*tx, part + "count.txt", "1", nullptr); + tx->commit(NoCommitOptions{}); + } + const String sink_prefix = mount->stagingKeyPrefix(); + const auto sinksSince = [&](size_t first) + { + WriteRecords sinks; + const auto records = storage->records(); + for (size_t i = first; i < records.size(); ++i) + if (!records[i]->copy && records[i]->key.starts_with(sink_prefix)) + sinks.push_back(records[i]); + return sinks; + }; + + auto limiter = std::make_shared(); + onKillableQueryThread([&](CasKillableQuery & query) + { + SCOPED_TRACE(name); + auto tx = mount->createTransaction(); + + const size_t before_txn_version = storage->records().size(); + writeWith(*tx, part + "txn_version.txt", "version: 1\n", limiter); + EXPECT_TRUE(sinksSince(before_txn_version).empty()) << "txn_version.txt opened a staging sink"; + + WriteSettings settings; + settings.remote_throttler = limiter; + settings.enable_filesystem_cache_log = true; + const size_t before_data = storage->records().size(); + { + auto buf = dynamic_cast(*tx).writeFile( + part + "data.bin", 65536, WriteMode::Rewrite, settings); + const String payload = fmt::format("guard sink: {}", name); + buf->write(payload.data(), payload.size()); + buf->finalize(); + } + const auto sinks = sinksSince(before_data); + ASSERT_EQ(sinks.size(), 1u) << "the data file did not go through one staging sink"; + + WriteSettings stripped = sinks.front()->settings; + stripped.remote_throttler = nullptr; + EXPECT_TRUE(stripped == WriteSettings{}) << "the sink's settings differ from the defaults beyond the throttler"; + const ThrottlerPtr sink_throttler = sinks.front()->settings.remote_throttler; + expectReachesOnly(sink_throttler, *limiter, {limiter.get()}); + tx->commit(NoCommitOptions{}); + + query.kill(); + ASSERT_NE(sink_throttler, nullptr); + EXPECT_EQ(codeOf([&] { sink_throttler->throttle(32768, 0); }), ErrorCodes::QUERY_WAS_CANCELLED); + }); + } +} + +TEST(CASUploadGuard, APoolJobInheritsTheBlockerOnlyForItself) +{ + ThreadPool pool(CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, CurrentMetrics::LocalThreadScheduled, 1, 1, 0); + + std::mutex mutex; + std::condition_variable cv; + bool released = false; + std::thread::id gate_thread; + std::thread::id thread_a; + std::thread::id thread_b; + bool active_a = false; + bool active_b = true; + + /// The only worker is busy here, so job A starts after the scheduling scope below is gone. + pool.scheduleOrThrow( + [&] + { + std::unique_lock lock(mutex); + gate_thread = std::this_thread::get_id(); + cv.wait(lock, [&] { return released; }); + }); + { + ThreadStatus::QueryCancellationBlocker blocker; + pool.scheduleOrThrow( + [&] + { + thread_a = std::this_thread::get_id(); + active_a = ThreadStatus::QueryCancellationBlocker::isActive(); + }); + } + EXPECT_FALSE(ThreadStatus::QueryCancellationBlocker::isActive()); + pool.scheduleOrThrow( + [&] + { + thread_b = std::this_thread::get_id(); + active_b = ThreadStatus::QueryCancellationBlocker::isActive(); + }); + { + std::lock_guard lock(mutex); + released = true; + } + cv.notify_all(); + pool.wait(); + + EXPECT_TRUE(active_a); + EXPECT_FALSE(active_b); + EXPECT_EQ(thread_a, gate_thread) << "the jobs must share the one retained worker"; + EXPECT_EQ(thread_b, gate_thread); +} + +#endif diff --git a/src/IO/ReadBufferFromS3.cpp b/src/IO/ReadBufferFromS3.cpp index 4eb5ee1ffec5..651493eda5ba 100644 --- a/src/IO/ReadBufferFromS3.cpp +++ b/src/IO/ReadBufferFromS3.cpp @@ -401,6 +401,9 @@ bool ReadBufferFromS3::processException(size_t read_offset, size_t attempt) cons bucket, key, version_id.empty() ? "Latest" : version_id, read_offset, attempt, request_settings[S3RequestSetting::max_single_read_retries].value, getCurrentExceptionMessage(/* with_stacktrace = */ false)); + /// Throws the cancellation cause, and is a no-op off-query, so an ordinary network error still retries. + CurrentThread::checkIfNotCancelled(); + /// A cancelled query must not keep retrying a transient read error (the SDK's RetryStrategy applies the same rule). if (CurrentThread::isInitialized() && CurrentThread::get().isQueryCanceled()) return false; diff --git a/src/IO/S3/copyS3File.cpp b/src/IO/S3/copyS3File.cpp index 76f2dbb2df57..2f65b6421e6c 100644 --- a/src/IO/S3/copyS3File.cpp +++ b/src/IO/S3/copyS3File.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -252,6 +253,9 @@ namespace void abortMultipartUpload() { + /// Keep the retries of this cleanup when the query or merge is cancelled. The in-flight parts are already waited for. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + LOG_TRACE(log, "Aborting multipart upload. Bucket: {}, Key: {}, Upload_id: {}", dest_bucket, dest_key, multipart_upload_id); S3::AbortMultipartUploadRequest abort_request; abort_request.SetBucket(dest_bucket); diff --git a/src/IO/WriteBufferFromS3.cpp b/src/IO/WriteBufferFromS3.cpp index 2b4be44f26c5..6d0e98d4db7c 100644 --- a/src/IO/WriteBufferFromS3.cpp +++ b/src/IO/WriteBufferFromS3.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -493,6 +494,9 @@ void WriteBufferFromS3::abortMultipartUpload() return; } + /// Keep the retries of this cleanup when the query or merge is cancelled. The in-flight parts are already waited for. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + LOG_INFO(log, "Abort multipart upload. {}", getVerboseLogDetails()); S3::AbortMultipartUploadRequest req; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index fa2901bdc812..4ef66e711781 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1083,12 +1083,55 @@ struct ContextSharedPart : boost::noncopyable LOG_TRACE(log, "Shutting down object storage queue streaming"); StreamingStorageRegistry::instance().shutdown(); - /// Stop all MergeTree background executors before shutting down databases. - /// This ensures no background tasks (merges, mutations, moves, part cleanup) - /// are running when storage objects are shut down or destroyed. - /// Without this, a background task could be accessing a storage's data_parts_indexes - /// while DatabaseCatalog::shutdown is destroying that storage, causing a SIGBUS. + /// Stop all MergeTree background executors and cancel the in-flight merges, + /// mutations, fetches and moves, in this order: + /// + /// 1. Flip every executor into shutdown mode without joining it. From this point on + /// no new task can be scheduled (`trySchedule` rejects them) and no pending task + /// can start (worker threads exit at the next step boundary), so the set of + /// running tasks cannot grow. + /// 2. Cancel the running merges, mutations, fetches and moves. `cancelAll` also marks entries + /// inserted later as cancelled, so a task that is inside its first step and has + /// not registered itself in the list yet cannot escape the cancellation. + /// 3. Join the executors. + /// + /// The executors' `wait` (step 3) does not interrupt already running tasks, and the + /// per-storage cancellation (`merges_blocker`, `fetcher.blocker`) happens only later, + /// in `DatabaseCatalog::shutdown`. Without step 2, `wait` would block until the + /// current task step completes, and a single slow step (e.g. a merge applying huge + /// patch parts, which can spend minutes inside one block under sanitizers, or a + /// fetch of a large part) would delay shutdown beyond any timeout. The results of + /// merges and fetches are discarded after the restart anyway, so finishing them is pure + /// waste. A finished move is kept, but it would only delay the shutdown. A running export step + /// is not cancelled and is waited for: the manifest of a direct `EXPORT PART` lives in memory + /// only, so a cancelled export would not be resumed. Without step 1, the cancellation would be racy: a task + /// scheduled after step 2 would be invisible to `cancelAll` and block `wait` again. + /// + /// Merge and mutate tasks check `MergeListElement::is_cancelled` on every block + /// through `MergeProgressCallback` and abort with the `ABORTED` exception; fetches + /// check `ReplicatedFetchListElement::is_cancelled` on every buffer refill. Fetches and moves + /// also run in their own thread group, whose predicates see `cancelAll` of their list, so + /// the writes below them stop as well. + /// + /// Waiting for the executors before shutting down databases also ensures no + /// background task is accessing a storage's data (e.g. data_parts_indexes) while + /// `DatabaseCatalog::shutdown` destroys that storage, which used to cause a SIGBUS. /// See https://github.com/ClickHouse/ClickHouse/issues/85433 + LOG_TRACE(log, "Stopping background executors from starting new tasks"); + if (merge_mutate_executor) + merge_mutate_executor->requestShutdown(); + if (fetch_executor) + fetch_executor->requestShutdown(); + if (moves_executor) + moves_executor->requestShutdown(); + if (common_executor) + common_executor->requestShutdown(); + + LOG_TRACE(log, "Cancelling merges, mutations, fetches and moves"); + merge_list.cancelAll(); + replicated_fetch_list.cancelAll(); + moves_list.cancelAll(); + SHUTDOWN(log, "merges executor", merge_mutate_executor, wait()); SHUTDOWN(log, "fetches executor", fetch_executor, wait()); SHUTDOWN(log, "moves executor", moves_executor, wait()); diff --git a/src/Interpreters/MergeTreeTransaction.cpp b/src/Interpreters/MergeTreeTransaction.cpp index 7f0e2f331333..c72de2f67ec1 100644 --- a/src/Interpreters/MergeTreeTransaction.cpp +++ b/src/Interpreters/MergeTreeTransaction.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -338,6 +339,8 @@ void MergeTreeTransaction::afterCommit(CSN assigned_csn) noexcept { auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + /// A cancelled query or merge must not interrupt this: an escaping exception terminates the server. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; DataPartsVector created_parts; DataPartsVector removed_parts; @@ -394,6 +397,8 @@ bool MergeTreeTransaction::rollback() noexcept { auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + /// A cancelled query or merge must not interrupt this: an escaping exception terminates the server. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; CSN expected = Tx::UnknownCSN; bool need_rollback = csn.compare_exchange_strong(expected, Tx::RolledBackCSN); diff --git a/src/Interpreters/ThreadStatusExt.cpp b/src/Interpreters/ThreadStatusExt.cpp index 36b18da61316..94ca3382a8e5 100644 --- a/src/Interpreters/ThreadStatusExt.cpp +++ b/src/Interpreters/ThreadStatusExt.cpp @@ -131,11 +131,23 @@ ThreadGroup::ThreadGroup(ContextPtr query_context_, Int32 os_threads_nice_value_ }; } +// c-tor for method createWithoutQueryContext +ThreadGroup::ThreadGroup(const ContextWeakPtr & global_context_) + : master_thread_id(CurrentThread::get().thread_id) + , global_context(global_context_) + , with_query_context(false) + , os_threads_nice_value(0) + , memory_spill_scheduler(std::make_shared()) + , memory_tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor*/ false) +{ +} + ThreadGroup::ThreadGroup(ThreadGroupPtr parent_thread_group) : parent(std::move(parent_thread_group)) , master_thread_id(parent->master_thread_id) , query_context(parent->query_context) , global_context(parent->global_context) + , with_query_context(parent->with_query_context) , fatal_error_callback(parent->fatal_error_callback) , os_threads_nice_value(parent->os_threads_nice_value) , memory_spill_scheduler(parent->memory_spill_scheduler) @@ -197,6 +209,13 @@ UInt64 ThreadGroup::getGroupElapsedMs() const return elapsed_group_ms; } +void ThreadGroup::setQueryCancellationPredicates(QueryIsCanceledPredicate is_canceled, ThrowIfQueryCanceledPredicate throw_if_canceled) +{ + std::lock_guard lock(mutex); + shared_data.query_is_canceled_predicate = std::move(is_canceled); + shared_data.throw_if_query_canceled_predicate = std::move(throw_if_canceled); +} + void ThreadGroup::linkThread(UInt64 thread_id) { std::lock_guard lock(mutex); @@ -262,6 +281,18 @@ ThreadGroupPtr ThreadGroup::createForMaterializedView(ContextPtr context) return res_group; } +ThreadGroupPtr ThreadGroup::createWithoutQueryContext(ContextPtr global_context_) +{ + return ThreadGroupPtr(new ThreadGroup(ContextWeakPtr(global_context_->getGlobalContext()))); +} + +ThreadGroupPtr ThreadGroup::createForBackgroundOperation(ContextPtr global_context_, ThreadGroupPtr parent_thread_group) +{ + if (!parent_thread_group) + return createWithoutQueryContext(std::move(global_context_)); + return ThreadGroupPtr(new ThreadGroup(std::move(parent_thread_group))); +} + ThreadGroupPtr ThreadGroup::createForExplainAnalyze(ThreadGroupPtr parent_thread_group) { return ThreadGroupPtr(new ThreadGroup(parent_thread_group)); @@ -426,7 +457,8 @@ void ThreadStatus::detachFromGroup() /// flush untracked memory before resetting memory_tracker parent flushUntrackedMemory(); - finalizeQueryProfiler(); + if (thread_group->with_query_context) + finalizeQueryProfiler(); finalizePerformanceCounters(); performance_counters.setParent(&ProfileEvents::global_counters); diff --git a/src/Interpreters/TransactionLog.cpp b/src/Interpreters/TransactionLog.cpp index dda4b78a0147..a31fe4487e45 100644 --- a/src/Interpreters/TransactionLog.cpp +++ b/src/Interpreters/TransactionLog.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -493,6 +494,7 @@ CSN TransactionLog::finalizeCommittedTransaction(MergeTreeTransaction * txn, CSN { LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); + ThreadStatus::QueryCancellationBlocker cancellation_blocker; chassert(!allocated_csn == txn->isReadOnly()); if (allocated_csn) { @@ -540,6 +542,7 @@ bool TransactionLog::waitForCSNLoaded(CSN csn) const void TransactionLog::rollbackTransaction(const MergeTreeTransactionPtr & txn) noexcept { LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + ThreadStatus::QueryCancellationBlocker cancellation_blocker; LOG_TRACE(log, "Rolling back transaction {}{}", txn->tid, std::uncaught_exceptions() ? fmt::format(" due to uncaught exception (code: {})", getCurrentExceptionCode()) : ""); diff --git a/src/Storages/MergeTree/BackgroundOperationCancellation.cpp b/src/Storages/MergeTree/BackgroundOperationCancellation.cpp new file mode 100644 index 000000000000..322a2cdd0952 --- /dev/null +++ b/src/Storages/MergeTree/BackgroundOperationCancellation.cpp @@ -0,0 +1,80 @@ +#include + +#include +#include + +namespace DB +{ + +namespace ErrorCodes +{ + extern const int ABORTED; + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace +{ + +/// Copies share the latch and the counters of the blockers. +struct StopPoll +{ + std::shared_ptr stopped; + std::vector blockers; + + bool operator()() const + { + if (stopped->load(std::memory_order_relaxed)) + return true; + for (const auto & blocker : blockers) + { + if (blocker.isCancelled()) + { + stopped->store(true, std::memory_order_relaxed); + return true; + } + } + return false; + } +}; + +} + +void installCancellationPredicates( + ThreadGroup & group, + std::shared_ptr stopped, + std::vector blockers, + std::string what) +{ + auto inherited = group.getSharedData(); + StopPoll poll{std::move(stopped), std::move(blockers)}; + + group.setQueryCancellationPredicates( + [inherited_is_canceled = std::move(inherited.query_is_canceled_predicate), poll]() -> bool + { + return (inherited_is_canceled && inherited_is_canceled()) || poll(); + }, + [inherited_throw = std::move(inherited.throw_if_query_canceled_predicate), poll, message = std::move(what)]() + { + if (inherited_throw) + inherited_throw(); + if (poll()) + throw Exception(ErrorCodes::ABORTED, "{}", message); + }); +} + +ThrowIfQueryCanceledPredicate getThrowingCancellationPredicate(const ThreadGroup & group) +{ + auto predicate = group.getSharedData().throw_if_query_canceled_predicate; + if (!predicate) + throw Exception(ErrorCodes::LOGICAL_ERROR, "No cancellation predicate installed on the thread group"); + return predicate; +} + +void checkAttachedTo(const ThreadGroupPtr & group) +{ + if (CurrentThread::getGroup() != group) + throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "Cannot attach the thread to the thread group of the background operation"); +} + +} diff --git a/src/Storages/MergeTree/BackgroundOperationCancellation.h b/src/Storages/MergeTree/BackgroundOperationCancellation.h new file mode 100644 index 000000000000..cd5fec123351 --- /dev/null +++ b/src/Storages/MergeTree/BackgroundOperationCancellation.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +/// Makes `group` report a stop when `stopped` is set or any of `blockers` is cancelled, in addition to whatever the +/// group already reports (a nested group inherits the predicates of its parent). The Boolean predicate returns true +/// when the inherited predicate does or when `stopped` is set or a blocker is cancelled; the +/// throwing one calls the inherited throwing predicate first and then throws `ABORTED` with `what`. +/// +/// Must be called before any thread attaches to the group. A poll that sees a cancelled blocker sets `stopped`, so the +/// stop outlives the blocker being released; a blocker that is cancelled and released between two polls is not seen. +/// The predicates own everything this function adds (the latch, the blockers, the message). The inherited ones +/// borrow their ancestor: a parent group, or the list entry of a merge, which no group owns. A copy of a predicate +/// is valid while the operation that installed the inherited predicates is alive. Holding the group is necessary +/// but not sufficient. +void installCancellationPredicates( + ThreadGroup & group, + std::shared_ptr stopped, + std::vector blockers, + std::string what); + +/// An owned copy of the throwing predicate of `group`, for checks made after the thread has left the group. +/// The copy is valid only while `group` is alive and the operation that installed its inherited predicates is +/// (see `installCancellationPredicates`). +/// Never empty: throws `LOGICAL_ERROR` if no predicate was installed, which means a call site forgot +/// `installCancellationPredicates`. +ThrowIfQueryCanceledPredicate getThrowingCancellationPredicate(const ThreadGroup & group); + +/// Throws `CANNOT_SCHEDULE_TASK` unless the current thread is attached to `group`. `ThreadGroupSwitcher` only logs +/// a failed attach, and an operation that goes on outside its group could not be stopped. +void checkAttachedTo(const ThreadGroupPtr & group); + +} diff --git a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp index b0646313fe02..7fe6dbecfe2f 100644 --- a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp +++ b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -921,6 +922,10 @@ MutableDataPartStoragePtr DataPartStorageOnDiskBase::clonePart( } catch (...) { + /// The copy may have failed because the move was cancelled, and the cancelled group is still + /// attached: the removal must keep the retries of its own requests. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + /// It's safe to remove it recursively (even with zero-copy-replication) /// because we've just did full copy through copyDirectoryContent LOG_WARNING(log, "Removing directory {} after failed attempt to move a data part", path_to_clone); diff --git a/src/Storages/MergeTree/DataPartsExchange.cpp b/src/Storages/MergeTree/DataPartsExchange.cpp index 1285f5152bad..a7e5bfe2a1c9 100644 --- a/src/Storages/MergeTree/DataPartsExchange.cpp +++ b/src/Storages/MergeTree/DataPartsExchange.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -35,8 +36,12 @@ #include #include #include +#include +#include +#include #include #include +#include namespace fs = std::filesystem; @@ -51,14 +56,18 @@ namespace DB namespace FailPoints { - /// CAS fetch-by-relink, receiver side. Both exist because the two exits they drive are properties of - /// the sender/receiver PAIR and of the interval between the receiver's publish and its confirm — and - /// neither is reachable from configuration, so an integration test cannot produce them any other way. + /// Receiver side of a relink: fails the relink mechanism before anything is staged. extern const char cas_relink_receiver_force_mechanism_failure[]; + /// Receiver side of a relink: cancels the current fetch while the relink is prepared. + extern const char cas_relink_receiver_cancel_fetches_in_preparation[]; + /// Receiver side of a relink: pauses between the publish and the confirm. extern const char cas_relink_receiver_pause_before_confirm[]; /// Stands in for a sender that predates the `cas_pool_uuid` response cookie: the offer is made /// without naming the pool, and the receiver has to fall back on "the single advertised pool". extern const char cas_relink_sender_omit_pool_cookie[]; + + /// Pauses the receiver between the projections and the base part of a byte fetch. + extern const char replicated_fetch_pause_after_projections[]; } namespace MergeTreeSetting @@ -69,6 +78,11 @@ namespace MergeTreeSetting extern const MergeTreeSettingsUInt64 min_compressed_bytes_to_fsync_after_fetch; } +namespace FailPoints +{ + extern const char replicated_sends_sleep_before_file_send[]; +} + namespace ErrorCodes { extern const int NO_SUCH_DATA_PART; @@ -78,6 +92,7 @@ namespace ErrorCodes extern const int INSECURE_PATH; extern const int LOGICAL_ERROR; extern const int NO_REPLICA_HAS_PART; + extern const int QUERY_WAS_CANCELLED; extern const int S3_ERROR; extern const int ZERO_COPY_REPLICATION_ERROR; } @@ -176,6 +191,12 @@ struct ReplicatedFetchReadCallback void operator() (size_t bytes_count) { + /// The entry is cancelled on server shutdown - there is no point in finishing + /// the download, its result would be discarded anyway. + if (replicated_fetch_entry->is_cancelled->load()) + throw Exception(ErrorCodes::ABORTED, + "Fetching of part {} was cancelled", replicated_fetch_entry->result_part_name); + replicated_fetch_entry->bytes_read_compressed.store(bytes_count, std::memory_order_relaxed); /// It's possible when we fetch part from very old clickhouse version @@ -563,6 +584,15 @@ MergeTreeData::DataPart::Checksums Service::sendPartFromDisk( writeBinary(replicated_description.files.size(), out); for (const auto & [file_name, desc] : replicated_description.files) { + /// The flush makes the send observable by the receiver: without it, small (e.g. zero-copy + /// metadata) files accumulate in `out` and are sent in one piece at the end, and the sleeps + /// would just delay that single send instead of simulating a slow streaming transfer. + fiu_do_on(FailPoints::replicated_sends_sleep_before_file_send, + { + out.next(); + sleepForSeconds(5); + }); + writeStringBinary(file_name, out); writeBinary(desc.file_size, out); @@ -819,9 +849,33 @@ std::pair Fetcher::fetchSelected .withMethod(Poco::Net::HTTPRequest::HTTP_POST) .withTimeouts(timeouts) .withSettings(read_settings) - .withDelayInit(false) + /// The buffer size determines how often `ReplicatedFetchReadCallback` observes the + /// cancellation of the fetch (e.g. on server shutdown): the underlying read blocks + /// until a whole buffer is received, and the callback runs between the refills. + .withBufSize(read_settings.remote_fs_settings.buffer_size) + /// Delay the request until the shutdown cancellation callback below is installed: + /// with eager initialization the constructor would perform the first blocking read + /// before `setNextCallback` can run. + .withDelayInit(true) .create(creds); + /// Make the shutdown cancellation (`ReplicatedFetchList::cancelAll`) effective from the very + /// first read of the response body: the part header (sizes, TTL infos, part type, UUID, + /// projection count) is read below before the fetch is registered in the list, and a sender + /// stalled in that prefix would otherwise pin the fetch worker until the HTTP timeouts fire. + /// The callback is replaced by `ReplicatedFetchReadCallback` after the registration. + auto & replicated_fetch_list = data.getContext()->getReplicatedFetchList(); + in->setNextCallback([&replicated_fetch_list, part_name](size_t) + { + if (replicated_fetch_list.isAllCancelled()) + throw Exception(ErrorCodes::ABORTED, "Fetching of part {} was cancelled", part_name); + }); + + /// Send the request and read the first chunk of the response body. `nextImpl` runs the callback + /// before the connection and each blocking refill, so the whole transfer is cancellable. + /// The response is needed just below for the cookies. + in->next(); + int server_protocol_version = parse(in->getResponseCookie("server_protocol_version", "0")); String remote_fs_metadata = parse(in->getResponseCookie("remote_fs_metadata", "")); @@ -942,6 +996,37 @@ std::pair Fetcher::fetchSelected if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION) readBinary(projections, *in); + /// Register the fetch before branching on `remote_fs_metadata`, so that both the regular and the + /// zero-copy download participate in the shutdown cancellation (`ReplicatedFetchList::cancelAll`): + /// the callback aborts the fetch with `ABORTED` on the next buffer refill after the entry is cancelled. + auto storage_id = data.getStorageID(); + String new_part_path = fs::path(data.getFullPathOnDisk(disk)) / part_name / ""; + auto entry = replicated_fetch_list.insert( + storage_id.getDatabaseName(), storage_id.getTableName(), + part_info.getPartitionId(), part_name, new_part_path, + replica_path, uri, to_detached, sum_files_size); + + /// Run the fetch in its own thread group, so that a stop reaches the writes below it (requests to the + /// destination and their retries) and not only the reads of the response. The predicates are installed + /// before any thread attaches to the group. + auto thread_group = ThreadGroup::createForBackgroundOperation(data.getContext(), CurrentThread::getGroup()); + installCancellationPredicates(*thread_group, (*entry)->is_cancelled, {blocker}, "Fetching of part was cancelled"); + std::optional group_switcher; + group_switcher.emplace(thread_group, getThreadName(), /*allow_existing_group=*/ true); + checkAttachedTo(thread_group); + + in->setNextCallback(ReplicatedFetchReadCallback(*entry)); + + /// Ends this attempt before a retry that calls this function again: the response must no longer touch the + /// entry, the group is left before the entry and the directory lock are released. + auto end_attempt = [&] + { + in->setNextCallback([](size_t) {}); + group_switcher.reset(); + entry.reset(); + temporary_directory_lock = {}; + }; + /// CAS replication — fetch-by-relink (`part_manifest_v2`). The sender /// chose to relink: it sent only the part's encoded PartManifest body, no file bytes, and the /// reservation above already went to the offered pool's disk. Build the part by staging this @@ -970,7 +1055,13 @@ std::pair Fetcher::fetchSelected /// one as evidence that the brake is redundant.) auto fall_back_to_byte_fetch = [&] { - temporary_directory_lock = {}; + /// Relink preparation reads a stop as "relink not possible", and a stopped fetch must not go on + /// to fetch the bytes. The recursive call does not see every stop at once: an inherited one (a + /// killed `FETCH PARTITION`, a fetch inside a merge task) and a latched one whose blocker was + /// released are visible only through this predicate. + getThrowingCancellationPredicate(*thread_group)(); + /// The recursive call registers its own entry in the `ReplicatedFetchList`. + end_attempt(); return fetchSelectedPart( metadata_snapshot, context, part_name, zookeeper_name, replica_path, host, port, timeouts, user, password, interserver_scheme, throttler, to_detached, tmp_prefix, nullptr, false, disk, @@ -1061,7 +1152,8 @@ std::pair Fetcher::fetchSelected LOG_WARNING(log, "Will retry fetching part without zero-copy: {}", e.message()); - temporary_directory_lock = {}; + /// The recursive call registers its own entry in the `ReplicatedFetchList`. + end_attempt(); /// Try again but without zero-copy. `allow_ca_relink=false` for the same reason as the relink /// branch's fallback above: this is a same-sender byte re-request, and it must not re-open a @@ -1081,15 +1173,6 @@ std::pair Fetcher::fetchSelected } } - auto storage_id = data.getStorageID(); - String new_part_path = fs::path(data.getFullPathOnDisk(disk)) / part_name / ""; - auto entry = data.getContext()->getReplicatedFetchList().insert( - storage_id.getDatabaseName(), storage_id.getTableName(), - part_info.getPartitionId(), part_name, new_part_path, - replica_path, uri, to_detached, sum_files_size); - - in->setNextCallback(ReplicatedFetchReadCallback(*entry)); - auto output_buffer_getter = [](IDataPartStorage & part_storage, const String & file_name, size_t file_size) { return part_storage.writeFile(file_name, std::min(file_size, DBMS_DEFAULT_BUFFER_SIZE), {}); @@ -1287,18 +1370,38 @@ MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( projection_name + ".proj", projection_checksum.getTotalSizeOnDisk(), projection_checksum.getTotalChecksumUInt128()); } + /// Test-only: lets a test stop the fetch while the projections are finalized and the base part is not started. + FailPointInjection::pauseFailPoint(FailPoints::replicated_fetch_pause_after_projections); + downloadBaseOrProjectionPartToDisk( replica_path, part_storage_for_loading, in, output_buffer_getter, data_checksums, throttler, sync); } catch (const Exception & e) { /// Remove the whole part directory if fetch of base - /// part or fetch of any projection was stopped. - if (e.code() == ErrorCodes::ABORTED) + /// part or fetch of any projection was stopped. A fetch run by a query is stopped by the + /// inherited predicate of the query, which throws `QUERY_WAS_CANCELLED`. + if (e.code() == ErrorCodes::ABORTED || e.code() == ErrorCodes::QUERY_WAS_CANCELLED) { - part_storage_for_loading->removeSharedRecursive(true); - if (part_storage_for_loading->hasActiveTransaction()) - part_storage_for_loading->commitTransaction(); + /// The group's predicates already report the stop, which would end the retries of this cleanup. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + try + { + part_storage_for_loading->removeSharedRecursive(true); + if (part_storage_for_loading->hasActiveTransaction()) + part_storage_for_loading->commitTransaction(); + } + catch (...) + { + /// Nothing may replace the stop that is rethrown below, and building the log prefix can throw. + try + { + tryLogCurrentException(log, "Cannot remove the directory of the stopped fetch"); + } + catch (...) // NOLINT(bugprone-empty-catch) + { + } + } } throw; } @@ -1310,11 +1413,16 @@ MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( if (part_storage_for_loading->hasActiveTransaction()) part_storage_for_loading->commitTransaction(); - MergeTreeDataPartBuilder builder(data, part_name, volume, part_relative_path, part_dir, getReadSettings(), PartDirIntent::OpenExisting); - new_data_part = builder.withPartFormatFromDisk().build(); + { + /// A stop between the commit and `is_temp` would leave a directory that no part object owns. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + + MergeTreeDataPartBuilder builder(data, part_name, volume, part_relative_path, part_dir, getReadSettings(), PartDirIntent::OpenExisting); + new_data_part = builder.withPartFormatFromDisk().build(); - new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); - new_data_part->is_temp = true; + new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); + new_data_part->is_temp = true; + } /// In case of replicated merge tree with zero copy replication /// Here ClickHouse claims that this new part can be deleted in temporary state without unlocking the blobs /// The blobs have to stay intact, this temporary part does not own them and does not share them yet. @@ -1534,6 +1642,15 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( return nullptr; } + /// Test-only. Cancels the running fetches the way a server shutdown does, which sets the flag of the + /// fetch's entry but not the fetcher's blocker. + fiu_do_on(FailPoints::cas_relink_receiver_cancel_fetches_in_preparation, + { + LOG_INFO(log, "Failpoint cas_relink_receiver_cancel_fetches_in_preparation: cancelling the fetches while part {} " + "is in relink preparation", part_name); + data.getContext()->getReplicatedFetchList().cancelCurrent(); + }); + /// Test-only. Forces the "mechanism failed, the sender still has the part" exit (the ACTION of /// taxonomy rows 2 and 5) on EVERY attempt, which is precisely the shape the recursion brake has to /// bound: a persistent property of this sender/receiver pair, so the byte re-request re-offers and @@ -1685,6 +1802,9 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( "committed, so the bytes must NOT be fetched; the fetch will be retried later", part_name, fetch_uri.getHost()); } + /// A stop between the commit and `is_temp` would leave a directory that no part object owns. + std::optional cancellation_blocker(std::in_place); + /// The single terminal operation is done, so the handle owes nothing; releasing it here also disarms /// the scope guard for the part-building code below. prepared.reset(); @@ -1699,6 +1819,7 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); new_data_part->is_temp = true; + cancellation_blocker.reset(); /// The blobs are shared in the pool; a discarded temporary relink part must NOT reclaim them (another /// replica's ref keeps them alive). Same policy a zero-copy-fetched temporary part uses. new_data_part->remove_tmp_policy = IMergeTreeDataPart::BlobsRemovalPolicyForTemporaryParts::PRESERVE_BLOBS; diff --git a/src/Storages/MergeTree/IMergeTreeDataPart.cpp b/src/Storages/MergeTree/IMergeTreeDataPart.cpp index e441968da1ea..5e9cf5673b1a 100644 --- a/src/Storages/MergeTree/IMergeTreeDataPart.cpp +++ b/src/Storages/MergeTree/IMergeTreeDataPart.cpp @@ -60,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -1149,6 +1150,9 @@ void IMergeTreeDataPart::removeIfNeeded() if (!is_temp && state != MergeTreeDataPartState::DeleteOnDestroy) return; + /// Keep the retries of this cleanup when the query or merge is cancelled (`plain_rewritable` removes synchronously). + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + try { if (!getDataPartStorage().exists()) // path diff --git a/src/Storages/MergeTree/MergeList.h b/src/Storages/MergeTree/MergeList.h index 5ef867c1a438..a192e152d421 100644 --- a/src/Storages/MergeTree/MergeList.h +++ b/src/Storages/MergeTree/MergeList.h @@ -95,6 +95,10 @@ struct MergeListElement : boost::noncopyable std::atomic progress{}; std::atomic is_cancelled{}; + /// Set once `MergeTask::prepare` has settled it: a regular merge that removes expired values is + /// cancellable by `SYSTEM STOP TTL MERGES`, one that had removal disabled up front is not. + std::atomic is_removing_expired_values{}; + UInt64 total_size_bytes_compressed{}; UInt64 total_size_bytes_uncompressed{}; UInt64 total_size_marks{}; @@ -159,6 +163,8 @@ class MergeList final : public BackgroundProcessList; std::atomic merges_with_ttl_counter = 0; + /// Set by cancelAll (on server shutdown): entries inserted after it are cancelled at birth. + std::atomic all_cancelled = false; public: MergeList() : Parent(CurrentMetrics::Merge) @@ -183,13 +189,34 @@ class MergeList final : public BackgroundProcessList + EntryPtr insert(Args &&... args) + { + auto entry = Parent::insert(std::forward(args)...); + if (all_cancelled) + (*entry)->is_cancelled = true; + return entry; + } + void cancelInPartition(const StorageID & table_id, const String & partition_id, Int64 delimiting_block_number) { std::lock_guard lock{mutex}; diff --git a/src/Storages/MergeTree/MergeTask.cpp b/src/Storages/MergeTree/MergeTask.cpp index 9904b970705a..283f662fb163 100644 --- a/src/Storages/MergeTree/MergeTask.cpp +++ b/src/Storages/MergeTree/MergeTask.cpp @@ -61,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -654,6 +655,9 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const ctx->need_remove_expired_values = false; } + global_ctx->merge_list_element_ptr->is_removing_expired_values.store( + ctx->need_remove_expired_values, std::memory_order_relaxed); + const auto & patch_parts = global_ctx->future_part->patch_parts; /// Snapshot of pending mutations for the source parts, fetched once and reused for @@ -1166,7 +1170,7 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const ctx->is_cancelled = [merges_blocker = global_ctx->merges_blocker, ttl_merges_blocker = global_ctx->ttl_merges_blocker, - need_remove = ctx->need_remove_expired_values, + ttl_cancellable = ctx->need_remove_expired_values || isTTLMergeType(global_ctx->future_part->merge_type), merge_list_element = global_ctx->merge_list_element_ptr, partition_id = global_ctx->future_part->part_info.getPartitionId()]() -> bool { @@ -1176,7 +1180,7 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const return true; bool cancelled = merges_blocker->isCancelledForPartition(partition_id) - || (need_remove && ttl_merges_blocker->isCancelled()); + || (ttl_cancellable && ttl_merges_blocker->isCancelled()); if (cancelled) { @@ -1187,6 +1191,15 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const return false; }; + /// Lets the worker threads of long single-block steps (e.g. vector similarity index build) stop on cancellation. + global_ctx->merge_list_element_ptr->thread_group->setQueryCancellationPredicates( + ctx->is_cancelled, + [is_cancelled = ctx->is_cancelled] + { + if (is_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + /// This is the end of preparation. Execution will be per block. return false; } diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp index 7c3bbfcd41bb..0ffe0d6df967 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -97,16 +98,43 @@ MergeTreeBackgroundExecutor::~MergeTreeBackgroundExecutor() wait(); } +template +void MergeTreeBackgroundExecutor::requestShutdown() +{ + LockGuardWithStopWatch lock(mutex, log, __PRETTY_FUNCTION__); + shutdown = true; + has_tasks.notify_all(); +} + template void MergeTreeBackgroundExecutor::wait() { + requestShutdown(); + + /// `threadFunction` breaks before popping once `shutdown` is set, so a task that `routine` + /// re-pushed keeps what it owns alive forever. Draining after `pool->wait()` is what makes it + /// complete: no worker can push to `pending` past that point. Also runs if `wait()` rethrows. + SCOPE_EXIT({ drainPendingTasks(); }); + + pool->wait(); +} + +template +void MergeTreeBackgroundExecutor::drainPendingTasks() +{ + std::vector tasks_to_cancel; { LockGuardWithStopWatch lock(mutex, log, __PRETTY_FUNCTION__); - shutdown = true; - has_tasks.notify_all(); + while (!pending.empty()) + tasks_to_cancel.push_back(pending.pop()); } - pool->wait(); + /// Cancelling and destroying a task can be slow, so do it outside the lock. + for (auto & item : tasks_to_cancel) + { + item->cancel(); + item.reset(); + } } template diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h index 8b93a5d4799e..1a98b4d9dd37 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h @@ -334,6 +334,17 @@ class MergeTreeBackgroundExecutor final : boost::noncopyable bool trySchedule(ExecutableTaskPtr task); void removeTasksCorrespondingToStorage(StorageID id); + + /// Flip the executor into shutdown mode without joining the worker threads: + /// new tasks are rejected by `trySchedule` and pending tasks are not started + /// (worker threads exit at the next step boundary). Used on server shutdown to + /// stop scheduling before the in-flight tasks are cancelled, so that no freshly + /// scheduled task can slip in after the cancellation and block `wait`. + void requestShutdown(); + + /// Implies `requestShutdown`, then joins the worker threads. Running tasks are + /// not interrupted: each finishes its current step. Tasks still waiting in + /// `pending` are cancelled and destroyed. void wait(); /// Update scheduling policy for pending tasks. It does nothing if `new_policy` is the same or unknown. @@ -352,6 +363,10 @@ class MergeTreeBackgroundExecutor final : boost::noncopyable void routine(TaskRuntimeDataPtr item); + /// Cancel and destroy every task still waiting in `pending`. Only complete once no worker can + /// push there any more, i.e. after `pool->wait()` in `wait()`. + void drainPendingTasks(); + /// libc++ does not provide TSA support for std::unique_lock -> TSA_NO_THREAD_SAFETY_ANALYSIS void threadFunction() TSA_NO_THREAD_SAFETY_ANALYSIS; diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index ad11f6d40f0d..2f02b517b8c7 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -4,12 +4,15 @@ #include #include #include +#include #include #include #include #include #include #include +#include +#include #include #include @@ -156,6 +159,7 @@ #include #include #include +#include #include #include #include @@ -10807,6 +10811,11 @@ void MergeTreeData::Transaction::rollback(DataPartsLock * acquired_lock) { if (!isEmpty()) { + /// The rollback of a cancelled merge or mutation must not be interrupted by its own cancellation: + /// otherwise reading the version metadata in `setAndStoreCreationCSN` may throw, and the rolled back part + /// stays without `RolledBackCSN`, which prevents merges of the neighbouring parts until the part is removed. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + for (const auto & part : precommitted_parts) part->version->setAndStoreCreationCSN(Tx::RolledBackCSN); @@ -12337,6 +12346,28 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & moving_part.reserved_space->getDisk()->getPath(), moving_part.part->getBytesOnDisk()); + /// The move runs in its own thread group, so that a stop (`SYSTEM STOP MOVES`, server shutdown, a killed + /// parent query) reaches the writes of the clone and not only the checks between its steps. + auto thread_group = ThreadGroup::createForBackgroundOperation(getContext(), CurrentThread::getGroup()); + installCancellationPredicates( + *thread_group, + (*moves_list_entry)->is_cancelled, + {parts_mover.moves_blocker, getContext()->getMovesList().getShutdownBlocker()}, + "Cancelled moving parts."); + + /// An owned copy, for the hook of `clonePart` (called inside the group) and for the checks made after + /// `clone_in_group` returned, when the group is no longer current. + /// `thread_group` is held because the copy calls the predicates the group inherited. Those can borrow + /// state the group does not own (a merge's list entry), which the enclosing task keeps alive. + const auto throw_if_cancelled = getThrowingCancellationPredicate(*thread_group); + + auto clone_in_group = [&] + { + ThreadGroupSwitcher group_switcher(thread_group, getThreadName(), /*allow_existing_group=*/ true); + checkAttachedTo(thread_group); + return parts_mover.clonePart(moving_part, read_settings, write_settings, throw_if_cancelled); + }; + try { /// If zero-copy replication enabled than replicas shouldn't try to @@ -12381,12 +12412,12 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & if (lock->isLocked()) { - cloned_part = parts_mover.clonePart(moving_part, read_settings, write_settings); + cloned_part = clone_in_group(); /// Cloning part can take a long time. /// Recheck if the lock (and keeper session expirity) is OK if (lock->isLocked()) { - parts_mover.swapClonedPart(cloned_part); + parts_mover.swapClonedPart(cloned_part, throw_if_cancelled); break; /// Successfully moved } else @@ -12414,8 +12445,8 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & } else /// Ordinary move as it should be { - cloned_part = parts_mover.clonePart(moving_part, read_settings, write_settings); - parts_mover.swapClonedPart(cloned_part); + cloned_part = clone_in_group(); + parts_mover.swapClonedPart(cloned_part, throw_if_cancelled); } write_part_log({}); } diff --git a/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp b/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp index 05c0e36766b8..b8b3bd9f1714 100644 --- a/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp +++ b/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -456,6 +457,54 @@ MergeTaskPtr MergeTreeDataMergerMutator::mergePartsToTemporaryPart( metadata_snapshot = future_part->parts.front()->getMetadataSnapshot(); } + /// Root merges only: a projection sub-merge re-enters this under a running merge whose group is already + /// attached, and an attach copies `shared_data` once, so a write here would not reach its threads. + if (!projection_merge_list_element) + { + auto entry_context = (*merge_entry)->thread_group->query_context.lock(); + if (!entry_context) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Merge list entry for part {} has no query context: every caller keeps it alive for the " + "whole merge", + future_part->name); + + /// `optimizeDryRun` runs the task inline under a user query's group, whose cancellation already applies. + if (entry_context->isBackgroundContext()) + { + /// Latched, because a blocker released between two independent polls must not resurrect the read. + auto is_cancelled = [&blocker = merges_blocker, + &ttl_blocker = ttl_merges_blocker, + is_ttl_merge = isTTLMergeType(future_part->merge_type), + merge_entry, + partition_id = future_part->part_info.getPartitionId()] + { + if ((*merge_entry)->is_cancelled.load(std::memory_order_relaxed)) + return true; + + const bool removes_expired_values + = is_ttl_merge || (*merge_entry)->is_removing_expired_values.load(std::memory_order_relaxed); + + if (blocker.isCancelledForPartition(partition_id) || (removes_expired_values && ttl_blocker.isCancelled())) + { + (*merge_entry)->is_cancelled.store(true, std::memory_order_relaxed); + return true; + } + + return false; + }; + + /// Installed before the first attach: `MergeTask::prepare` replaces it only at its end, after its first reads. + (*merge_entry)->thread_group->setQueryCancellationPredicates( + is_cancelled, + [is_cancelled] + { + if (is_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + } + } + return std::make_shared( std::move(future_part), std::move(metadata_snapshot), @@ -503,8 +552,12 @@ MutateTaskPtr MergeTreeDataMergerMutator::mutatePartToTemporaryPart( context->setInteractiveCancelCallback( [&blocker = merges_blocker, merge_entry, partition_id]() { + /// Persisted for the IO layer, which polls rarely and may miss a short-lived blocker. if (blocker.isCancelledForPartition(partition_id) || (*merge_entry)->is_cancelled) + { + (*merge_entry)->is_cancelled.store(true, std::memory_order_relaxed); throw Exception(ErrorCodes::ABORTED, "Cancelled mutating parts"); + } return false; }); diff --git a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp index 7ca361f46477..2c26274f0d8e 100644 --- a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp @@ -24,7 +24,10 @@ #include #include +#include #include +#include +#include #include #include @@ -374,12 +377,9 @@ void updateImpl(const ColumnArray * column_array, const ColumnArray::Offsets & c /// the runner is destroyed first (waits for all tasks) and the lambda is destroyed second. auto add_vector_to_index = [&](USearchIndex::vector_key_t key, size_t row) { - /// Check if the query has been cancelled. USearch internally does not check for cancellation, - /// and a single `add` call can take a very long time under sanitizers. Without this check, KILL QUERY - /// cannot stop the index building. The check is cheap (reads an atomic flag). - if (auto query_context = CurrentThread::tryGetQueryContext()) - if (auto query_status = query_context->getProcessListElementSafe()) - query_status->throwIfKilled(); + /// USearch internally does not check for cancellation, and a single `add` call can take a very long time + /// under sanitizers. Without this check, KILL QUERY or cancelling a merge cannot stop the index building. + CurrentThread::checkIfNotCancelled(); const typename Column::ValueType & value = column_array_data_float_data[column_array_offsets[row - 1]]; @@ -410,14 +410,51 @@ void updateImpl(const ColumnArray * column_array, const ColumnArray::Offsets & c size_t index_size = index->size(); + + /// Stop waiting at the first error (e.g. cancellation) instead of waiting for every queued row: the pool is shared with + /// other index builds, so the rest of our rows may sit behind a lot of their work. The runner's destructor drops them. + std::mutex mutex; + std::condition_variable finished_or_failed; + size_t remaining_rows = rows; + std::exception_ptr first_exception; + std::atomic failed = false; + auto add_row = [&](USearchIndex::vector_key_t key, size_t row) + { + if (failed) + return; + try + { + add_vector_to_index(key, row); + } + catch (...) + { + std::lock_guard lock(mutex); + if (!first_exception) + first_exception = std::current_exception(); + failed = true; + finished_or_failed.notify_all(); + return; + } + std::lock_guard lock(mutex); + if (--remaining_rows == 0) + finished_or_failed.notify_all(); + }; + ThreadPoolCallbackRunnerLocal runner(thread_pool, ThreadName::MERGETREE_VECTOR_SIM_INDEX); - for (size_t row = 0; row < rows; ++row) + /// Enqueueing can block on a full pool queue for a long time, so it must stop on an error too + for (size_t row = 0; row < rows && !failed; ++row) { auto key = static_cast(index_size + row); - /// Passing add_vector_to_index by reference is safe because it outlives the runner - runner.enqueueAndKeepTrack([&add_vector_to_index, key, row] { add_vector_to_index(key, row); }); + /// Passing add_row by reference is safe because it outlives the runner + runner.enqueueAndKeepTrack([&add_row, key, row] { add_row(key, row); }); } + { + std::unique_lock lock(mutex); + finished_or_failed.wait(lock, [&] { return remaining_rows == 0 || first_exception; }); + if (first_exception) + std::rethrow_exception(first_exception); + } runner.waitForAllToFinishAndRethrowFirstError(); } diff --git a/src/Storages/MergeTree/MergeTreePartsMover.cpp b/src/Storages/MergeTree/MergeTreePartsMover.cpp index 7638d6d43cb3..4203ce57819b 100644 --- a/src/Storages/MergeTree/MergeTreePartsMover.cpp +++ b/src/Storages/MergeTree/MergeTreePartsMover.cpp @@ -18,7 +18,6 @@ namespace MergeTreeSetting namespace ErrorCodes { - extern const int ABORTED; extern const int DIRECTORY_ALREADY_EXISTS; } @@ -220,13 +219,13 @@ bool MergeTreePartsMover::selectPartsForMove( return false; } -MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const MergeTreeMoveEntry & moving_part, const ReadSettings & read_settings, const WriteSettings & write_settings) const +MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart( + const MergeTreeMoveEntry & moving_part, + const ReadSettings & read_settings, + const WriteSettings & write_settings, + const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const { - auto cancellation_hook = [&my_moves_blocker = moves_blocker]() - { - if (my_moves_blocker.isCancelled()) - throw Exception(ErrorCodes::ABORTED, "Cancelled moving parts."); - }; + auto cancellation_hook = [throw_if_cancelled]() { throw_if_cancelled(); }; cancellation_hook(); auto settings = data->getSettings(); @@ -238,6 +237,10 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me MutableDataPartStoragePtr cloned_part_storage; bool preserve_blobs = false; + + /// From the moment the clone exists until the part object owns it (`is_temp` and the removal policy), + /// a stop must not fail a request and leave a directory that nothing removes. + std::optional ownership_handoff_blocker; if (disk->supportZeroCopyReplication() && (*settings)[MergeTreeSetting::allow_remote_fs_zero_copy_replication]) { /// Try zero-copy replication and fallback to default copy if it's not possible @@ -264,6 +267,7 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me if (zero_copy_part) { + ownership_handoff_blocker.emplace(); /// FIXME for some reason we cannot just use this part, we have to re-create it through MergeTreeDataPartBuilder preserve_blobs = true; zero_copy_part->is_temp = false; /// Do not remove it in dtor @@ -274,11 +278,13 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me LOG_INFO(log, "Part {} was not fetched, we are the first who move it to another disk, so we will copy it", part->name); cloned_part_storage = part->getDataPartStorage().clonePart( path_to_clone, part->getDataPartStorage().getPartDirectory(), disk, read_settings, write_settings, log, cancellation_hook); + ownership_handoff_blocker.emplace(); } } else { cloned_part_storage = part->makeCloneOnDisk(disk, MergeTreeData::MOVING_DIR_NAME, read_settings, write_settings, cancellation_hook); + ownership_handoff_blocker.emplace(); } MergeTreeDataPartBuilder builder(*data, part->name, cloned_part_storage, getReadSettings(), PartDirIntent::OpenExisting); @@ -296,6 +302,7 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me else cloned_part.part->remove_tmp_policy = IMergeTreeDataPart::BlobsRemovalPolicyForTemporaryParts::REMOVE_BLOBS; } + ownership_handoff_blocker.reset(); cloned_part.part->loadColumnsChecksumsIndexes(true, true); cloned_part.part->version->loadAndUpdateMetadata(); cloned_part.part->modification_time = cloned_part.part->getDataPartStorage().getLastModified().epochTime(); @@ -325,12 +332,11 @@ catch (...) throw; } -void MergeTreePartsMover::swapClonedPart(TemporaryClonedPart & cloned_part) const +void MergeTreePartsMover::swapClonedPart(TemporaryClonedPart & cloned_part, const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const { /// Used to get some stuck parts in the moving directory by stopping moves while pause is active FailPointInjection::pauseFailPoint(FailPoints::stop_moving_part_before_swap_with_active); - if (moves_blocker.isCancelled()) - throw Exception(ErrorCodes::ABORTED, "Cancelled moving parts."); + throw_if_cancelled(); /// `getActiveContainingPart` and `swapActivePart` are called under the same lock /// to prevent part becoming inactive between calls diff --git a/src/Storages/MergeTree/MergeTreePartsMover.h b/src/Storages/MergeTree/MergeTreePartsMover.h index 7a6583008c0d..5dd6c56a71a4 100644 --- a/src/Storages/MergeTree/MergeTreePartsMover.h +++ b/src/Storages/MergeTree/MergeTreePartsMover.h @@ -8,6 +8,7 @@ #include #include #include +#include namespace DB { @@ -66,14 +67,20 @@ class MergeTreePartsMover const std::lock_guard & moving_parts_lock); /// Copies part to selected reservation in detached folder. Throws exception if part already exists. - TemporaryClonedPart clonePart(const MergeTreeMoveEntry & moving_part, const ReadSettings & read_settings, const WriteSettings & write_settings) const; + /// `throw_if_cancelled` is called between the steps of the copy; it throws when the move must stop. + TemporaryClonedPart clonePart( + const MergeTreeMoveEntry & moving_part, + const ReadSettings & read_settings, + const WriteSettings & write_settings, + const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const; /// Replaces cloned part from detached directory into active data parts set. /// Replacing part changes state to DeleteOnDestroy and will be removed from disk after destructor of /// IMergeTreeDataPart called. If replacing part doesn't exists or not active (committed) than /// cloned part will be removed and log message will be reported. It may happen in case of concurrent /// merge or mutation. - void swapClonedPart(TemporaryClonedPart & cloned_part) const; + /// `throw_if_cancelled` is called once before the part is locked and renamed. + void swapClonedPart(TemporaryClonedPart & cloned_part, const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const; /// Rename cloned part from `moving/` directory to the actual part storage void renameClonedPart(IMergeTreeDataPart & part) const; diff --git a/src/Storages/MergeTree/MergeTreeSequentialSource.cpp b/src/Storages/MergeTree/MergeTreeSequentialSource.cpp index 232c4fac0b1f..e1f0fa05c687 100644 --- a/src/Storages/MergeTree/MergeTreeSequentialSource.cpp +++ b/src/Storages/MergeTree/MergeTreeSequentialSource.cpp @@ -22,7 +22,9 @@ #include #include #include +#include #include +#include namespace DB { @@ -32,6 +34,11 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace FailPoints +{ + extern const char merge_tree_sequential_source_sleep_before_read[]; +} + namespace Setting { extern const SettingsNonZeroUInt64 merge_tree_min_read_task_size; @@ -239,6 +246,10 @@ try if (isCancelled()) return {}; + /// Used in tests to emulate a merge whose single reading step is very slow + /// (e.g. applying huge patch parts), to check that shutdown does not wait for it. + fiu_do_on(FailPoints::merge_tree_sequential_source_sleep_before_read, { sleepForSeconds(10); }); + auto read_result = readers_chain.read(current_rows_to_read, mark_ranges, patch_ranges); if (!read_result.num_rows) return {}; diff --git a/src/Storages/MergeTree/MovesList.cpp b/src/Storages/MergeTree/MovesList.cpp index 730cd44a6979..4a1cf0e0fe4b 100644 --- a/src/Storages/MergeTree/MovesList.cpp +++ b/src/Storages/MergeTree/MovesList.cpp @@ -20,6 +20,11 @@ MovesListElement::MovesListElement( { } +void MovesList::cancelAll() +{ + shutdown_blocker.cancelForever(); +} + MoveInfo MovesListElement::getInfo() const { MoveInfo res; diff --git a/src/Storages/MergeTree/MovesList.h b/src/Storages/MergeTree/MovesList.h index fc1e7ffaadc0..11e910b23a26 100644 --- a/src/Storages/MergeTree/MovesList.h +++ b/src/Storages/MergeTree/MovesList.h @@ -1,9 +1,12 @@ #pragma once #include #include +#include #include #include #include +#include +#include #include namespace CurrentMetrics @@ -38,6 +41,10 @@ struct MovesListElement : private boost::noncopyable Stopwatch watch; const UInt64 thread_id; + /// Latch of the cancellation predicates of the move's thread group. Shared, because copies of the predicates + /// outlive the entry's scope. + std::shared_ptr is_cancelled = std::make_shared(false); + MovesListElement( const StorageID & table_id_, const std::string & part_name_, @@ -59,6 +66,17 @@ class MovesList final : public BackgroundProcessList MovesList() : Parent(CurrentMetrics::Move) {} + + /// Cancel all current and future moves. Used on server shutdown. + /// A move sees it through the predicates it installs on its thread group. + void cancelAll(); + + /// Every entry's predicate holds a copy. The blocker stays cancelled for good, so a move that registers after + /// `cancelAll` is stopped too. A copy shares the counter with the list, also if taken before `cancelAll`. + ActionBlocker getShutdownBlocker() const { return shutdown_blocker; } + +private: + ActionBlocker shutdown_blocker; }; } diff --git a/src/Storages/MergeTree/MutateTask.cpp b/src/Storages/MergeTree/MutateTask.cpp index 42653cba1036..819ea2cb2bd5 100644 --- a/src/Storages/MergeTree/MutateTask.cpp +++ b/src/Storages/MergeTree/MutateTask.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -3660,6 +3661,32 @@ MutateTask::MutateTask( ctx->storage_columns = metadata_snapshot_->getColumns().getAllPhysical(); ctx->txn = txn; ctx->source_part = ctx->future_part->parts[0]; + + /// Lets the worker threads of long single-block steps (e.g. vector similarity index build) stop on cancellation. + /// Same condition as `checkOperationIsNotCanceled`. + auto mutation_cancelled = [merges_blocker = ctx->merges_blocker, + partition_id = ctx->future_part->part_info.getPartitionId(), + mutate_entry = ctx->mutate_entry] + { + /// Latched, so that a blocker released between two polls does not resurrect a cancelled read. + if ((*mutate_entry)->is_cancelled.load(std::memory_order_relaxed)) + return true; + + if (merges_blocker->isCancelledForPartition(partition_id)) + { + (*mutate_entry)->is_cancelled.store(true, std::memory_order_relaxed); + return true; + } + + return false; + }; + (*ctx->mutate_entry)->thread_group->setQueryCancellationPredicates( + mutation_cancelled, + [mutation_cancelled] + { + if (mutation_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled mutating parts"); + }); } diff --git a/src/Storages/MergeTree/ReplicatedFetchList.h b/src/Storages/MergeTree/ReplicatedFetchList.h index 321b11e082c7..a0416efff0b0 100644 --- a/src/Storages/MergeTree/ReplicatedFetchList.h +++ b/src/Storages/MergeTree/ReplicatedFetchList.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include @@ -69,6 +71,13 @@ struct ReplicatedFetchListElement : private boost::noncopyable const UInt64 thread_id; + /// Set on server shutdown, or when a poll of the cancellation predicates sees the fetcher's blocker cancelled. + /// Checked in `ReplicatedFetchReadCallback` on every buffer refill of the part download, which aborts with + /// the `ABORTED` exception. + /// Shared, unlike `MergeListElement::is_cancelled`: the cancellation predicates of the fetch's thread group + /// outlive the entry's scope on other threads. + std::shared_ptr is_cancelled = std::make_shared(false); + ReplicatedFetchListElement( const std::string & database_, const std::string & table_, const std::string & partition_id_, const std::string & result_part_name_, @@ -86,11 +95,44 @@ class ReplicatedFetchList final : public BackgroundProcessList; + /// Set by cancelAll (on server shutdown): entries inserted after it are cancelled at birth. + std::atomic all_cancelled = false; public: ReplicatedFetchList () : Parent(CurrentMetrics::ReplicatedFetch) {} + + /// Whether `cancelAll` has been called (the server is shutting down). + /// Checked in `fetchSelectedPart` while reading the part header, before the fetch + /// is registered in the list and gets its own per-entry `is_cancelled` flag. + bool isAllCancelled() const { return all_cancelled; } + + /// Cancel all current and future fetches. + /// Used on server shutdown, when their results would be discarded anyway. + void cancelAll() + { + /// See the comment in `MergeList::cancelAll` about the ordering with `insert`. + all_cancelled = true; + cancelCurrent(); + } + + /// Cancel all current fetches. + void cancelCurrent() + { + std::lock_guard lock{mutex}; + for (auto & fetch_element : entries) + fetch_element.is_cancelled->store(true); + } + + template + EntryPtr insert(Args &&... args) + { + auto entry = Parent::insert(std::forward(args)...); + if (all_cancelled) + (*entry)->is_cancelled->store(true); + return entry; + } }; } diff --git a/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp b/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp new file mode 100644 index 000000000000..32cae7a20a18 --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp @@ -0,0 +1,278 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB +{ + +namespace ErrorCodes +{ + extern const int ABORTED; + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; +} + +namespace +{ + +/// Runs `body` on a thread with its own `ThreadStatus`, as the groups read it on creation. +template +void runOnThread(F && body) +{ + std::thread t([&] + { + ThreadStatus ts; + body(getContext().context); + }); + t.join(); +} + +int errorCodeOf(const std::function & f) +{ + try + { + f(); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; +} + +} + +TEST(BackgroundOperationCancellation, ParentThrowingPredicateFiresFirst) +{ + runOnThread([](ContextPtr context) + { + auto parent = ThreadGroup::createWithoutQueryContext(context); + parent->setQueryCancellationPredicates( + [] { return false; }, + [] { throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "parent"); }); + + auto child = ThreadGroup::createForBackgroundOperation(context, parent); + auto stopped = std::make_shared(true); + installCancellationPredicates(*child, stopped, {}, "child"); + + /// Both are stopped; the parent's message must win. + try + { + getThrowingCancellationPredicate(*child)(); + FAIL() << "expected an exception"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_NE(e.message().find("parent"), std::string::npos); + } + }); +} + +TEST(BackgroundOperationCancellation, BooleanFormInheritsAndPolls) +{ + runOnThread([](ContextPtr context) + { + auto parent_stopped = std::make_shared(false); + auto parent = ThreadGroup::createWithoutQueryContext(context); + parent->setQueryCancellationPredicates([parent_stopped] { return parent_stopped->load(); }, [] {}); + + auto child = ThreadGroup::createForBackgroundOperation(context, parent); + auto stopped = std::make_shared(false); + installCancellationPredicates(*child, stopped, {}, "stopped"); + + auto is_canceled = child->getSharedData().query_is_canceled_predicate; + EXPECT_FALSE(is_canceled()); + parent_stopped->store(true); + EXPECT_TRUE(is_canceled()); + parent_stopped->store(false); + stopped->store(true); + EXPECT_TRUE(is_canceled()); + }); +} + +TEST(BackgroundOperationCancellation, ThrowingFormSeesBlockerWithoutBooleanForm) +{ + runOnThread([](ContextPtr context) + { + ActionBlocker blocker; + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, std::make_shared(false), {blocker}, "stopped by blocker"); + + auto throwing = getThrowingCancellationPredicate(*group); + EXPECT_EQ(errorCodeOf(throwing), 0); + + blocker.cancelForever(); + EXPECT_EQ(errorCodeOf(throwing), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, BlockerSeenCancelledLatches) +{ + runOnThread([](ContextPtr context) + { + ActionBlocker blocker; + auto stopped = std::make_shared(false); + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, stopped, {blocker}, "stopped"); + + std::optional lock = blocker.cancel(); + auto is_canceled = group->getSharedData().query_is_canceled_predicate; + EXPECT_TRUE(is_canceled()); + EXPECT_TRUE(stopped->load()); + + lock.reset(); + EXPECT_FALSE(blocker.isCancelled()); + EXPECT_TRUE(is_canceled()); + EXPECT_EQ(errorCodeOf(getThrowingCancellationPredicate(*group)), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, PredicateOutlivesItsListEntry) +{ + runOnThread([](ContextPtr context) + { + ThrowIfQueryCanceledPredicate throwing; + QueryIsCanceledPredicate is_canceled; + { + MovesList list; + auto entry = std::make_unique(StorageID("db", "t"), "part", "disk", "/path", 1); + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, entry->is_cancelled, {list.getShutdownBlocker()}, "stopped"); + throwing = getThrowingCancellationPredicate(*group); + is_canceled = group->getSharedData().query_is_canceled_predicate; + entry->is_cancelled->store(true); + } + /// The entry, its group and the list are gone. + EXPECT_TRUE(is_canceled()); + EXPECT_EQ(errorCodeOf(throwing), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, ExceptionUnderSwitcherLeavesOriginalGroup) +{ + runOnThread([](ContextPtr context) + { + auto original = std::make_shared(context, 0); + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(original); + auto * original_status = current_thread; + + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, std::make_shared(true), {}, "stopped"); + + try + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + checkAttachedTo(group); + EXPECT_EQ(CurrentThread::getGroup(), group); + throw Exception(ErrorCodes::ABORTED, "from under the switcher"); + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::ABORTED); + } + + EXPECT_EQ(current_thread, original_status); + EXPECT_EQ(CurrentThread::getGroup(), original); + EXPECT_EQ(getThreadName(), ThreadName::TCP_HANDLER); + CurrentThread::detachFromGroupIfNotDetached(); + }); +} + +TEST(BackgroundOperationCancellation, CheckAttachedToThrowsWhenAttachFailed) +{ + runOnThread([](ContextPtr context) + { + auto original = std::make_shared(context, 0); + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(original); + + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + + FailPointInjection::enableFailPoint(FailPoints::thread_group_switcher_post_attach_failure); + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + EXPECT_EQ(errorCodeOf([&] { checkAttachedTo(group); }), ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_EQ(CurrentThread::getGroup(), original); + } + FailPointInjection::disableFailPoint(FailPoints::thread_group_switcher_post_attach_failure); + + EXPECT_EQ(CurrentThread::getGroup(), original); + CurrentThread::detachFromGroupIfNotDetached(); + }); +} + +TEST(BackgroundOperationCancellation, ChildOfContextlessRootHasNoQueryContext) +{ + runOnThread([](ContextPtr context) + { + auto root = ThreadGroup::createWithoutQueryContext(context); + auto child = ThreadGroup::createForBackgroundOperation(context, root); + EXPECT_FALSE(root->with_query_context); + EXPECT_FALSE(child->with_query_context); + }); +} + +/// A group nobody installed predicates on is a call site that forgot to; `LOGICAL_ERROR` aborts in debug and +/// sanitizer builds. +#ifndef DEBUG_OR_SANITIZER_BUILD +TEST(BackgroundOperationCancellation, ThrowingPredicateWithoutInstallThrowsLogicalError) +{ + runOnThread([](ContextPtr context) + { + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + EXPECT_EQ(errorCodeOf([&] { getThrowingCancellationPredicate(*group); }), ErrorCodes::LOGICAL_ERROR); + }); +} +#else +TEST(BackgroundOperationCancellationDeathTest, ThrowingPredicateWithoutInstallAborts) +{ + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + EXPECT_DEATH( + { + runOnThread([](ContextPtr context) + { + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + getThrowingCancellationPredicate(*group); + }); + }, + "No cancellation predicate installed"); +} +#endif + +TEST(BackgroundOperationCancellation, MovesListCancelAllCoversEarlierAndLaterBlockers) +{ + MovesList list; + auto before = list.getShutdownBlocker(); + EXPECT_FALSE(before.isCancelled()); + + list.cancelAll(); + + auto after = list.getShutdownBlocker(); + EXPECT_TRUE(before.isCancelled()); + EXPECT_TRUE(after.isCancelled()); +} + +} diff --git a/src/Storages/MergeTree/tests/gtest_executor.cpp b/src/Storages/MergeTree/tests/gtest_executor.cpp index 5bc591f8a78a..20288f611a65 100644 --- a/src/Storages/MergeTree/tests/gtest_executor.cpp +++ b/src/Storages/MergeTree/tests/gtest_executor.cpp @@ -6,6 +6,8 @@ #include #include +#include +#include #include #include #include @@ -390,3 +392,94 @@ TEST(Executor, SlowTaskDestructionBlocksRemoveTasks) executor->wait(); } + + +/// Task that always asks for another step, so `routine` keeps re-pushing it to the pending queue. +/// It records whether it was cancelled; a real merge task releases most of its resources in +/// `cancel` and keeps its `TableLockHolder` alive for as long as the task object exists. +class NeverFinishingTask : public IExecutableTask +{ +public: + NeverFinishingTask(const String & name_, std::latch & step_executed_, std::atomic & cancelled_) + : name(name_) + , step_executed(step_executed_) + , cancelled(cancelled_) + {} + + bool executeStep() override + { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + if (!step_reported.exchange(true)) + step_executed.count_down(); + return true; + } + + void cancel() noexcept override { cancelled = true; } + StorageID getStorageID() const override { return {"test", name}; } + void onCompleted() override {} + Priority getPriority() const override { return {}; } + String getQueryId() const override { return "test::never_finishing"; } + +private: + String name; + std::latch & step_executed; + std::atomic & cancelled; + std::atomic step_reported{false}; +}; + + +/// A multi-step task waiting in the pending queue must not survive `wait()`. +/// +/// `threadFunction` breaks out of its loop before popping once `shutdown` is set, so a task that +/// `routine` re-pushed for another step is neither resumed nor cancelled. A real merge task holds +/// a `TableLockHolder` (a table share lock) for its whole lifetime, so such an abandoned task +/// blocks every later exclusive lock on its table until the acquisition times out. That is how a +/// `RENAME` rotating an obsolete `system.session_log` during shutdown ends in `DEADLOCK_AVOIDED` +/// once that timeout expires. +TEST(Executor, ShutdownReleasesPendingTasks) +{ + /// More than one task, so that draining a single one is not enough to pass. + static constexpr size_t tasks_count = 3; + + /// Declared before the executor so they outlive it (its destructor calls `wait`). + std::latch step_executed(tasks_count); + std::array, tasks_count> cancelled{}; + std::array, tasks_count> weak_tasks; + + auto executor = std::make_shared> + ( + ThreadName::TEST_SCHEDULER, + 1, // threads + 10, // max_tasks + CurrentMetrics::BackgroundMergesAndMutationsPoolTask, + CurrentMetrics::BackgroundMergesAndMutationsPoolSize, + ProfileEvents::CommonBackgroundExecutorTaskExecuteStepMicroseconds, + ProfileEvents::CommonBackgroundExecutorTaskCancelMicroseconds, + ProfileEvents::CommonBackgroundExecutorTaskResetMicroseconds, + ProfileEvents::CommonBackgroundExecutorWaitMicroseconds + ); + + for (size_t i = 0; i < tasks_count; ++i) + { + auto task = std::make_shared( + "pending_storage_" + std::to_string(i), step_executed, cancelled[i]); + weak_tasks[i] = task; + ASSERT_TRUE(executor->trySchedule(std::move(task))); + } + + /// Wait until every task has run a step, so each is known to be cycling through the pending + /// queue rather than never having been picked up. The single worker pops them in turn, and + /// `routine` re-pushes each one, so all of them are queued again by the time `wait()` runs. + step_executed.wait(); + + executor->wait(); + + for (size_t i = 0; i < tasks_count; ++i) + { + EXPECT_TRUE(weak_tasks[i].expired()) + << "task " << i << " was left in the pending queue and outlived executor shutdown, so " + "the resources it owns (for a merge task, a table share lock) were never released"; + EXPECT_TRUE(cancelled[i].load()) + << "task " << i << " was left in the pending queue and not cancelled on executor shutdown"; + } +} diff --git a/tests/integration/helpers/cas_paced_body.py b/tests/integration/helpers/cas_paced_body.py new file mode 100644 index 000000000000..e1962a0be0cc --- /dev/null +++ b/tests/integration/helpers/cas_paced_body.py @@ -0,0 +1,147 @@ +"""Controller side of the paced-body mode of `s3_fault_proxy.py`. + +The proxy reads one selected upload body at a fixed rate and traces it (`paced_trace` in `/stats`). A request is +described by a record: `request_id`, `method`, `key`, `upload_id`, `part_number`, `content_length`, +`rate_bytes_per_s`, `received`, `outcome` (None while the body is still being read, else `complete`, `peer_eof`, +`peer_reset`, `timeout` or `proxy_error`), `t_unpaced_mono_ms`, `t_began_mono_ms` and `t_ended_mono_ms` on the proxy's +clock, and `forwarded` (True once the proxy sent the complete body on to the object store; a short body never is). + +`peer_eof` is a close by the sender, and a client-side request timeout looks the same: a caller keeps its client +timeouts far above the paced time and runs a no-signal control for every paced path. + +Cutting a paced request, the pattern of a case: `wait_body_gate`, then the signal (and the statement that sets the stop +flag returns), then `release_pace`, then `wait_cut`. The bytes the sender had already queued in the kernel arrive before +its close is seen, and at the paced rate that can take longer than the deadline; `release_pace` drains them at full +speed, so a sender that stopped ends the request short (`peer_eof`, `peer_reset`) and one that did not finishes the body +(`complete`). +""" + +import json +import time +import urllib.request + +DEFAULT_RATE_BYTES_PER_S = 256 * 1024 +CUT_OUTCOMES = ("peer_eof", "peer_reset") + + +def control_call(control_url, path, patch=None): + """A JSON `GET` (no `patch`) or `POST` to the control port of the proxy; returns the decoded reply.""" + data = None if patch is None else json.dumps(patch).encode() + request = urllib.request.Request( + control_url + path, data=data, headers={"Content-Type": "application/json"}, + method="GET" if data is None else "POST") + with urllib.request.urlopen(request, timeout=10) as response: + return json.loads(response.read().decode()) + + +def arm_paced_body(control_url, prefix, min_content_length, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S): + """Arms the proxy to pace the first `PutObject` or `UploadPart` whose path starts with `prefix` and whose + `Content-Length` is at least `min_content_length` (above 0). The mode disarms itself when it claims a request. + Returns the request id the claimed request will carry; `wait_body_gate` waits for that one.""" + assert min_content_length > 0, "a paced body needs a size lower bound, or any small PUT would be claimed" + reply = control_call(control_url, "/config", {"paced_body": { + "prefix": prefix, "min_content_length": min_content_length, "rate_bytes_per_s": rate_bytes_per_s}}) + return reply["config"]["paced_body"]["request_id"] + + +def now_mono_ms(control_url): + """The proxy's monotonic clock, the clock of every `t_*_mono_ms` field.""" + return control_call(control_url, "/stats")["now_mono_ms"] + + +def release_pace(control_url, record): + """Makes the proxy read the rest of the claimed request at full speed.""" + control_call(control_url, "/config", {"unpace": {"request_id": record["request_id"]}}) + + +def paced_requests(control_url): + """The records of every claimed request, oldest first.""" + records = {} + for event in control_call(control_url, "/stats")["paced_trace"]: + record = records.setdefault(event["request_id"], {"received": 0, "outcome": None, "t_ended_mono_ms": None, "forwarded": False}) + if event["event"] == "began": + record.update( + request_id=event["request_id"], method=event["method"], key=event["key"], + upload_id=event["upload_id"], part_number=event["part_number"], + content_length=event["content_length"], rate_bytes_per_s=event["rate_bytes_per_s"], + t_began_mono_ms=event["t_mono_ms"]) + elif event["event"] == "forwarded": + record["forwarded"] = True + else: + record["received"] = event["bytes_read"] + if event["event"] == "unpaced": + record["t_unpaced_mono_ms"] = event["t_mono_ms"] + record["received_at_unpace"] = event["bytes_read"] + if event["event"] == "ended": + record["outcome"] = event["outcome"] + record["t_ended_mono_ms"] = event["t_mono_ms"] + return list(records.values()) + + +def _record(control_url, request_id): + return next((r for r in paced_requests(control_url) if r["request_id"] == request_id), None) + + +def record_of(control_url, record): + """The current record of the request that `record` describes. Fails when the proxy has no such record.""" + current = _record(control_url, record["request_id"]) + assert current is not None, "the proxy has no record of request {}".format(record["request_id"]) + return current + + +def wait_body_gate(control_url, request_id, min_received=256 << 10, min_left_s=5, timeout_s=60): + """Waits for the claimed request `request_id` (from `arm_paced_body`) to have received `min_received` bytes while + at least `min_left_s` seconds of body are left at its rate: the body must outlast the signal that follows. Returns + its record. Fails when the request ended or the time left is already too short.""" + end = time.monotonic() + timeout_s + last = None + while time.monotonic() < end: + last = _record(control_url, request_id) + if last is not None and "content_length" in last: + assert last["outcome"] is None, "the paced request ended before the gate: {}".format(last) + if last["received"] >= min_received: + left_s = (last["content_length"] - last["received"]) / last["rate_bytes_per_s"] + assert left_s >= min_left_s, "only {:.0f} s of body left at the gate: {}".format(left_s, last) + return last + time.sleep(0.2) + raise AssertionError("request {} did not reach {} bytes within {} s: {}".format(request_id, min_received, timeout_s, last)) + + +def _wait_ended(control_url, record, timeout_s): + end = time.monotonic() + timeout_s + current = record + while time.monotonic() < end: + current = _record(control_url, record["request_id"]) + if current is not None and current["outcome"] is not None: + return current + time.sleep(0.2) + return None + + +def wait_cut(control_url, record, deadline_s, not_before_mono_ms=None, signal_mono_ms=None): + """Asserts that the proxy saw the sender close the request early within `deadline_s` seconds from now: outcome + `peer_eof` or `peer_reset` with fewer bytes than `Content-Length`, ended at or after `not_before_mono_ms` (the + proxy's clock, read just before the signal) when given. A `timeout`, a `proxy_error` and a `complete` body fail. + With `signal_mono_ms` (the proxy's clock, read before the signal statement was issued) the end must also be within + `deadline_s` seconds of it, so a statement that itself takes long to cut cannot pass.""" + ended = _wait_ended(control_url, record, deadline_s) + assert ended is not None, "the body was not cut within {} s: {}".format( + deadline_s, _record(control_url, record["request_id"])) + assert ended["outcome"] in CUT_OUTCOMES, "the body ended as {}, not cut: {}".format(ended["outcome"], ended) + assert ended["received"] < ended["content_length"], "the cut body was complete: {}".format(ended) + assert not_before_mono_ms is None or ended["t_ended_mono_ms"] >= not_before_mono_ms, \ + "the body ended before the signal: {}".format(ended) + assert signal_mono_ms is None or ended["t_ended_mono_ms"] - signal_mono_ms <= deadline_s * 1000, \ + "the body ended {:.1f} s after the signal statement was issued, over {} s: {}".format( + (ended["t_ended_mono_ms"] - signal_mono_ms) / 1000.0, deadline_s, ended) + return ended + + +def wait_complete(control_url, record, timeout_s): + """Asserts that the whole body arrived within `timeout_s` seconds from now. Returns its final record.""" + ended = _wait_ended(control_url, record, timeout_s) + assert ended is not None, "the body did not end within {} s: {}".format( + timeout_s, _record(control_url, record["request_id"])) + assert ended["outcome"] == "complete", "the body ended as {}, not complete: {}".format(ended["outcome"], ended) + assert ended["received"] == ended["content_length"], ended + return ended diff --git a/tests/integration/helpers/s3_mocks/broken_s3.py b/tests/integration/helpers/s3_mocks/broken_s3.py index a3fd6ab5852d..114113f8ddc1 100644 --- a/tests/integration/helpers/s3_mocks/broken_s3.py +++ b/tests/integration/helpers/s3_mocks/broken_s3.py @@ -1,4 +1,5 @@ import http.server +import json import random import socket import socketserver @@ -70,9 +71,60 @@ def setup_at_part_upload(self, **kwargs): def setup_at_listing(self, **kwargs): self.setup_action("at_listing", **kwargs) + def setup_at_object_get(self, **kwargs): + self.setup_action("at_object_get", **kwargs) + def setup_at_create_multi_part_upload(self, **kwargs): self.setup_action("at_create_multi_part_upload", **kwargs) + def setup_key_rule( + self, name, prefix, target="put", contains=None, excludes=None, **kwargs + ): + """Fault the requests of kind `target` whose path starts with `prefix`, independently of + the other rules. `target` is one of: put (object and part uploads), object, part, delete, + delete_objects. `contains` and `excludes` narrow the path by a substring. `kwargs` are + those of `setup_action`: count, after, action, action_args.""" + url = ( + f"http://localhost:{self._port}/mock_settings/key_rule" + f"?name={urllib.parse.quote(name)}" + f"&prefix={urllib.parse.quote(prefix)}&target={target}" + ) + if contains is not None: + url += f"&contains={urllib.parse.quote(contains)}" + if excludes is not None: + url += f"&excludes={urllib.parse.quote(excludes)}" + for key in ("count", "after", "action"): + if kwargs.get(key) is not None: + url += f"&{key}={kwargs[key]}" + for arg in kwargs.get("action_args") or []: + url += f"&action_args={arg}" + self._apply(url) + + def remove_key_rule(self, name): + """Stops the rule from faulting; its counters stay readable until `reset`.""" + self._apply( + f"http://localhost:{self._port}/mock_settings/key_rule_remove" + f"?name={urllib.parse.quote(name)}" + ) + + def key_rule_stats(self, name): + """Returns {"seen", "hits", "max_hits_per_url", "retried_urls"}: the requests that matched + the rule, those it faulted, the largest number of faults answered to one URL, and the + number of URLs faulted at least twice (a retry shows as >= 2).""" + response = self._cluster.exec_in_container( + self._cluster.get_container_id(self._container), + [ + "curl", + "-s", + "--max-time", + "5", + f"http://localhost:{self._port}/mock_settings/key_rule_stats" + f"?name={urllib.parse.quote(name)}", + ], + nothrow=True, + ) + return json.loads(response) + def setup_fake_puts(self, part_length): self._apply( f"http://localhost:{self._port}/mock_settings/fake_puts?when_length_bigger={part_length}" @@ -260,6 +312,9 @@ def inject_error(self, request_handler): request_handler.write_error(404, data) class SlowDownAction: + def __init__(self, http_code="429"): + self.http_code = int(http_code) + def inject_error(self, request_handler): data = ( '' @@ -269,7 +324,7 @@ def inject_error(self, request_handler): "txfbd566d03042474888193-00608d7537" "" ) - request_handler.write_error(429, data) + request_handler.write_error(self.http_code, data) # make sure that Alibaba errors (QpsLimitExceeded, TotalQpsLimitExceededAction) are retriable # we patched contrib/aws to achive it: https://github.com/ClickHouse/aws-sdk-cpp/pull/22 https://github.com/ClickHouse/aws-sdk-cpp/pull/23 @@ -458,8 +513,60 @@ def has_effect(self): def inject_error(self, request_handler): self.error_handler.inject_error(request_handler) + class KeyRule: + def __init__(self, lock, prefix, target, counter, contains=None, excludes=None): + self.lock = lock + self.prefix = prefix + self.contains = contains + self.excludes = excludes + self.target = target + self.counter = counter + self.active = True + self.seen = 0 + self.hits = 0 + self.hits_per_url = dict() + + def matches(self, kind, path): + if not path.startswith(self.prefix): + return False + if self.contains is not None and self.contains not in path: + return False + if self.excludes is not None and self.excludes in path: + return False + if self.target == "put": + return kind in ("object", "part") + return kind == self.target + + def try_inject(self, request_handler, kind, url): + with self.lock: + if not self.active or not self.matches( + kind, urllib.parse.urlsplit(url).path + ): + return False + self.seen += 1 + if not self.counter.has_effect(): + return False + with self.lock: + self.hits += 1 + self.hits_per_url[url] = self.hits_per_url.get(url, 0) + 1 + request_handler.log_message("key rule %s hit %s", self.target, url) + self.counter.inject_error(request_handler) + return True + + def stats(self): + with self.lock: + return { + "seen": self.seen, + "hits": self.hits, + "max_hits_per_url": max(self.hits_per_url.values(), default=0), + "retried_urls": sum( + 1 for count in self.hits_per_url.values() if count >= 2 + ), + } + def __init__(self): self.lock = threading.Lock() + self.key_rules = dict() self.at_part_upload = None self.at_object_upload = None self.fake_put_when_length_bigger = None @@ -468,6 +575,8 @@ def __init__(self): self.slow_get = None self.fake_multipart_upload = None self.at_create_multi_part_upload = None + self.at_listing = None + self.at_object_get = None def register_fake_upload(self, upload_id, key): with self.lock: @@ -479,8 +588,14 @@ def is_fake_upload(self, upload_id, key): return self.fake_uploads[upload_id] == key return False + def inject_by_key_rules(self, request_handler, kind, url): + with self.lock: + rules = list(self.key_rules.values()) + return any(rule.try_inject(request_handler, kind, url) for rule in rules) + def reset(self): with self.lock: + self.key_rules = dict() self.at_part_upload = None self.at_object_upload = None self.fake_put_when_length_bigger = None @@ -490,6 +605,7 @@ def reset(self): self.fake_multipart_upload = None self.at_create_multi_part_upload = None self.at_listing = None + self.at_object_get = None _runtime = _ServerRuntime() @@ -685,6 +801,58 @@ def _mock_settings(self): self.log_message("set at_listing %s", _runtime.at_listing) return self._ok() + if path[1] == "at_object_get": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + _runtime.at_object_get = _ServerRuntime.CountAfter.from_cgi_params( + _runtime.lock, params + ) + self.log_message("set at_object_get %s", _runtime.at_object_get) + return self._ok() + + if path[1] == "key_rule": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + rule = _ServerRuntime.KeyRule( + _runtime.lock, + params["prefix"][0], + params.get("target", ["put"])[0], + _ServerRuntime.CountAfter.from_cgi_params(_runtime.lock, params), + params.get("contains", [None])[0], + params.get("excludes", [None])[0], + ) + with _runtime.lock: + _runtime.key_rules[params["name"][0]] = rule + self.log_message( + "set key_rule %s %s %s", params["name"][0], rule.target, rule.prefix + ) + return self._ok() + + if path[1] == "key_rule_remove": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + with _runtime.lock: + rule = _runtime.key_rules.get(params["name"][0]) + if rule is not None: + with rule.lock: + rule.active = False + self.log_message("remove key_rule %s", params["name"][0]) + return self._ok() + + if path[1] == "key_rule_stats": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + with _runtime.lock: + rule = _runtime.key_rules.get(params["name"][0]) + stats = ( + rule.stats() + if rule is not None + else {"seen": 0, "hits": 0, "max_hits_per_url": 0, "retried_urls": 0} + ) + data = json.dumps(stats) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(bytes(data, "UTF-8")) + return + if path[1] == "reset": _runtime.reset() self.log_message("reset") @@ -707,6 +875,11 @@ def do_GET(self): if _runtime.at_listing.has_effect(): return _runtime.at_listing.inject_error(self) + if not is_listing and _runtime.at_object_get is not None: + if _runtime.at_object_get.has_effect(): + self.log_message("get at_object_get %s", _runtime.at_object_get) + return _runtime.at_object_get.inject_error(self) + if not is_listing and _runtime.slow_get is not None: timeout = _runtime.slow_get.get_timeout() if timeout is not None: @@ -729,6 +902,11 @@ def do_PUT(self): params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) upload_id = params.get("uploadId", [None])[0] + if _runtime.inject_by_key_rules( + self, "object" if upload_id is None else "part", self.path + ): + return + if upload_id is not None: if _runtime.at_part_upload is not None: self.log_message( @@ -771,6 +949,11 @@ def do_PUT(self): def do_POST(self): parts = urllib.parse.urlsplit(self.path) params = urllib.parse.parse_qs(parts.query, keep_blank_values=True) + if "delete" in params and _runtime.inject_by_key_rules( + self, "delete_objects", self.path + ): + return + uploads = params.get("uploads", [None])[0] if uploads is not None: if _runtime.at_create_multi_part_upload is not None: @@ -797,6 +980,8 @@ def do_HEAD(self): self.redirect() def do_DELETE(self): + if _runtime.inject_by_key_rules(self, "delete", self.path): + return self.redirect() diff --git a/tests/integration/helpers/s3_mocks/s3_fault_proxy.py b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py index 641599683a30..e6b4759a67cf 100644 --- a/tests/integration/helpers/s3_mocks/s3_fault_proxy.py +++ b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py @@ -27,7 +27,8 @@ (optionally scoped by `trace_path_substring`) and `/stats` returns it as `trace`, with the proxy's monotonic clock as `now_mono_ms`. A record names the fault it got; after a trickle, `outcome` is `delivered` once the last piece is flushed or `disconnected` when a write fails, and -`t_last_piece_mono_ms` is when the last piece started to be written. With `trace_bodies: true` a record +`t_last_piece_mono_ms` is when the last piece started to be written. `t_done_mono_ms` is when the +handler finished the request (response written, or a failure). With `trace_bodies: true` a record also carries the request body as Latin-1 text when it is at most `TRACE_BODY_MAX_BYTES`, else None. `rules` is an ordered script of `{method, path_substring, action, count}` with an optional @@ -39,6 +40,29 @@ parked request gets `t_release_mono_ms` when it is released. `GET /parked` lists the parked requests; `/stats` returns the rules with their remaining counts. +Three modes for the tests that cut an upload or a download (each is armed through `/config`, claims exactly one +request atomically before its body is read, and disarms itself): + +- `paced_body: {prefix, min_content_length, rate_bytes_per_s, recv_buffer_bytes, read_timeout_s}` claims the first + `PutObject` (a `PUT` with no query, no `x-amz-copy-source`) or `UploadPart` (`partNumber` and `uploadId` only) + whose path starts with `prefix` and whose `Content-Length` is at least `min_content_length` (required, above 0). + Arming answers with the `request_id` the claimed request will carry. It reads the body in small chunks on a timer + at `rate_bytes_per_s` (default 128 KiB/s) and never stops reading, so a back-pressured sender keeps sending at + that rate. A complete body is forwarded; a short one is never forwarded. `{"unpace": {"request_id"}}` makes the + claimed request read the rest at full speed and traces an `unpaced` event with the byte count at that moment. + `/stats` carries `paced_trace`: records with `event` `began` (request id, method, key, upload id, part number, + content length, receive buffer), `progress` (bytes read, about once a second), `unpaced` and `ended` (bytes read, + `outcome`). + Outcomes of `ended`: `complete`; `peer_eof` (the sender closed: FIN); `peer_reset` (connection error); `timeout` + (the proxy's own read gave up after `read_timeout_s`); `proxy_error` (any other exception). A client-side request + timeout looks like an early close (`peer_eof`), so a caller keeps its client timeouts far above the paced time and + runs a no-signal control for each paced path. When the server closes an upload, the bytes already queued in its + kernel send buffer are delivered before the close is seen; `unpace` drains them quickly. +- `hold_get: {prefix}` forwards the response headers of the first object `GET` under `prefix`, waits until + `POST /release_get {id}`, then sends half of the body and closes. `/stats` carries `held_gets`. +- `fail_abort: {key, upload_id, remaining}` answers `remaining` (default 1) `DELETE`s of that key with that + `uploadId` with 503. `/stats` carries `abort_trace` with every such `DELETE` and the status it got. + Control plane (separate port): POST /config {json}, GET /stats, GET /healthz. Deterministic: fault decisions are driven by a seeded PRNG keyed per-request-index, so a given (seed, rate) is reproducible. """ @@ -55,6 +79,7 @@ import sys import threading import time +import urllib.parse UPSTREAM = os.environ.get("RUSTFS_UPSTREAM", "rustfs1:11121") # host:port of the real store S3_PORT = int(os.environ.get("S3_PROXY_PORT", "11121")) @@ -82,6 +107,9 @@ "list_anomaly": None, # None | "duplicate" | "drop_token" "list_prefix": "roots/", # only LIST calls whose prefix contains this are perturbed "rules": [], # ordered script; see the module docstring + "paced_body": None, # see the module docstring + "hold_get": None, + "fail_abort": None, } _DEFAULT_STATS = { "forwarded": 0, @@ -90,17 +118,41 @@ "by_mode": {}, "drop_after_forward": [], "trace": [], + "paced_trace": [], + "abort_trace": [], } _cfg = dict(_DEFAULT_CFG) _stats = dict(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] _stats["trace"] = [] +_stats["paced_trace"] = [] +_stats["abort_trace"] = [] _req_index = [0] _idx_lock = threading.Lock() # id -> {"id", "method", "path", "t_mono_ms", "event", "respond", "trace"}; guarded by _cfg_lock. _parked = {} _parked_ids = [0] +# id -> {"id", "key", "t_headers_mono_ms", "t_release_mono_ms", "state", "event"}; guarded by _cfg_lock. +_held_gets = {} +_held_get_ids = [0] +_paced_ids = [0] +# Bumped by `_reset`: a claimed paced request of an earlier generation drops its connection and records nothing. +_generation = [0] +# Ids of claimed paced requests whose pacing was released by `unpace`; guarded by `_cfg_lock`. +_unpaced_ids = set() +PACED_DEFAULT_RATE = 128 * 1024 +PACED_TICK_S = 0.1 +PACED_UNPACED_CHUNK = 1 << 20 +PACED_UNPACED_RECV_BUFFER = 4 << 20 +PACED_PROGRESS_S = 1.0 +PACED_DEFAULT_RECV_BUFFER = 4096 +PACED_DEFAULT_READ_TIMEOUT_S = 30 +HELD_GET_MAX_WAIT_S = 600 +# Hop-by-hop headers and `Expect`: the proxy sends the buffered body at once, so a relayed `Expect: 100-continue` +# would make the upstream reply with an interim 100 that `getresponse` would misread. +_HOP_HEADERS = {"transfer-encoding", "expect", "connection", "keep-alive", "proxy-connection", + "te", "trailer", "upgrade"} def _get_cfg(): @@ -149,6 +201,11 @@ def _reset(): for record in _parked.values(): _release(record, "503") _parked.clear() + for held in _held_gets.values(): + held["event"].set() + _held_gets.clear() + _generation[0] += 1 + _unpaced_ids.clear() _cfg.clear() _cfg.update(_DEFAULT_CFG) _stats.clear() @@ -156,6 +213,8 @@ def _reset(): _stats["by_mode"] = {} _stats["drop_after_forward"] = [] _stats["trace"] = [] + _stats["paced_trace"] = [] + _stats["abort_trace"] = [] with _idx_lock: _req_index[0] = 0 @@ -205,7 +264,8 @@ def _admit(self, ingress_mono_ms): # Every key exists before the record is published; later fields start as None. self._trace_record = {"t_mono_ms": ingress_mono_ms, "method": self.command, "path": self.path, "fault": None, "rule": action, "status": None, "outcome": None, - "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "body": body} + "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "t_done_mono_ms": None, + "body": body} _stats["trace"].append(self._trace_record) parked = None if action == "hold": @@ -299,6 +359,181 @@ def _emit_fault(self, mode): elif mode == "trickle": self._forward(trickle=True) + # --- paced body, held GET, failed abort --------------------------------- + def _claim_paced(self): + """Atomically disarms `paced_body` and returns its config when this request is the one to pace: a + `PutObject` or an `UploadPart` with the armed prefix and size. Tagging, ACL and copy requests never match.""" + if self.command != "PUT" or self.headers.get("x-amz-copy-source") is not None: + return None + length = self.headers.get("Content-Length") + if length is None: + return None + parsed = urllib.parse.urlparse(self.path) + query = set(urllib.parse.parse_qs(parsed.query, keep_blank_values=True)) + if query not in (set(), {"partNumber", "uploadId"}): + return None + with _cfg_lock: + armed = _cfg.get("paced_body") + if (armed is None or not parsed.path.startswith(armed["prefix"]) + or int(length) < armed["min_content_length"]): + return None + _cfg["paced_body"] = None + return dict(armed, generation=_generation[0]) + + def _paced_event(self, claim, **fields): + """Appends a record unless a reset happened since the claim.""" + with _cfg_lock: + if claim["generation"] != _generation[0]: + return False + _stats["paced_trace"].append(dict(fields, request_id=claim["request_id"], t_mono_ms=time.monotonic() * 1000.0)) + return True + + def _paced_body(self, claim): + """Reads the claimed body at the configured rate. A complete body goes upstream; any other end closes the + connection and forwards nothing.""" + length = int(self.headers["Content-Length"]) + rate = int(claim.get("rate_bytes_per_s", PACED_DEFAULT_RATE)) + query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + sock = self.connection + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, int(claim.get("recv_buffer_bytes", PACED_DEFAULT_RECV_BUFFER))) + sock.settimeout(claim.get("read_timeout_s", PACED_DEFAULT_READ_TIMEOUT_S)) + self._paced_event( + claim, event="began", method=self.command, key=urllib.parse.unquote(urllib.parse.urlparse(self.path).path), + upload_id=(query.get("uploadId") or [None])[0], part_number=(query.get("partNumber") or [None])[0], + content_length=length, rate_bytes_per_s=rate, rcvbuf=sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)) + body = bytearray() + start = next_progress = time.monotonic() + outcome = None + error = None + unpaced = False + try: + while len(body) < length: + if not unpaced: + with _cfg_lock: + unpaced = claim["request_id"] in _unpaced_ids + if unpaced: + self._paced_event(claim, event="unpaced", bytes_read=len(body)) + # The small receive buffer of the paced read caps the transfer by itself (measured: tens of + # KiB/s); raising it alone does not help, the window clamp has to be raised as well. + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, PACED_UNPACED_RECV_BUFFER) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_WINDOW_CLAMP, PACED_UNPACED_RECV_BUFFER) + chunk = PACED_UNPACED_CHUNK if unpaced else max(1, int(rate * PACED_TICK_S)) + data = self.rfile.read1(min(chunk, length - len(body))) + if not data: + outcome = "peer_eof" + break + body += data + now = time.monotonic() + if now >= next_progress: + next_progress = now + PACED_PROGRESS_S + if not self._paced_event(claim, event="progress", bytes_read=len(body)): + self._abandon() + return + pause = start + len(body) / rate - now + if pause > 0 and not unpaced: + time.sleep(pause) + else: + outcome = "complete" + except TimeoutError: + outcome = "timeout" + except ConnectionError as e: + outcome = "peer_reset" + error = repr(e) + except Exception as e: + outcome = "proxy_error" + error = repr(e) + if not self._paced_event(claim, event="ended", bytes_read=len(body), outcome=outcome, error=error): + self._abandon() + return + if outcome != "complete": + self._abandon() + return + sock.settimeout(None) + self._cached_body = bytes(body) + self._paced_event(claim, event="forwarded") + self._forward() + + def _abandon(self): + self.close_connection = True + try: + self.connection.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def _claim_held_get(self): + if self.command != "GET": + return None + parsed = urllib.parse.urlparse(self.path) + if "list-type" in parsed.query or "uploads" in parsed.query: + return None + with _cfg_lock: + armed = _cfg.get("hold_get") + if armed is None or not parsed.path.startswith(armed["prefix"]): + return None + _cfg["hold_get"] = None + _held_get_ids[0] += 1 + held = {"id": _held_get_ids[0], "key": urllib.parse.unquote(parsed.path), "t_headers_mono_ms": None, + "t_release_mono_ms": None, "state": "claimed", "content_length": None, "event": threading.Event()} + _held_gets[held["id"]] = held + return held + + def _hold_get(self, held): + """Sends the real response headers, waits for `/release_get`, then sends half of the body and closes.""" + conn = http.client.HTTPConnection(UPSTREAM, timeout=60) + try: + conn.request("GET", self.path, headers=self._upstream_headers(0)) + resp = conn.getresponse() + data = resp.read() + finally: + conn.close() + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in ("transfer-encoding", "connection", "content-length"): + self.send_header(k, v) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.flush() + with _cfg_lock: + held["t_headers_mono_ms"] = time.monotonic() * 1000.0 + held["content_length"] = len(data) + held["state"] = "waiting" + held["event"].wait(HELD_GET_MAX_WAIT_S) + try: + self.wfile.write(data[:len(data) // 2]) + self.wfile.flush() + except OSError: + pass + with _cfg_lock: + held["state"] = "truncated" + self._abandon() + + def _match_abort(self): + """The key and upload id of a `DELETE` that `fail_abort` is about, else None.""" + if self.command != "DELETE": + return None + parsed = urllib.parse.urlparse(self.path) + upload_id = (urllib.parse.parse_qs(parsed.query).get("uploadId") or [None])[0] + with _cfg_lock: + armed = _cfg.get("fail_abort") + if armed is None or upload_id != armed["upload_id"] or urllib.parse.unquote(parsed.path) != armed["key"]: + return None + return armed["key"], upload_id + + def _fail_abort(self, key, upload_id): + """Records the `DELETE`, answers it 503 while the budget lasts and forwards it afterwards.""" + with _cfg_lock: + armed = _cfg["fail_abort"] + inject = armed.get("remaining", 1) > 0 + if inject: + armed["remaining"] = armed.get("remaining", 1) - 1 + self._abort_record = {"t_mono_ms": time.monotonic() * 1000.0, "key": key, "upload_id": upload_id, + "injected": inject, "status": None} + _stats["abort_trace"].append(self._abort_record) + if inject: + self._send_error(503, _SLOWDOWN_BODY) + else: + self._forward() + # --- request body ------------------------------------------------------- def _read_body(self): length = self.headers.get("Content-Length") @@ -321,6 +556,12 @@ def _read_body(self): return b"" # --- forward to upstream ------------------------------------------------ + def _upstream_headers(self, body_length): + """The client's headers verbatim, including `Host` so that SigV4 stays valid, minus the hop-by-hop ones.""" + headers = {k: v for k, v in self.headers.items() if k.lower() not in _HOP_HEADERS} + headers["Content-Length"] = str(body_length) + return headers + def _forward(self, drop_after_forward=False, trickle=False): body = getattr(self, "_cached_body", None) if body is None: @@ -332,14 +573,7 @@ def _forward(self, drop_after_forward=False, trickle=False): # so relaying Expect makes the upstream reply with an interim 100 that getresponse() would # misread — corrupting the upload (observed: size-0 blobs on >=64 KiB PUTs). We already # buffered the full body and send it directly, so no 100-continue negotiation is needed. - _HOP = {"transfer-encoding", "expect", "connection", "keep-alive", "proxy-connection", - "te", "trailer", "upgrade"} - fwd_headers = {} - for k, v in self.headers.items(): - if k.lower() in _HOP: - continue - fwd_headers[k] = v - fwd_headers["Content-Length"] = str(len(body)) + fwd_headers = self._upstream_headers(len(body)) try: conn.request(self.command, self.path, body=body, headers=fwd_headers) resp = conn.getresponse() @@ -422,11 +656,28 @@ def _forward(self, drop_after_forward=False, trickle=False): def _trace_status(self, status): if self._trace_record is not None: self._trace_record["status"] = status + if self._abort_record is not None: + self._abort_record["status"] = status def _handle(self): - cfg = _get_cfg() self._trace_record = None + try: + self._dispatch() + finally: + if self._trace_record is not None: + self._trace_record["t_done_mono_ms"] = time.monotonic() * 1000.0 + + def _dispatch(self): + cfg = _get_cfg() + self._abort_record = None ingress_mono_ms = time.monotonic() * 1000.0 + # Claimed before the body is read: a paced body must never be buffered at full speed first. + claim = self._claim_paced() + if claim is not None: + return self._paced_body(claim) + held = self._claim_held_get() + if held is not None: + return self._hold_get(held) # Cache body once (fault paths + forward both may need it). try: self._cached_body = self._read_body() @@ -436,6 +687,9 @@ def _handle(self): print(f"[dbg] {self.command} {self.path[:60]} CL={self.headers.get('Content-Length')} " f"TE={self.headers.get('Transfer-Encoding')} CE={self.headers.get('Content-Encoding')} " f"Expect={self.headers.get('Expect')} read={len(self._cached_body)}", flush=True) + abort = self._match_abort() + if abort is not None: + return self._fail_abort(*abort) action, parked = self._admit(ingress_mono_ms) mode = self._should_fault(cfg) if action is None else None if self._trace_record is not None: @@ -513,6 +767,9 @@ def do_GET(self): snapshot["by_mode"] = dict(_stats["by_mode"]) snapshot["drop_after_forward"] = list(_stats["drop_after_forward"]) snapshot["trace"] = [dict(r) for r in _stats["trace"]] + snapshot["paced_trace"] = [dict(r) for r in _stats["paced_trace"]] + snapshot["abort_trace"] = [dict(r) for r in _stats["abort_trace"]] + snapshot["held_gets"] = [{k: v for k, v in r.items() if k != "event"} for r in _held_gets.values()] snapshot["rules"] = [dict(r) for r in _cfg["rules"]] snapshot["now_mono_ms"] = time.monotonic() * 1000.0 return self._json(200, snapshot) @@ -529,6 +786,14 @@ def do_POST(self): patch = json.loads(self.rfile.read(length) or b"{}") except Exception as e: return self._json(400, {"error": f"bad json: {e}"}) + if self.path.startswith("/release_get"): + with _cfg_lock: + held = _held_gets.get(patch.get("id")) + if held is None or held["state"] != "waiting" or held["event"].is_set(): + return self._json(404, {"error": "no waiting held GET"}) + held["t_release_mono_ms"] = time.monotonic() * 1000.0 + held["event"].set() + return self._json(200, {"ok": True}) if self.path.startswith("/release"): respond = patch.get("respond", "forward") if respond not in ("forward", "503"): @@ -544,6 +809,17 @@ def do_POST(self): reset = bool(patch.pop("reset", False)) if reset: _reset() + unpace = patch.pop("unpace", None) + if unpace is not None: + with _cfg_lock: + _unpaced_ids.add(unpace["request_id"]) + paced = patch.get("paced_body") + if paced is not None: + if int(paced.get("min_content_length") or 0) <= 0: + return self._json(400, {"error": "paced_body needs min_content_length above 0"}) + with _cfg_lock: + _paced_ids[0] += 1 + patch["paced_body"] = dict(paced, request_id=_paced_ids[0]) with _cfg_lock: if "rules" in patch: patch["rules"] = [dict(r) for r in patch["rules"]] diff --git a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml index 3134abe48998..8f65c8fadadb 100644 --- a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml +++ b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml @@ -1,7 +1,7 @@ - @@ -19,6 +19,44 @@ node2_other 0 + + + object_storage + s3 + cas + 30 + 10000 + http://rustfs1:11121/test/other_pool_s3/ + clickhouse + clickhouse + node2_other_s3 + s3 + 0 + + + + object_storage + s3 + cas + http://rustfs1:11121/test/other_pool/ + clickhouse + clickhouse + node2_other + true + 0 + + + object_storage + s3 + cas + http://rustfs1:11121/test/other_pool_s3/ + clickhouse + clickhouse + node2_other_s3 + true + 0 + @@ -28,6 +66,13 @@ + + +
+ disk_cas_other_s3 +
+
+
diff --git a/tests/integration/test_cas_replicated_relink/test.py b/tests/integration/test_cas_replicated_relink/test.py index 8665ac4d9633..9f31a7ae4c19 100644 --- a/tests/integration/test_cas_replicated_relink/test.py +++ b/tests/integration/test_cas_replicated_relink/test.py @@ -21,6 +21,8 @@ # must degrade to bytes. OTHER_STORAGE_POLICY = "cas_other" OTHER_CA_DISK = "disk_cas_other" +OTHER_S3_STORAGE_POLICY = "cas_other_s3" +OTHER_S3_CA_DISK = "disk_cas_other_s3" # node2-only policies (configs/storage_conf_tiered.xml). `cas_tiered` = [local `default`] then # [disk_cas_shared]: an ordinary reservation lands on `default`, so a relink onto the pool's disk is a @@ -756,6 +758,105 @@ def test_recursion_brake_bounds_relink_to_one_attempt(): drop_everywhere(table) +def test_cancelled_fetch_does_not_fall_back_to_a_byte_fetch(): + """A fetch cancelled while relink is in progress ends with `ABORTED` and asks the sender nothing more. + + Relink preparation reads a stop as "relink not possible", and the fallback then fetched the bytes. + A stop that the byte fetch sees on entry (`SYSTEM STOP FETCHES`) would end the fallback anyway. The veto + matters for a stop it does not see: an inherited one (a killed `FETCH PARTITION`, a merge task's fetch) + or a latched per-attempt one. The first failpoint injects that kind of stop by cancelling the fetch's own + entry, not the fetcher's blocker. The second failpoint lands in the mechanism-failure branch, the one that + falls back. The sender must see relink offers only and no byte request; the part arrives by relink once + the failpoints are off. + """ + node1 = cluster.instances["node1"] + node2 = cluster.instances["node2"] + table = "veto" + drop_everywhere(table) + + create_replicated(node1, table) + create_replicated(node2, table) + + node2.query("SYSTEM STOP FETCHES {}".format(table)) + insert_rows(node1, table, 2_000_000) + part = active_part_names(node1, table)[0] + # Every pattern names the table and the part, and counts start from a baseline: a part name repeats across + # tables and a rerun of the test leaves lines of the same table in the log. + sender_requests = r"default\.{} .*Sending part {}$".format(table, re.escape(part)) + sender_offers = relink_offer_pattern(table, part) + aborted = r"default\.{} .*Fetching of part was cancelled".format(table) + forced_failure = r"default\.{} .*Failpoint cas_relink_receiver_force_mechanism_failure: abandoning the relink of part {}".format( + table, re.escape(part) + ) + not_possible = r"default\.{} .*Relink of part {} is not possible on this pair".format(table, re.escape(part)) + byte_download = download_finished_pattern(table, part) + + def new_lines(node, pattern): + return log_lines(node, pattern)[baseline[(node.name, pattern)]:] + + baseline = { + (node.name, pattern): len(log_lines(node, pattern)) + for node, patterns in ((node1, (sender_requests, sender_offers)), (node2, (aborted, forced_failure, not_possible, byte_download))) + for pattern in patterns + } + + node2.query("SYSTEM ENABLE FAILPOINT cas_relink_receiver_cancel_fetches_in_preparation") + node2.query("SYSTEM ENABLE FAILPOINT cas_relink_receiver_force_mechanism_failure") + try: + node2.query("SYSTEM START FETCHES {}".format(table)) + + wait_until( + lambda: new_lines(node2, aborted) or new_lines(node2, byte_download), + timeout=60, + what="the fetch of {} to end".format(part), + ) + assert not new_lines(node2, byte_download), "the cancelled fetch fetched the bytes" + assert new_lines(node2, aborted), "the fetch did not end with ABORTED" + assert new_lines(node2, forced_failure), "the mechanism-failure branch was not reached" + assert new_lines(node2, not_possible) + # The receiver logs the abort before the queue entry publishes `last_exception`, so the entry is awaited. + wait_until( + lambda: "ABORTED" + in node2.query( + "SELECT last_exception FROM system.replication_queue WHERE database = 'default' AND table = '{}'".format(table) + ), + timeout=30, + what="the queue entry of {} to publish the abort".format(part), + ) + + def sender_counts(): + """New request lines and new offer lines, counted in one read of the sender's log.""" + lines = log_lines(node1, "({})|({})".format(sender_requests, sender_offers)) + requests = [line for line in lines if re.search(sender_requests, line)] + offers = [line for line in lines if re.search(sender_offers, line)] + return ( + len(requests) - baseline[(node1.name, sender_requests)], + len(offers) - baseline[(node1.name, sender_offers)], + ) + + # Every request the sender logs must be a relink offer: an offer logs both lines, a byte request only the + # first. The second line follows the first, so the counts are awaited; a byte request never evens them. + def only_offers(): + requests, offers = sender_counts() + return offers > 0 and requests == offers + + wait_until( + only_offers, + timeout=10, + what="every request of the sender for {} to be a relink offer".format(part), + ) + assert active_part_names(node2, table) == [] + finally: + node2.query("SYSTEM DISABLE FAILPOINT cas_relink_receiver_force_mechanism_failure") + node2.query("SYSTEM DISABLE FAILPOINT cas_relink_receiver_cancel_fetches_in_preparation") + + node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) + assert_relinked(node2, table, part) + assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS + + drop_everywhere(table) + + # Settings that make node1 drop an outdated part — and with it the CA ref the confirm asks about — # within a few seconds instead of the default eight minutes. FAST_OLD_PART_REMOVAL = ( @@ -1233,3 +1334,79 @@ def test_relink_wins_over_ttl_then_mover_converges(): node2.query("SYSTEM START FETCHES {}".format(table)) node2.query("SYSTEM START MOVES {}".format(table)) drop_everywhere(table) + + +def list_disk_dir(node, disk, path): + """Entries of `path` as the disk lists them (a staged part is a ref, not a file in a local directory).""" + out = node.exec_in_container( + [ + "bash", + "-c", + "clickhouse disks -C /etc/clickhouse-server/config.xml --disk {} --save-logs --query {} 2>&1; true".format( + shlex.quote(disk + "_ro"), shlex.quote("list '{}'".format(path)) + ), + ] + ) + assert "Code:" not in out, out + return out.split() + + +@pytest.mark.parametrize( + "policy, disk", + [ + pytest.param(OTHER_STORAGE_POLICY, OTHER_CA_DISK, id="local"), + pytest.param(OTHER_S3_STORAGE_POLICY, OTHER_S3_CA_DISK, id="s3"), + ], +) +def test_stopped_byte_fetch_leaves_no_tmp_fetch_ref(policy, disk): + node1 = cluster.instances["node1"] + node2 = cluster.instances["node2"] + table = "stopped_fetch_" + policy + failpoint = "replicated_fetch_pause_after_projections" + create_sql = ( + "CREATE TABLE " + table + " (id Int64, v UInt64, s String, " + "PROJECTION p_by_s (SELECT s, sum(v) GROUP BY s)) " + "ENGINE = ReplicatedMergeTree('{zk}', '{{replica}}') ORDER BY id " + "SETTINGS storage_policy = '{policy}'" + ) + drop_everywhere(table) + try: + zk = "/clickhouse/tables/" + table + node1.query(create_sql.format(policy=STORAGE_POLICY, zk=zk)) + node2.query(create_sql.format(policy=policy, zk=zk)) + node2.query("SYSTEM STOP FETCHES {}".format(table)) + insert_rows(node1, table, 0) + part = active_part_names(node1, table)[0] + expected_digest = node1.query("SELECT count(), sum(cityHash64(id, v, s)) FROM {}".format(table)) + data_path = node2.query( + "SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(table) + ).strip() + table_path = data_path[data_path.index("store/"):] + + node2.query("SYSTEM ENABLE FAILPOINT " + failpoint) + try: + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM WAIT FAILPOINT {} PAUSE".format(failpoint), timeout=120) + assert int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 1 + node2.query("SYSTEM STOP FETCHES {}".format(table)) + finally: + node2.query("SYSTEM DISABLE FAILPOINT " + failpoint) + + wait_until( + lambda: int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 0, + 60, + "the stopped fetch to leave system.replicated_fetches", + ) + entries = list_disk_dir(node2, disk, table_path) + list_disk_dir(node2, disk, table_path + "detached") + assert not [e for e in entries if e.startswith("tmp-fetch_")], entries + assert fsck(node2, disk)["dangling"] == "0" + assert any_state_part_count(node2, table, part) == 0 + + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) + assert node2.query("SELECT count(), sum(cityHash64(id, v, s)) FROM {}".format(table)) == expected_digest + assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS + # Control for the listing helper: it must see the part that arrived. + assert part in list_disk_dir(node2, disk, table_path) + finally: + drop_everywhere(table) diff --git a/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml b/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml new file mode 100644 index 000000000000..f8c1473a7f58 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml @@ -0,0 +1,32 @@ + + + + + + object_storage + s3 + cas + http://rustfs1:11121/test/cas_request_cut/ + clickhouse + clickhouse + itest-cas-cut + true + false + + + object_storage + s3 + cas + http://rustfs1:11121/test/cas_request_cut_s3/ + clickhouse + clickhouse + itest-cas-cut-s3 + s3 + true + false + + + + diff --git a/tests/integration/test_cas_request_window/configs/guard.xml b/tests/integration/test_cas_request_window/configs/guard.xml new file mode 100644 index 000000000000..4590c24737d9 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/guard.xml @@ -0,0 +1,39 @@ + + + 1000000 + + 30 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-guard + http://rustfs1:11121/test/cas_request_guard/ + clickhouse + clickhouse + false + + 500 + 1000 + 5000 + 10000 + 2000 + 500 + + + + + +
+ disk_cas_guard +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml b/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml new file mode 100644 index 000000000000..67bbcac74a15 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml @@ -0,0 +1,158 @@ + + + 01 + node_cut + + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut + http://s3proxy:11121/test/cas_request_cut/ + clickhouse + clickhouse + false + + 300000 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-s3 + http://s3proxy:11121/test/cas_request_cut_s3/ + clickhouse + clickhouse + s3 + false + 300000 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-mp + http://s3proxy:11121/test/cas_request_cut_mp/ + clickhouse + clickhouse + false + 300000 + 5242880 + 5242880 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-s3-mp + http://s3proxy:11121/test/cas_request_cut_s3_mp/ + clickhouse + clickhouse + s3 + false + 300000 + 5242880 + 5242880 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_cut +
+
+
+ + +
+ disk_cas_cut_s3 +
+
+
+ + +
+ disk_cas_cut_mp +
+
+
+ + +
+ disk_cas_cut_s3_mp +
+
+
+ + + + + default + + + disk_cas_cut + 0 + + + 0 + + + + + default + + + disk_cas_cut_s3 + 0 + + + 0 + +
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml index 1e57ebc461a5..ffb893666d4a 100644 --- a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml +++ b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml @@ -24,6 +24,27 @@ 2000 500 + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-stop-s3 + http://s3proxy:11121/test/cas_request_stop_s3/ + clickhouse + clickhouse + s3 + false + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 +
@@ -33,6 +54,13 @@ + + +
+ disk_cas_stop_s3 +
+
+
diff --git a/tests/integration/test_cas_request_window/docker_compose_proxy.yml b/tests/integration/test_cas_request_window/docker_compose_proxy.yml index 210d732547b7..73118f2b628f 100644 --- a/tests/integration/test_cas_request_window/docker_compose_proxy.yml +++ b/tests/integration/test_cas_request_window/docker_compose_proxy.yml @@ -38,3 +38,8 @@ services: depends_on: s3proxy: condition: service_healthy + + node_cut: + depends_on: + s3proxy: + condition: service_healthy diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py index 124ce4d0d64d..abef5a4a12ae 100644 --- a/tests/integration/test_cas_request_window/test.py +++ b/tests/integration/test_cas_request_window/test.py @@ -12,24 +12,42 @@ there is removed at once (configs/drop_delay.xml). It runs with Keeper and transactions enabled (configs/transactions.xml), and uploads a part's blobs one at a time (configs/blob_upload_serial.xml). +The upload tests stop a part body that `max_remote_write_network_bandwidth` paces, on `disk_cas_stop` (local +staging) and `disk_cas_stop_s3` (S3 staging). `node_guard` (configs/guard.xml) paces every body by a server-wide +limit, pins its mount lease and waits 30 s for connections at shutdown; only the upload guard tests run there. + The GC test runs on `node_gc` (configs/storage_conf_gc.xml): the same timing and a one-hour GC interval. A manual round never takes the GC lease from another process, and a restart leaves the lease with the previous one, so this server is never restarted. Each test drops the tables it leaves and scopes its fault rules and trace to its own pool, so the module passes in any order and when repeated. + +The cut-upload tests (from `CUT_PREFIX` on) run a reduced parameter set by default; `CAS_CUT_FULL_MATRIX=1` selects +all listed variants (`matrix`). Both sets were run locally. """ +import datetime +import hashlib +import hmac import json +import logging import os import re +import shlex import subprocess import threading import time +import urllib.error +import urllib.parse import urllib.request +from xml.etree import ElementTree import pytest +from helpers.cas_paced_body import ( + DEFAULT_RATE_BYTES_PER_S, arm_paced_body, control_call, now_mono_ms, paced_requests, record_of, release_pace, wait_body_gate, + wait_complete, wait_cut) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) @@ -51,23 +69,16 @@ GC_POOL = "cas_request_gc" -def _control(url, path, patch=None): - data = None if patch is None else json.dumps(patch).encode() - request = urllib.request.Request( - url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if data is None else "POST" - ) - with urllib.request.urlopen(request, timeout=10) as response: - return json.loads(response.read().decode()) - - -def _wait_until(probe, timeout): +def _wait_until(probe, timeout, describe=None): + """Polls `probe` until it returns a true value. On a timeout the error carries `describe()`, when given.""" end = time.monotonic() + timeout while time.monotonic() < end: result = probe() if result: return result time.sleep(0.2) - raise AssertionError("condition did not become true within {}s".format(timeout)) + raise AssertionError("condition did not become true within {}s{}".format( + timeout, "" if describe is None else ": " + str(describe()))) @pytest.fixture(scope="module") @@ -82,12 +93,17 @@ def node(): "configs/transactions.xml", "configs/blob_upload_serial.xml"], with_rustfs=True, with_zookeeper=True, stay_alive=True) cluster.add_instance("node_gc", main_configs=["configs/storage_conf_gc.xml"], with_rustfs=True) + cluster.add_instance("node_guard", main_configs=["configs/guard.xml"], with_rustfs=True, stay_alive=True) + # The source of the fetches into `node_cut`: its tables are on the local disk, so a part is sent as bytes. + cluster.add_instance("node_src", macros={"shard": "01", "replica": "node_src"}, with_zookeeper=True) + cluster.add_instance("node_cut", main_configs=["configs/storage_conf_cut.xml", "configs/drop_delay.xml"], + with_rustfs=True, with_zookeeper=True, stay_alive=True) cluster.base_cmd.extend(["--file", os.path.join(os.path.dirname(__file__), "docker_compose_proxy.yml")]) try: cluster.start() binding = subprocess.check_output(cluster.base_cmd + ["port", "s3proxy", "8474"], text=True).strip() cluster.proxy_url = "http://{}".format(binding) - _wait_until(lambda: _control(cluster.proxy_url, "/healthz"), timeout=30) + _wait_until(lambda: control_call(cluster.proxy_url, "/healthz"), timeout=30) yield cluster.instances["node"] finally: cluster.shutdown() @@ -103,6 +119,23 @@ def node_gc(node): return cluster.instances["node_gc"] +@pytest.fixture(scope="module") +def node_guard(node): + return cluster.instances["node_guard"] + + +@pytest.fixture(scope="module") +def node_src(node): + return cluster.instances["node_src"] + + +@pytest.fixture(scope="module") +def node_cut(node): + """Keeper, a local-staging and an S3-staging CAS policy on pools of their own behind the proxy, and no other + writer to those pools. Body requests may last 300 s, longer than the paced duration of the largest body.""" + return cluster.instances["node_cut"] + + def _drop_all_tables(instance): for name in instance.query("SELECT table FROM system.detached_tables WHERE database = 'default'").split(): instance.query("ATTACH TABLE default.`{}`".format(name)) @@ -111,20 +144,26 @@ def _drop_all_tables(instance): @pytest.fixture(autouse=True) -def clean_state(node, node_stop, node_gc): - _control(cluster.proxy_url, "/config", {"reset": True}) +def clean_state(request, node, node_stop, node_gc, node_guard, node_cut, node_src): + control_call(cluster.proxy_url, "/config", {"reset": True}) + first_line = node_cut.count_log_lines() + 1 yield - _control(cluster.proxy_url, "/config", {"reset": True}) - for instance in (node, node_stop, node_gc): + control_call(cluster.proxy_url, "/config", {"reset": True}) + # A statement of `in_thread` that a failed case left running ends once the proxy is reset; the drop must not race it. + for thread in RUNNING_STATEMENTS: + thread.join(120) + RUNNING_STATEMENTS.clear() + for instance in (node, node_stop, node_gc, node_guard, node_cut, node_src): _drop_all_tables(instance) + record_log_anomalies(node_cut, request.node.name, first_line) def _arm(**config): - _control(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) + control_call(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) def _stats(): - return _control(cluster.proxy_url, "/stats") + return control_call(cluster.proxy_url, "/stats") def _create(node, name): @@ -226,7 +265,7 @@ def _rule(method, path_substring, action, count=1, body_substring=None): def _arm_rules(rules): - _control(cluster.proxy_url, "/config", + control_call(cluster.proxy_url, "/config", {"rules": rules, "trace": True, "trace_path_substring": STOP_PREFIX, "trace_bodies": True}) @@ -239,7 +278,7 @@ def _stop_and_release(node, query_id, path_substring, respond="forward", kill=Tr """Parked request, stop, `is_cancelled`, release: nothing the stopped query does after the release can predate the stop. Returns the release time on the proxy's clock.""" parked = _wait_until( - lambda: [p for p in _control(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) + lambda: [p for p in control_call(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) assert len(parked) == 1, parked # The release must reach the parked request before its socket times out, or the stopped query sees a timeout # instead of the released answer. Killed and polled over HTTP: a client start per query is slow in a sanitizer @@ -250,7 +289,7 @@ def _stop_and_release(node, query_id, path_substring, respond="forward", kill=Tr _wait_until(lambda: node.http_query( "SELECT is_cancelled FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1", timeout=STOP_ATTEMPT_TIMEOUT_S - 1) - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) released = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None] assert len(released) == 1, released return released[0]["t_release_mono_ms"] @@ -376,7 +415,7 @@ def test_failed_read_after_a_lost_race_and_stop_starts_no_further_put(node_stop, query's own stop.""" def lose_race_then_fail_the_read(suffix): - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), _rule("PUT", STOP_CATALOG, "412", count=1000)]) query_id = "failed_read_{}_{}".format(suffix, stop) @@ -391,7 +430,7 @@ def lose_race_then_fail_the_read(suffix): return request.get_error() # A table created without faults leaves the lane holding the catalog it wrote. - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) node_stop.query(_create_sql("failed_read_warm_" + stop), timeout=120) error = lose_race_then_fail_the_read("cached") # `ABORTED`: the conflict the settling read could not resolve. @@ -416,7 +455,7 @@ def test_kill_after_ambiguous_create_keeps_unresolved_exit(node_stop): assert _remaining_counts() == [0, 0] # Control: a live owner decides again after each ambiguous attempt until one lands. - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) _arm_rules([_rule("PUT", STOP_CATALOG, "503", count=8)]) node_stop.query(_create_sql("ambiguous_create_live"), timeout=120) statuses = [r["status"] for r in _catalog_puts(_stats()["trace"])] @@ -437,7 +476,7 @@ def test_killed_leader_with_chunk_in_flight_leaves_a_usable_lane(node_stop): sync = {"async_insert": 0} leader = node_stop.get_query_request("INSERT INTO ref_batch VALUES (1, 'leader')", query_id="ref_batch_leader", settings=sync, timeout=120) - _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) neighbor = node_stop.get_query_request("INSERT INTO ref_batch VALUES (2, 'neighbor')", settings=sync, timeout=120) # The release answers 503 without forwarding, so the chunk's settling read meets a 404. released_ms = _stop_and_release(node_stop, "ref_batch_leader", "/_log/", respond="503") @@ -466,16 +505,16 @@ def test_atomic_sync_drop_kill_releases_only_waiter(node_stop): seen = len(_stats()["trace"]) query_id = "atomic_sync_drop" request = node_stop.get_query_request("DROP TABLE atomic_sync_drop SYNC", query_id=query_id, timeout=120) - parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + parked = _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) assert len(parked) == 1, parked # Over HTTP: the parked write must still be parked when the kill returns. node_stop.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) _wait_until(lambda: request.process.poll() is not None, timeout=30) error = request.get_error() assert re.search(r"Code: 394\b", error), error - assert _control(cluster.proxy_url, "/parked")["parked"] == parked + assert control_call(cluster.proxy_url, "/parked")["parked"] == parked - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) _wait_until(lambda: node_stop.query( "SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0", timeout=60) _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][seen:], life), timeout=60) @@ -497,7 +536,7 @@ def _detach_cold(node, name): parts = _active_parts(node, name) node.query("DETACH TABLE {} PERMANENTLY".format(name)) node.restart_clickhouse() - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) return life, parts @@ -581,7 +620,7 @@ def recovery_retries(): assert re.search(r"Code: 210\b", error) and re.search(r"_log/.*gave up at the \w+ deadline", error, re.DOTALL), error assert len([r for r in _stats()["trace"] if life in r["path"]]) == life_gets_at_kill, "another walk started" - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) node_stop.query("ATTACH TABLE {}".format(name)) _assert_reattached(node_stop, name, parts) @@ -646,7 +685,7 @@ def _checked_blob_fixture(node, name, table, insert, new_blobs): assert len(puts) == new_blobs and puts == missing, \ "the fixture of {} publishes {} blob(s), not {}: PUT {}, HEAD 404 {}".format(name, len(puts), new_blobs, puts, missing) node.query("CREATE TABLE {} {}".format(name, table)) - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) def _blob_fixture_insert(node, name, insert): @@ -911,7 +950,7 @@ def test_manual_gc_kill_preserves_owner_code(node_gc): params={"default_format": "JSONEachRow"}, method="POST")) assert first["acquired_lease"] in (1, True), first catalog = GC_POOL + "/cas/ref_catalog" - _control(cluster.proxy_url, "/config", + control_call(cluster.proxy_url, "/config", {"rules": [_rule("GET", catalog, "hold")], "trace": True, "trace_path_substring": GC_POOL}) query_id = "manual_gc_kill" request = node_gc.get_query_request("SYSTEM CAS GC RUN {}".format(GC_DISK), query_id=query_id, timeout=120) @@ -942,22 +981,21 @@ def test_shutdown_hands_atomic_drop_to_restart(node_stop): shutting_down_before = int(node_stop.count_in_log("Waiting for current connections to close").strip()) fatal_before = int(node_stop.count_in_log("").strip()) # Taken before the hold, so only the kill and the log poll run before the parked `PUT`'s attempt timeout. - pid = node_stop.get_process_pid("clickhouse") - assert pid is not None + pid = server_pid(node_stop) - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) # Only this table's `Live -> Removing` write names its life as `Removing`. _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) node_stop.query("DROP TABLE {}".format(name)) - parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + parked = _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) assert len(parked) == 1, parked node_stop.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") # Logged right after `IsServerShuttingDown` is set, so the removal resumes under shutdown. _wait_until(lambda: int(node_stop.count_in_log("Waiting for current connections to close").strip()) > shutting_down_before, timeout=30) - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) released_ms = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None][0]["t_release_mono_ms"] - _wait_until(lambda: node_stop.get_process_pid("clickhouse") is None, timeout=60) + _wait_until(lambda: not _server_alive(node_stop, pid), timeout=60) trace = _stats()["trace"] held = next(r for r in trace if r["rule"] == "hold") @@ -986,3 +1024,1347 @@ def appended_through_terminal(): # The retried removal may seal the previous writer epoch first. appended = _wait_until(appended_through_terminal, timeout=60) assert all(r["status"] == 200 for r in appended), _brief(appended) + + +# A fresh incompressible body per insert, so the store holds no copy to reuse. At `PACED_LIMIT` it needs 120 s. +BODY_BYTES = 60_000_000 +PACED_LIMIT = 500_000 +PACED_INSERT = "INSERT INTO {} SELECT 1, randomString(60000000)" +# Above the one-second burst of the throttler and far below half of the body. +PROGRESS_BYTES = 4_000_000 +STOP_BOUND_S = 20 +# A stop that is not honoured waits for the rest of the body, about 100 s at `PACED_LIMIT`. +UNSTOPPED_WAIT_S = 300 +GUARD_POLICY = "cas_guard" +GUARD_DISK = "disk_cas_guard" +# `configs/guard.xml`. +SERVER_LIMIT = 1_000_000 +GUARD_LEASE_TTL_S = 10 +GUARD_RENEW_PERIOD_S = 2 + + +def _paced(settings=None): + return dict({"max_remote_write_network_bandwidth": PACED_LIMIT, "async_insert": 0}, **(settings or {})) + + +def _query_throttled_bytes(node, query_id): + """The bytes that the query's own write limit let through so far. None while the query has no row in + `system.processes`: before the server registered it and after it ended.""" + value = node.http_query("SELECT ProfileEvents['QueryRemoteWriteThrottlerBytes'] FROM system.processes " + "WHERE query_id = '{}'".format(query_id)).strip() + return int(value) if value else None + + +def _wait_body_going_out(node, request, query_id, baseline, timeout=180): + """Waits until the query's limit let `PROGRESS_BYTES` through beyond `baseline`, with most of the body left to + send. Returns the byte count then.""" + end = time.monotonic() + timeout + last = None + while True: + # No row before the server registers the query, and none after it ended. + sent = _query_throttled_bytes(node, query_id) + if sent is not None: + last = sent + if sent >= baseline + PROGRESS_BYTES: + break + assert request.process.poll() is None, \ + "the query ended before its body went out paced: {} bytes over the limit when last seen".format(last) + assert time.monotonic() < end, "{} bytes over the limit after {} s".format(last, timeout) + time.sleep(0.2) + assert sent - baseline <= BODY_BYTES // 2, (baseline, sent) + return sent + + +def _kill_and_time(node, request, query_id): + """Kills the query and returns the seconds from before the kill to the query's end.""" + started = time.monotonic() + node.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id), timeout=UNSTOPPED_WAIT_S) + _wait_until(lambda: request.process.poll() is not None, timeout=UNSTOPPED_WAIT_S) + return time.monotonic() - started + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_upload_is_stopped_in_flight(node_stop, staging, stop): + """A query stopped while its part body goes out paced by its write limit ends within `STOP_BOUND_S`: from before + `KILL QUERY`, or from the `max_execution_time` deadline. No part is committed, and the same insert without a limit + then succeeds. With S3 staging the body goes out while the part file is written.""" + name = "paced_{}_{}".format(staging, stop) + node_stop.query("CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(name, STOP_POLICY if staging == "local" else "cas_stop_s3")) + query_id = name + "_insert" + # The gate passes about 8 s after the upload starts. At the deadline at most 30.5 MB went out, so the rest of + # the body still needs about 59 s. + timeout = {"max_execution_time": 60, "timeout_overflow_mode": "throw"} if stop == "timeout" else {} + submitted = time.monotonic() + request = node_stop.get_query_request(PACED_INSERT.format(name), query_id=query_id, settings=_paced(timeout), + timeout=UNSTOPPED_WAIT_S + 60) + sent = _wait_body_going_out(node_stop, request, query_id, baseline=0) + gated = time.monotonic() - submitted + if stop == "kill": + elapsed = _kill_and_time(node_stop, request, query_id) + code = 394 + else: + deadline = submitted + timeout["max_execution_time"] + assert time.monotonic() < deadline, "the gate passed {:.1f} s after submission, past the {} s deadline".format( + gated, timeout["max_execution_time"]) + _wait_until(lambda: request.process.poll() is not None, timeout=UNSTOPPED_WAIT_S) + elapsed = time.monotonic() - deadline + code = 159 + logging.info("%s: %d bytes paced at the gate %.1f s after submission, ended %.1f s after the stop", + name, sent, gated, elapsed) + assert elapsed <= STOP_BOUND_S, "ended {:.1f} s after the stop".format(elapsed) + error = request.get_error() + assert re.search(r"Code: {}\b".format(code), error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "0" + + node_stop.query(PACED_INSERT.format(name), settings={"async_insert": 0}, timeout=120) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + + +def _server_throttled_bytes(node): + return _events(node, "RemoteWriteThrottlerBytes") + + +def _guard_mount(node): + rows = node.query("SELECT writer_epoch, renewal_sequence FROM system.cas_mounts WHERE disk = '{}' " + "AND server_root_id = 'itest-cas-guard'".format(GUARD_DISK)).strip().splitlines() + assert len(rows) == 1, rows + return tuple(int(v) for v in rows[0].split("\t")) + + +def test_limit_applies_and_the_mount_stays_live(node_guard): + """Mount renewals pass no bytes through the server-wide limit. Concurrent inserts of distinct bodies under that + limit take at least 90% of the time that their bytes, less one second of burst and one send quantum, need at the + limit. While they upload for more than one lease period the mount renews in the same epoch.""" + bodies, body_bytes = 3, 8_000_000 + idle_baseline = _server_throttled_bytes(node_guard) + idle_mount = _guard_mount(node_guard) + # Three renewal periods with no upload: the renewals in them must leave the counter where it was. + time.sleep(3 * GUARD_RENEW_PERIOD_S) + renewed = _guard_mount(node_guard) + assert renewed[0] == idle_mount[0] and renewed[1] > idle_mount[1], (idle_mount, renewed) + # Holds while no other test leaves merging tables on `node_guard`. + assert _server_throttled_bytes(node_guard) == idle_baseline, (idle_baseline, _server_throttled_bytes(node_guard)) + node_guard.query("CREATE TABLE server_limit (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(GUARD_POLICY)) + baseline = _server_throttled_bytes(node_guard) + started = time.monotonic() + requests = [node_guard.get_query_request( + "INSERT INTO server_limit SELECT {}, randomString({})".format(i, body_bytes), + settings={"async_insert": 0}, timeout=300) for i in range(bodies)] + _wait_until(lambda: _server_throttled_bytes(node_guard) >= baseline + PROGRESS_BYTES // 2, timeout=120, + describe=lambda: "{} bytes over the limit".format(_server_throttled_bytes(node_guard) - baseline)) + + samples = [(time.monotonic(), _guard_mount(node_guard))] + while samples[-1][0] - samples[0][0] <= GUARD_LEASE_TTL_S: + # Three renewal periods between samples, so each sample follows at least one renewal even if one is slow. + time.sleep(3 * GUARD_RENEW_PERIOD_S) + mount = _guard_mount(node_guard) + assert any(r.process.poll() is None for r in requests), \ + "the uploads ended {:.1f} s into the sampling".format(time.monotonic() - samples[0][0]) + samples.append((time.monotonic(), mount)) + logging.info("mount samples: %s", samples) + epochs = {mount[0] for _, mount in samples} + assert len(epochs) == 1, samples + sequences = [mount[1] for _, mount in samples] + assert all(later > earlier for earlier, later in zip(sequences, sequences[1:])), samples + + for request in requests: + request.get_answer() + wall = time.monotonic() - started + # The burst cap is applied after a call's amount is taken off, so the first call after an idle spell passes one + # quantum, at least 32 KiB, free. + # 10% slack: a socket charges the larger of the send size and 32 KiB per call, so the free amount varies. + bound = 0.9 * (bodies * body_bytes - SERVER_LIMIT - 32 * 1024) / SERVER_LIMIT + logging.info("%d bytes under %d B/s: %.1f s, bound %.1f s", bodies * body_bytes, SERVER_LIMIT, wall, bound) + assert wall >= bound, (wall, bound) + assert node_guard.query("SELECT count() FROM server_limit").strip() == str(bodies) + + +def test_killed_transaction_rolls_back_during_a_paced_upload(node_stop): + """An `INSERT` in an implicit transaction writes a tiny first part and a large second one, and is killed while the + second part's body goes out paced: it ends within `STOP_BOUND_S`, and the transaction rolls back the first part. + A ref-log record that lands after the kill installs that part with the rolled-back creation CSN.""" + name = "txn_paced_kill" + life = _create_with_life(node_stop, name) + try: + node_stop.query("SYSTEM STOP MERGES") + node_stop.query("INSERT INTO {} VALUES (1000, 'first')".format(name)) + fatal_before = int(node_stop.count_in_log("").strip()) + query_id = "txn_paced_kill_insert" + request = node_stop.get_query_request( + "INSERT INTO {} SELECT number, if(number = 0, 'x', randomString({})) FROM numbers(2)".format(name, BODY_BYTES), + # One thread, so the tiny part is written and committed before the large one is built. + query_id=query_id, settings=_paced(dict(ONE_PART_PER_SECOND, implicit_transaction=1, max_threads=1, + max_insert_threads=1)), + timeout=UNSTOPPED_WAIT_S + 60) + registered = _wait_until(lambda: node_stop.query( + "SELECT name FROM system.parts WHERE table = '{}' AND active AND creation_csn = 0 LIMIT 1".format(name)).strip(), + timeout=60) + baseline = _query_throttled_bytes(node_stop, query_id) + assert baseline is not None, "the query ended with its first part" + sent = _wait_body_going_out(node_stop, request, query_id, baseline) + killed_at = len(_stats()["trace"]) + elapsed = _kill_and_time(node_stop, request, query_id) + ended_at = len(_stats()["trace"]) + logging.info("%s: %d bytes paced past %d at the gate, ended %.1f s after the kill", name, sent, baseline, elapsed) + assert elapsed <= STOP_BOUND_S, "ended {:.1f} s after the kill".format(elapsed) + # A merge of transactional parts is not supported on a CAS disk. + node_stop.query("SYSTEM STOP MERGES {}".format(name)) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + window = _stats()["trace"][killed_at:ended_at] + assert _rolled_back_installs(node_stop, window, life, registered), (registered, _brief(window)) + # The cleanup may already have removed the rolled-back part. + csn = node_stop.query( + "SELECT creation_csn FROM system.parts WHERE table = '{}' AND name = '{}'".format(name, registered)).strip() + assert csn in ("", str(ROLLED_BACK_CSN)), (registered, csn) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + assert int(node_stop.count_in_log("").strip()) == fatal_before + + node_stop.query("INSERT INTO {} VALUES (100, 'next')".format(name), + settings={"implicit_transaction": 1, "async_insert": 0}) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "2" + finally: + try: + node_stop.query("DROP TABLE IF EXISTS {} SYNC".format(name)) + finally: + node_stop.query("SYSTEM START MERGES") + + +def _server_alive(node, pid): + state = node.exec_in_container(["bash", "-c", "ps -o stat= -p {} || true".format(pid)], user="root").strip() + return bool(state) and not state.startswith("Z") + + +def server_pid(instance): + """The PID the running server logged at its start: the server process itself. `get_process_pid` returns the + first match of `pgrep`, which can be the watchdog that supervises the server.""" + line = instance.exec_in_container(["bash", "-c", "grep -a 'Application: Starting ClickHouse' " + "/var/log/clickhouse-server/clickhouse-server.log | tail -n 1"]) + pid = int(line.rsplit("PID ", 1)[1].strip()) + assert _server_alive(instance, pid), line + return pid + + +def sigterm_orderly(instance, exit_deadline_s=30, after_exit=None): + """One SIGTERM to the exact server PID: the server must exit by itself within `exit_deadline_s` and log the + orderly shutdown (a forced exit can lose its own line, so the two success lines carry the check). A second + signal, or SIGKILL, would end the process without the shutdown under test, so the process is killed only when + the check failed. `after_exit(seconds)` runs between the exit and the check of the log. Returns the seconds from the + signal to the exit. The caller starts the server again.""" + # The success line only: the warning about remaining connections starts with the same words. + closed = "Application: Closed connections\\.$" + forced = "Will shutdown forcefully" + storages = "Shut down storages\\." + markers = (closed, forced, storages, "", "LOGICAL_ERROR") + before = {line: int(instance.count_in_log(line).strip()) for line in markers} + pid = server_pid(instance) + signalled = time.monotonic() + try: + instance.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") + # The deadline runs from the signal, the exec that sends it included, and a probe that succeeds after it fails. + _wait_until(lambda: not _server_alive(instance, pid), timeout=max(0.0, exit_deadline_s - (time.monotonic() - signalled)), + describe=lambda: "{} still alive {:.1f} s after the signal".format(pid, time.monotonic() - signalled)) + exited = time.monotonic() - signalled + assert exited <= exit_deadline_s, "the server exited {:.1f} s after the signal, over {} s".format(exited, exit_deadline_s) + if after_exit is not None: + after_exit(exited) + delta = {line: int(instance.count_in_log(line).strip()) - count for line, count in before.items()} + assert delta == {closed: 1, forced: 0, storages: 1, "": 0, "LOGICAL_ERROR": 0}, delta + finally: + if _server_alive(instance, pid): + instance.exec_in_container(["bash", "-c", "kill -9 {}".format(pid)], user="root") + return exited + + +def test_sigterm_during_insert_upload_is_orderly(node_guard): + """SIGTERM while a paced body goes out: shutdown kills the query, its upload stops, and the server closes its + connections within `shutdown_wait_unfinished` (30 s, well below the body's remaining time), shuts its storages + down and exits without the forced exit. One SIGTERM to the exact server PID: a second one, or SIGKILL, would end + the process without the orderly shutdown under test.""" + node_guard.query("CREATE TABLE sigterm_upload (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(GUARD_POLICY)) + query_id = "sigterm_upload_insert" + request = node_guard.get_query_request(PACED_INSERT.format("sigterm_upload"), query_id=query_id, + settings=_paced(), timeout=UNSTOPPED_WAIT_S) + try: + sent = _wait_body_going_out(node_guard, request, query_id, baseline=0) + exited = sigterm_orderly(node_guard, exit_deadline_s=120, + after_exit=lambda _: _wait_until(lambda: request.process.poll() is not None, timeout=60)) + logging.info("sigterm: %d bytes paced at the gate, server exited %.1f s after the signal", sent, exited) + finally: + node_guard.start_clickhouse() + assert node_guard.query("SELECT 1").strip() == "1" + + +# The paced-body tooling (`helpers/cas_paced_body.py`) and the pools of `node_cut` (`configs/storage_conf_cut.xml`). +# Where a data body goes: local staging uploads it to `blobs/` at the disk commit of the part; S3 staging uploads it to +# `staging/` while the file is written. Arming on these prefixes keeps leases, ref logs and manifests out of reach. +CUT_PREFIX = {"local": "/test/cas_request_cut/blobs/", "s3": "/test/cas_request_cut_s3/staging/", + "local_mp": "/test/cas_request_cut_mp/blobs/", "s3_mp": "/test/cas_request_cut_s3_mp/staging/"} +CUT_POLICY = {"local": "cas_cut", "s3": "cas_cut_s3", "local_mp": "cas_cut_mp", "s3_mp": "cas_cut_s3_mp"} +# A body of a cut case: incompressible, over the claim bound `CUT_MIN_BODY`, and over what the kernels of both ends queue +# for a sender (about 2.3 MB were measured on loopback): a sender that is stopped must still have bytes to withhold, or +# the proxy sees the whole body. At the default pace (256 KiB/s) it is in flight for 32 s, far longer than the few +# seconds from the gate to the signal. +CUT_BODY = 8 << 20 +CUT_MIN_BODY = 1 << 20 +# The merge selector takes equal parts only once there are enough of them. +SEED_PARTS = 6 +SEED_PART = CUT_BODY // SEED_PARTS +# A no-signal control proves that a paced body completes and no timeout is taken for a cut, so its body is small and +# its pace is fast enough to finish in seconds, slow enough to be seen at the gate. +CONTROL_BODY = 2 << 20 +CONTROL_SEED_PART = CONTROL_BODY // SEED_PARTS +CONTROL_RATE = 512 << 10 +CONTROL_MIN_LEFT_S = 1 +NO_SIGNAL_TIMEOUT_S = 60 +# The multipart cases use the `*_mp` disks, whose part size is the smallest the object store accepts: a body over two +# parts is multipart and the claim bound is a full part (parts go out in parallel and the last one is shorter). +CUT_PART = 5 << 20 +MULTIPART_BODY = 12 << 20 +MULTIPART_SEED_PART = MULTIPART_BODY // SEED_PARTS + +FULL_MATRIX = os.environ.get("CAS_CUT_FULL_MATRIX") == "1" + + +def matrix(default, full): + """The parameter list of a cut-upload test: `default` in CI, `full` when `CAS_CUT_FULL_MATRIX=1`.""" + return full if FULL_MATRIX else default + + +def create_large_body_table(instance, name, staging, replicated=False): + """A table whose data is one incompressible `String` column in a `Wide` part, so that a part of + `insert_large_body` has one body of its own.""" + engine = "ReplicatedMergeTree('/clickhouse/tables/{}', '{{replica}}')".format(name) if replicated else "MergeTree" + instance.query( + "CREATE TABLE {} (id UInt64, payload String CODEC(NONE)) ENGINE = {} ORDER BY id " + "SETTINGS storage_policy = '{}', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, " + "min_bytes_for_full_part_storage = 0".format(name, engine, CUT_POLICY[staging])) + + +def insert_large_body(instance, name, row_id, size=CUT_BODY): + """One part holding one row with `size` random bytes.""" + instance.query("INSERT INTO {} SELECT {}, randomString({})".format(name, row_id, size), + settings={"async_insert": 0}, timeout=120) + + +def seed_mergeable_parts(instance, name, parts=SEED_PARTS, size=SEED_PART): + """Stops merges of `name` and inserts `parts` equal parts, so that the merge selector takes all of them at once + after `SYSTEM START MERGES`. The merged column body is `parts * size` bytes.""" + instance.query("SYSTEM STOP MERGES {}".format(name)) + for row_id in range(1, parts + 1): + insert_large_body(instance, name, row_id, size=size) + + +def payload_digest(instance, name): + return instance.query("SELECT count(), sum(cityHash64(id, payload)) FROM {}".format(name)).strip() + + +def _s3_url(pool, key): + return "http://s3proxy:11121/test/{}/{}".format(pool, key) + + +def _s3_function(pool, key): + return "s3('{}', 'clickhouse', 'clickhouse', 'RawBLOB', 'x String')".format(_s3_url(pool, key)) + + +# The self-tests only need some bytes at the gate; the paced read of a sender that writes at full speed is slow to start. +SELFTEST_GATE_BYTES = 64 << 10 + + +def test_proxy_paces_one_body(node_cut): + """The proxy claims one matching body and then disarms: a second matching upload passes at once, while the claimed + body is still being read at the armed rate. The order is read from the proxy's own records.""" + size = 1 << 20 + claimed_size = 8 << 20 + rate = 256 << 10 + control_call(cluster.proxy_url, "/config", {"trace": True, "trace_path_substring": "/test/selftest_paced/bystander"}) + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_paced/", 512 << 10, rate_bytes_per_s=rate) + request = node_cut.get_query_request( + "INSERT INTO FUNCTION {} SELECT randomString({})".format(_s3_function("selftest_paced", "claimed.bin"), claimed_size), + timeout=120) + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES, min_left_s=20) + assert record["method"] == "PUT" and record["key"] == "/test/selftest_paced/claimed.bin", record + assert record["content_length"] == claimed_size and record["upload_id"] is None, record + + # The bystander matches the armed prefix and size: it passes only if the mode disarmed after the claim. + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString({})".format( + _s3_function("selftest_paced", "bystander.bin"), size)) + + def bystander_done(): + stats = _stats() + done = [r for r in stats["trace"] if r["method"] == "PUT" and r["path"] == "/test/selftest_paced/bystander.bin" + and r["t_done_mono_ms"] is not None] + return (done, stats) if done else None + + bystander, stats = _wait_until(bystander_done, timeout=60) + assert len(bystander) == 1 and bystander[0]["status"] == 200, bystander + assert not [e for e in stats["paced_trace"] if e["event"] == "ended"], stats["paced_trace"] + assert {e["request_id"] for e in stats["paced_trace"]} == {request_id}, stats["paced_trace"] + + release_pace(cluster.proxy_url, record) + ended = wait_complete(cluster.proxy_url, record, timeout_s=60) + assert bystander[0]["t_done_mono_ms"] < ended["t_ended_mono_ms"], \ + "the bystander finished only after the claimed body: {} {}".format(bystander, ended) + request.get_answer() + for key, expected in (("claimed.bin", claimed_size), ("bystander.bin", size)): + assert node_cut.query("SELECT length(x) FROM {}".format(_s3_function("selftest_paced", key))).strip() == str(expected) + assert len({e["request_id"] for e in _stats()["paced_trace"]}) == 1 + + +def test_proxy_holds_a_get_after_its_headers(node_cut): + """`hold_get` sends the headers of the first `GET`, waits for the release and then sends half of the body.""" + size = 1 << 20 + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString({})".format(_s3_function("selftest_get", "o.bin"), size)) + control_call(cluster.proxy_url, "/config", {"hold_get": {"prefix": "/test/selftest_get/"}}) + request = node_cut.get_query_request( + "SELECT length(x) FROM {} SETTINGS s3_max_get_rps = 0, s3_retry_attempts = 1".format( + _s3_function("selftest_get", "o.bin")), timeout=60) + held = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "waiting"), None), timeout=30) + # The first `GET` may be a ranged read, so its body can be shorter than the object. + assert held["key"] == "/test/selftest_get/o.bin" and 0 < held["content_length"] <= size, held + assert held["t_release_mono_ms"] is None, held + control_call(cluster.proxy_url, "/release_get", {"id": held["id"]}) + released = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "truncated"), None), timeout=30) + assert released["t_release_mono_ms"] >= held["t_headers_mono_ms"], released + # The client may serve the query from another read or retry this one: the mode disarmed itself. + _wait_until(lambda: request.process.poll() is not None, timeout=60) + + +def test_proxy_fails_one_abort(node_cut): + """`fail_abort` answers the first `DELETE ?uploadId=` of the key with 503 and forwards the second.""" + key = "/test/selftest_abort/k.bin" + control_call(cluster.proxy_url, "/config", {"fail_abort": {"key": key, "upload_id": "u1", "remaining": 1}}) + url = "http://s3proxy:11121{}?uploadId=u1".format(key) + statuses = [node_cut.exec_in_container( + ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "DELETE", url]).strip() for _ in range(2)] + other = node_cut.exec_in_container( + ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "DELETE", url.replace("u1", "u2")]).strip() + assert statuses[0] == "503" and statuses[1] != "503" and other != "503", (statuses, other) + trace = _stats()["abort_trace"] + assert [(r["upload_id"], r["injected"], r["status"]) for r in trace] == [("u1", True, 503), ("u1", False, int(statuses[1]))], trace + + +# A client for the cut self-tests, run next to the proxy: it sends one large `PUT` as fast as the connection takes it. +# `fin` and `rst` wait for a line on stdin and then end the process, like a server that stops its upload: the kernel +# closes the socket with a FIN queued behind the bytes it still holds, or with an RST that drops them. `complete` +# sends the whole body. +PUT_CLIENT = r""" +import os, socket, struct, sys, threading +mode, size, key = sys.argv[1], int(sys.argv[2]), sys.argv[3] +sock = socket.create_connection(("127.0.0.1", 11121)) +sock.sendall(("PUT %s HTTP/1.1\r\nHost: s3proxy:11121\r\nContent-Length: %d\r\n\r\n" % (key, size)).encode()) +print("connected", flush=True) +body = b"x" * size +if mode == "complete": + sock.sendall(body) + print("sent", flush=True) + print(sock.recv(4096).split(b"\r\n")[0].decode(), flush=True) +else: + threading.Thread(target=lambda: sock.sendall(body), daemon=True).start() + sys.stdin.readline() + if mode == "rst": + sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + os._exit(0) +""" +# Over what the kernels of both ends queue for a sender (about 2.3 MB were measured), so that the sender is still +# writing when it ends. +SELFTEST_CUT_SIZE = 8 << 20 + + +def start_put_client(mode, key): + return subprocess.Popen( + cluster.base_cmd + ["exec", "-T", "s3proxy", "python3", "-c", PUT_CLIENT, mode, str(SELFTEST_CUT_SIZE), "/test/selftest_cut/" + key], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + + +def close_put_client(client): + client.stdin.write("close\n") + client.stdin.flush() + client.wait(timeout=30) + + +@pytest.mark.parametrize("mode", matrix(["fin"], ["fin", "rst"])) +def test_proxy_sees_a_cut_body(node_cut, mode): + """A sender that ends its process mid-body is seen as `peer_eof` (FIN) or `peer_reset` (RST) with fewer bytes than + `Content-Length`, promptly after `release_pace`. Without the release the queued bytes drain at the paced rate first + (measured once with a 24 MiB body: 60 s after a FIN, so the tests always release).""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client(mode, "{}.bin".format(mode)) + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + before_close = now_mono_ms(cluster.proxy_url) + close_put_client(client) + release_pace(cluster.proxy_url, record) + ended = wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=before_close) + finally: + if client.poll() is None: + client.kill() + assert record_of(cluster.proxy_url, record)["forwarded"] is False, "a short body must not be forwarded: {}".format( + record_of(cluster.proxy_url, record)) + delay = (ended["t_ended_mono_ms"] - before_close) / 1000.0 + expected = "peer_eof" if mode == "fin" else "peer_reset" + record_measurement("selftest_cut_" + mode, delay_s=round(delay, 1), outcome=ended["outcome"], + received=ended["received"], received_at_close=record["received"]) + assert ended["outcome"] == expected, ended + assert delay < 15, "a released pace must see the close quickly: {}".format(ended) + + +def test_proxy_sees_a_complete_body_after_release(node_cut): + """The reverse control: a sender that is not cut finishes the body at full speed after `release_pace`, and + `wait_cut` rejects it while `wait_complete` accepts it.""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("complete", "complete.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + release_pace(cluster.proxy_url, record) + with pytest.raises(AssertionError, match="not cut"): + wait_cut(cluster.proxy_url, record, 30) + wait_complete(cluster.proxy_url, record, 5) + _wait_until(lambda: record_of(cluster.proxy_url, record)["forwarded"], timeout=10) + finally: + client.kill() + + +def test_wait_cut_rejects_a_cut_before_the_signal(node_cut): + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("rst", "early.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + close_put_client(client) + after_close = now_mono_ms(cluster.proxy_url) + release_pace(cluster.proxy_url, record) + with pytest.raises(AssertionError, match="before the signal"): + wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=after_close + 1000) + finally: + if client.poll() is None: + client.kill() + + +def test_wait_cut_bounds_the_time_from_the_signal_statement(node_cut): + """The deadline counts from the clock read before the signal statement, not from when the wait starts.""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("rst", "late.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + before_close = now_mono_ms(cluster.proxy_url) + close_put_client(client) + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=before_close, signal_mono_ms=before_close) + with pytest.raises(AssertionError, match="after the signal statement was issued"): + wait_cut(cluster.proxy_url, record, 30, signal_mono_ms=before_close - 60 * 1000) + finally: + if client.poll() is None: + client.kill() + + +def test_paced_body_claims_only_the_bodies_it_is_armed_for(node_cut): + """A lower bound of 0 is refused. Under the armed prefix a small `PUT`, a large `PUT` with a query (`?tagging`) and + a large `PUT` with `x-amz-copy-source` are not claimed; the control is that a plain large `PUT` is.""" + with pytest.raises(AssertionError): + arm_paced_body(cluster.proxy_url, "/test/selftest_claim/", 0) + with pytest.raises(urllib.error.HTTPError): + control_call(cluster.proxy_url, "/config", {"paced_body": {"prefix": "/test/selftest_claim/", "min_content_length": 0}}) + arm_paced_body(cluster.proxy_url, "/test/selftest_claim/", 1 << 20, rate_bytes_per_s=1 << 20) + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString(1000)".format(_s3_function("selftest_claim", "small.bin"))) + node_cut.exec_in_container(["bash", "-c", "head -c 2000000 /dev/zero > /tmp/claim_body.bin"]) + + def put(path, *headers): + # Unsigned: the store refuses it, which does not matter; the proxy decides on the request line and headers. + node_cut.exec_in_container(["curl", "-s", "--max-time", "60", "-o", "/dev/null", "-X", "PUT", "--data-binary", "@/tmp/claim_body.bin", + *[a for h in headers for a in ("-H", h)], "http://s3proxy:11121/test/selftest_claim/" + path]) + + put("tagged.bin?tagging") + put("copied.bin", "x-amz-copy-source: /test/selftest_claim/small.bin") + assert _stats()["paced_trace"] == [] + put("plain.bin") + claimed = _wait_until(lambda: [r for r in paced_requests(cluster.proxy_url) if r["key"] == "/test/selftest_claim/plain.bin"], + timeout=30) + assert claimed[0]["content_length"] == 2000000, claimed + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_merge_without_a_stop_completes_paced(node_cut, staging): + """No-signal control of a merge: the paced body is neither cut nor timed out, the merge commits and the data is + the sources' data.""" + name = "ctl_merge_" + staging + create_large_body_table(node_cut, name, staging) + merge, record, sources, digest = start_paced_merge( + node_cut, name, staging, part_size=CONTROL_SEED_PART, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + _wait_until(lambda: part_names(node_cut, name, active_only=True) == [merge], timeout=NO_SIGNAL_TIMEOUT_S) + assert payload_digest(node_cut, name) == digest + + +def test_mutation_without_a_stop_completes_paced(node_cut): + """No-signal control of a mutation (local staging): the paced body of the rewritten column completes, the + mutation finishes and the data is the mutated data.""" + name = "ctl_mutation" + create_large_body_table(node_cut, name, "local") + source, result_part, record, original, mutated = start_paced_mutation( + node_cut, name, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=NO_SIGNAL_TIMEOUT_S) + assert payload_digest(node_cut, name) == mutated + + +CUT_DISK = {"local": "disk_cas_cut", "s3": "disk_cas_cut_s3", "local_mp": "disk_cas_cut_mp", "s3_mp": "disk_cas_cut_s3_mp"} +# An upper bound: a stopped body is cut within about a second. +CUT_DEADLINE_S = 10 +# The cases whose signal is a synchronous statement (`DROP TABLE ... SYNC`, `DETACH TABLE ... SYNC`, +# `KILL QUERY ... SYNC`) free the pace only after the statement has returned. That takes 5 to 6 s on the development +# machine, so the bound leaves room for a runner that is twice as slow. The other cases cut within 1 s locally and +# keep `CUT_DEADLINE_S`. +SYNC_CUT_DEADLINE_S = 20 +RO_DISKS_CONFIG = "/etc/clickhouse-server/cut_ro_disks.xml" + + +def list_disk_dir(instance, disk, path): + """Entries of `path` as the pool's read-only window lists them: a part's files are refs, not files of a local + directory. An absent directory lists as empty; any other error fails the test.""" + return list_disk_dir_or_absent(instance, disk, path) or [] + + +def list_disk_dir_or_absent(instance, disk, path): + """Like `list_disk_dir`, but None for an absent directory, so that "absent" and "present and empty" differ.""" + instance.copy_file_to_container(os.path.join(os.path.dirname(__file__), "configs", "cut_ro_disks.xml"), RO_DISKS_CONFIG) + out = instance.exec_in_container( + ["bash", "-c", "clickhouse disks -C {} --disk {} --save-logs --query {} 2>&1; true".format( + RO_DISKS_CONFIG, shlex.quote(disk + "_ro"), shlex.quote("list '{}'".format(path)))]) + if "Code: 107" in out or "Code: 479" in out: + return None + assert "Code:" not in out, out + return out.split() + + +def fsck(instance, disk): + """`SYSTEM CAS FSCK ` as a dict of column -> value.""" + out = instance.exec_in_container( + ["bash", "-c", "clickhouse client --format TSVWithNames --query {}".format(shlex.quote("SYSTEM CAS FSCK '{}'".format(disk)))] + ).splitlines() + summary = dict(zip(out[0].split("\t"), out[1].split("\t"))) + assert "dangling" in summary, out + return summary + + +def table_namespace(instance, name): + data_path = instance.query("SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() + first = data_path.splitlines()[0] + return first[first.index("store/"):] + + +def part_names(instance, name, active_only=False): + return instance.query("SELECT name FROM system.parts WHERE database = 'default' AND table = '{}'{} ORDER BY name".format( + name, " AND active" if active_only else "")).split() + + +def assert_namespace_holds_only_parts(instance, name, staging, namespace): + """The table's directory lists the parts the table knows (any state) and nothing else; `detached/` and `moving/` + are empty. The listing has a positive control: it must show the active parts.""" + disk = CUT_DISK[staging] + entries = list_disk_dir(instance, disk, namespace) + known = set(part_names(instance, name)) + assert set(part_names(instance, name, active_only=True)) <= set(entries), ("the listing does not show the active parts", entries) + extra = {e for e in set(entries) - known - {"detached", "moving", "format_version.txt"} if not re.fullmatch(r"mutation_\d+\.txt", e)} + assert not extra, ("extra entries in the table namespace", sorted(extra), entries) + for sub in ("detached", "moving"): + assert list_disk_dir(instance, disk, namespace + sub) == [], sub + assert instance.query("SELECT count() FROM system.detached_parts WHERE database = 'default' AND table = '{}'".format(name)).strip() == "0" + assert fsck(instance, disk)["dangling"] == "0" + + +def merges_of(instance, name): + return int(instance.query("SELECT count() FROM system.merges WHERE database = 'default' AND table = '{}'".format(name))) + + +def timed_cut(instance, name, record, signal, rows=merges_of, deadline_s=CUT_DEADLINE_S): + """Runs `signal`, which may return a waiter for a statement that is still running (waited for, so the stop flag is + set), then releases the pace, requires the body to be cut within the deadline and the task to leave + its system table (`rows` counts the table's rows there, merges by default). Returns the seconds from the signal to + the cut (proxy clock) and to the row leaving that table, the outcome and the bytes received.""" + t_proxy = now_mono_ms(cluster.proxy_url) + t_signal = time.monotonic() + waiter = signal() + statement = waiter(STATEMENT_RETURN_S) if callable(waiter) else None + release_pace(cluster.proxy_url, record) + ended = wait_cut(cluster.proxy_url, record, deadline_s, not_before_mono_ms=t_proxy, signal_mono_ms=t_proxy) + _wait_until(lambda: rows(instance, name) == 0, timeout=deadline_s) + result = ((ended["t_ended_mono_ms"] - t_proxy) / 1000.0, time.monotonic() - t_signal, ended["outcome"], ended["received"]) + record_measurement(name, cut_s=round(result[0], 1), row_gone_s=round(result[1], 1), outcome=result[2], received=result[3], + statement_s=None if statement is None else round(statement[0], 1)) + return result + + +def record_measurement(case, **values): + """Logs a measurement for the reader of a run.""" + logging.info("MEASURED %s %s", case, values) + + +def part_blocks(part): + """(min block, max block) of a part name such as `all_0_4_1`.""" + fields = part.split("_") + return int(fields[1]), int(fields[2]) + + +def start_paced_merge(instance, name, staging, part_size=SEED_PART, min_body=CUT_MIN_BODY, + rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """Seeds mergeable parts, arms the proxy, starts the merge and waits at the gate. Returns the result part name, + the gate record, the source part names and the data digest. The selector may leave the newest part out of the + range (a replicated table does), so the range is read from `system.merges` and checked against the sources.""" + seed_mergeable_parts(instance, name, size=part_size) + sources = part_names(instance, name, active_only=True) + digest = payload_digest(instance, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], min_body, rate_bytes_per_s) + instance.query("SYSTEM START MERGES {}".format(name)) + merge = _wait_until(lambda: instance.query("SELECT result_part_name FROM system.merges WHERE table = '{}'".format(name)).strip(), + timeout=60) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert merges_of(instance, name) == 1 + first, last = part_blocks(merge) + lowest = min(part_blocks(source)[0] for source in sources) + highest = max(part_blocks(source)[1] for source in sources) + assert lowest <= first and last <= highest, (merge, sources) + assert last > first, merge + if not instance.query("SELECT engine FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).startswith("Replicated"): + # A plain table merges every source: the result is deterministic. + assert merge == "all_{}_{}_1".format(lowest, highest), (merge, sources) + return merge, record, sources, digest + + +def merge_result_active(instance, name, merge): + """A part that covers `merge` is active: the merge completed, or was followed by a wider one.""" + first, last = part_blocks(merge) + return int(instance.query("SELECT count() FROM system.parts WHERE database = 'default' AND table = '{}' AND active " + "AND min_block_number <= {} AND max_block_number >= {}".format(name, first, last))) == 1 + + +def queue_entry(instance, name): + return instance.query("SELECT node_name, num_tries FROM system.replication_queue WHERE database = 'default' AND table = '{}' " + "AND type = 'MERGE_PARTS'".format(name)).strip() + + +@pytest.mark.parametrize("engine, staging", matrix( + [("mergetree", "local"), ("replicated", "s3")], + [("mergetree", "local"), ("mergetree", "s3"), ("replicated", "local"), ("replicated", "s3")])) +def test_stop_merges_cuts_the_merge_upload(node_cut, engine, staging): + name = "stop_{}_{}".format(engine, staging) + replicated = engine == "replicated" + create_large_body_table(node_cut, name, staging, replicated) + merge, record, sources, digest = start_paced_merge(node_cut, name, staging) + queue = queue_entry(node_cut, name) if replicated else None + assert not replicated or queue, "no MERGE_PARTS entry while the merge runs" + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + # While the stop holds: no merge starts, the queue entry is the same and was not tried again. + assert_quiet(node_cut, name) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + if replicated: + assert queue_entry(node_cut, name) == queue, (queue, queue_entry(node_cut, name)) + record_measurement("stop_" + engine + "_" + staging + "_queue", before=queue, held=queue_entry(node_cut, name)) + namespace = table_namespace(node_cut, name) + assert_namespace_holds_only_parts(node_cut, name, staging, namespace) + node_cut.query("SYSTEM START MERGES {}".format(name)) + _wait_until(lambda: merge_result_active(node_cut, name, merge), timeout=120, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == digest + assert_namespace_holds_only_parts(node_cut, name, staging, namespace) + + +MUTATION_SQL = "ALTER TABLE {} UPDATE payload = reverse(payload) WHERE 1" +MUTATED_DIGEST_SQL = "SELECT count(), sum(cityHash64(id, reverse(payload))) FROM {}" +# How long a stopped task must stay unselected. The full matrix keeps the 10 s that match the idle sleep of a +# background assignee; the default set waits half of it. +QUIET_S = 10 if FULL_MATRIX else 5 +# A statement that waits for the cut task: measured at 0.2 to 0.6 s, so this bound has a wide margin. +STATEMENT_RETURN_S = 60 + + +def start_paced_mutation(instance, name, staging="local", size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, + min_left_s=5): + """One part with one large body, a mutation that rewrites it, the proxy armed, the mutation at the gate. Returns + the part name, the gate record, the digest of the original data and the digest the mutation produces.""" + insert_large_body(instance, name, 1, size=size) + source = part_names(instance, name, active_only=True) + assert len(source) == 1, source + original = payload_digest(instance, name) + mutated = instance.query(MUTATED_DIGEST_SQL.format(name)).strip() + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + instance.query(MUTATION_SQL.format(name), settings={"mutations_sync": 0}) + probe = "SELECT result_part_name FROM system.merges WHERE database = 'default' AND table = '{}' AND is_mutation".format(name) + result_part = _wait_until(lambda: instance.query(probe).strip(), timeout=60) + assert result_part.startswith(source[0] + "_"), (source, result_part) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert merges_of(instance, name) == 1 + return source[0], result_part, record, original, mutated + + +def assert_quiet(instance, name, rows=merges_of): + """No task of the table starts while the stop or the kill holds. `rows` counts the table's rows in the system + table of the task.""" + for _ in range(2 * QUIET_S): + assert rows(instance, name) == 0 + time.sleep(0.5) + + +# Threads of `in_thread`; `clean_state` joins them before the tables are dropped. +RUNNING_STATEMENTS = [] + + +def in_thread(statement): + """Runs `statement` in a thread. Returns a function that waits for it and returns the seconds it took.""" + outcome = {} + + def run(): + begin = time.monotonic() + try: + statement() + except Exception as error: # reported by the waiter, in the test's thread + outcome["error"] = error + outcome["seconds"] = time.monotonic() - begin + + thread = threading.Thread(target=run, daemon=True) + RUNNING_STATEMENTS.append(thread) + thread.start() + + def wait(timeout_s): + thread.join(timeout_s) + assert not thread.is_alive(), "the statement did not return within {} s".format(timeout_s) + assert "error" not in outcome, outcome["error"] + return (outcome["seconds"],) + + return wait + + +def mutation_rows(instance, name): + return int(instance.query("SELECT count() FROM system.mutations WHERE database = 'default' AND table = '{}'".format(name))) + + +def test_stop_then_start_resumes_a_registered_mutation(node_cut): + name = "stop_mutation_local" + create_large_body_table(node_cut, name, "local") + source, result_part, record, original, mutated = start_paced_mutation(node_cut, name) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + assert_quiet(node_cut, name) + assert part_names(node_cut, name, active_only=True) == [source] + assert payload_digest(node_cut, name) == original + assert node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "0" + namespace = table_namespace(node_cut, name) + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + node_cut.query("SYSTEM START MERGES {}".format(name)) + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=120) + assert part_names(node_cut, name, active_only=True) == [result_part] + assert payload_digest(node_cut, name) == mutated + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + + +@pytest.mark.parametrize("engine, staging", matrix( + [("replicated", "local")], + [("mergetree", "local"), ("replicated", "local"), ("mergetree", "s3"), ("replicated", "s3")])) +def test_kill_mutation_cuts_the_upload(node_cut, engine, staging): + name = "kill_mutation_{}_{}".format(engine, staging) + replicated = engine == "replicated" + create_large_body_table(node_cut, name, staging, replicated) + source, result_part, record, original, mutated = start_paced_mutation(node_cut, name, staging) + kill = "KILL MUTATION WHERE database = 'default' AND table = '{}'".format(name) + timed_cut(node_cut, name, record, lambda: node_cut.query(kill)) + _wait_until(lambda: mutation_rows(node_cut, name) == 0, timeout=60) + if replicated: + # The entry that survives the kill runs once more with no command left, which shows as a merge row, so the + # quiet period starts when it has left the queue. + _wait_until(lambda: node_cut.query("SELECT count() FROM system.replication_queue WHERE database = 'default' " + "AND table = '{}' AND type = 'MUTATE_PART'".format(name)).strip() == "0", timeout=60, + describe=lambda: node_cut.query("SELECT * FROM system.replication_queue WHERE table = '{}' FORMAT Vertical".format(name))) + assert_quiet(node_cut, name) + active = part_names(node_cut, name, active_only=True) + # A replicated entry that survives the kill runs again with no command left and may leave the part one data + # version higher with the same data: the digest is the check, the name is recorded. + assert active == [source] or (replicated and len(active) == 1 and active[0].startswith(source + "_")), active + record_measurement(name + "_part", source=source, active=active) + assert payload_digest(node_cut, name) == original + assert_namespace_holds_only_parts(node_cut, name, staging, table_namespace(node_cut, name)) + + +def store_request(method, key, query=""): + """A hand-signed (SigV4) request sent to the object store directly, not through the proxy. `key` is a proxy path + such as `/test//blobs/`. Returns `(status, body)`; an error status is returned, not raised.""" + bucket, _, object_key = key.lstrip("/").partition("/") + host = "{}:{}".format(cluster.rustfs_ip, cluster.rustfs_port) + now = datetime.datetime.now(datetime.timezone.utc) + amz_date, date = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d") + payload_hash = hashlib.sha256(b"").hexdigest() + path = "/" + bucket + ("/" + urllib.parse.quote(object_key, safe="/-_.~") if object_key and not query else "") + headers = "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n".format(host, payload_hash, amz_date) + signed = "host;x-amz-content-sha256;x-amz-date" + canonical = "\n".join([method, path, query, headers, signed, payload_hash]) + scope = "{}/us-east-1/s3/aws4_request".format(date) + to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()]) + + def mac(key_bytes, message): + return hmac.new(key_bytes, message.encode(), hashlib.sha256).digest() + + signing_key = mac(mac(mac(mac(("AWS4" + cluster.rustfs_secret_key).encode(), date), "us-east-1"), "s3"), "aws4_request") + request = urllib.request.Request("http://{}{}{}".format(host, path, "?" + query if query else ""), method=method, headers={ + "x-amz-date": amz_date, "x-amz-content-sha256": payload_hash, + "Authorization": "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}".format( + cluster.rustfs_access_key, scope, signed, hmac.new(signing_key, to_sign.encode(), hashlib.sha256).hexdigest())}) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return response.status, response.read() + except urllib.error.HTTPError as error: + return error.code, error.read() + + +def open_multipart_uploads(key): + """`(key, upload id)` of every multipart upload the store lists for `key` (a proxy path), by a signed + `ListMultipartUploads`. An error status fails the test.""" + bucket, _, object_key = key.lstrip("/").partition("/") + status, body = store_request("GET", "/" + bucket, "prefix={}&uploads=".format(urllib.parse.quote(object_key, safe="-_.~"))) + assert status == 200, "ListMultipartUploads answered {}: {}".format(status, body[:300]) + uploads = [] + for upload in ElementTree.fromstring(body).iter(): + if upload.tag.rpartition("}")[2] == "Upload": + fields = {child.tag.rpartition("}")[2]: child.text for child in upload} + uploads.append((fields["Key"], fields["UploadId"])) + return uploads + + +def arm_failed_abort(record): + """The proxy answers the first abort of the claimed multipart upload with 503 and forwards the retry. The listing + must show the upload now: that is the control for the listing that later shows it gone.""" + assert record["upload_id"], "the claimed body is not a part of a multipart upload: {}".format(record) + object_key = record["key"].partition("/")[2].partition("/")[2] + assert (object_key, record["upload_id"]) in open_multipart_uploads(record["key"]), record + control_call(cluster.proxy_url, "/config", {"fail_abort": {"key": record["key"], "upload_id": record["upload_id"], "remaining": 1}}) + + +def assert_abort_retried_and_gone(record): + """The abort `DELETE` of the upload failed once (injected 503) and succeeded on retry, and the store no longer + lists the upload.""" + def attempts(): + trace = [r for r in _stats()["abort_trace"] if r["key"] == record["key"] and r["upload_id"] == record["upload_id"]] + # The proxy records a `DELETE` before it forwards it, so the retry's status is set a moment later. + return trace if len(trace) >= 2 and trace[1]["status"] is not None else None + + trace = _wait_until(attempts, timeout=30, describe=lambda: _stats()["abort_trace"]) + assert [(r["injected"], r["status"]) for r in trace][0] == (True, 503), trace + assert not trace[1]["injected"] and 200 <= trace[1]["status"] < 300, trace + _wait_until(lambda: not open_multipart_uploads(record["key"]), timeout=30, describe=lambda: open_multipart_uploads(record["key"])) + assert not any(upload_id == record["upload_id"] for _, upload_id in open_multipart_uploads(record["key"])) + + +def test_killed_insert_retries_the_multipart_abort(node_cut): + name = "abort_insert" + create_large_body_table(node_cut, name, "local_mp") + insert_large_body(node_cut, name, 0, size=1 << 20) + digest = payload_digest(node_cut, name) + sources = part_names(node_cut, name, active_only=True) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX["local_mp"], CUT_PART) + query_id = name + "_insert" + request = node_cut.get_query_request( + "INSERT INTO {} SELECT 1, randomString({})".format(name, MULTIPART_BODY), query_id=query_id, + settings={"async_insert": 0}, timeout=NO_SIGNAL_TIMEOUT_S) + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + assert node_cut.query("SELECT count() FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1" + arm_failed_abort(record) + t_proxy = now_mono_ms(cluster.proxy_url) + node_cut.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id), timeout=STATEMENT_RETURN_S) + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, SYNC_CUT_DEADLINE_S, not_before_mono_ms=t_proxy, signal_mono_ms=t_proxy) + assert_abort_retried_and_gone(record) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +def test_stopped_merge_retries_the_multipart_abort(node_cut): + name = "abort_merge" + create_large_body_table(node_cut, name, "s3_mp") + # The merged body is over two parts of the `*_mp` disk, so it goes out as a multipart upload. + merge, record, sources, digest = start_paced_merge(node_cut, name, "s3_mp", part_size=MULTIPART_SEED_PART, min_body=CUT_PART) + arm_failed_abort(record) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + assert_abort_retried_and_gone(record) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +def queue_state(instance, name, result_part): + """The one queue entry that creates `result_part`, as a dict of the columns that a failure changes.""" + rows = instance.query( + "SELECT is_currently_executing, num_tries, num_postponed, last_exception, postpone_reason FROM system.replication_queue " + "WHERE database = 'default' AND table = '{}' AND type = 'MERGE_PARTS' AND new_part_name = '{}' FORMAT JSONEachRow".format( + name, result_part)).splitlines() + assert len(rows) == 1, rows + return json.loads(rows[0]) + + +def test_merge_stopped_during_a_failing_read_ends_aborted(node_cut): + """A source read that is held after its headers and then truncated fails while the merge is already stopped. The + cancellation must win over the read error. The check that carries this is `last_exception`: it must be empty or + the cancellation. `num_tries` unchanged is only the no-backoff half and holds with the read error too. + + What the trace does not prove: that the held `GET` is a read of this merge. The proxy is armed after the table is + filled and its digest read, and nothing else reads that prefix then, so the first `GET` under `blobs/` after + `SYSTEM START MERGES` can only be the merge's; the key is not mapped to a source part.""" + name = "read_order" + create_large_body_table(node_cut, name, "local", replicated=True) + seed_mergeable_parts(node_cut, name) + sources = part_names(node_cut, name, active_only=True) + digest = payload_digest(node_cut, name) + control_call(cluster.proxy_url, "/config", {"hold_get": {"prefix": CUT_PREFIX["local"]}}) + node_cut.query("SYSTEM START MERGES {}".format(name)) + held = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "waiting"), None), timeout=60) + assert held["key"].startswith(CUT_PREFIX["local"]), held + result_part = _wait_until(lambda: node_cut.query("SELECT result_part_name FROM system.merges WHERE table = '{}'".format(name)).strip(), + timeout=60) + assert merges_of(node_cut, name) == 1 + before = queue_state(node_cut, name, result_part) + assert before["is_currently_executing"] == 1, before + node_cut.query("SYSTEM STOP MERGES {}".format(name)) + control_call(cluster.proxy_url, "/release_get", {"id": held["id"]}) + _wait_until(lambda: merges_of(node_cut, name) == 0, timeout=CUT_DEADLINE_S) + # The entry records the outcome of the attempt when the executing flag drops. + after = _wait_until(lambda: (lambda state: state if state["is_currently_executing"] == 0 else None)(queue_state(node_cut, name, result_part)), + timeout=CUT_DEADLINE_S) + record_measurement("read_order_queue", before=before, after=after, held=held) + assert after["last_exception"] == "" or "Cancelled merging parts" in after["last_exception"], str(after)[:400] + assert after["num_tries"] == before["num_tries"], (before, after) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_drop_table_cuts_the_merge_upload(node_cut, staging): + name = "drop_" + staging + create_large_body_table(node_cut, name, staging) + merge, record, sources, digest = start_paced_merge(node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + + +def test_detach_table_cuts_the_merge_upload(node_cut): + name = "detach_replicated_local" + create_large_body_table(node_cut, name, "local", replicated=True) + merge, record, sources, digest = start_paced_merge(node_cut, name, "local") + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DETACH TABLE {} SYNC".format(name))), deadline_s=SYNC_CUT_DEADLINE_S) + assert node_cut.query("SELECT count() FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() == "0" + node_cut.query("ATTACH TABLE {}".format(name)) + assert payload_digest(node_cut, name) == digest + _wait_until(lambda: merge_result_active(node_cut, name, merge), timeout=180, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == digest + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + + +@pytest.mark.parametrize("task, staging", matrix( + [("merge", "local"), ("mutation", "s3")], + [("merge", "local"), ("merge", "s3"), ("mutation", "local"), ("mutation", "s3")])) +def test_sigterm_during_a_background_task_upload_is_orderly(node_cut, task, staging): + """One SIGTERM to the exact server PID while a background merge or mutation sends its paced body, with no client + connected. The process must exit by itself within 30 s; the task finishes after the restart.""" + name = "sigterm_{}_{}".format(task, staging) + create_large_body_table(node_cut, name, staging) + if task == "merge": + target, record, _, digest = start_paced_merge(node_cut, name, staging) + expected_digest = digest + else: + source, target, record, digest, expected_digest = start_paced_mutation(node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_{}_{}".format(task, staging), record) + if task == "merge": + _wait_until(lambda: merge_result_active(node_cut, name, target), timeout=180, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == expected_digest + else: + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=180) + assert part_names(node_cut, name, active_only=True) == [target] + assert payload_digest(node_cut, name) == expected_digest + + +# Fetches and moves onto the pool. A fetch is a byte fetch from `node_src` (local disk, so the sender offers no relink) +# into a replica on a CAS pool; a move is a TTL move from the local volume to the CAS volume of `cas_move`. Nothing +# paces either one except the proxy. +MOVE_POLICY = {"local": "cas_move", "s3": "cas_move_s3"} +# The cold volumes do not take a part at insert (`perform_ttl_move_on_insert` 0), so rows that are already expired +# still land on the local volume and only the move task takes them away. +MOVE_TTL_S = 3 +WIDE_SETTINGS = "min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, min_bytes_for_full_part_storage = 0" + + +def fetches_of(instance, name): + return int(instance.query("SELECT count() FROM system.replicated_fetches WHERE database = 'default' AND table = '{}'".format(name))) + + +def moves_of(instance, name): + return int(instance.query("SELECT count() FROM system.moves WHERE database = 'default' AND table = '{}'".format(name))) + + +def assert_cas_namespace(instance, staging, namespace, parts): + """The table's directory on the pool lists exactly `parts` (the part refs, in any state) and nothing else, so no + `tmp-fetch_` ref is left; `detached/` and `moving/` are empty and the pool has no dangling blob. A call with the + part present is the positive control of the listing.""" + disk = CUT_DISK[staging] + entries = list_disk_dir(instance, disk, namespace) + listed = sorted(set(entries) - {"detached", "moving", "format_version.txt"}) + assert listed == sorted(parts), ("the table namespace lists other entries than the parts", listed, entries) + for sub in ("detached", "moving"): + assert list_disk_dir(instance, disk, namespace + sub) == [], sub + assert fsck(instance, disk)["dangling"] == "0" + + +def start_paced_fetch(source, receiver, name, staging, size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """A replica on the `staging` pool of `receiver` with fetches stopped, one large part inserted on `source`, the + proxy armed, fetches started and the fetch waited for at the gate. Returns the part name, the gate record and the + data digest.""" + ddl = ("CREATE TABLE {} (id UInt64, payload String CODEC(NONE)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{}', " + "'{{replica}}') ORDER BY id SETTINGS {}") + source.query(ddl.format(name, name, WIDE_SETTINGS)) + receiver.query(ddl.format(name, name, WIDE_SETTINGS + ", storage_policy = '{}'".format(CUT_POLICY[staging]))) + receiver.query("SYSTEM STOP FETCHES {}".format(name)) + insert_large_body(source, name, 1, size=size) + part = part_names(source, name, active_only=True)[0] + digest = payload_digest(source, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + receiver.query("SYSTEM START FETCHES {}".format(name)) + _wait_until(lambda: fetches_of(receiver, name) == 1, timeout=60, describe=lambda: part_names(receiver, name)) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert fetches_of(receiver, name) == 1 + return part, record, digest + + +def assert_fetch_completes(source, receiver, name, staging, part, digest): + _wait_until(lambda: part_names(receiver, name, active_only=True) == [part], timeout=120, + describe=lambda: part_names(receiver, name)) + assert payload_digest(receiver, name) == digest + assert payload_digest(source, name) == digest + assert_cas_namespace(receiver, staging, table_namespace(receiver, name), [part]) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_fetch_without_a_stop_completes_paced(node_cut, node_src, staging): + """No-signal control of a fetch: the paced body is neither cut nor timed out and the part arrives whole.""" + name = "ctl_fetch_" + staging + part, record, digest = start_paced_fetch( + node_src, node_cut, name, staging, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + # The part directory exists on the pool only as a ref after the publish, so at the gate the listing is non-empty + # but holds no part: the absence assertions of `assert_cas_namespace` prove "no published temporary part" only. + in_flight = list_disk_dir(node_cut, CUT_DISK[staging], table_namespace(node_cut, name)) + assert in_flight == ["format_version.txt"], in_flight + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +FETCH_LIMIT_BODY = 6 << 20 +FETCH_LIMIT = 1 << 20 +# The throttler lets one second of the limit through at once, and the bound keeps a margin under the rest. +FETCH_LIMIT_MIN_S = 0.8 * (FETCH_LIMIT_BODY - FETCH_LIMIT) / FETCH_LIMIT + + +def timed_byte_fetch(source, receiver, name, staging, source_settings="", receiver_settings=""): + """One `FETCH_LIMIT_BODY` part fetched as bytes into the `staging` pool of `receiver`, not paced by the proxy. + Returns the seconds the fetch took by the receiver's `system.part_log`, so the time of the client, of the + replication queue and of the polling here is not in it.""" + ddl = ("CREATE TABLE {} (id UInt64, payload String CODEC(NONE)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{}', " + "'{{replica}}') ORDER BY id SETTINGS {}") + source.query(ddl.format(name, name, WIDE_SETTINGS + source_settings)) + receiver.query(ddl.format(name, name, WIDE_SETTINGS + ", storage_policy = '{}'".format(CUT_POLICY[staging]) + + receiver_settings)) + receiver.query("SYSTEM STOP FETCHES {}".format(name)) + insert_large_body(source, name, 1, size=FETCH_LIMIT_BODY) + part = part_names(source, name, active_only=True)[0] + digest = payload_digest(source, name) + receiver.query("SYSTEM START FETCHES {}".format(name)) + _wait_until(lambda: part_names(receiver, name, active_only=True) == [part], timeout=60, + describe=lambda: part_names(receiver, name)) + assert payload_digest(receiver, name) == digest + assert_cas_namespace(receiver, staging, table_namespace(receiver, name), [part]) + receiver.query("SYSTEM FLUSH LOGS part_log") + durations = receiver.query( + "SELECT duration_ms FROM system.part_log WHERE database = 'default' AND table = '{}' " + "AND event_type = 'DownloadPart' AND part_name = '{}' AND error = 0".format(name, part)).split() + assert len(durations) == 1, durations + return int(durations[0]) / 1000.0 + + +@pytest.mark.parametrize("limit, staging", matrix( + [("fetches", "local"), ("sends", "s3")], + [("fetches", "local"), ("fetches", "s3"), ("sends", "local"), ("sends", "s3")])) +def test_replication_bandwidth_limit_paces_a_byte_fetch(node_cut, node_src, limit, staging): + """`max_replicated_fetches_network_bandwidth` of the receiving table and `max_replicated_sends_network_bandwidth` + of the sending one pace a byte fetch into a CAS pool. The same fetch without the limit is the control.""" + name = "limit_{}_{}".format(limit, staging) + setting = ", max_replicated_{}_network_bandwidth = {}".format(limit, FETCH_LIMIT) + free_s = timed_byte_fetch(node_src, node_cut, name + "_free", staging) + limited_s = timed_byte_fetch( + node_src, node_cut, name, staging, + source_settings=setting if limit == "sends" else "", receiver_settings=setting if limit == "fetches" else "") + record_measurement(name, free_s=round(free_s, 1), limited_s=round(limited_s, 1)) + assert free_s < FETCH_LIMIT_MIN_S, "the control fetch is as slow as a paced one" + assert limited_s >= FETCH_LIMIT_MIN_S + + +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_stop_fetches_cuts_the_fetch_upload(node_cut, node_src, staging): + name = "stop_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP FETCHES {}".format(name)), rows=fetches_of) + # While the stop holds: no fetch starts and no part appears. + assert_quiet(node_cut, name, fetches_of) + assert part_names(node_cut, name) == [] + assert part_names(node_src, name, active_only=True) == [part] + assert payload_digest(node_src, name) == digest + namespace = table_namespace(node_cut, name) + assert_cas_namespace(node_cut, staging, namespace, []) + node_cut.query("SYSTEM START FETCHES {}".format(name)) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_drop_table_cuts_the_fetch_upload(node_cut, node_src, staging): + name = "drop_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), rows=fetches_of, deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + assert part_names(node_src, name, active_only=True) == [part] + assert payload_digest(node_src, name) == digest + + +def assert_dropped_and_clean(instance, name, staging, namespace): + """The table is gone, the pool has no dangling blob and the table's namespace on it is absent or empty.""" + assert instance.query("SELECT count() FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() == "0" + assert fsck(instance, CUT_DISK[staging])["dangling"] == "0" + entries = list_disk_dir_or_absent(instance, CUT_DISK[staging], namespace) + record_measurement("drop_" + name + "_namespace_after", entries=entries) + assert entries in (None, []), "the dropped table's namespace still lists {}".format(entries) + + +def seed_ttl_move(instance, name, staging, size=CUT_BODY): + """A table whose one large part sits on the local volume with its move TTL expired and moves stopped, so that + `SYSTEM START MOVES` is what starts the move.""" + instance.query( + "CREATE TABLE {} (id UInt64, payload String CODEC(NONE), d DateTime) ENGINE = MergeTree ORDER BY id " + "TTL d + toIntervalSecond({}) TO VOLUME 'cold' SETTINGS storage_policy = '{}', {}".format( + name, MOVE_TTL_S, MOVE_POLICY[staging], WIDE_SETTINGS)) + instance.query("SYSTEM STOP MOVES {}".format(name)) + instance.query("INSERT INTO {} SELECT 1, randomString({}), now() - toIntervalHour(1)".format(name, size), + settings={"async_insert": 0}, timeout=120) + assert part_disks(instance, name) == ["default"] + + +def part_disks(instance, name): + return instance.query("SELECT disk_name FROM system.parts WHERE database = 'default' AND table = '{}' AND active".format(name)).split() + + +def start_paced_move(instance, name, staging, size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """Returns the part name, the gate record and the data digest of a move that is going out at the gate.""" + seed_ttl_move(instance, name, staging, size=size) + part = part_names(instance, name, active_only=True)[0] + digest = payload_digest(instance, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + instance.query("SYSTEM START MOVES {}".format(name)) + _wait_until(lambda: moves_of(instance, name) == 1, timeout=60, describe=lambda: part_disks(instance, name)) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert moves_of(instance, name) == 1 + return part, record, digest + + +def assert_move_completes(instance, name, staging, part, digest): + _wait_until(lambda: part_disks(instance, name) == [CUT_DISK[staging]], timeout=120, describe=lambda: part_disks(instance, name)) + assert part_names(instance, name, active_only=True) == [part] + assert payload_digest(instance, name) == digest + assert_cas_namespace(instance, staging, table_namespace(instance, name), [part]) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_move_without_a_stop_completes_paced(node_cut, staging): + """No-signal control of a policy move: the paced body is neither cut nor timed out and the part is on the pool.""" + name = "ctl_move_" + staging + part, record, digest = start_paced_move( + node_cut, name, staging, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + assert_move_completes(node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_stop_moves_cuts_the_move_upload(node_cut, staging): + name = "stop_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MOVES {}".format(name)), rows=moves_of) + assert_quiet(node_cut, name, moves_of) + assert part_disks(node_cut, name) == ["default"] + assert part_names(node_cut, name, active_only=True) == [part] + assert payload_digest(node_cut, name) == digest + assert_cas_namespace(node_cut, staging, table_namespace(node_cut, name), []) + # The TTL rule selects the part again once moves are allowed. + node_cut.query("SYSTEM START MOVES {}".format(name)) + assert_move_completes(node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_drop_table_cuts_the_move_upload(node_cut, staging): + name = "drop_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), rows=moves_of, deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + + +def sigterm_and_restart(instance, case, record): + """`sigterm_orderly` while the claimed body `record` is going out, with no client connected. The pace is released + after the exit: the dead process closed the connection whatever the product did, so this checks that the body did + not complete, not how fast it was cut. The server is started again before the function returns.""" + t_proxy = now_mono_ms(cluster.proxy_url) + + def body_did_not_complete(exited): + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, CUT_DEADLINE_S, not_before_mono_ms=t_proxy) + ended = record_of(cluster.proxy_url, record) + record_measurement(case, exit_s=round(exited, 1), cut_s=round((ended["t_ended_mono_ms"] - t_proxy) / 1000.0, 1), + outcome=ended["outcome"]) + + try: + sigterm_orderly(instance, after_exit=body_did_not_complete) + finally: + instance.start_clickhouse() + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_sigterm_during_a_fetch_upload_is_orderly(node_cut, node_src, staging): + """The fetch is a queue entry, so it runs again after the restart and the part arrives whole.""" + name = "sigterm_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_fetch_" + staging, record) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_sigterm_during_a_move_upload_is_orderly(node_cut, staging): + """The expired TTL selects the part again after the restart, and it ends on the pool.""" + name = "sigterm_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_move_" + staging, record) + assert_move_completes(node_cut, name, staging, part, digest) + + +def record_log_anomalies(instance, case, first_line): + """Records the distinct `` and `` messages and every `LOGICAL_ERROR` that `instance` logged since + `first_line`, for the reader of a run: a passed test can still log them.""" + lines = instance.exec_in_container( + ["bash", "-c", "tail -n +{} /var/log/clickhouse-server/clickhouse-server.log | grep -a '\\|\\|LOGICAL_ERROR' || true".format(first_line)]) + distinct = {} + for line in lines.splitlines(): + # Drop the timestamp, thread and query id: what is left is the logger and the message. + key = re.sub(r"^\S+ \S+ \[ \d+ \] \{[^}]*\} ", "", line)[:300] + distinct[key] = distinct.get(key, 0) + 1 + if distinct: + record_measurement("log_anomalies:" + case, messages=sorted(distinct.items(), key=lambda kv: -kv[1])[:20]) + diff --git a/tests/integration/test_fetch_move_cancellation_s3/__init__.py b/tests/integration/test_fetch_move_cancellation_s3/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml new file mode 100644 index 000000000000..2f57ee207625 --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml @@ -0,0 +1,42 @@ + + + + + s3 + http://resolver:8083/root/data/move_s3/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + + + object_storage + s3 + plain_rewritable + http://resolver:8083/root/data/move_plain/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + 1000000 + + + + + + default + move_s3 + + + 0 + + + + default + move_plain + + 0 + + + + diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml new file mode 100644 index 000000000000..5da63a789a0f --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml @@ -0,0 +1,20 @@ + + + + + s3 + http://resolver:8083/root/data/fetch/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + + + + +
broken_s3
+
+
+
+
diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml new file mode 100644 index 000000000000..e0c7d50d6f12 --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml @@ -0,0 +1,9 @@ + + + + +
default
+
+
+
+
diff --git a/tests/integration/test_fetch_move_cancellation_s3/test.py b/tests/integration/test_fetch_move_cancellation_s3/test.py new file mode 100644 index 000000000000..f81c7641bd6d --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/test.py @@ -0,0 +1,601 @@ +#!/usr/bin/env python3 + +"""A replication fetch or a part move blocked in a write to its destination disk must stop on +`SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES` and server shutdown. + +The destination is a plain S3 disk behind `broken_s3`: every write under its key prefix is answered with +`SlowDown` and the disk retries for far longer than any deadline here, so the operation can only end +because the stop reaches the retry loop of the S3 client. +""" + +import logging +import os +import time + +import pytest + +from helpers.cluster import ClickHouseCluster +from helpers.mock_servers import start_s3_mock + +FETCH_PREFIX = "/root/data/fetch/" +MOVE_PREFIX = "/root/data/move_s3/" +PLAIN_PREFIX = "/root/data/move_plain/" + +# The stop is noticed before the next retry, so it takes at most the longest backoff plus the +# time to unwind. The retry budget of the disks is far beyond both deadlines. +STOP_DEADLINE_SECONDS = 20 +SHUTDOWN_DEADLINE_SECONDS = 30 + +# Moves of a TTL rule start by themselves this long after the insert; the fault is armed first. +MOVE_TTL_SECONDS = 5 + +cluster = ClickHouseCluster(__file__) +source = cluster.add_instance( + "source", + main_configs=["configs/source_storage.xml"], + with_zookeeper=True, + macros={"shard": "s1", "replica": "source"}, +) +receiver = cluster.add_instance( + "receiver", + main_configs=["configs/receiver_storage.xml"], + with_minio=True, + with_zookeeper=True, + stay_alive=True, + macros={"shard": "s1", "replica": "receiver"}, +) +# Its config is installed after the mock is up: a `plain_rewritable` disk lists its bucket at startup. +mover = cluster.add_instance("mover", with_minio=True, stay_alive=True) + +CONFIG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs") + + +@pytest.fixture(scope="module") +def init_broken_s3(): + try: + cluster.start() + control = start_s3_mock(cluster, "broken_s3", "8083") + mover.stop_clickhouse() + mover.copy_file_to_container( + os.path.join(CONFIG_DIR, "mover_storage.xml"), + "/etc/clickhouse-server/config.d/mover_storage.xml", + ) + mover.start_clickhouse() + yield control + finally: + cluster.shutdown() + + +@pytest.fixture(scope="function") +def broken_s3(init_broken_s3): + init_broken_s3.reset() + yield init_broken_s3 + init_broken_s3.reset() + + +def wait_until(probe, timeout, describe=None, interval=0.1, since=None): + """Polls `probe` until it returns a true value, within `timeout` wall-clock seconds from `since` + (default: now). Returns the elapsed seconds. A probe that returns true after the deadline fails + too, so a slow probe cannot stretch the bound. `describe()` is added to the error. + """ + started = time.monotonic() if since is None else since + while True: + done = probe() + elapsed = time.monotonic() - started + if elapsed > timeout or (not done and elapsed >= timeout): + detail = "" if describe is None else ": " + str(describe()) + state = "was true only after" if done else "not true within" + raise AssertionError( + f"{state} {timeout} s (elapsed {elapsed:.1f} s){detail}" + ) + if done: + return elapsed + time.sleep(min(interval, timeout - elapsed)) + + +def fault_writes(broken_s3, name, prefix, **kwargs): + """Answers every write under `prefix` with `SlowDown`.""" + broken_s3.setup_key_rule( + name, prefix, target="put", action="slow_down", action_args=[503], **kwargs + ) + + +def wait_for_failed_write_and_retry(broken_s3, name, retried_urls=1): + """The case is only meaningful if a write failed and was sent again.""" + wait_until( + lambda: broken_s3.key_rule_stats(name)["retried_urls"] >= retried_urls, + 60, + lambda: broken_s3.key_rule_stats(name), + ) + stats = broken_s3.key_rule_stats(name) + assert stats["hits"] >= 2 and stats["max_hits_per_url"] >= 2, stats + return stats + + +def log_count(node, text): + """Lines with `text` in the server log; reads the file, so it opens no query on the node.""" + return int(node.count_in_log(text)) + + +def wait_for_new_log_line(node, text, baseline): + """Waits for a `text` line beyond the `baseline` count: lines of earlier cases match too.""" + wait_until( + lambda: log_count(node, text) > baseline, + 20, + lambda: f"no new `{text}` line in the log of {node.name}", + ) + + +def count(node, query): + return int(node.query(query).strip() or 0) + + +def create_replicated_pair(table): + path = f"/clickhouse/tables/{{shard}}/{table}" + for node in (source, receiver): + node.query(f""" + CREATE TABLE {table} (p UInt8, k UInt64, s String) + ENGINE = ReplicatedMergeTree('{path}', '{{replica}}') + PARTITION BY p ORDER BY k + SETTINGS storage_policy = 'fetch_target', min_bytes_for_wide_part = 0 + """) + + +def drop_tables(node, *tables): + for table in tables: + node.query(f"SYSTEM STOP FETCHES {table}", ignore_error=True) + node.query(f"SYSTEM STOP MOVES {table}", ignore_error=True) + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + +def fetches_of(table): + return count( + receiver, + f"SELECT count() FROM system.replicated_fetches " + f"WHERE database = currentDatabase() AND table = '{table}'", + ) + + +def test_stop_fetches_cancels_fetch_blocked_in_a_write(broken_s3): + table = "fetch_stop" + create_replicated_pair(table) + try: + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + source.query( + f"INSERT INTO {table} SELECT 1, number, repeat('x', 100) FROM numbers(20000)" + ) + + wait_until(lambda: fetches_of(table) == 1, 60, lambda: fetches_of(table)) + wait_for_failed_write_and_retry(broken_s3, "fetch") + assert fetches_of(table) == 1, "the fetch ended before the stop" + + cancelled = "Fetching of part was cancelled" + cancelled_before = log_count(receiver, cancelled) + started = time.monotonic() + receiver.query(f"SYSTEM STOP FETCHES {table}") + wait_until( + lambda: fetches_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("fetch"), + since=started, + ) + logging.info( + "fetch left system.replicated_fetches after %.1f s", + time.monotonic() - started, + ) + wait_for_new_log_line(receiver, cancelled, cancelled_before) + + assert count(receiver, f"SELECT count() FROM {table}") == 0 + + broken_s3.remove_key_rule("fetch") + receiver.query(f"SYSTEM START FETCHES {table}") + wait_until( + lambda: count(receiver, f"SELECT count() FROM {table}") == 20000, + 60, + lambda: receiver.query( + f"SELECT last_exception FROM system.replication_queue WHERE table = '{table}'" + ), + ) + finally: + broken_s3.reset() + drop_tables(receiver, table) + drop_tables(source, table) + + +def test_kill_query_stops_fetch_partition_blocked_in_writes(broken_s3): + """Control: a fetch run by a query is a child of the query's group and has always stopped on + `KILL QUERY`.""" + table = "fetch_partition_src" + destination = "fetch_partition_dst" + create_replicated_pair(table) + receiver.query(f""" + CREATE TABLE {destination} (p UInt8, k UInt64, s String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/{{shard}}/{destination}', '{{replica}}') + PARTITION BY p ORDER BY k + SETTINGS storage_policy = 'fetch_target', min_bytes_for_wide_part = 0 + """) + try: + source.query(f"SYSTEM STOP MERGES {table}") + receiver.query(f"SYSTEM STOP FETCHES {table}") + for offset in (0, 20000): + source.query( + f"INSERT INTO {table} SELECT 1, number + {offset}, repeat('x', 100) FROM numbers(20000)" + ) + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + + query_id = "fetch_partition_to_kill" + request = receiver.get_query_request( + f"ALTER TABLE {destination} FETCH PARTITION 1 FROM '/clickhouse/tables/s1/{table}'", + query_id=query_id, + ) + wait_until( + lambda: fetches_of(destination) == 2, 60, lambda: fetches_of(destination) + ) + wait_for_failed_write_and_retry(broken_s3, "fetch", retried_urls=2) + # A fetch writes one file at a time, so two retried URLs belong to two fetches, and these + # are of two different parts. + assert ( + count( + receiver, + f"SELECT uniqExact(result_part_name) FROM system.replicated_fetches " + f"WHERE table = '{destination}'", + ) + == 2 + ) + + started = time.monotonic() + receiver.query(f"KILL QUERY WHERE query_id = '{query_id}'") + wait_until( + lambda: fetches_of(destination) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("fetch"), + since=started, + ) + logging.info("both fetches left after %.1f s", time.monotonic() - started) + _, error = request.get_answer_and_error() + assert error, "the query was expected to be cancelled" + assert ( + count( + receiver, + f"SELECT count() FROM system.detached_parts WHERE table = '{destination}'", + ) + == 0 + ) + finally: + broken_s3.reset() + drop_tables(receiver, table, destination) + drop_tables(source, table) + + +def create_tiered_table(table, policy="tiered"): + mover.query(f""" + CREATE TABLE {table} (d DateTime, k UInt64, s String) + ENGINE = MergeTree ORDER BY k + TTL d + INTERVAL {MOVE_TTL_SECONDS} SECOND TO VOLUME 'cold' + SETTINGS storage_policy = '{policy}', min_bytes_for_wide_part = 0 + """) + + +def insert_into_tiered_table(table, rows=20000): + mover.query( + f"INSERT INTO {table} SELECT now(), number, repeat('x', 100) FROM numbers({rows})" + ) + + +def moves_of(table): + return count( + mover, + f"SELECT count() FROM system.moves " + f"WHERE database = currentDatabase() AND table = '{table}'", + ) + + +def disks_of_active_parts(table): + return mover.query( + f"SELECT groupArray(disk_name) FROM system.parts " + f"WHERE database = currentDatabase() AND table = '{table}' AND active" + ).strip() + + +def drop_tiered_table(table): + drop_tables(mover, table) + + +def test_stop_moves_cancels_move_blocked_in_a_write(broken_s3): + table = "move_stop" + create_tiered_table(table) + try: + fault_writes(broken_s3, "move", MOVE_PREFIX) + insert_into_tiered_table(table) + + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + assert moves_of(table) == 1, "the move ended before the stop" + + cancelled = "Cancelled moving parts" + cancelled_before = log_count(mover, cancelled) + started = time.monotonic() + mover.query(f"SYSTEM STOP MOVES {table}") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("move"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + wait_for_new_log_line(mover, cancelled, cancelled_before) + + assert disks_of_active_parts(table) == "['default']" + assert count(mover, f"SELECT count() FROM {table}") == 20000 + + broken_s3.remove_key_rule("move") + mover.query(f"SYSTEM START MOVES {table}") + wait_until( + lambda: disks_of_active_parts(table) == "['move_s3']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def test_kill_query_stops_synchronous_alter_move_blocked_in_a_write(broken_s3): + """Control: a synchronous `ALTER ... MOVE` is a child of the query's group.""" + table = "move_kill" + mover.query(f""" + CREATE TABLE {table} (k UInt64, s String) + ENGINE = MergeTree ORDER BY k + SETTINGS storage_policy = 'tiered', min_bytes_for_wide_part = 0 + """) + try: + mover.query( + f"INSERT INTO {table} SELECT number, repeat('x', 100) FROM numbers(20000)" + ) + fault_writes(broken_s3, "move", MOVE_PREFIX) + + query_id = "alter_move_to_kill" + part = mover.query( + f"SELECT name FROM system.parts WHERE database = currentDatabase() AND table = '{table}' AND active" + ).strip() + request = mover.get_query_request( + f"ALTER TABLE {table} MOVE PART '{part}' TO DISK 'move_s3'", + query_id=query_id, + ) + wait_until( + lambda: moves_of(table) == 1, 60, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + + started = time.monotonic() + mover.query(f"KILL QUERY WHERE query_id = '{query_id}'") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("move"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + _, error = request.get_answer_and_error() + assert error, "the query was expected to be cancelled" + assert disks_of_active_parts(table) == "['default']" + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def directories_of_plain_disk(): + """The directory paths that the plain disk's metadata objects name.""" + return mover.query( + "SELECT line FROM s3('http://minio1:9001/root/data/move_plain/__meta/**', 'minio', " + "'ClickHouse_Minio_P@ssw0rd', 'LineAsString') ORDER BY line " + "SETTINGS s3_throw_on_zero_files_match = 0" + ).split() + + +def clone_directory(directories): + return [d for d in directories if d.endswith("/moving/all_1_1_0/")] + + +def test_cleanup_of_cut_clone_is_not_cut_on_plain_rewritable_disk(broken_s3): + """The clone of a cut move is removed with a directory rewrite and a delete. A failed rewrite + must be retried although the move is already cancelled, or the directory stays and the next + attempt of the move finds it.""" + table = "move_plain" + create_tiered_table(table, policy="tiered_plain") + try: + broken_s3.setup_key_rule( + "data", + PLAIN_PREFIX, + target="put", + excludes="/__meta/", + action="slow_down", + action_args=[503], + ) + insert_into_tiered_table(table) + + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "data") + assert len(clone_directory(directories_of_plain_disk())) == 1 + + # The next directory write is the cleanup's, as no other operation writes to this disk. + broken_s3.setup_key_rule( + "directory", + PLAIN_PREFIX, + target="put", + contains="/__meta/", + count=1, + action="slow_down", + action_args=[503], + ) + cancelled = "Cancelled moving parts" + cancelled_before = log_count(mover, cancelled) + started = time.monotonic() + mover.query(f"SYSTEM STOP MOVES {table}") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("data"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + wait_for_new_log_line(mover, cancelled, cancelled_before) + + directory_stats = broken_s3.key_rule_stats("directory") + assert ( + directory_stats["hits"] == 1 and directory_stats["seen"] >= 2 + ), directory_stats + assert clone_directory(directories_of_plain_disk()) == [] + assert disks_of_active_parts(table) == "['default']" + + broken_s3.reset() + mover.query(f"SYSTEM START MOVES {table}") + wait_until( + lambda: disks_of_active_parts(table) == "['move_plain']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def server_is_alive(node, pid): + state = node.exec_in_container( + ["bash", "-c", f"ps -o stat= -p {pid} || true"], user="root" + ).strip() + return state != "" and not state.startswith("Z") + + +def server_pid(node): + """The PID the running server logged at its start: the server process itself. `get_process_pid` + returns the first match of `pgrep`, which can be the watchdog that supervises the server. + """ + line = node.exec_in_container( + [ + "bash", + "-c", + "grep -a 'Application: Starting ClickHouse' " + "/var/log/clickhouse-server/clickhouse-server.log | tail -n 1", + ] + ) + pid = int(line.rsplit("PID ", 1)[1].strip()) + assert server_is_alive(node, pid), line + return pid + + +def sigterm_and_expect_orderly_shutdown(node): + """One SIGTERM to the exact server PID, with no client connected: the server must exit by itself + within the deadline, through the orderly shutdown. The caller starts it again.""" + closed = "Application: Closed connections\\.$" + forced = "Will shutdown forcefully" + storages = "Shut down storages\\." + markers = (closed, forced, storages, "", "LOGICAL_ERROR") + before = {m: log_count(node, m) for m in markers} + pid = server_pid(node) + try: + # Taken before the command: the exec itself takes time that counts against the server. + signalled = time.monotonic() + # One signal: a second one would end the process without the orderly shutdown. + node.exec_in_container(["bash", "-c", f"kill -15 {pid}"], user="root") + exited_after = wait_until( + lambda: not server_is_alive(node, pid), + SHUTDOWN_DEADLINE_SECONDS, + lambda: f"{pid} still alive", + since=signalled, + ) + assert exited_after <= SHUTDOWN_DEADLINE_SECONDS, exited_after + logging.info("server exited %.1f s after SIGTERM", exited_after) + + delta = {m: log_count(node, m) - before[m] for m in markers} + assert delta == { + closed: 1, + forced: 0, + storages: 1, + "": 0, + "LOGICAL_ERROR": 0, + }, delta + finally: + if server_is_alive(node, pid): + node.exec_in_container(["bash", "-c", f"kill -9 {pid}"], user="root") + + +def test_sigterm_cancels_move_blocked_in_a_write(broken_s3): + """With no client connected, one SIGTERM ends the server although a move is retrying a write.""" + table = "move_sigterm" + create_tiered_table(table) + body_failed = False + try: + fault_writes(broken_s3, "move", MOVE_PREFIX) + insert_into_tiered_table(table) + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + + sigterm_and_expect_orderly_shutdown(mover) + except BaseException: + body_failed = True + raise + finally: + broken_s3.reset() + mover.start_clickhouse() + try: + wait_until( + lambda: disks_of_active_parts(table) == "['move_s3']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + except Exception: + # A failed wait must not replace the exception of the test body. + if not body_failed: + raise + logging.exception("the restart check failed after the test body failed") + finally: + drop_tiered_table(table) + + +def test_sigterm_cancels_fetch_blocked_in_a_write(broken_s3): + """With no client connected, one SIGTERM ends the server although a fetch is retrying a write; the + fetch is a queue entry, so it completes after the restart.""" + table = "fetch_sigterm" + create_replicated_pair(table) + body_failed = False + try: + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + source.query( + f"INSERT INTO {table} SELECT 1, number, repeat('x', 100) FROM numbers(20000)" + ) + wait_until(lambda: fetches_of(table) == 1, 60, lambda: fetches_of(table)) + wait_for_failed_write_and_retry(broken_s3, "fetch") + + sigterm_and_expect_orderly_shutdown(receiver) + except BaseException: + body_failed = True + raise + finally: + broken_s3.reset() + receiver.start_clickhouse() + try: + wait_until( + lambda: count(receiver, f"SELECT count() FROM {table}") == 20000, + 120, + lambda: receiver.query( + f"SELECT last_exception FROM system.replication_queue WHERE table = '{table}'" + ), + ) + except Exception: + # A failed wait must not replace the exception of the test body. + if not body_failed: + raise + logging.exception("the restart check failed after the test body failed") + finally: + drop_tables(receiver, table) + drop_tables(source, table) diff --git a/tests/integration/test_merge_cancel_s3_read/__init__.py b/tests/integration/test_merge_cancel_s3_read/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml b/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml new file mode 100644 index 000000000000..203527349b55 --- /dev/null +++ b/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml @@ -0,0 +1,21 @@ + + + + + s3 + http://resolver:8087/root/data/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + 1000000 + + + + +
broken_s3
+
+
+
+
diff --git a/tests/integration/test_merge_cancel_s3_read/test.py b/tests/integration/test_merge_cancel_s3_read/test.py new file mode 100644 index 000000000000..150aa4481e7c --- /dev/null +++ b/tests/integration/test_merge_cancel_s3_read/test.py @@ -0,0 +1,581 @@ +#!/usr/bin/env python3 + +import logging +import os +import time + +import pytest + +from helpers.cluster import ClickHouseCluster +from helpers.mock_servers import start_s3_mock + +CONFIG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs") + +# Enough GETs to prove the merge is inside the retry loop rather than merely slow. +ATTEMPTS_TO_ACCRUE = 20 + +# The window oracle (b) must observe in full before it may pass. +SETTLED_WINDOW_SECONDS = 15 + +# A cancellation reaching the retry loop is observed after at most the remaining backoff +# (`DEFAULT_RETRY_MAX_DELAY_MS`, `IO/S3Defines.h`), so within seconds, while the retry budget it +# replaces is tens of minutes. Past this budget `stop_clickhouse` escalates to SIGKILL and reports +# the stop as not graceful, which is what the shutdown arm keys on. +SHUTDOWN_BUDGET_SECONDS = 60 + + +@pytest.fixture(scope="module") +def cluster(): + try: + cluster = ClickHouseCluster(__file__) + cluster.add_instance( + "node", + main_configs=["configs/storage_conf.xml"], + with_minio=True, + # The oracles count S3 events, which are server-global: a metadata disk would add + # its own requests to them. + with_remote_database_disk=False, + with_zookeeper=True, + stay_alive=True, + ) + logging.info("Starting cluster...") + cluster.start() + logging.info("Cluster started") + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(scope="module") +def init_broken_s3(cluster): + yield start_s3_mock(cluster, "broken_s3", "8087") + + +@pytest.fixture(scope="function") +def broken_s3(init_broken_s3): + init_broken_s3.reset() + yield init_broken_s3 + + +# `DiskS3ReadRequestsCount` counts every request attempt, so it moves whatever error class the +# mock injects. The alternatives are both wrong here: `DiskS3GetObject` counts only the read +# buffer's outer attempts, not the SDK retries doing the spinning (measured 15 vs 2064 over one +# such read), and `...Errors` stays flat for a 429, which is accounted as throttling instead. +# `sumIf` because an event that has never fired has no row in `system.events` at all. +ATTEMPTS_QUERY = ( + "SELECT sumIf(value, event = 'DiskS3ReadRequestsCount') FROM system.events" +) + + +def get_attempts(node): + return int(node.query(ATTEMPTS_QUERY).strip() or 0) + + +def wait_for(node, query, predicate, attempts=300, sleep_time=0.2): + for _ in range(attempts): + value = node.query(query).strip() + if predicate(value): + return True + time.sleep(sleep_time) + return False + + +@pytest.mark.parametrize("replicated", [False, True]) +def test_stop_merges_cancels_s3_read(cluster, broken_s3, replicated): + """`SYSTEM STOP MERGES` must interrupt a merge stuck retrying an S3 read. + + A merge/mutate thread group's cancellation predicates resolve through a process-list + element it does not have, so before the fix they were constant `false` and the S3 retry + loop never observed the cancellation: the merge retried to its budget while holding the + table, which is what the stress-test hung check reported. + + Both engines are covered because the two root callers pass different contexts: the plain + one passes its per-task context, the replicated one passes the shared storage context. + A guard keyed on the argument rather than on the merge list entry's own thread group + would cover only the plain case. + """ + node = cluster.instances["node"] + table = "t_repl" if replicated else "t_plain" + engine = ( + f"ReplicatedMergeTree('/clickhouse/tables/{table}', 'r1')" + if replicated + else "MergeTree" + ) + + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query( + f""" + CREATE TABLE {table} (id UInt64, s String) ENGINE = {engine} ORDER BY id + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0 + """ + ) + node.query("SYSTEM STOP MERGES " + table) + node.query( + f"INSERT INTO {table} SELECT number, repeat('x', 200) FROM numbers(200000)" + ) + node.query( + f"INSERT INTO {table} SELECT number + 200000, repeat('y', 200) FROM numbers(200000)" + ) + assert ( + int( + node.query( + f"SELECT count() FROM system.parts " + f"WHERE database = currentDatabase() AND table = '{table}' AND active" + ) + ) + == 2 + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + # Immediate retryable failures, deliberately NOT `slow_get`: a sleep inside the request + # blocks a fixed and an unfixed server equally, so the arm would prove nothing. These + # spin the retry loop instead, so the cancellation predicate is polled promptly. + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + before = get_attempts(node) + node.query("SYSTEM START MERGES " + table) + # Not `node.query`: for a plain table OPTIMIZE runs the merge in this thread, so awaiting it + # would deadlock against the very hang under test. + optimize = node.get_query_request( + f"OPTIMIZE TABLE {table} FINAL SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) >= 1, + ), "the merge never started, so the assertions below would be vacuous" + + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + node.query("SYSTEM STOP MERGES " + table) + + # Oracle (a): the merge exits instead of retrying to its budget. + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) == 0, + ), "the merge kept running after SYSTEM STOP MERGES" + + # Oracle (b): and it stops issuing requests. (a) alone could pass on a slow but finite + # read; (b) alone could pass on a merge that never started. + # Every sample across the whole window must hold, so a pass cannot be granted by the first + # one: `wait_for` would return on its initial evaluation, before any request had time to land. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + attempts = get_attempts(node) + assert attempts - settled <= 2, ( + f"the read kept retrying after the merge left system.merges " + f"({attempts - settled} requests since it was cancelled)" + ) + + broken_s3.reset() + optimize.get_answer_and_error() + node.query("SYSTEM START MERGES " + table) + + # A cancelled merge keeps its source parts, so no data is lost. + assert int(node.query(f"SELECT count() FROM {table}")) == 400000 + node.query(f"DROP TABLE {table} SYNC") + + +def test_stop_ttl_merges_does_not_cancel_regular_merge(cluster, broken_s3): + """`SYSTEM STOP TTL MERGES` must not abort a merge that only happens to drop TTL values. + + The blocker is state-aware on the merge path: when it is already set as a regular merge + starts, `prepare()` disables opportunistic TTL removal and the merge must then run to + completion. The predicate therefore keys on the *settled* removal state, so an unguarded + condition -- or one publishing the pre-downgrade value -- would abort this merge. + + The merge runs through the broken mock, so it is parked in the retry loop polling the + predicate. Without that the arm would never reach the code it exists to constrain, and the + unguarded form -- the single mutant it targets -- would leave it green. + """ + node = cluster.instances["node"] + node.query("DROP TABLE IF EXISTS t_ttl SYNC") + node.query( + """ + CREATE TABLE t_ttl (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY x + TTL d + INTERVAL 1 SECOND + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + merge_with_ttl_timeout = 0 + """ + ) + node.query("SYSTEM STOP MERGES t_ttl") + node.query("INSERT INTO t_ttl SELECT now() - 3600, number FROM numbers(20000)") + node.query( + "INSERT INTO t_ttl SELECT now() - 3600, number + 20000 FROM numbers(20000)" + ) + + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + node.query("SYSTEM STOP TTL MERGES t_ttl") + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + before = get_attempts(node) + node.query("SYSTEM START MERGES t_ttl") + # Not `node.query`, for the same reason as the sibling arm: on a plain table OPTIMIZE runs + # the merge in this thread, so awaiting it would block until the mock is reset. + optimize = node.get_query_request( + "OPTIMIZE TABLE t_ttl PARTITION tuple() FINAL " + "SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + # The oracle is "the merge is still alive", so every wait below must fail the moment it dies: + # otherwise an abort looks like a merge that is merely slow to get going, and the mutant this + # arm targets gets reported as a vacuous arm instead of as the bug it is. + # Keyed on our own OPTIMIZE still running: it drives the merge inline, and being `FINAL` it waits + # for a competing merge on these parts rather than returning, so it survives as long as the merge + # does. `system.merges` cannot tell "aborted" from "not started yet", and the server log is + # shared with the sibling arm, which cancels merges by design. + # `NOT LIKE '%system.processes%'` so this query does not match its own text. + optimize_running_query = ( + "SELECT count() FROM system.processes " + "WHERE query LIKE '%OPTIMIZE TABLE t_ttl%' AND query NOT LIKE '%system.processes%'" + ) + + def assert_not_aborted(): + assert ( + int(node.query(optimize_running_query)) >= 1 + ), "SYSTEM STOP TTL MERGES aborted a regular merge" + + # `get_query_request` only spawns a client and returns, so until the query reaches the server + # "not running" does not distinguish an abort from a connection still being made. + assert wait_for( + node, optimize_running_query, lambda v: int(v) >= 1 + ), "the OPTIMIZE never reached the server, so the assertions below would be vacuous" + + # Vacuity guard: the merge reaches the retry loop, so it does poll the predicate and the + # window below is an observation rather than an idle wait. + accrued = False + for _ in range(300): + assert_not_aborted() + if get_attempts(node) - before >= ATTEMPTS_TO_ACCRUE: + accrued = True + break + time.sleep(0.2) + assert accrued, "the merge is not retrying the read, so it never polls the predicate" + + # The oracle: with TTL merges stopped, this merge must NOT be cancelled. It stays alive across + # a window many times longer than the abort it guards against takes. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + assert_not_aborted() + assert ( + get_attempts(node) - settled >= 1 + ), "the merge stopped reading, so it is no longer in the retry loop" + + broken_s3.reset() + optimize.get_answer_and_error() + + # A `FINAL` optimize waits for a competing merge on the same parts rather than returning, so + # its answer above does not by itself mean the merge list has drained. + assert wait_for( + node, + "SELECT count() FROM system.merges " + "WHERE database = currentDatabase() AND table = 't_ttl'", + lambda v: int(v) == 0, + ), "the merge did not finish after the mock stopped failing" + + assert ( + int( + node.query( + "SELECT count() FROM system.parts " + "WHERE database = currentDatabase() AND table = 't_ttl' AND active" + ) + ) + == 1 + ), "the merge was aborted instead of completing without TTL removal" + # TTL removal was skipped, which is what stopping TTL merges is supposed to do. + assert int(node.query("SELECT count() FROM t_ttl")) == 40000 + + node.query("SYSTEM START TTL MERGES t_ttl") + node.query("DROP TABLE t_ttl SYNC") + + +def create_partly_expired_ttl_table(node, table, ttl, extra_settings=""): + """Two wide parts on the broken disk, each half expired, with merges held off. + + Deliberately NOT fully expired: `TTLPartDropMergeSelector` runs at higher priority than the + row-delete one and keys on the part's *max* TTL, so all-expired parts would be assigned + `TTLDrop`, which skips creating the read pipeline altogether and so never reaches S3. The + live half keeps `part_max_ttl` in the future. The expired half is also what makes the merge + read enough to be cancellable. + """ + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query( + f""" + CREATE TABLE {table} (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY x + TTL {ttl} + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + merge_with_ttl_timeout = 0{extra_settings} + """ + ) + node.query(f"SYSTEM STOP MERGES {table}") + for part in range(2): + node.query( + f"INSERT INTO {table} SELECT " + f"if(number % 2, now() + 3600, now() - 3600), number + {part} * 40000 " + f"FROM numbers(40000)" + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + +def drop_table_stopping_any_merge(node, table): + """Teardown that must run even when an assertion above failed. + + `ATTEMPTS_QUERY` is a server-global counter, so a merge left retrying by a failed arm keeps + issuing requests once the next arm's fixture resets the mock, and that arm's request-plateau + oracle fails for a reason that has nothing to do with it. `SYSTEM STOP MERGES` cancels the + merge outright, which is the path this PR's headline fix makes reliable. + """ + node.query(f"SYSTEM STOP MERGES {table}") + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query(f"SYSTEM START TTL MERGES {table}", ignore_error=True) + + +def assert_ttl_cancellation_reaches_the_read(node, table, before): + """The two oracles the headline arm uses, after `SYSTEM STOP TTL MERGES`. + + Preconditions: the merge is in `system.merges` and inside the retry loop. + """ + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + node.query(f"SYSTEM STOP TTL MERGES {table}") + + # Oracle (a): the merge exits instead of retrying to its budget. + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) == 0, + ), "the merge kept running after SYSTEM STOP TTL MERGES" + + # Only TTL merges are stopped, so the assignee is free to retry these same parts as a + # regular merge, which would keep reading and defeat oracle (b) for reasons unrelated to + # the branch under test. Stop merges outright now that oracle (a) has been observed. + node.query(f"SYSTEM STOP MERGES {table}") + + # Oracle (b): and it stops issuing requests. Sampled across the whole window, so a pass + # cannot be granted by the first sample, before any request had time to land. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + attempts = get_attempts(node) + assert attempts - settled <= 2, ( + f"the read kept retrying after the merge left system.merges " + f"({attempts - settled} requests since it was cancelled)" + ) + + +# Cold, the merge stalls in `MergeTask::prepare`, loading statistics and marks. Warm, with neither +# left to load, it stalls on the first data read, after `prepare` replaced the group's predicates. +@pytest.mark.parametrize("warm", [False, True]) +def test_stop_ttl_merges_cancels_assigned_recompression_merge(cluster, broken_s3, warm): + """`SYSTEM STOP TTL MERGES` must interrupt an assigned TTL merge stuck in an S3 read. + + Recompression specifically, because it is the only assigned TTL merge that the sibling + entry-flag condition does not already cover: a recompression TTL is recorded with + `update_part_min_max_ttls = false` (`MergeTreeDataWriter.cpp:997`), so it never feeds + `part_min_ttl` and `MergeTask::prepare` leaves `need_remove_expired_values` false. A + `TTLDelete` or `TTLDrop` merge is instead selected *by* `part_min_ttl <= now`, which is the + very condition that sets that flag, so for those the `isTTLMergeType` term is redundant and + an arm built on them cannot observe it. + + The merge is left to the background assignee: an explicit `OPTIMIZE` is always + `MergeType::Regular`. + """ + node = cluster.instances["node"] + table = "t_ttl_recompress" + # `d - INTERVAL 1 HOUR` so the expired half is already due for recompression while the live + # half keeps the part from being fully expired. `default_compression_codec` must differ from + # the target, or `will_change_codec` is false and no recompression merge is ever selected. + create_partly_expired_ttl_table( + node, + table, + ttl="d - INTERVAL 1 HOUR RECOMPRESS CODEC(ZSTD(3))", + extra_settings=", default_compression_codec = 'LZ4'" + + (", auto_statistics_types = ''" if warm else ""), + ) + if warm: + node.query(f"SELECT * FROM {table} FORMAT Null") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + + # Vacuity guard: the running merge really is an assigned TTL merge, so the branch under + # test is the one being exercised. `merge_type` is `magic_enum::enum_name(MergeType)` + # (`MergeList.cpp` -> `IO/WriteHelpers.h:1190`), so the enum spelling, not SCREAMING_CASE. + assert wait_for( + node, + f"SELECT count() FROM system.merges WHERE database = currentDatabase() " + f"AND table = '{table}' AND merge_type = 'TTLRecompress'", + lambda v: int(v) >= 1, + ), "no recompression TTL merge was assigned, so the assertions below would be vacuous" + + assert_ttl_cancellation_reaches_the_read(node, table, before) + + broken_s3.reset() + # A cancelled merge keeps its source parts, so no data is lost. + assert int(node.query(f"SELECT count() FROM {table}")) == 80000 + finally: + drop_table_stopping_any_merge(node, table) + + +def test_stop_ttl_merges_cancels_regular_merge_removing_expired_values( + cluster, broken_s3 +): + """`SYSTEM STOP TTL MERGES` must interrupt a regular merge that is removing expired values. + + `MergeTask` has two TTL cancellation conditions, and this is the second: a regular merge + whose `need_remove_expired_values` survived the check in `prepare()` treats a later block + as cancellation. The TTL blocker must therefore still be unset while `prepare()` runs -- + were it already set, removal would be disabled up front and the merge must instead run to + completion, which is what `test_stop_ttl_merges_does_not_cancel_regular_merge` pins. + """ + node = cluster.instances["node"] + table = "t_ttl_regular" + # `max_number_of_merges_with_ttl_in_pool = 0` makes `merge_with_ttl_allowed` false, so the + # assignee cannot pick a TTL merge for these parts and steal them before `OPTIMIZE` -- which + # bypasses the selector and is always `MergeType::Regular` -- gets them. + create_partly_expired_ttl_table( + node, + table, + ttl="d + INTERVAL 1 SECOND", + extra_settings=", max_number_of_merges_with_ttl_in_pool = 0", + ) + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + # Not `node.query`: for a plain table OPTIMIZE runs the merge in this thread, so awaiting + # it would deadlock against the very hang under test. + optimize = node.get_query_request( + f"OPTIMIZE TABLE {table} PARTITION tuple() FINAL " + f"SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + # Vacuity guard: this arm is about the *regular* branch, so a background TTL merge + # claiming the parts first would silently make it a duplicate of the sibling arm. + assert wait_for( + node, + f"SELECT count() FROM system.merges WHERE database = currentDatabase() " + f"AND table = '{table}' AND merge_type = 'Regular'", + lambda v: int(v) >= 1, + ), "no regular merge started, so the assertions below would be vacuous" + + assert_ttl_cancellation_reaches_the_read(node, table, before) + + broken_s3.reset() + optimize.get_answer_and_error() + assert int(node.query(f"SELECT count() FROM {table}")) == 80000 + finally: + drop_table_stopping_any_merge(node, table) + + +def test_shutdown_cancels_s3_read(cluster, broken_s3): + """Shutdown must interrupt a background merge stuck retrying an S3 read. + + A different branch of the predicate from the arms above, and the only one shutdown can reach + while it matters: `Context::shutdown` cancels through `MergeList::cancelAll`, which sets the + merge list entry's own flag, and then waits for the merge executor, whereas the per-storage + `merges_blocker` is cancelled only later, in `DatabaseCatalog::shutdown` + (`Interpreters/Context.cpp`). That wait has no timeout: `Server.cpp`'s `safeExit` path is + registered in a later scope guard, so it runs first and covers only connections, refresh + tasks, background queries and backups. + + The merge is left to the background assignee. An `OPTIMIZE` would hold a client connection + open across the shutdown, and `waitServersToFinish` would then reach that forced exit after + `shutdown_wait_unfinished`, passing this arm with the merge never cancelled at all. + """ + node = cluster.instances["node"] + table = "t_shutdown" + + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + # `min_age_to_force_merge_seconds` because the selector declines two parts of this size on its + # own heuristic ("no need to merge parts according to merge selector algorithm"), and the + # merge has to come from the assignee rather than from `OPTIMIZE`. The short selecting sleep + # keeps the wait for it inside `wait_for`'s window. + node.query( + f""" + CREATE TABLE {table} (id UInt64, s String) ENGINE = MergeTree ORDER BY id + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + min_age_to_force_merge_seconds = 1, merge_selecting_sleep_ms = 1000 + """ + ) + node.query(f"SYSTEM STOP MERGES {table}") + node.query( + f"INSERT INTO {table} SELECT number, repeat('x', 200) FROM numbers(200000)" + ) + node.query( + f"INSERT INTO {table} SELECT number + 200000, repeat('y', 200) FROM numbers(200000)" + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + + in_merges = ( + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'" + ) + assert wait_for( + node, in_merges, lambda v: int(v) >= 1 + ), "the assignee never started the merge, so the assertions below would be vacuous" + + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + # And it is still retrying as the shutdown starts: otherwise a prompt shutdown could be + # granted by a merge that had already finished, or that something else had cancelled. + assert ( + int(node.query(in_merges)) >= 1 + ), "the merge left system.merges before the shutdown, so this arm would be vacuous" + + # The oracle: SIGTERM completes on its own. `stop_clickhouse` returns True only when the + # process is gone within the budget, and force-kills past it. + assert node.stop_clickhouse(stop_wait_sec=SHUTDOWN_BUDGET_SECONDS) is True, ( + f"the server did not shut down within {SHUTDOWN_BUDGET_SECONDS}s and had to be " + f"killed: the merge kept retrying the read after MergeList::cancelAll" + ) + finally: + # The mock must stop failing before the server reads these parts back on startup. The + # stop is a no-op after the oracle and stops a still-running server after an earlier + # failure, so the restart is deterministic either way. + broken_s3.reset() + node.stop_clickhouse() + node.start_clickhouse() + drop_table_stopping_any_merge(node, table) diff --git a/tests/integration/test_oom_canary/test.py b/tests/integration/test_oom_canary/test.py index 149f61b5f84d..ed3ccbb529d8 100644 --- a/tests/integration/test_oom_canary/test.py +++ b/tests/integration/test_oom_canary/test.py @@ -116,8 +116,8 @@ def slow_query(): # The merge-cancellation step of the OOM response: a cancelled merge is # rescheduled by the background executor, so there is no stable end state - # to assert on; instead check that the response reached MergeList::cancelAll. - node.wait_for_log_line("Cancelled all running merges") + # to assert on; instead check that the response reached MergeList::cancelCurrent. + node.wait_for_log_line("Cancelled currently running merges") slow_query_thread.join(timeout=10) assert slow_query_error is not None and "QUERY_WAS_CANCELLED" in str(slow_query_error), slow_query_error diff --git a/tests/integration/test_shutdown_cancels_merges/__init__.py b/tests/integration/test_shutdown_cancels_merges/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml b/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml new file mode 100644 index 000000000000..ed82e47f67b2 --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml @@ -0,0 +1,25 @@ + + + test + + + + + + s3 + http://minio1:9001/root/data/ + minio + ClickHouse_Minio_P@ssw0rd + + + + + +
+ s3 +
+
+
+
+
+
diff --git a/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml b/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml new file mode 100644 index 000000000000..5e4122894604 --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml @@ -0,0 +1,11 @@ + + + + + 1024 + + + diff --git a/tests/integration/test_shutdown_cancels_merges/test.py b/tests/integration/test_shutdown_cancels_merges/test.py new file mode 100644 index 000000000000..7dcbfaa04bde --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/test.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 + +import time + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node = cluster.add_instance("node", stay_alive=True) +node1 = cluster.add_instance("node1", with_zookeeper=True) +node2 = cluster.add_instance("node2", with_zookeeper=True, stay_alive=True) +node3 = cluster.add_instance( + "node3", + main_configs=["configs/storage_conf.xml"], + with_zookeeper=True, + with_minio=True, +) +node4 = cluster.add_instance( + "node4", + main_configs=["configs/storage_conf.xml"], + user_configs=["configs/users_small_fetch_buffer.xml"], + with_zookeeper=True, + with_minio=True, + stay_alive=True, +) + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_shutdown_cancels_running_merge(started_cluster): + """A graceful shutdown must cancel in-flight merges instead of waiting for + them to finish. The `merge_tree_sequential_source_sleep_before_read` + failpoint makes every reading step of the merge sleep for 10 seconds, so + the merge of 16 parts runs for at least 160 seconds. Without cancellation + the server cannot stop before the timeout below (the background executor's + `wait` does not interrupt running tasks, and per-storage cancellation + happens only after that wait). See the `Possible deadlock on shutdown` + stress test failures where a merge applying patch parts blocked shutdown: + https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a013c79d6ac80373b820381527ea85823ab03834&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29 + """ + node.query(""" + CREATE TABLE t_shutdown_merge (k UInt64, v UInt64) + ENGINE = MergeTree ORDER BY k + SETTINGS min_parts_to_merge_at_once = 16 + """) + + node.query("SYSTEM STOP MERGES t_shutdown_merge") + + for i in range(16): + node.query( + f"INSERT INTO t_shutdown_merge SELECT number + {i} * 10000, number FROM numbers(10000)" + ) + + node.query("SYSTEM ENABLE FAILPOINT merge_tree_sequential_source_sleep_before_read") + node.query("SYSTEM START MERGES t_shutdown_merge") + + # Wait until the background merge picks up the parts. With + # min_parts_to_merge_at_once = 16 the only merge the selector can assign + # takes all 16 parts at once. + for _ in range(300): + num_parts = node.query( + "SELECT num_parts FROM system.merges WHERE table = 't_shutdown_merge'" + ).strip() + if num_parts: + assert int(num_parts) == 16 + break + time.sleep(0.2) + else: + raise Exception("The background merge did not start") + + start = time.time() + assert node.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + node.start_clickhouse() + + # The merge was aborted, the source parts and the data are intact. + assert node.query("SELECT count() FROM t_shutdown_merge") == "160000\n" + + node.query("DROP TABLE t_shutdown_merge SYNC") + + +def test_shutdown_cancels_running_fetch(started_cluster): + """A graceful shutdown must also cancel in-flight fetches of parts from + other replicas: a fetch runs inside a single step of a background task, so + the executors' `wait` would otherwise block for the whole download. The + sender is throttled to 1 MiB/s and the part is ~150 MB of incompressible + data, so without cancellation the fetch holds the shutdown for ~150 + seconds. + """ + node1.query(""" + CREATE TABLE t_shutdown_fetch (k UInt64, v String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_fetch', 'r1') + ORDER BY k + SETTINGS max_replicated_sends_network_bandwidth = 1048576 + """) + node1.query( + "INSERT INTO t_shutdown_fetch SELECT number, randomString(1000) FROM numbers(150000)" + ) + + node2.query(""" + CREATE TABLE t_shutdown_fetch (k UInt64, v String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_fetch', 'r2') + ORDER BY k + """) + + for _ in range(300): + fetches = node2.query( + "SELECT count() FROM system.replicated_fetches WHERE table = 't_shutdown_fetch'" + ).strip() + if fetches != "0": + break + time.sleep(0.2) + else: + raise Exception("The fetch did not start") + + start = time.time() + assert node2.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + # The fetch was aborted by the cancellation of the `ReplicatedFetchList` + # entry (the `ABORTED` message includes the part name), not by anything else. + assert node2.contains_in_log("Fetching of part all_.* was cancelled") + + node2.start_clickhouse() + + # After the restart the fetch is retried; dropping the table cancels it + # again, through the per-storage blockers. + node2.query("DROP TABLE t_shutdown_fetch SYNC") + node1.query("DROP TABLE t_shutdown_fetch SYNC") + + +def test_shutdown_cancels_running_zero_copy_fetch(started_cluster): + """The zero-copy fetch branch (`remote_fs_metadata`) must participate in + the shutdown cancellation too: the `ReplicatedFetchList` entry is created + and the read callback is installed before the branch on the fetch mode. + The `replicated_sends_sleep_before_file_send` failpoint makes the sender + flush and then sleep 5 seconds before each metadata file, and the part is + wide with 20 columns (several dozen files), so without cancellation the + metadata transfer holds the shutdown for well over 90 seconds. The + receiver observes the cancellation between the refills of its read + buffer, and the whole metadata stream is a few KB, so node4 shrinks + `max_read_buffer_size_remote_fs` to 1 KiB (see the comment in + `users_small_fetch_buffer.xml`). + """ + columns = ", ".join(f"v{i} String" for i in range(20)) + node3.query(f""" + CREATE TABLE t_shutdown_zc_fetch (k UInt64, {columns}) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_zc_fetch', 'r1') + ORDER BY k + SETTINGS storage_policy = 's3', allow_remote_fs_zero_copy_replication = 1, + min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0 + """) + node3.query( + f"INSERT INTO t_shutdown_zc_fetch SELECT * FROM generateRandom('k UInt64, {columns}') LIMIT 100" + ) + + node3.query("SYSTEM ENABLE FAILPOINT replicated_sends_sleep_before_file_send") + + node4.query(f""" + CREATE TABLE t_shutdown_zc_fetch (k UInt64, {columns}) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_zc_fetch', 'r2') + ORDER BY k + SETTINGS storage_policy = 's3', allow_remote_fs_zero_copy_replication = 1, + min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0 + """) + + for _ in range(300): + fetches = node4.query( + "SELECT count() FROM system.replicated_fetches WHERE table = 't_shutdown_zc_fetch'" + ).strip() + if fetches != "0": + break + time.sleep(0.2) + else: + raise Exception("The fetch did not start") + + start = time.time() + assert node4.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + # The fetch took the zero-copy branch and was aborted by the cancellation + # of the `ReplicatedFetchList` entry (the `ABORTED` message). + assert node4.contains_in_log("metadata onto disk") + assert node4.contains_in_log("Fetching of part all_.* was cancelled") + + node3.query("SYSTEM DISABLE FAILPOINT replicated_sends_sleep_before_file_send") + node4.start_clickhouse() + + node4.query("DROP TABLE t_shutdown_zc_fetch SYNC") + node3.query("DROP TABLE t_shutdown_zc_fetch SYNC") diff --git a/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference new file mode 100644 index 000000000000..3fdf4950382a --- /dev/null +++ b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference @@ -0,0 +1,8 @@ +mutation started: 1 +mutation stopped: 1 +cancelled, not S3 error: 1 +dropped: 0 +stop merges: mutation started: 1 +stop merges cancels the read: 1 +toggle: mutation started: 1 +toggle stop/start cancels the read: 1 diff --git a/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh new file mode 100755 index 000000000000..be6efc354693 --- /dev/null +++ b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: uses the s3 table function. + +# `KILL MUTATION` must stop a mutation whose `IN` subquery is stuck reading an unreachable S3 +# endpoint. The read happens while the mutation's plan is still being built (materializing the set for +# primary-key analysis), where cancellation is observable only through the thread's cancellation +# predicate -- which used to be constant `false` for background tasks, so the mutation retried the +# request to its budget and blocked any later DROP/DETACH of the table behind it. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The pool pin makes the mutation schedulable regardless of what else this run has queued, and +# `auto_statistics_types = ''` keeps the set from being built via the statistics estimation path, so the +# read under test is the key-analysis build. Both siblings of this family pin the same pair. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_mut (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_mut SELECT number FROM numbers(1000)" + +# Nothing listens on this port, so the read never completes on its own. `enable_parallel_replicas = 0` +# keeps the read under test inside the background mutation: with parallel replicas `s3` resolves to the +# cluster engine, whose constructor probes the endpoint while `ALTER` is still being analysed, so the +# statement blocks instead of queueing a mutation. +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_mut DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" + +# Wait for the mutation to actually start before killing it, otherwise the kill races the scheduler +# and the test would pass without ever exercising the cancellation. +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_mut'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +$CLICKHOUSE_CLIENT -q "KILL MUTATION WHERE database = currentDatabase() AND table = 't_mut' FORMAT Null" + +# The oracle is the task LEAVING system.merges, not the KILL statement returning: the KILL returns +# immediately even when the mutation keeps retrying, which is precisely the bug. No wall-clock +# assertion -- only that it stops well inside the retry budget it used to exhaust. +gone=0 +for _ in {1..300}; do + running=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_mut'") + if [[ "$running" -eq 0 ]]; then + gone=1 + break + fi + sleep 0.2 +done +echo "mutation stopped: $gone" + +# It must stop *because it was cancelled*, not with whatever S3/network error the last attempt +# happened to produce. A cancellation the read reports as an ordinary request failure instead would +# end the mutation in a misleading S3_ERROR, so error 236 and not 499 is the assertion. +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS part_log" +echo "cancelled, not S3 error: $($CLICKHOUSE_CLIENT -q " + SELECT countIf(error = 236) > 0 AND countIf(error = 499) = 0 + FROM system.part_log + WHERE database = currentDatabase() AND table = 't_mut' + AND event_type = 'MutatePart' AND error != 0")" + +# The table must now be droppable: before the fix the in-flight task still held it, so the DROP waited +# for the read to exhaust its retries, which is what the stress-test hung check reported. Bounded so a +# regression is reported as a diff rather than as a test timeout. +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_mut SYNC" >/dev/null 2>&1 +echo "dropped: $?" + +# The second cancellation source: stopping merges must reach the read as well, so that shutting a +# table (or the server) down does not wait out the retry budget either. `KILL MUTATION` cancels only +# the one mutation, so without this arm nothing covers the per-table stop. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_stop (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_stop SELECT number FROM numbers(1000)" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_stop DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_stop'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "stop merges: mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +$CLICKHOUSE_CLIENT -q "SYSTEM STOP MERGES t_stop" +stopped=0 +for _ in {1..300}; do + running=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_stop'") + if [[ "$running" -eq 0 ]]; then + stopped=1 + break + fi + sleep 0.2 +done +echo "stop merges cancels the read: $stopped" +$CLICKHOUSE_CLIENT -q "SYSTEM START MERGES t_stop" +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_stop SYNC" >/dev/null 2>&1 + +# The blocker above stays cancelled until the task exits, so it does not cover a blocker that is +# released again while the read is still retrying -- which ordinary DDL does on every scope exit +# (TRUNCATE, DROP/DETACH PARTITION, REPLACE PARTITION all take a scoped lock). The read and the +# interactive-cancel callback poll the predicate independently, so a detected cancellation must be +# persisted rather than re-read, exactly as the merge path already does. +# +# The oracle here is the attempt REPORTING cancellation, not the task leaving system.merges: a +# released blocker leaves the mutation schedulable, so the entry legitimately reappears and the +# arm above's oracle is unsatisfiable for this shape. +# +# Exactly ONE read here. The flaky check runs this test in as many workers as the runner has cores, +# and they share the server's background mutation slots, so a premise that needs several of this +# run's own mutations resident at the same instant is not satisfiable in that job. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_toggle (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_toggle SELECT number FROM numbers(1000)" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_toggle DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_toggle'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "toggle: mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +# An entry in system.merges only means the task is running: the subquery's S3 client is built later, +# and under a sanitizer that took 16s, so a toggle can be over before the read makes its first +# attempt and cancel nothing. Each round leaves the mutation schedulable, so it is simply retried. +# No round is STARTED past the deadline below, which leaves one whole round plus the teardown +# inside the flaky check's per-test limit of 180s however slow the arms above were. +cancelled=0 +toggle_deadline=$((SECONDS + 70)) +[[ "$toggle_deadline" -gt 125 ]] && toggle_deadline=125 +while [[ "$cancelled" -eq 0 && "$SECONDS" -lt "$toggle_deadline" ]]; do + # The read tests cancellation once per retry attempt, 5s apart once its backoff has saturated. + # The settle both waits for that and is drawn over a whole attempt period: a narrower draw + # resonates with it, because the restart after a cancelled attempt re-creates the same phase. + settle=$((9000 + RANDOM % 5100)) + sleep "$(printf '%d.%03d' $((settle / 1000)) $((settle % 1000)))" + # One call: the window is a server-side sleep plus two round trips, so client startup cannot + # stretch it, and the fail times bracket it. It has to hold the blocker cancelled long enough for + # a poller to observe it, and still end well inside the read's own attempt cadence: an attempt + # that fell INSIDE the window read the blocker itself, which proves nothing, so that round is + # spent on a fresh draw rather than on the poll below. + mapfile -t stamps < <($CLICKHOUSE_CLIENT -q " + SELECT max(toUnixTimestamp(latest_fail_time)) FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'; + SYSTEM STOP MERGES t_toggle; + SELECT sleep(0.5) FORMAT Null; + SYSTEM START MERGES t_toggle; + SELECT max(toUnixTimestamp(latest_fail_time)) FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'") + [[ "${#stamps[@]}" -eq 2 && "${stamps[0]}" == "${stamps[1]}" ]] || continue + # A released blocker answers every later poll with "not cancelled", so a cancellation recorded + # after the release can only come from one that was persisted. An earlier one would only show + # the read reading the blocker itself, which the arm above already covers. + seen_deadline=$((SECONDS + 10)) + while [[ "$SECONDS" -lt "$seen_deadline" ]]; do + seen=$($CLICKHOUSE_CLIENT -q " + SELECT countIf(latest_fail_reason LIKE '%Cancelled mutating parts%' + AND toUnixTimestamp(latest_fail_time) > ${stamps[1]}) + FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'") + if [[ "${seen:-0}" -ge 1 ]]; then + cancelled=1 + break + fi + sleep 0.5 + done +done +echo "toggle stop/start cancels the read: $cancelled" +$CLICKHOUSE_CLIENT -q "KILL MUTATION WHERE database = currentDatabase() AND table = 't_toggle' FORMAT Null" +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_toggle SYNC" >/dev/null 2>&1 diff --git a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference new file mode 100644 index 000000000000..d86bac9de59a --- /dev/null +++ b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference @@ -0,0 +1 @@ +OK diff --git a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh new file mode 100755 index 000000000000..86d92dc6e00f --- /dev/null +++ b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no usearch + +# DROP TABLE SYNC must cancel a merge that is building a vector similarity index in one long step +# (one block of 200000 rows), instead of waiting minutes for the index build to finish. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE tab + ( + id Int32, + vec Array(Float32), + INDEX idx vec TYPE vector_similarity('hnsw', 'L2Distance', 64, 'f32', 200, 400) + ) + ENGINE = MergeTree + ORDER BY id + SETTINGS merge_max_block_size = 10000000, merge_max_block_size_bytes = 10000000000; + + SYSTEM STOP MERGES tab; + SET materialize_skip_indexes_on_insert = 0; + INSERT INTO tab SELECT number, arrayMap(x -> rand(x) / 4294967295., range(64)) FROM numbers(100000); + INSERT INTO tab SELECT number + 100000, arrayMap(x -> rand(x) / 4294967295., range(64)) FROM numbers(100000); + SYSTEM START MERGES tab; +" + +$CLICKHOUSE_CLIENT -q "OPTIMIZE TABLE tab FINAL" >/dev/null 2>&1 & +optimize_pid=$! + +merge_started=0 +for _ in {1..600}; do + if [ "$($CLICKHOUSE_CLIENT -q "SELECT count() FROM system.merges WHERE database = currentDatabase() AND table = 'tab' AND elapsed > 3")" != 0 ]; then + merge_started=1 + break + fi + sleep 0.1 +done + +# DROP TABLE SYNC also waits for the server-wide queue of dropped tables, which a concurrent drop of another table +# can hold for a long time, so time only the cancellation of the merge: the OPTIMIZE that runs it returns then. +start=$(date +%s) +$CLICKHOUSE_CLIENT -q "DROP TABLE tab SYNC" & +drop_pid=$! +wait $optimize_pid +elapsed=$(( $(date +%s) - start )) +wait $drop_pid + +if [ "$merge_started" -eq 0 ]; then + echo "The merge did not run for more than 3 seconds" +elif [ "$elapsed" -lt 30 ]; then + echo "OK" +else + echo "Cancelling the merge took $elapsed seconds" +fi