diff --git a/programs/local/LocalServer.cpp b/programs/local/LocalServer.cpp index 5160588062d0..fec7c68cd3bf 100644 --- a/programs/local/LocalServer.cpp +++ b/programs/local/LocalServer.cpp @@ -218,9 +218,6 @@ namespace ServerSetting extern const ServerSettingsUInt64 max_format_parsing_thread_pool_free_size; extern const ServerSettingsUInt64 format_parsing_thread_pool_queue_size; extern const ServerSettingsUInt64 cas_blob_upload_pool_size; - extern const ServerSettingsUInt64 max_iceberg_manifest_decode_thread_pool_size; - extern const ServerSettingsUInt64 max_iceberg_manifest_decode_thread_pool_free_size; - extern const ServerSettingsUInt64 iceberg_manifest_decode_thread_pool_queue_size; extern const ServerSettingsNonZeroUInt64 ai_function_max_thread_pool_size; extern const ServerSettingsUInt64 ai_function_max_thread_pool_free_size; extern const ServerSettingsUInt64 ai_function_thread_pool_queue_size; @@ -479,10 +476,6 @@ void LocalServer::initialize(Poco::Util::Application & self) /// pool unconditionally once a `cas` disk commits a part, so every entry point /// that can run a CA INSERT must initialize it, not only `clickhouse-server`. DB::Cas::initializeBlobUploadPool(server_settings[ServerSetting::cas_blob_upload_pool_size]); - getIcebergManifestDecodeThreadPool().initialize( - server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_size], - server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_free_size], - server_settings[ServerSetting::iceberg_manifest_decode_thread_pool_queue_size]); getAIRequestThreadPool().initialize( server_settings[ServerSetting::ai_function_max_thread_pool_size], diff --git a/programs/server/Server.cpp b/programs/server/Server.cpp index 386666c19ea8..2f48904bbf32 100644 --- a/programs/server/Server.cpp +++ b/programs/server/Server.cpp @@ -432,9 +432,6 @@ namespace ServerSetting extern const ServerSettingsUInt64 max_format_parsing_thread_pool_free_size; extern const ServerSettingsUInt64 format_parsing_thread_pool_queue_size; extern const ServerSettingsUInt64 cas_blob_upload_pool_size; - extern const ServerSettingsUInt64 max_iceberg_manifest_decode_thread_pool_size; - extern const ServerSettingsUInt64 max_iceberg_manifest_decode_thread_pool_free_size; - extern const ServerSettingsUInt64 iceberg_manifest_decode_thread_pool_queue_size; extern const ServerSettingsNonZeroUInt64 ai_function_max_thread_pool_size; extern const ServerSettingsUInt64 ai_function_max_thread_pool_free_size; extern const ServerSettingsUInt64 ai_function_thread_pool_queue_size; @@ -2014,10 +2011,6 @@ try server_settings[ServerSetting::format_parsing_thread_pool_queue_size]); DB::Cas::initializeBlobUploadPool(server_settings[ServerSetting::cas_blob_upload_pool_size]); - getIcebergManifestDecodeThreadPool().initialize( - server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_size], - server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_free_size], - server_settings[ServerSetting::iceberg_manifest_decode_thread_pool_queue_size]); getAIRequestThreadPool().initialize( server_settings[ServerSetting::ai_function_max_thread_pool_size], @@ -3081,11 +3074,6 @@ try new_server_settings[ServerSetting::max_format_parsing_thread_pool_free_size], new_server_settings[ServerSetting::format_parsing_thread_pool_queue_size]); - getIcebergManifestDecodeThreadPool().reloadConfiguration( - new_server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_size], - new_server_settings[ServerSetting::max_iceberg_manifest_decode_thread_pool_free_size], - new_server_settings[ServerSetting::iceberg_manifest_decode_thread_pool_queue_size]); - getAIRequestThreadPool().reloadConfiguration( new_server_settings[ServerSetting::ai_function_max_thread_pool_size], new_server_settings[ServerSetting::ai_function_max_thread_pool_free_size], diff --git a/src/Common/CurrentMetrics.cpp b/src/Common/CurrentMetrics.cpp index 3c78839353a0..7e3940032eca 100644 --- a/src/Common/CurrentMetrics.cpp +++ b/src/Common/CurrentMetrics.cpp @@ -301,9 +301,6 @@ M(FormatParsingThreads, "Number of threads in the thread pool used for parsing input.") \ M(FormatParsingThreadsActive, "Number of threads in the thread pool used for parsing input running a task.") \ M(FormatParsingThreadsScheduled, "Number of queued or active jobs in the thread pool used for parsing input.") \ - M(IcebergManifestDecodeThreads, "Number of threads in the thread pool used for decoding Iceberg data manifest files.") \ - M(IcebergManifestDecodeThreadsActive, "Number of threads in the thread pool used for decoding Iceberg data manifest files running a task.") \ - M(IcebergManifestDecodeThreadsScheduled, "Number of queued or active jobs in the thread pool used for decoding Iceberg data manifest files.") \ M(OutdatedPartsLoadingThreads, "Number of threads in the threadpool for loading Outdated data parts.") \ M(OutdatedPartsLoadingThreadsActive, "Number of active threads in the threadpool for loading Outdated data parts.") \ M(OutdatedPartsLoadingThreadsScheduled, "Number of queued or active jobs in the threadpool for loading Outdated data parts.") \ diff --git a/src/Common/setThreadName.h b/src/Common/setThreadName.h index 0f05f9073b7d..2921f2ff49ba 100644 --- a/src/Common/setThreadName.h +++ b/src/Common/setThreadName.h @@ -81,7 +81,6 @@ namespace DB M(HASHED_DICT_LOAD, "HashedDictLoad") \ M(HTTP_HANDLER, "HTTPHandler") \ M(HTTP_SERVER_CONN, "HTTPSrvConn") \ - M(ICEBERG_DELETE_DECODE, "IcebergDelDec") \ M(ICEBERG_ITERATOR, "IcebergIter") \ M(ICEBERG_SCHEDULE_POOL, "IcebergSchPool") \ M(INTERSERVER_HANDLER, "IntersrvHandler") \ diff --git a/src/Core/ServerSettings.cpp b/src/Core/ServerSettings.cpp index 7cd1c05b6b53..3c95ed029eaf 100644 --- a/src/Core/ServerSettings.cpp +++ b/src/Core/ServerSettings.cpp @@ -189,17 +189,9 @@ ClickHouse uses threads from this dedicated server-wide pool to upload blobs in committing a content-addressed (CAS) part. `cas_blob_upload_pool_size` limits the maximum number of threads in the pool. Zero is rejected: the pool must have at least one thread. )", 0) \ - DECLARE(UInt64, max_iceberg_manifest_decode_thread_pool_size, 100, R"( -Maximum total number of threads to use for decoding Iceberg data manifest files. - -The pool is separate from the IO pool on purpose: a decode task can block until the query consumes the entries it has produced, while the delete manifest decode waits for its tasks on the IO pool before any entry is consumed - sharing one pool could deadlock. -)", 0) \ - DECLARE(UInt64, max_iceberg_manifest_decode_thread_pool_free_size, 0, R"( -Maximum number of idle standby threads to keep in the thread pool for decoding Iceberg data manifest files. -)", 0) \ - DECLARE(UInt64, iceberg_manifest_decode_thread_pool_queue_size, 10000, R"( -The maximum number of jobs that can be scheduled on the thread pool for decoding Iceberg data manifest files. -)", 0) \ + DECLARE(UInt64, max_iceberg_manifest_decode_thread_pool_size, 100, R"(Maximum total number of threads to use for decoding Iceberg data manifest files. The setting is deprecated and has no effect: Iceberg manifest files are read on the IO thread pool.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, max_iceberg_manifest_decode_thread_pool_free_size, 0, R"(Maximum number of idle standby threads to keep in the thread pool for decoding Iceberg data manifest files. The setting is deprecated and has no effect: Iceberg manifest files are read on the IO thread pool.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, iceberg_manifest_decode_thread_pool_queue_size, 10000, R"(The maximum number of jobs that can be scheduled on the thread pool for decoding Iceberg data manifest files. The setting is deprecated and has no effect: Iceberg manifest files are read on the IO thread pool.)", SettingsTierType::OBSOLETE) \ DECLARE(NonZeroUInt64, ai_function_max_thread_pool_size, 1000, R"( Maximum total number of threads to use for requests to AI providers. One thread holds one request, so this caps how many AI provider requests the whole server has in flight at once, across all queries. [`ai_function_max_concurrent_requests_per_thread`](/reference/settings/session-settings/ai-function#ai_function_max_concurrent_requests_per_thread) bounds each query thread's share of it. )", 0) \ @@ -3712,12 +3704,6 @@ ChangeableSettingsMap collectChangeableServerSettings(ContextPtr context) {getFormatParsingThreadPool().isInitialized() ? std::to_string(getFormatParsingThreadPool().get().getMaxFreeThreads()) : "0", ChangeableWithoutRestart::Yes}}, {"format_parsing_thread_pool_queue_size", {getFormatParsingThreadPool().isInitialized() ? std::to_string(getFormatParsingThreadPool().get().getQueueSize()) : "0", ChangeableWithoutRestart::Yes}}, - {"max_iceberg_manifest_decode_thread_pool_size", - {getIcebergManifestDecodeThreadPool().isInitialized() ? std::to_string(getIcebergManifestDecodeThreadPool().get().getMaxThreads()) : "0", ChangeableWithoutRestart::Yes}}, - {"max_iceberg_manifest_decode_thread_pool_free_size", - {getIcebergManifestDecodeThreadPool().isInitialized() ? std::to_string(getIcebergManifestDecodeThreadPool().get().getMaxFreeThreads()) : "0", ChangeableWithoutRestart::Yes}}, - {"iceberg_manifest_decode_thread_pool_queue_size", - {getIcebergManifestDecodeThreadPool().isInitialized() ? std::to_string(getIcebergManifestDecodeThreadPool().get().getQueueSize()) : "0", ChangeableWithoutRestart::Yes}}, {"ai_function_max_thread_pool_size", {getAIRequestThreadPool().isInitialized() ? std::to_string(getAIRequestThreadPool().get().getMaxThreads()) : "0", ChangeableWithoutRestart::Yes}}, {"ai_function_max_thread_pool_free_size", diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index 99c27e42f5cd..bd0107ed2f2c 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -6109,22 +6109,6 @@ Possible values: )", 0) \ DECLARE(UInt64, iceberg_metadata_staleness_ms, 0, R"( If non-zero, skip fetching iceberg metadata from remote catalog if there is a cached metadata snapshot, more recent than the given staleness window. Zero means to always fetch the latest metadata version from the remote catalog. Setting this a non-zero trades staleness to a lower latency of read operations. -)", 0) \ - DECLARE_WITH_ALIAS(NonZeroUInt64, iceberg_manifest_decode_concurrency, 4, R"( -Maximum number of Iceberg manifest files decoded concurrently while reading a table. - -Delete manifests are all decoded before any data file is read; data manifests are decoded while the list of data files for the query is produced, and new ones are decoded only as the query consumes already decoded entries. Decoding several manifests at a time overlaps the object storage round-trips and the per-entry pruning work. - -Higher values raise peak memory when the Iceberg metadata files cache is disabled or full, since each in-flight manifest then holds its own decoded contents. - -Must be greater than zero; `1` decodes the manifests one at a time. -)", 0, iceberg_delete_manifest_decode_concurrency) \ - DECLARE(NonZeroUInt64, iceberg_file_entries_queue_size, 100, R"( -Capacity of the queue between the Iceberg data manifest decode tasks and the query, in data file entries. - -The decode tasks pause once the queue is full and the query is not consuming, so this also bounds the read-ahead. - -Must be greater than zero. )", 0) \ DECLARE(Bool, use_parquet_metadata_cache, true, R"( If turned on, parquet format may utilize the parquet metadata cache. @@ -9662,7 +9646,10 @@ Enable experimental table function `eval`. MAKE_OBSOLETE(M, Bool, query_plan_use_new_logical_join_step, true) \ MAKE_OBSOLETE(M, UInt64, cloud_mode_database_engine, 1) \ MAKE_OBSOLETE(M, Bool, allow_retries_in_cluster_requests, false) \ - MAKE_OBSOLETE(M, Bool, allow_named_collection_override_by_default, true) + MAKE_OBSOLETE(M, Bool, allow_named_collection_override_by_default, true) \ + MAKE_OBSOLETE(M, NonZeroUInt64, iceberg_manifest_decode_concurrency, 4) \ + MAKE_OBSOLETE(M, NonZeroUInt64, iceberg_delete_manifest_decode_concurrency, 4) \ + MAKE_OBSOLETE(M, NonZeroUInt64, iceberg_file_entries_queue_size, 100) /** The section above is for obsolete settings. Do not add anything there. */ #endif /// __CLION_IDE__ diff --git a/src/IO/SharedThreadPools.h b/src/IO/SharedThreadPools.h index f502cdc3aeac..1782d200dda4 100644 --- a/src/IO/SharedThreadPools.h +++ b/src/IO/SharedThreadPools.h @@ -71,7 +71,6 @@ class StaticThreadPool M(MergeTreePrefixesDeserialization, "MergeTreePrefixesDeserializationThreadPool", MergeTreeSubcolumnsReader) \ M(DropDistributedCache, "DropDistributedCacheThreadPool", DropDistributedCache) \ M(FormatParsing, "FormatParsingThreadPool", FormatParsing) \ - M(IcebergManifestDecode, "IcebergManifestDecodeThreadPool", IcebergManifestDecode) \ M(ParquetEncoder, "ParquetEncoderThreadPool", ParquetEncoder) \ M(AIRequest, "AIRequestThreadPool", AIRequest) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp index 931981a49932..7acd2247f97e 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp @@ -1,12 +1,8 @@ #include "config.h" -#include #if USE_AVRO #include -#include #include -#include -#include #include #include #include @@ -14,7 +10,6 @@ #include #include #include -#include #include #include @@ -28,7 +23,6 @@ #include #include -#include #include #include #include @@ -55,8 +49,8 @@ #include #include +#include #include -#include #include #include @@ -85,8 +79,6 @@ namespace Setting { extern const SettingsBool use_iceberg_partition_pruning; extern const SettingsBool use_iceberg_manifest_list_partition_pruning; -extern const SettingsNonZeroUInt64 iceberg_file_entries_queue_size; -extern const SettingsNonZeroUInt64 iceberg_manifest_decode_concurrency; }; using namespace Iceberg; @@ -94,9 +86,6 @@ using namespace Iceberg; namespace { -/// All entries of one manifest file, produced by a single decode task. -using ManifestEntryBatch = std::vector; - /// decode path agrees on whether pruning applies. std::shared_ptr makeManifestFilterDag(const ActionsDAG * filter_dag, const ContextPtr & context) { @@ -184,157 +173,6 @@ std::span defineDeletesSpan( } -namespace Iceberg -{ - -DataFileEntriesStream::DataFileEntriesStream( - size_t queue_size_, - size_t decode_concurrency_, - IcebergDataSnapshotPtr data_snapshot_, - std::function prepare_, - CreateManifestIterator create_manifest_iterator_, - SkipManifest skip_manifest_) - : chunk_size(queue_size_) - , decode_concurrency(decode_concurrency_) - , data_snapshot(std::move(data_snapshot_)) - , prepare(std::move(prepare_)) - , create_manifest_iterator(std::move(create_manifest_iterator_)) - , skip_manifest(std::move(skip_manifest_)) - , queue(queue_size_) -{ - producer = std::make_unique( - [this, thread_group = CurrentThread::getGroup()]() - { - DB::ThreadGroupSwitcher switcher(thread_group, DB::ThreadName::ICEBERG_ITERATOR); - try - { - run(); - } - catch (...) - { - std::lock_guard lock(exception_mutex); - if (!exception) - { - exception = std::current_exception(); - } - } - stop(); - }); -} - -DataFileEntriesStream::~DataFileEntriesStream() -{ - stop(); - if (producer) - { - producer->join(); - } -} - -bool DataFileEntriesStream::pop(ProcessedManifestFileEntryPtr & entry) -{ - return queue.pop(entry); -} - -void DataFileEntriesStream::clearAndFinish() -{ - stopped.store(true, std::memory_order_relaxed); - queue.clearAndFinish(); -} - -void DataFileEntriesStream::stop() -{ - stopped.store(true, std::memory_order_relaxed); - queue.finish(); -} - -std::exception_ptr DataFileEntriesStream::getException() const -{ - std::lock_guard lock(exception_mutex); - return exception; -} - -void DataFileEntriesStream::run() -{ - if (!data_snapshot) - return; - - if (prepare) - prepare(); - - auto stream_runner = threadPoolCallbackRunnerUnsafe(getIcebergManifestDecodeThreadPool().get(), DB::ThreadName::ICEBERG_ITERATOR); - - std::deque> in_flight; - SCOPE_EXIT({ - for (auto & manifest : in_flight) - { - if (manifest->future.valid()) - manifest->future.wait(); - } - }); - - const auto & manifest_list_entries = data_snapshot->manifest_list_entries; - size_t next_index = 0; - while (!stopped.load(std::memory_order_relaxed)) - { - while (in_flight.size() < decode_concurrency && next_index < manifest_list_entries.size()) - { - const size_t index = next_index++; - if (manifest_list_entries[index].content_type != ManifestFileContentType::DATA) - continue; - if (skip_manifest && skip_manifest(manifest_list_entries[index])) - continue; - auto manifest = std::make_unique(manifest_list_entries[index]); - auto * scheduled = manifest.get(); - manifest->future = stream_runner([this, scheduled] { decodeChunk(*scheduled); }, Priority{}); - in_flight.push_back(std::move(manifest)); - } - - if (in_flight.empty()) - return; - - auto & manifest = *in_flight.front(); - manifest.future.get(); - - for (auto & entry : manifest.chunk) - { - if (!queue.push(std::move(entry))) - return; - } - manifest.chunk.clear(); - - if (manifest.exhausted) - in_flight.pop_front(); - else - manifest.future = stream_runner([this, scheduled = &manifest] { decodeChunk(*scheduled); }, Priority{}); - } -} - -void DataFileEntriesStream::decodeChunk(InFlightManifest & manifest) -{ - if (stopped.load(std::memory_order_relaxed)) - { - manifest.exhausted = true; - return; - } - - if (!manifest.iterator) - manifest.iterator = create_manifest_iterator(manifest.key, &stopped); - - while (manifest.chunk.size() < chunk_size) - { - auto entry = manifest.iterator->next(); - if (!entry) - { - manifest.exhausted = true; - return; - } - manifest.chunk.push_back(std::move(entry)); - } -} - -} - IcebergIterator::IcebergIterator( ObjectStoragePtr object_storage_, ContextPtr local_context_, @@ -365,75 +203,171 @@ IcebergIterator::IcebergIterator( && local_context->getSettingsRef()[Setting::use_iceberg_partition_pruning] && local_context->getSettingsRef()[Setting::use_iceberg_manifest_list_partition_pruning]; - data_files_stream = std::make_unique( - local_context->getSettingsRef()[Setting::iceberg_file_entries_queue_size], - local_context->getSettingsRef()[Setting::iceberg_manifest_decode_concurrency], - data_snapshot, - [this, manifest_list_pruning_enabled] - { - if (manifest_filter_dag) - VirtualColumnUtils::buildOrderedSetsForDAG(*manifest_filter_dag, local_context); - /// The key conditions of the pruner are built over the filter DAG, so they need its - /// ordered sets to be ready. - if (manifest_list_pruning_enabled) - manifest_list_pruner = std::make_unique( - *persistent_components.schema_processor, - table_state_snapshot->schema_id, - data_snapshot->schema_id_on_snapshot_commit, - data_snapshot->partition_specs, - manifest_filter_dag.get(), - local_context); - }, - [this](const ManifestFileCacheKey & manifest_list_entry, const std::atomic * stop_flag) - { return createManifestIterator(manifest_list_entry, stop_flag); }, - [this](const ManifestFileCacheKey & manifest_list_entry) + /// The filter sets are shared with the reader of this table, which prepares them on its own + /// thread, so they must be ready before any manifest is pruned. + if (data_snapshot && manifest_filter_dag) + VirtualColumnUtils::buildOrderedSetsForDAG(*manifest_filter_dag, local_context); + + /// The key conditions of the pruner are built over the filter DAG, so they need its ordered sets + /// to be ready. + std::unique_ptr manifest_list_pruner; + if (manifest_list_pruning_enabled) + manifest_list_pruner = std::make_unique( + *persistent_components.schema_processor, + table_state_snapshot->schema_id, + data_snapshot->schema_id_on_snapshot_commit, + data_snapshot->partition_specs, + manifest_filter_dag.get(), + local_context); + + ManifestFileCacheKeys delete_manifest_keys; + ManifestFileCacheKeys data_manifest_keys; + if (data_snapshot) + { + for (const auto & manifest_list_entry : data_snapshot->manifest_list_entries) { - if (!manifest_list_pruner - || !manifest_list_pruner->canBePruned(manifest_list_entry.partition_spec_id, manifest_list_entry.partition_summaries)) - return false; - ProfileEvents::increment(ProfileEvents::IcebergPartitionPrunedManifestFiles); - /// The data files of a skipped manifest are skipped by partition pruning just as the ones - /// rejected entry by entry, so they are counted the same way; without this the counter - /// silently drops to zero exactly when pruning got better. - ProfileEvents::increment(ProfileEvents::IcebergPartitionPrunedFiles, manifest_list_entry.live_files_count); - return true; - }); + if (manifest_list_entry.content_type == Iceberg::ManifestFileContentType::DELETE) + { + delete_manifest_keys.push_back(manifest_list_entry); + continue; + } + if (manifest_list_pruner + && manifest_list_pruner->canBePruned(manifest_list_entry.partition_spec_id, manifest_list_entry.partition_summaries)) + { + ProfileEvents::increment(ProfileEvents::IcebergPartitionPrunedManifestFiles); + /// The data files of a skipped manifest are skipped by partition pruning just as the ones + /// rejected entry by entry, so they are counted the same way; without this the counter + /// silently drops to zero exactly when pruning got better. + ProfileEvents::increment(ProfileEvents::IcebergPartitionPrunedFiles, manifest_list_entry.live_files_count); + continue; + } + data_manifest_keys.push_back(manifest_list_entry); + } + } + + delete_manifests_left = delete_manifest_keys.size(); + ManifestFileCacheKeys manifest_keys = std::move(delete_manifest_keys); + manifest_keys.insert( + manifest_keys.end(), std::make_move_iterator(data_manifest_keys.begin()), std::make_move_iterator(data_manifest_keys.end())); + manifests = std::make_unique( + object_storage, persistent_components, local_context, logger, std::move(manifest_keys), external_storages); } void IcebergIterator::ensureDeletesReady() { - std::lock_guard lock(deletes_mutex); - if (!deletes_ready) + /// Threads arriving before the deletes are ready share the delete manifests; the last one to finish sorts. + UniqueLock lock(deletes_mutex); + while (!deletes_ready) { - ProfileEventTimeIncrement watch(ProfileEvents::IcebergIteratorInitializationMicroseconds); + /// Stored rather than rethrown from a fresh parse, so that every `next` thread sees one error. + if (deletes_exception) + std::rethrow_exception(copyMutableException(deletes_exception)); + + if (delete_manifests_left == 0) + { + if (delete_manifests_in_progress != 0) + { + delete_manifest_parsed.wait(lock.getUnderlyingLock()); + continue; + } + + ProfileEventTimeIncrement watch(ProfileEvents::IcebergIteratorInitializationMicroseconds); + /// Sort objects by common_partition_specification, partition_key_value and added_sequence_number. + /// This is needed to efficiently match delete and data manifests in defineDeletesSpan(). + LOG_DEBUG( + logger, + "Taken {} deletion vector files, {} parquet position delete files and {} equality delete files in iceberg iterator", + deletion_vector_files.size(), + parquet_position_deletes_files.size(), + equality_deletes_files.size()); + std::sort(equality_deletes_files.begin(), equality_deletes_files.end()); + std::sort(deletion_vector_files.begin(), deletion_vector_files.end()); + std::sort(parquet_position_deletes_files.begin(), parquet_position_deletes_files.end()); + deletes_ready = true; + delete_manifest_parsed.notify_all(); + break; + } + + Iceberg::ManifestFilesPrefetcher::FetchPtr fetch; try { - decodeDeleteManifests(); + /// Lock order: `deletes_mutex`, then `data_files_mutex`. + std::lock_guard data_lock(data_files_mutex); + fetch = manifests->take(); } catch (...) { deletes_exception = std::current_exception(); - data_files_stream->clearAndFinish(); + delete_manifest_parsed.notify_all(); + throw; + } + + if (!fetch) + { + /// Every slot is held by a delete manifest another thread is parsing. + if (delete_manifests_in_progress == 0) + { + deletes_exception = std::make_exception_ptr(Exception( + ErrorCodes::LOGICAL_ERROR, "No read-ahead slot is free while no Iceberg delete manifest is being parsed")); + delete_manifest_parsed.notify_all(); + continue; + } + delete_manifest_parsed.wait(lock.getUnderlyingLock()); + continue; } - deletes_ready = true; + chassert(fetch->key().content_type == Iceberg::ManifestFileContentType::DELETE); + --delete_manifests_left; + ++delete_manifests_in_progress; + lock.unlock(); + + std::vector delete_files; + std::exception_ptr error; + try + { + ProfileEventTimeIncrement watch(ProfileEvents::IcebergIteratorInitializationMicroseconds); + auto manifest_file_iterator = createManifestIterator(fetch->key(), fetch->get()); + fetch.reset(); + while (auto entry = manifest_file_iterator->next()) + delete_files.push_back(std::move(entry)); + } + catch (...) + { + error = std::current_exception(); + } + fetch.reset(); + + lock.lock(); + --delete_manifests_in_progress; + if (!error) + { + try + { + for (auto & delete_file : delete_files) + { + if (delete_file->parsed_entry->equality_ids.has_value()) + equality_deletes_files.emplace_back(std::move(delete_file)); + else if (delete_file->parsed_entry->isDeletionVector()) + deletion_vector_files.emplace_back(std::move(delete_file)); + else + parquet_position_deletes_files.emplace_back(std::move(delete_file)); + } + } + catch (...) + { + error = std::current_exception(); + } + } + if (error && !deletes_exception) + deletes_exception = error; + delete_manifest_parsed.notify_all(); } - /// Stored rather than rethrown from a fresh decode, so that every `next` thread sees one error. - if (deletes_exception) - std::rethrow_exception(deletes_exception); } -Iceberg::ManifestIteratorPtr IcebergIterator::createManifestIterator(const ManifestFileCacheKey & manifest_list_entry, const std::atomic * stop_flag) const +Iceberg::ManifestIteratorPtr IcebergIterator::createManifestIterator( + const ManifestFileCacheKey & manifest_list_entry, const Iceberg::ManifestFileCacheableInfo & manifest_file) const { - auto manifest_file_cacheable_part = Iceberg::getManifestFile( - object_storage, - persistent_components, - local_context, - logger, - manifest_list_entry.manifest_file_path, - *external_storages); - return Iceberg::ManifestFileIterator::create( - manifest_file_cacheable_part.deserializer, + manifest_file.getDeserializer(), manifest_list_entry.manifest_file_path, persistent_components.path_resolver, *persistent_components.schema_processor, @@ -442,97 +376,97 @@ Iceberg::ManifestIteratorPtr IcebergIterator::createManifestIterator(const Manif manifest_list_entry.first_row_id, local_context, manifest_filter_dag, - table_state_snapshot->schema_id, - stop_flag); -} - -std::vector IcebergIterator::decodeManifest(const ManifestFileCacheKey & manifest_list_entry, const std::atomic * stop_flag) const -{ - if (stop_flag && stop_flag->load(std::memory_order_relaxed)) - return {}; - - auto manifest_file_iterator = createManifestIterator(manifest_list_entry, stop_flag); - - ManifestEntryBatch batch; - while (auto entry = manifest_file_iterator->next()) - batch.push_back(entry); - /// Iterator and deserializer die here, before the batch is handed over. - return batch; + table_state_snapshot->schema_id); } -void IcebergIterator::decodeDeleteManifests() +Iceberg::ProcessedManifestFileEntryPtr IcebergIterator::nextDataFileEntry() { - std::vector delete_manifests; - if (data_snapshot) + /// The threads calling `next` share the data manifests: each one continues an idle partially read + /// manifest, or else parses the next one, so with one thread the files come in the manifests' order. + UniqueLock lock(data_files_mutex); + while (true) { - for (const auto & manifest_list_entry : data_snapshot->manifest_list_entries) + if (data_files_exception) + std::rethrow_exception(copyMutableException(data_files_exception)); + + Iceberg::ManifestIteratorPtr manifest; + Iceberg::ManifestFilesPrefetcher::FetchPtr fetch; + if (!idle_data_manifests.empty()) { - if (manifest_list_entry.content_type == Iceberg::ManifestFileContentType::DELETE) - delete_manifests.push_back(manifest_list_entry); + manifest = std::move(idle_data_manifests.back()); + idle_data_manifests.pop_back(); } - } + else + { + try + { + fetch = manifests->take(); + } + catch (...) + { + data_files_exception = std::current_exception(); + data_manifest_released.notify_all(); + throw; + } - /// Cap concurrency: each in-flight manifest holds its decoded contents. - const size_t max_in_flight = local_context->getSettingsRef()[Setting::iceberg_manifest_decode_concurrency]; + if (!fetch) + { + if (data_manifests_in_use == 0) + return nullptr; + data_manifest_released.wait(lock.getUnderlyingLock()); + continue; + } + } - auto decode_runner - = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), DB::ThreadName::ICEBERG_DELETE_DECODE); + ++data_manifests_in_use; + lock.unlock(); - std::deque> in_flight; - /// The tasks capture `this`, so none of them may still be running when this function is left. - SCOPE_EXIT({ - for (auto & future : in_flight) + Iceberg::ProcessedManifestFileEntryPtr entry; + std::exception_ptr error; + try { - if (future.valid()) - future.wait(); + if (fetch) + { + manifest = createManifestIterator(fetch->key(), fetch->get()); + fetch.reset(); + } + entry = manifest->next(); } - }); - - size_t next_to_decode = 0; - while (next_to_decode < delete_manifests.size() || !in_flight.empty()) - { - while (in_flight.size() < max_in_flight && next_to_decode < delete_manifests.size()) + catch (...) { - auto decode = [this, manifest_list_entry = delete_manifests[next_to_decode++]]() - { return decodeManifest(manifest_list_entry, /* stop_flag */ nullptr); }; - in_flight.push_back(decode_runner(std::move(decode), Priority{})); + error = std::current_exception(); } + fetch.reset(); + if (!entry) + manifest.reset(); - auto pending = std::move(in_flight.front()); - in_flight.pop_front(); - /// Collected in manifest list order, so the failure reported is the first one in that order. - for (auto & delete_file : pending.get()) + lock.lock(); + --data_manifests_in_use; + if (!error && entry) { - if (delete_file->parsed_entry->equality_ids.has_value()) - equality_deletes_files.emplace_back(std::move(delete_file)); - else if (delete_file->parsed_entry->isDeletionVector()) - deletion_vector_files.emplace_back(std::move(delete_file)); - else - parquet_position_deletes_files.emplace_back(std::move(delete_file)); + try + { + idle_data_manifests.push_back(std::move(manifest)); + } + catch (...) + { + error = std::current_exception(); + } } + if (error && !data_files_exception) + data_files_exception = error; + data_manifest_released.notify_all(); + + if (!error && entry) + return entry; } - chassert(in_flight.empty()); - chassert(next_to_decode == delete_manifests.size()); - - /// Sort objects by common_partition_specification, partition_key_value and added_sequence_number. - /// This is needed to efficiently match delete and data manifests in defineDeletesSpan(). - LOG_DEBUG( - logger, - "Taken {} deletion vector files, {} parquet position delete files and {} equality delete files in iceberg iterator", - deletion_vector_files.size(), - parquet_position_deletes_files.size(), - equality_deletes_files.size()); - std::sort(equality_deletes_files.begin(), equality_deletes_files.end()); - std::sort(deletion_vector_files.begin(), deletion_vector_files.end()); - std::sort(parquet_position_deletes_files.begin(), parquet_position_deletes_files.end()); } ObjectInfoPtr IcebergIterator::next(size_t) { ProfileEventTimeIncrement watch(ProfileEvents::IcebergMetadataReadWaitTimeMicroseconds); ensureDeletesReady(); - Iceberg::ProcessedManifestFileEntryPtr manifest_file_entry; - if (data_files_stream->pop(manifest_file_entry)) + if (auto manifest_file_entry = nextDataFileEntry()) { const auto & raw_metadata_path = manifest_file_entry->parsed_entry->file_path_key.serialize(); auto [storage_to_use, resolved_key] = resolveObjectStorageForPath( @@ -715,12 +649,6 @@ ObjectInfoPtr IcebergIterator::next(size_t) return object_info; } - if (auto exception = data_files_stream->getException()) - { - auto exception_message = getExceptionMessage(exception, true, true); - auto exception_code = getExceptionErrorCode(exception); - throw DB::Exception(exception_code, "Iceberg iterator is failed with exception: {}", exception_message); - } return nullptr; } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.h index 03479370b9e8..bd03e01efc4e 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.h @@ -15,11 +15,7 @@ #include #include -#include -#include - -#include -#include +#include #include #include #include @@ -39,61 +35,7 @@ namespace DB namespace Iceberg { - -class DataFileEntriesStream -{ -public: - using CreateManifestIterator = std::function *)>; - /// Called on the producer thread, after `prepare`, for every data manifest of the snapshot. - using SkipManifest = std::function; - - DataFileEntriesStream( - size_t queue_size_, - size_t decode_concurrency_, - IcebergDataSnapshotPtr data_snapshot_, - std::function prepare_, - CreateManifestIterator create_manifest_iterator_, - SkipManifest skip_manifest_); - - ~DataFileEntriesStream(); - - bool pop(ProcessedManifestFileEntryPtr & entry); - void clearAndFinish(); - std::exception_ptr getException() const; - -private: - struct InFlightManifest - { - explicit InFlightManifest(ManifestFileCacheKey key_) - : key(std::move(key_)) - { - } - - ManifestFileCacheKey key; - ManifestIteratorPtr iterator; - std::vector chunk; - bool exhausted = false; - std::future future; - }; - - void run(); - void decodeChunk(InFlightManifest & manifest); - void stop(); - - const size_t chunk_size; - const size_t decode_concurrency; - const IcebergDataSnapshotPtr data_snapshot; - - const std::function prepare; - const CreateManifestIterator create_manifest_iterator; - const SkipManifest skip_manifest; - ConcurrentBoundedQueue queue; - std::atomic stopped{false}; - mutable std::mutex exception_mutex; - std::exception_ptr exception TSA_GUARDED_BY(exception_mutex); - std::unique_ptr producer; -}; - +class ManifestFilesPrefetcher; } class IcebergIterator : public IObjectIterator @@ -116,9 +58,9 @@ class IcebergIterator : public IObjectIterator private: void ensureDeletesReady(); - void decodeDeleteManifests(); - Iceberg::ManifestIteratorPtr createManifestIterator(const ManifestFileCacheKey & manifest_list_entry, const std::atomic * stop_flag) const; - std::vector decodeManifest(const ManifestFileCacheKey & manifest_list_entry, const std::atomic * stop_flag) const; + Iceberg::ProcessedManifestFileEntryPtr nextDataFileEntry(); + Iceberg::ManifestIteratorPtr createManifestIterator( + const ManifestFileCacheKey & manifest_list_entry, const Iceberg::ManifestFileCacheableInfo & manifest_file) const; LoggerPtr logger; ObjectStoragePtr object_storage; @@ -126,24 +68,33 @@ class IcebergIterator : public IObjectIterator const Iceberg::TableStateSnapshotPtr table_state_snapshot; Iceberg::IcebergDataSnapshotPtr data_snapshot; Iceberg::PersistentTableComponents persistent_components; - /// Shared read-only by the concurrent data- and delete-manifest decode tasks. + /// Shared read-only by the threads parsing data and delete manifests concurrently. std::shared_ptr manifest_filter_dag; IDataLakeMetadata::FileProgressCallback callback; - /// Filled once under `deletes_mutex` and never mutated afterwards, so `next` may read them + + /// Filled under `deletes_mutex` and never mutated after `deletes_ready`, so `next` may read them /// unguarded once it has gone through `ensureDeletesReady`. std::vector deletion_vector_files; std::vector parquet_position_deletes_files; std::vector equality_deletes_files; std::mutex deletes_mutex; + std::condition_variable delete_manifest_parsed; + /// Delete manifests not yet taken. + size_t delete_manifests_left TSA_GUARDED_BY(deletes_mutex) = 0; + size_t delete_manifests_in_progress TSA_GUARDED_BY(deletes_mutex) = 0; bool deletes_ready TSA_GUARDED_BY(deletes_mutex) = false; std::exception_ptr deletes_exception TSA_GUARDED_BY(deletes_mutex); Int32 table_schema_id; std::shared_ptr external_storages; - /// Built on the producer thread of `data_files_stream` and read only there. - std::unique_ptr manifest_list_pruner; - /// Declared last: its tasks call back into `createManifestIterator`, so it must be destroyed - /// (producer joined, tasks drained) before any other member. - std::unique_ptr data_files_stream; + + std::mutex data_files_mutex; + std::condition_variable data_manifest_released; + /// The delete manifests, then the data manifests: one read-ahead window for both. + std::unique_ptr manifests TSA_GUARDED_BY(data_files_mutex); + /// Partially read manifests, each used by one thread at a time. + std::vector idle_data_manifests TSA_GUARDED_BY(data_files_mutex); + size_t data_manifests_in_use TSA_GUARDED_BY(data_files_mutex) = 0; + std::exception_ptr data_files_exception TSA_GUARDED_BY(data_files_mutex); }; } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h index f46865883f36..aee98eed0668 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadataFilesCache.h @@ -193,6 +193,16 @@ class IcebergMetadataFilesCache : public CacheBase(result.first->cached_element); } + /// A miss is not counted: the caller is expected to load the file with `getOrSetManifestFile`, which counts it. + std::optional tryGetManifestFile(const String & data_path) + { + auto cell = Base::get(data_path); + if (!cell) + return std::nullopt; + ProfileEvents::increment(ProfileEvents::IcebergMetadataFilesCacheHits); + return std::get(cell->cached_element); + } + template LatestMetadataVersionPtr getOrSetLatestMetadataVersion(const String & table_path, const std::optional & table_uuid, LoadFunc && load_fn, time_t tolerated_staleness_ms) { diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.cpp index b1e16d047ea6..6374e0c6f273 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.cpp @@ -4,9 +4,14 @@ #include #include +#include #include +#include +#include +#include + #include #include #include @@ -21,6 +26,48 @@ namespace DB::ErrorCodes namespace DB::Iceberg { +struct ManifestFileCacheableInfo::State +{ + State(String bytes_, const IcebergPathFromMetadata & path_, const FormatSettings & format_settings_) + : path(path_) + , bytes(std::move(bytes_)) + , format_settings(format_settings_) + { + } + + const IcebergPathFromMetadata path; + /// Released once parsed. + String bytes; + std::optional format_settings; + + std::once_flag parsed; + std::shared_ptr deserializer; +}; + +ManifestFileCacheableInfo ManifestFileCacheableInfo::fromBytes( + String bytes, const IcebergPathFromMetadata & path, const FormatSettings & format_settings) +{ + const size_t size = bytes.size(); + return ManifestFileCacheableInfo{std::make_shared(std::move(bytes), path, format_settings), size}; +} + +std::shared_ptr ManifestFileCacheableInfo::getDeserializer() const +{ + chassert(state); + std::call_once( + state->parsed, + [&parsed_state = *state] + { + parsed_state.deserializer = std::make_shared( + std::make_unique(parsed_state.path.serialize(), parsed_state.bytes), + parsed_state.path, + *parsed_state.format_settings); + String().swap(parsed_state.bytes); + parsed_state.format_settings.reset(); + }); + return state->deserializer; +} + String FileContentTypeToString(FileContentType type) { switch (type) diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.h index e29418e683c2..9f5f22aaf646 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFile.h @@ -31,6 +31,11 @@ struct ColumnInfo #include +namespace DB +{ +struct FormatSettings; +} + namespace DB::Iceberg { @@ -83,10 +88,18 @@ struct PartitionFieldSummary using PartitionFieldSummaries = std::vector; +/// The bytes of a manifest file, parsed by the first `getDeserializer` call. struct ManifestFileCacheableInfo { - std::shared_ptr deserializer; - size_t file_bytes_size; + struct State; + + static ManifestFileCacheableInfo fromBytes(String bytes, const IcebergPathFromMetadata & path, const FormatSettings & format_settings); + + /// Thread-safe. Concurrent callers wait for one parse; if it throws, the next caller parses again. + std::shared_ptr getDeserializer() const; + + std::shared_ptr state; + size_t file_bytes_size = 0; }; /// Description of Data file in manifest file diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp index 770164f7d361..42c422641be3 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp @@ -238,8 +238,7 @@ std::shared_ptr ManifestFileIterator::create( std::optional inherited_first_row_id_, DB::ContextPtr context_, std::shared_ptr filter_dag_, - Int32 table_snapshot_schema_id_, - const std::atomic * stop_flag_) + Int32 table_snapshot_schema_id_) { auto dump_metadata = [&]()->String { return manifest_file_deserializer_->getMetadataContent(); }; insertRowToLogTable( @@ -337,8 +336,7 @@ std::shared_ptr ManifestFileIterator::create( partition_key.partition_spec_fields_count, total_rows, std::move(filter_dag_), - table_snapshot_schema_id_, - stop_flag_)); + table_snapshot_schema_id_)); } ManifestFileIterator::ManifestFileIterator( @@ -358,8 +356,7 @@ ManifestFileIterator::ManifestFileIterator( size_t partition_spec_fields_count_, size_t total_rows_, std::shared_ptr filter_dag_, - Int32 table_snapshot_schema_id_, - const std::atomic * stop_flag_) + Int32 table_snapshot_schema_id_) : manifest_file_deserializer(std::move(manifest_file_deserializer_)) , path_to_manifest_file(path_to_manifest_file_) , format_version(format_version_) @@ -374,7 +371,6 @@ ManifestFileIterator::ManifestFileIterator( , partition_spec_fields_count(partition_spec_fields_count_) , table_snapshot_schema_id(table_snapshot_schema_id_) , total_rows(total_rows_) - , stop_flag(stop_flag_) , data_files_without_deleted(std::make_shared>()) , position_deletes_files_without_deleted(std::make_shared>()) , equality_deletes_files_without_deleted(std::make_shared>()) @@ -662,11 +658,6 @@ ProcessedManifestFileEntryPtr ManifestFileIterator::next() fully_initialized.store(true); return nullptr; } - /// The data manifest decode tasks pass the stream's stopped flag here, so a cancelled - /// query stops decoding mid-manifest. Checked between rows rather than by the caller, - /// because a long stretch of pruned rows yields nothing the caller could check on. - if (stop_flag && stop_flag->load(std::memory_order_relaxed)) - return nullptr; auto entry = processRow(row_index); if (entry) return entry; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.h index dea46c624da5..bf3a571bd984 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.h @@ -95,8 +95,7 @@ class ManifestFileIterator : public boost::noncopyable std::optional inherited_first_row_id, DB::ContextPtr context, std::shared_ptr filter_dag_, - Int32 table_snapshot_schema_id_, - const std::atomic * stop_flag = nullptr); + Int32 table_snapshot_schema_id_); ManifestFileEntriesHandle getFilesWithoutDeletedHandle() const; @@ -143,8 +142,7 @@ class ManifestFileIterator : public boost::noncopyable size_t partition_spec_fields_count, size_t total_rows, std::shared_ptr filter_dag, - Int32 table_snapshot_schema_id, - const std::atomic * stop_flag); + Int32 table_snapshot_schema_id); ProcessedManifestFileEntryPtr processRow(size_t row_index); @@ -169,8 +167,6 @@ class ManifestFileIterator : public boost::noncopyable /// Iteration state const size_t total_rows; - /// When set and observed true, `next` gives up between rows and returns nullptr as on EOF. - const std::atomic * const stop_flag; std::atomic current_row_index{0}; std::atomic fully_initialized{false}; std::atomic active_fetchers{0}; diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp index 2062e8eacb95..efd827f1d538 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.cpp @@ -47,9 +47,12 @@ #include +#include #include #include #include +#include +#include namespace DB { @@ -123,6 +126,12 @@ PartitionFieldSummaries parsePartitionFieldSummaries(const AvroForIcebergDeseria return summaries; } +bool useMetadataCacheForManifestFiles(const PersistentTableComponents & persistent_table_components, const ContextPtr & local_context) +{ + return persistent_table_components.metadata_cache + && local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value < DB::IcebergMetadataLogLevel::ManifestFileMetadata; +} + } Iceberg::ManifestFileCacheableInfo getManifestFile( @@ -133,10 +142,7 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( const IcebergPathFromMetadata & filename, ExternalStorageCache & external_storages) { - auto log_level = local_context->getSettingsRef()[Setting::iceberg_metadata_log_level].value; - - bool use_iceberg_metadata_cache - = (persistent_table_components.metadata_cache && log_level < DB::IcebergMetadataLogLevel::ManifestFileMetadata); + const bool use_iceberg_metadata_cache = useMetadataCacheForManifestFiles(persistent_table_components, local_context); auto create_fn = [&, use_iceberg_metadata_cache]() { @@ -158,11 +164,10 @@ Iceberg::ManifestFileCacheableInfo getManifestFile( }); auto buffer = createReadBuffer(manifest_object_info, storage_to_use, local_context, log, read_settings); - auto manifest_file_deserializer = std::make_shared( - std::move(buffer), filename, getFormatSettings(local_context)); + String manifest_file_bytes; + readStringUntilEOF(manifest_file_bytes, *buffer); - const size_t manifest_file_bytes = manifest_file_deserializer->bytesRead(); - return Iceberg::ManifestFileCacheableInfo{std::move(manifest_file_deserializer), manifest_file_bytes}; + return Iceberg::ManifestFileCacheableInfo::fromBytes(std::move(manifest_file_bytes), filename, getFormatSettings(local_context)); }; if (use_iceberg_metadata_cache && persistent_table_components.table_uuid.has_value()) @@ -191,8 +196,18 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH cache_key.manifest_file_path, external_storages); + return getManifestFileEntriesHandle(cacheable_info, persistent_table_components, local_context, cache_key, table_snapshot_schema_id); +} + +Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesHandle( + const ManifestFileCacheableInfo & manifest_file, + const PersistentTableComponents & persistent_table_components, + ContextPtr local_context, + const ManifestFileCacheKey & cache_key, + Int32 table_snapshot_schema_id) +{ auto iterator = Iceberg::ManifestFileIterator::create( - cacheable_info.deserializer, + manifest_file.getDeserializer(), cache_key.manifest_file_path, persistent_table_components.path_resolver, *persistent_table_components.schema_processor, @@ -356,6 +371,100 @@ ManifestFileCacheKeys getManifestList( return manifest_file_cache_keys; } +ManifestFilesPrefetcher::Fetch::Fetch(ManifestFilesPrefetcher & owner_, const ManifestFileCacheKey & manifest_, size_t leased_bytes_) + : owner(owner_) + , manifest(manifest_) + , leased_bytes(leased_bytes_) +{ + ++owner.leased; + owner.leased_bytes += leased_bytes; +} + +ManifestFilesPrefetcher::Fetch::~Fetch() +{ + if (pending.valid()) + pending.wait(); + owner.leased_bytes -= leased_bytes; + --owner.leased; +} + +ManifestFileCacheableInfo ManifestFilesPrefetcher::Fetch::get() +{ + if (!cached) + cached = pending.get(); + return *cached; +} + +ManifestFilesPrefetcher::ManifestFilesPrefetcher( + ObjectStoragePtr object_storage_, + const PersistentTableComponents & persistent_table_components_, + ContextPtr local_context_, + LoggerPtr log_, + ManifestFileCacheKeys manifests_, + std::shared_ptr external_storages_) + : object_storage(std::move(object_storage_)) + , persistent_table_components(persistent_table_components_) + , local_context(std::move(local_context_)) + , log(std::move(log_)) + , manifests(std::move(manifests_)) + , external_storages(std::move(external_storages_)) + , use_metadata_cache( + useMetadataCacheForManifestFiles(persistent_table_components, local_context) && persistent_table_components.table_uuid.has_value()) +{ + fill(); +} + +ManifestFilesPrefetcher::~ManifestFilesPrefetcher() +{ + *stopped = true; + window.clear(); +} + +ManifestFilesPrefetcher::FetchPtr ManifestFilesPrefetcher::take() +{ + fill(); + if (window.empty()) + return nullptr; + auto fetch = std::move(window.front()); + window.pop_front(); + return fetch; +} + +void ManifestFilesPrefetcher::fill() +{ + auto runner = threadPoolCallbackRunnerUnsafe(getIOThreadPool().get(), ThreadName::ICEBERG_ITERATOR); + + while (next_to_fetch < manifests.size() && leased < max_manifest_files_in_flight) + { + const auto & manifest = manifests[next_to_fetch]; + + std::optional cached; + if (use_metadata_cache) + cached = persistent_table_components.metadata_cache->tryGetManifestFile( + IcebergMetadataFilesCache::getKey(*persistent_table_components.table_uuid, manifest.manifest_file_path.serialize())); + + const size_t bytes = cached ? 0 : manifest.manifest_file_byte_size; + if (bytes != 0 && leased_bytes != 0 && leased_bytes + bytes > max_manifest_bytes_in_flight) + break; + + auto fetch = FetchPtr(new Fetch(*this, manifest, bytes)); + if (cached) + fetch->cached = std::move(cached); + else + fetch->pending = runner( + [stopped_ = stopped, object_storage_ = object_storage, components = persistent_table_components, context = local_context, log_ = log, path = manifest.manifest_file_path, external_storages_ = external_storages] + { + if (*stopped_) + return ManifestFileCacheableInfo{}; + return getManifestFile(object_storage_, components, context, log_, path, *external_storages_); + }, + Priority{}); + + window.push_back(std::move(fetch)); + ++next_to_fetch; + } +} + } } diff --git a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h index 58f69f65c966..944ae9f79a01 100644 --- a/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h +++ b/src/Storages/ObjectStorage/DataLakes/Iceberg/StatelessMetadataFileGetter.h @@ -2,7 +2,12 @@ #include "config.h" #if USE_AVRO +#include #include +#include +#include +#include +#include #include @@ -19,9 +24,12 @@ #include #include +#include + namespace DB::Iceberg { +/// Reads the manifest file without parsing it; the parse happens on the first `getDeserializer` call. Iceberg::ManifestFileCacheableInfo getManifestFile( ObjectStoragePtr object_storage, const PersistentTableComponents & persistent_table_components, @@ -42,6 +50,13 @@ Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesH Int32 table_snapshot_schema_id, ExternalStorageCache & external_storages); +Iceberg::ManifestFileIterator::ManifestFileEntriesHandle getManifestFileEntriesHandle( + const ManifestFileCacheableInfo & manifest_file, + const PersistentTableComponents & persistent_table_components, + ContextPtr local_context, + const ManifestFileCacheKey & cache_key, + Int32 table_snapshot_schema_id); + ManifestFileCacheKeys getManifestList( ObjectStoragePtr object_storage, @@ -51,6 +66,75 @@ ManifestFileCacheKeys getManifestList( LoggerPtr log, ExternalStorageCache & external_storages); +/// Reads manifest files ahead, in order, on the IO thread pool. Not thread-safe. +class ManifestFilesPrefetcher : private boost::noncopyable +{ +public: + /// A manifest file that is read or being read. Holds one of the prefetcher's slots until destroyed, + /// so it must not outlive the prefetcher. + class Fetch : private boost::noncopyable + { + public: + ~Fetch(); + + const ManifestFileCacheKey & key() const { return manifest; } + + /// Waits for the read. Must be called at most once. + ManifestFileCacheableInfo get(); + + private: + friend class ManifestFilesPrefetcher; + + Fetch(ManifestFilesPrefetcher & owner_, const ManifestFileCacheKey & manifest_, size_t leased_bytes_); + + ManifestFilesPrefetcher & owner; + const ManifestFileCacheKey & manifest; + const size_t leased_bytes; + std::optional cached; + std::future pending; + }; + + using FetchPtr = std::unique_ptr; + + ManifestFilesPrefetcher( + ObjectStoragePtr object_storage_, + const PersistentTableComponents & persistent_table_components_, + ContextPtr local_context_, + LoggerPtr log_, + ManifestFileCacheKeys manifests_, + std::shared_ptr external_storages_); + + ~ManifestFilesPrefetcher(); + + /// The next manifest file in order. Returns nullptr when none is left, and also while all slots are + /// held by taken fetches: then it succeeds again once one of them is destroyed. + FetchPtr take(); + +private: + void fill(); + + static constexpr size_t max_manifest_files_in_flight = 64; + /// Counts only the files that are not in the metadata files cache. A larger file is still read when it is the only one. + static constexpr size_t max_manifest_bytes_in_flight = 64 << 20; + + const ObjectStoragePtr object_storage; + const PersistentTableComponents persistent_table_components; + const ContextPtr local_context; + const LoggerPtr log; + const ManifestFileCacheKeys manifests; + /// Shared with the reads in flight, which may outlive the prefetcher. + const std::shared_ptr external_storages; + const bool use_metadata_cache; + + size_t next_to_fetch = 0; + /// Released by `Fetch` destructors, which may run outside the owner's lock. + std::atomic leased = 0; + std::atomic leased_bytes = 0; + /// Set on destruction: the reads that have not started yet are skipped. + const std::shared_ptr> stopped = std::make_shared>(false); + std::deque window; +}; + } #endif diff --git a/tests/integration/test_iceberg_manifest_decode_pool/__init__.py b/tests/integration/test_iceberg_manifest_decode_pool/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/integration/test_iceberg_manifest_decode_pool/configs/decode_pool.xml b/tests/integration/test_iceberg_manifest_decode_pool/configs/decode_pool.xml deleted file mode 100644 index e0ad5b6cbbf8..000000000000 --- a/tests/integration/test_iceberg_manifest_decode_pool/configs/decode_pool.xml +++ /dev/null @@ -1,3 +0,0 @@ - - 1 - diff --git a/tests/integration/test_iceberg_manifest_decode_pool/test.py b/tests/integration/test_iceberg_manifest_decode_pool/test.py deleted file mode 100644 index 3492ffa904c4..000000000000 --- a/tests/integration/test_iceberg_manifest_decode_pool/test.py +++ /dev/null @@ -1,98 +0,0 @@ -import pytest - -from helpers.cluster import ClickHouseCluster - -cluster = ClickHouseCluster(__file__) -node = cluster.add_instance("node", main_configs=["configs/decode_pool.xml"]) - - -@pytest.fixture(scope="module") -def started_cluster(): - try: - cluster.start() - yield cluster - finally: - cluster.shutdown() - - -def test_nested_iceberg_read_with_single_pool_thread(started_cluster): - """A pruning subquery reading another Iceberg table must not deadlock the decode - pool: the sets are built on the producer thread before any pool task runs, so the - single pool thread is never held by a task that waits for a nested read.""" - node.query( - """ - CREATE TABLE ice_main (id Int64, part Int64) - ENGINE = IcebergLocal(concat(getServerSetting('user_files_path'), '/ice_main/')) - """ - ) - node.query( - """ - CREATE TABLE ice_parts (part Int64) - ENGINE = IcebergLocal(concat(getServerSetting('user_files_path'), '/ice_parts/')) - """ - ) - # One commit per insert, so both tables have several manifests to decode. - for part in range(8): - node.query( - f"INSERT INTO ice_main SELECT number + {part} * 10, {part} FROM numbers(10) " - "SETTINGS allow_insert_into_iceberg = 1" - ) - for part in [1, 3, 6]: - node.query( - f"INSERT INTO ice_parts SELECT {part} " - "SETTINGS allow_insert_into_iceberg = 1" - ) - - result = node.query( - "SELECT count() FROM ice_main WHERE part IN (SELECT part FROM ice_parts)", - settings={ - "iceberg_manifest_decode_concurrency": 4, - "use_iceberg_metadata_files_cache": 0, - }, - timeout=120, - ) - assert int(result.strip()) == 30 - - node.query("DROP TABLE ice_main") - node.query("DROP TABLE ice_parts") - - -def test_join_of_two_iceberg_tables_with_single_pool_thread(started_cluster): - node.query( - """ - CREATE TABLE ice_left (id Int64) - ENGINE = IcebergLocal(concat(getServerSetting('user_files_path'), '/ice_left/')) - """ - ) - node.query( - """ - CREATE TABLE ice_right (id Int64) - ENGINE = IcebergLocal(concat(getServerSetting('user_files_path'), '/ice_right/')) - """ - ) - # One commit per insert, so each side has several data files to hand over. - for i in range(8): - node.query( - f"INSERT INTO ice_left SELECT number + {i} * 10 FROM numbers(10) " - "SETTINGS allow_insert_into_iceberg = 1" - ) - node.query( - f"INSERT INTO ice_right SELECT number + {i} * 10 FROM numbers(10) " - "SETTINGS allow_insert_into_iceberg = 1" - ) - - result = node.query( - "SELECT count() FROM ice_left AS l INNER JOIN ice_right AS r ON l.id = r.id", - settings={ - "iceberg_manifest_decode_concurrency": 4, - # The smallest queue: the second data file of a side already has to wait for the - # query to consume the first one, which is what used to park a pool thread. - "iceberg_file_entries_queue_size": 1, - "use_iceberg_metadata_files_cache": 0, - }, - timeout=120, - ) - assert int(result.strip()) == 80 - - node.query("DROP TABLE ice_left") - node.query("DROP TABLE ice_right") diff --git a/tests/integration/test_storage_iceberg_with_spark/test_data_manifest_decode_concurrency.py b/tests/integration/test_storage_iceberg_with_spark/test_data_manifest_decode_concurrency.py index e027ec542382..aef69fc9f238 100644 --- a/tests/integration/test_storage_iceberg_with_spark/test_data_manifest_decode_concurrency.py +++ b/tests/integration/test_storage_iceberg_with_spark/test_data_manifest_decode_concurrency.py @@ -9,9 +9,6 @@ ROWS_PER_INSERT = 4 ROW_COUNT = DATA_MANIFEST_COUNT * ROWS_PER_INSERT -# Must match the delay the `iceberg_slow_manifest_read` failpoint injects. -SLEEP_PER_MANIFEST_SECONDS = 0.40 - STORAGE_TYPE = "local" @@ -19,17 +16,6 @@ def get_array(query_result: str): return sorted([int(x) for x in query_result.strip().split("\n")]) -def elapsed(node, query, **kwargs): - query_id = get_uuid_str() - node.query(query, query_id=query_id, **kwargs) - node.query("SYSTEM FLUSH LOGS query_log") - duration_result = node.query( - f"""SELECT query_duration_ms / 1000.0 as duration FROM system.query_log - WHERE type = 'QueryFinish' AND query_id = '{query_id}' LIMIT 1""" - ) - return float(duration_result.strip()) - - def write_table( started_cluster, table_name: str, merge_on_read: bool = False, format_version: int = 2 ): @@ -92,7 +78,8 @@ def check_data_manifests(instance, table_expression: str) -> None: def test_data_manifest_decode_concurrency(started_cluster_iceberg_with_spark): - """The result must not depend on `iceberg_manifest_decode_concurrency`.""" + """The result must not depend on how many threads read the table: one thread parses + the manifests in order, several threads parse different manifests concurrently.""" instance = started_cluster_iceberg_with_spark.instances["node1"] TABLE_NAME = "test_data_manifest_decode_concurrency_" + get_uuid_str() @@ -103,20 +90,18 @@ def test_data_manifest_decode_concurrency(started_cluster_iceberg_with_spark): check_data_manifests(instance, TABLE_NAME) expected = list(range(ROW_COUNT)) - for concurrency in [1, 2, 4, 16]: + for max_threads in [1, 16]: assert ( get_array( instance.query( f"SELECT id FROM {TABLE_NAME} ORDER BY id", - settings={ - "iceberg_manifest_decode_concurrency": concurrency - }, + settings={"max_threads": max_threads}, ) ) == expected - ), f"wrong result with iceberg_manifest_decode_concurrency={concurrency}" + ), f"wrong result with max_threads={max_threads}" - # A filter on the partition column makes every concurrent decode task evaluate the same + # A filter on the partition column makes every thread parsing a manifest evaluate the same # shared filter DAG (with its lazily materialized IN set) while pruning manifest entries. filtered_parts = [1, 3, 6] expected_filtered = sorted( @@ -124,18 +109,16 @@ def test_data_manifest_decode_concurrency(started_cluster_iceberg_with_spark): for row_id in range(ROW_COUNT) if row_id // ROWS_PER_INSERT in filtered_parts ) - for concurrency in [1, 2, 4, 16]: + for max_threads in [1, 16]: result = get_array( instance.query( f"SELECT id FROM {TABLE_NAME} WHERE part IN (1, 3, 6) ORDER BY id", - settings={ - "iceberg_manifest_decode_concurrency": concurrency - }, + settings={"max_threads": max_threads}, ) ) assert ( result == expected_filtered - ), f"wrong filtered result with iceberg_manifest_decode_concurrency={concurrency}" + ), f"wrong filtered result with max_threads={max_threads}" instance.query(f"DROP TABLE {TABLE_NAME}") @@ -143,8 +126,8 @@ def test_data_manifest_decode_concurrency(started_cluster_iceberg_with_spark): def test_data_and_delete_manifest_decode_concurrency( started_cluster_iceberg_with_spark, ): - """Data- and delete-manifest decode run concurrently and share one filter DAG; - the result must not depend on the concurrency setting.""" + """Data and delete manifests are parsed concurrently and share one filter DAG; + the result must not depend on how many threads read the table.""" instance = started_cluster_iceberg_with_spark.instances["node1"] TABLE_NAME = "test_data_and_delete_manifest_decode_concurrency_" + get_uuid_str() @@ -171,26 +154,21 @@ def test_data_and_delete_manifest_decode_concurrency( for row_id in range(ROW_COUNT) if row_id // ROWS_PER_INSERT in filtered_parts and row_id not in deleted_ids ) - for concurrency in [1, 4, 16]: + for max_threads in [1, 16]: result = get_array( instance.query( f"SELECT id FROM {TABLE_NAME} WHERE part IN (1, 3, 6) ORDER BY id", - settings={ - "iceberg_manifest_decode_concurrency": concurrency, - }, + settings={"max_threads": max_threads}, ) ) - assert result == expected, ( - f"wrong result with iceberg_manifest_decode_concurrency={concurrency}" - ) + assert result == expected, f"wrong result with max_threads={max_threads}" instance.query(f"DROP TABLE {TABLE_NAME}") def test_data_manifest_decode_large_manifest(started_cluster_iceberg_with_spark): - """A single manifest holding three times more entries than the producer queue's - capacity (100), so pushes block in the middle of the manifest at every concurrency; - the result must not depend on the concurrency.""" + """A single manifest with 300 entries, read by one thread or by several threads + taking turns on it; the result must not depend on how many threads read the table.""" instance = started_cluster_iceberg_with_spark.instances["node1"] spark = started_cluster_iceberg_with_spark.spark_session TABLE_NAME = "test_data_manifest_decode_large_manifest_" + get_uuid_str() @@ -217,33 +195,31 @@ def test_data_manifest_decode_large_manifest(started_cluster_iceberg_with_spark) ) expected = list(range(entry_count)) - for concurrency in [1, 4]: + for max_threads in [1, 16]: result = get_array( instance.query( f"SELECT id FROM {TABLE_NAME} ORDER BY id", settings={ - "iceberg_manifest_decode_concurrency": concurrency, + "max_threads": max_threads, "use_iceberg_metadata_files_cache": 0, }, ) ) - assert ( - result == expected - ), f"wrong result with iceberg_manifest_decode_concurrency={concurrency}" + assert result == expected, f"wrong result with max_threads={max_threads}" # A filter pruning every entry keeps the row loop inside `ManifestFileIterator::next` # busy for the whole manifest without yielding. - for concurrency in [1, 16]: + for max_threads in [1, 16]: count = instance.query( f"SELECT count() FROM {TABLE_NAME} WHERE id < 0", settings={ - "iceberg_manifest_decode_concurrency": concurrency, + "max_threads": max_threads, "use_iceberg_metadata_files_cache": 0, }, ) assert ( int(count.strip()) == 0 - ), f"fully pruned read returned rows with iceberg_manifest_decode_concurrency={concurrency}" + ), f"fully pruned read returned rows with max_threads={max_threads}" instance.query(f"DROP TABLE {TABLE_NAME}") @@ -251,10 +227,10 @@ def test_data_manifest_decode_large_manifest(started_cluster_iceberg_with_spark) def test_data_manifest_decode_concurrency_subquery_filter( started_cluster_iceberg_with_spark, ): - """`part IN (SELECT ...)` is backed by `FutureSetFromSubquery`, which the concurrent - decode tasks build lazily through the shared filter DAG; the result must not depend - on the concurrency. (Literal tuple `IN` goes through `FutureSetFromTuple` instead - and is covered above.)""" + """`part IN (SELECT ...)` is backed by `FutureSetFromSubquery`, which the threads + parsing manifests concurrently use through the shared filter DAG; the result must not + depend on how many threads read the table. (Literal tuple `IN` goes through + `FutureSetFromTuple` instead and is covered above.)""" instance = started_cluster_iceberg_with_spark.instances["node1"] TABLE_NAME = "test_data_manifest_decode_concurrency_subquery_" + get_uuid_str() @@ -270,7 +246,7 @@ def test_data_manifest_decode_concurrency_subquery_filter( for row_id in range(ROW_COUNT) if row_id // ROWS_PER_INSERT in filtered_parts ) - for concurrency in [1, 4, 16]: + for max_threads in [1, 16]: for _ in range(2): result = get_array( instance.query( @@ -278,72 +254,14 @@ def test_data_manifest_decode_concurrency_subquery_filter( "WHERE part IN (SELECT toInt32(number * 2 + 1) FROM numbers(3)) " "ORDER BY id", settings={ - "iceberg_manifest_decode_concurrency": concurrency, + "max_threads": max_threads, "use_iceberg_metadata_files_cache": 0, }, ) ) assert result == expected, ( - f"wrong subquery-filtered result with " - f"iceberg_manifest_decode_concurrency={concurrency}" + f"wrong subquery-filtered result with max_threads={max_threads}" ) instance.query(f"DROP TABLE {TABLE_NAME}") - -def test_data_manifest_decode_concurrency_bounds_reads( - started_cluster_iceberg_with_spark, -): - """`iceberg_manifest_decode_concurrency = 1` reads the manifests one at a - time, so with the failpoint delaying every manifest read the query cannot run - faster than one delay per manifest; a higher value overlaps the reads.""" - instance = started_cluster_iceberg_with_spark.instances["node1"] - - # Skip timing asserts on slow builds. - slow_build = ( - instance.is_built_with_sanitizer() or instance.is_built_with_llvm_coverage() - ) - - TABLE_NAME = "test_data_manifest_decode_concurrency_bounds_" + get_uuid_str() - - write_table(started_cluster_iceberg_with_spark, TABLE_NAME) - create_iceberg_table( - STORAGE_TYPE, instance, TABLE_NAME, started_cluster_iceberg_with_spark - ) - - instance.query("SYSTEM ENABLE FAILPOINT iceberg_slow_manifest_read") - try: - serial_duration = elapsed( - instance, - f"SELECT * FROM {TABLE_NAME} FORMAT Null", - settings={ - "iceberg_manifest_decode_concurrency": 1, - "use_iceberg_metadata_files_cache": 0, - }, - ) - parallel_duration = elapsed( - instance, - f"SELECT * FROM {TABLE_NAME} FORMAT Null", - settings={ - "iceberg_manifest_decode_concurrency": 16, - "use_iceberg_metadata_files_cache": 0, - }, - ) - finally: - instance.query("SYSTEM DISABLE FAILPOINT iceberg_slow_manifest_read") - instance.query(f"DROP TABLE {TABLE_NAME}") - - if slow_build: - return - - serial_floor = 0.9 * DATA_MANIFEST_COUNT * SLEEP_PER_MANIFEST_SECONDS - assert serial_duration >= serial_floor, ( - f"the serial read of {DATA_MANIFEST_COUNT} manifests took {serial_duration:.3f}s, " - f"below the {serial_floor:.3f}s floor of one failpoint delay per manifest, so " - f"iceberg_manifest_decode_concurrency = 1 did not decode them one at a time" - ) - assert parallel_duration < 0.6 * serial_duration, ( - f"the read with iceberg_manifest_decode_concurrency = 16 took " - f"{parallel_duration:.3f}s against {serial_duration:.3f}s serially, so the " - f"manifest reads were likely not overlapped" - ) diff --git a/tests/integration/test_storage_iceberg_with_spark/test_delete_manifest_decode_concurrency.py b/tests/integration/test_storage_iceberg_with_spark/test_delete_manifest_decode_concurrency.py index 4daabe792fff..8134b5ac606f 100644 --- a/tests/integration/test_storage_iceberg_with_spark/test_delete_manifest_decode_concurrency.py +++ b/tests/integration/test_storage_iceberg_with_spark/test_delete_manifest_decode_concurrency.py @@ -87,7 +87,8 @@ def elapsed(instance, query, **kwargs) -> float: def test_delete_manifest_decode_concurrency(started_cluster_iceberg_with_spark): - """The result must not depend on `iceberg_delete_manifest_decode_concurrency`.""" + """The result must not depend on how many threads read the table: the threads that + need the deletes first parse the delete manifests together.""" instance = started_cluster_iceberg_with_spark.instances["node1"] TABLE_NAME = "test_delete_manifest_decode_concurrency_" + get_uuid_str() @@ -98,18 +99,16 @@ def test_delete_manifest_decode_concurrency(started_cluster_iceberg_with_spark): check_delete_manifests(instance, TABLE_NAME) expected = list(range(DELETE_COUNT, ROW_COUNT)) - for concurrency in [1, 2, 4, 16]: + for max_threads in [1, 16]: assert ( get_array( instance.query( f"SELECT id FROM {TABLE_NAME} ORDER BY id", - settings={ - "iceberg_delete_manifest_decode_concurrency": concurrency - }, + settings={"max_threads": max_threads}, ) ) == expected - ), f"wrong result with iceberg_delete_manifest_decode_concurrency={concurrency}" + ), f"wrong result with max_threads={max_threads}" instance.query(f"DROP TABLE {TABLE_NAME}") diff --git a/tests/queries/0_stateless/02888_obsolete_settings.reference b/tests/queries/0_stateless/02888_obsolete_settings.reference index e6e3555b7746..ec48fb5fd7c2 100644 --- a/tests/queries/0_stateless/02888_obsolete_settings.reference +++ b/tests/queries/0_stateless/02888_obsolete_settings.reference @@ -2,6 +2,9 @@ allow_experimental_webterminal allow_impersonate_user dictionaries_lib_path +iceberg_manifest_decode_thread_pool_queue_size +max_iceberg_manifest_decode_thread_pool_free_size +max_iceberg_manifest_decode_thread_pool_size storage_metadata_write_full_object_key -- Obsolete general settings 1 diff --git a/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.reference b/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.reference new file mode 100644 index 000000000000..f60e994e3f13 --- /dev/null +++ b/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.reference @@ -0,0 +1,6 @@ +67 +1 1 +67 2370 +67 2370 +67 2370 +67 2370 diff --git a/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.sh b/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.sh new file mode 100755 index 000000000000..fbd3ea361d18 --- /dev/null +++ b/tests/queries/0_stateless/05441_iceberg_more_manifests_than_read_ahead.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# A table with more manifest files than are read ahead at once is read whole, with one and with several reading threads, with and without the metadata cache. +# +# Tags: no-fasttest +# - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +CH="${CLICKHOUSE_CLIENT} --allow_insert_into_iceberg=1" +TABLE="t_${CLICKHOUSE_DATABASE}" +TABLE_PATH="${USER_FILES_PATH:?}/${TABLE}" +trap 'rm -rf "${TABLE_PATH}"' EXIT + +$CH --query "CREATE TABLE ${TABLE} (id Int64) ENGINE = IcebergLocal('${TABLE_PATH}/', 'Parquet') SETTINGS allow_experimental_iceberg_compaction = 0" +# One data manifest per INSERT. +$CH --query "$(for i in $(seq 70); do echo "INSERT INTO ${TABLE} VALUES ($i);"; done)" + +$CH --query "ALTER TABLE ${TABLE} DELETE WHERE id = 5; ALTER TABLE ${TABLE} DELETE WHERE id = 40; ALTER TABLE ${TABLE} DELETE WHERE id = 70;" +# The trivial count reads the 70 data manifests before it meets a delete manifest and falls back to reading the table. +$CH --query "SELECT count() FROM ${TABLE} SETTINGS optimize_trivial_count_query = 1, use_iceberg_metadata_files_cache = 0, max_threads = 1" + +# More than 64 data manifests and at least one delete manifest. +PREMISE_ID="${CLICKHOUSE_DATABASE}_premise_${RANDOM}${RANDOM}" +$CH --query_id "$PREMISE_ID" --query "SELECT * FROM ${TABLE} SETTINGS iceberg_metadata_log_level = 'manifest_list_entry', use_iceberg_metadata_files_cache = 0, max_threads = 1 FORMAT Null" +$CH --query "SYSTEM FLUSH LOGS iceberg_metadata_log" +$CH --query " + SELECT countIf(c = 0) > 64, countIf(c = 1) > 0 + FROM ( + SELECT JSONExtractString(content, 'manifest_path') AS path, any(JSONExtractInt(content, 'content')) AS c + FROM system.iceberg_metadata_log + WHERE query_id = '$PREMISE_ID' AND content_type = 'ManifestListEntry' + GROUP BY path)" + +# The table keeps the metadata cache it was created with, so the uncached reads go through the table function. +$CH --query "SELECT count(), sum(id) FROM icebergLocal('${TABLE_PATH}/') SETTINGS max_threads = 1, use_iceberg_metadata_files_cache = 0" +$CH --query "SELECT count(), sum(id) FROM icebergLocal('${TABLE_PATH}/') SETTINGS max_threads = 8, use_iceberg_metadata_files_cache = 0" +$CH --query "SELECT count(), sum(id) FROM ${TABLE} SETTINGS max_threads = 8, use_iceberg_metadata_files_cache = 1" +$CH --query "SELECT count(), sum(id) FROM ${TABLE} SETTINGS max_threads = 8, use_iceberg_metadata_files_cache = 1" + +$CH --query "DROP TABLE ${TABLE}"