Skip to content

Antalya 25.6: Forward port of #805 - Object storage list objects cache #919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: antalya-25.6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions programs/server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
#include <Storages/System/attachSystemTables.h>
#include <Storages/System/attachInformationSchemaTables.h>
#include <Storages/Cache/registerRemoteFileMetadatas.h>
#include <Storages/Cache/ObjectStorageListObjectsCache.h>
#include <AggregateFunctions/registerAggregateFunctions.h>
#include <Functions/UserDefined/IUserDefinedSQLObjectsStorage.h>
#include <Functions/registerFunctions.h>
Expand Down Expand Up @@ -326,6 +327,9 @@ namespace ServerSetting
extern const ServerSettingsUInt64 os_cpu_busy_time_threshold;
extern const ServerSettingsFloat min_os_cpu_wait_time_ratio_to_drop_connection;
extern const ServerSettingsFloat max_os_cpu_wait_time_ratio_to_drop_connection;
extern const ServerSettingsUInt64 object_storage_list_objects_cache_size;
extern const ServerSettingsUInt64 object_storage_list_objects_cache_max_entries;
extern const ServerSettingsUInt64 object_storage_list_objects_cache_ttl;
}

namespace ErrorCodes
Expand Down Expand Up @@ -413,6 +417,7 @@ namespace ErrorCodes
extern const int NETWORK_ERROR;
extern const int CORRUPTED_DATA;
extern const int BAD_ARGUMENTS;
extern const int STARTUP_SCRIPTS_ERROR;
}


Expand Down Expand Up @@ -2421,6 +2426,10 @@ try
if (dns_cache_updater)
dns_cache_updater->start();

ObjectStorageListObjectsCache::instance().setMaxSizeInBytes(server_settings[ServerSetting::object_storage_list_objects_cache_size]);
ObjectStorageListObjectsCache::instance().setMaxCount(server_settings[ServerSetting::object_storage_list_objects_cache_max_entries]);
ObjectStorageListObjectsCache::instance().setTTL(server_settings[ServerSetting::object_storage_list_objects_cache_ttl]);

auto replicas_reconnector = ReplicasReconnector::init(global_context);

/// Set current database name before loading tables and databases because
Expand Down
1 change: 1 addition & 0 deletions src/Access/Common/AccessType.h
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ enum class AccessType : uint8_t
M(SYSTEM_DROP_SCHEMA_CACHE, "SYSTEM DROP SCHEMA CACHE, DROP SCHEMA CACHE", GLOBAL, SYSTEM_DROP_CACHE) \
M(SYSTEM_DROP_FORMAT_SCHEMA_CACHE, "SYSTEM DROP FORMAT SCHEMA CACHE, DROP FORMAT SCHEMA CACHE", GLOBAL, SYSTEM_DROP_CACHE) \
M(SYSTEM_DROP_S3_CLIENT_CACHE, "SYSTEM DROP S3 CLIENT, DROP S3 CLIENT CACHE", GLOBAL, SYSTEM_DROP_CACHE) \
M(SYSTEM_DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE, "SYSTEM DROP OBJECT STORAGE LIST OBJECTS CACHE", GLOBAL, SYSTEM_DROP_CACHE) \
M(SYSTEM_DROP_CACHE, "DROP CACHE", GROUP, SYSTEM) \
M(SYSTEM_RELOAD_CONFIG, "RELOAD CONFIG", GLOBAL, SYSTEM_RELOAD) \
M(SYSTEM_RELOAD_USERS, "RELOAD USERS", GLOBAL, SYSTEM_RELOAD) \
Expand Down
5 changes: 4 additions & 1 deletion src/Common/ProfileEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,10 @@ The server successfully detected this situation and will download merged part fr
M(IndexBinarySearchAlgorithm, "Number of times the binary search algorithm is used over the index marks", ValueType::Number) \
M(IndexGenericExclusionSearchAlgorithm, "Number of times the generic exclusion search algorithm is used over the index marks", ValueType::Number) \
M(ParallelReplicasQueryCount, "Number of (sub)queries executed using parallel replicas during a query execution", ValueType::Number) \

M(ObjectStorageListObjectsCacheHits, "Number of times object storage list objects operation hit the cache.", ValueType::Number) \
M(ObjectStorageListObjectsCacheMisses, "Number of times object storage list objects operation miss the cache.", ValueType::Number) \
M(ObjectStorageListObjectsCacheExactMatchHits, "Number of times object storage list objects operation hit the cache with an exact match.", ValueType::Number) \
M(ObjectStorageListObjectsCachePrefixMatchHits, "Number of times object storage list objects operation miss the cache using prefix matching.", ValueType::Number) \

#ifdef APPLY_FOR_EXTERNAL_EVENTS
#define APPLY_FOR_EVENTS(M) APPLY_FOR_BUILTIN_EVENTS(M) APPLY_FOR_EXTERNAL_EVENTS(M)
Expand Down
4 changes: 2 additions & 2 deletions src/Common/TTLCachePolicy.h
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,10 @@ class TTLCachePolicy : public ICachePolicy<Key, Mapped, HashFunction, WeightFunc
return res;
}

private:
protected:
using Cache = std::unordered_map<Key, MappedPtr, HashFunction>;
Cache cache;

private:
/// TODO To speed up removal of stale entries, we could also add another container sorted on expiry times which maps keys to iterators
/// into the cache. To insert an entry, add it to the cache + add the iterator to the sorted container. To remove stale entries, do a
/// binary search on the sorted container and erase all left of the found key.
Expand Down
5 changes: 3 additions & 2 deletions src/Core/ServerSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1064,8 +1064,9 @@ The policy on how to perform a scheduling of CPU slots specified by `concurrent_
See [Controlling behavior on server CPU overload](/operations/settings/server-overload) for more details.
)", 0) \
DECLARE(Float, distributed_cache_keep_up_free_connections_ratio, 0.1f, "Soft limit for number of active connection distributed cache will try to keep free. After the number of free connections goes below distributed_cache_keep_up_free_connections_ratio * max_connections, connections with oldest activity will be closed until the number goes above the limit.", 0) \


DECLARE(UInt64, object_storage_list_objects_cache_size, 500000000, "Maximum size of ObjectStorage list objects cache in bytes. Zero means disabled.", 0) \
DECLARE(UInt64, object_storage_list_objects_cache_max_entries, 1000, "Maximum size of ObjectStorage list objects cache in entries. Zero means disabled.", 0) \
DECLARE(UInt64, object_storage_list_objects_cache_ttl, 3600, "Time to live of records in ObjectStorage list objects cache in seconds. Zero means unlimited", 0)
// clang-format on

/// If you add a setting which can be updated at runtime, please update 'changeable_settings' map in dumpToSystemServerSettingsColumns below
Expand Down
3 changes: 3 additions & 0 deletions src/Core/Settings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6844,6 +6844,9 @@ Default number of buckets for distributed shuffle-hash-join.
)", EXPERIMENTAL) \
DECLARE(UInt64, distributed_plan_default_reader_bucket_count, 8, R"(
Default number of tasks for parallel reading in distributed query. Tasks are spread across between replicas.
)", EXPERIMENTAL) \
DECLARE(Bool, use_object_storage_list_objects_cache, false, R"(
Cache the list of objects returned by list objects calls in object storage
)", EXPERIMENTAL) \
DECLARE(Bool, distributed_plan_optimize_exchanges, true, R"(
Removes unnecessary exchanges in distributed query plan. Disable it for debugging.
Expand Down
4 changes: 4 additions & 0 deletions src/Core/SettingsChangesHistory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory()
{"parallel_replicas_insert_select_local_pipeline", false, false, "Use local pipeline during distributed INSERT SELECT with parallel replicas. Currently disabled due to performance issues"},
{"parallel_hash_join_threshold", 0, 0, "New setting"},
/// Release closed. Please use 25.5
// Altinity Antalya modifications atop of 25.2
{"object_storage_cluster", "", "", "New setting"},
{"object_storage_max_nodes", 0, 0, "New setting"},
{"use_object_storage_list_objects_cache", true, false, "New setting."},
});
addSettingsChanges(settings_changes_history, "25.3",
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class AzureObjectStorage : public IObjectStorage
const String & object_namespace_,
const String & description_);

bool supportsListObjectsCache() override { return true; }

void listObjects(const std::string & path, RelativePathsWithMetadata & children, size_t max_keys) const override;

/// Sanitizer build may crash with max_keys=1; this looks like a false positive.
Expand Down
2 changes: 2 additions & 0 deletions src/Disks/ObjectStorages/IObjectStorage.h
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,8 @@ class IObjectStorage
#endif


virtual bool supportsListObjectsCache() { return false; }

private:
mutable std::mutex throttlers_mutex;
ThrottlerPtr remote_read_throttler;
Expand Down
2 changes: 2 additions & 0 deletions src/Disks/ObjectStorages/S3/S3ObjectStorage.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ class S3ObjectStorage : public IObjectStorage

ObjectStorageType getType() const override { return ObjectStorageType::S3; }

bool supportsListObjectsCache() override { return true; }

bool exists(const StoredObject & object) const override;

std::unique_ptr<ReadBufferFromFileBase> readObject( /// NOLINT
Expand Down
8 changes: 8 additions & 0 deletions src/Interpreters/InterpreterSystemQuery.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTSystemQuery.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <Storages/Cache/ObjectStorageListObjectsCache.h>
#include <Storages/Freeze.h>
#include <Storages/MaterializedView/RefreshTask.h>
#include <Storages/ObjectStorage/Azure/Configuration.h>
Expand Down Expand Up @@ -433,6 +434,12 @@ BlockIO InterpreterSystemQuery::execute()
getContext()->clearQueryResultCache(query.query_result_cache_tag);
break;
}
case Type::DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE:
{
getContext()->checkAccess(AccessType::SYSTEM_DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE);
ObjectStorageListObjectsCache::instance().clear();
break;
}
case Type::DROP_COMPILED_EXPRESSION_CACHE:
#if USE_EMBEDDED_COMPILER
getContext()->checkAccess(AccessType::SYSTEM_DROP_COMPILED_EXPRESSION_CACHE);
Expand Down Expand Up @@ -1518,6 +1525,7 @@ AccessRightsElements InterpreterSystemQuery::getRequiredAccessForDDLOnCluster()
case Type::DROP_PAGE_CACHE:
case Type::DROP_SCHEMA_CACHE:
case Type::DROP_FORMAT_SCHEMA_CACHE:
case Type::DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE:
case Type::DROP_S3_CLIENT_CACHE:
{
required_access.emplace_back(AccessType::SYSTEM_DROP_CACHE);
Expand Down
1 change: 1 addition & 0 deletions src/Parsers/ASTSystemQuery.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,7 @@ void ASTSystemQuery::formatImpl(WriteBuffer & ostr, const FormatSettings & setti
case Type::DROP_COMPILED_EXPRESSION_CACHE:
case Type::DROP_S3_CLIENT_CACHE:
case Type::DROP_ICEBERG_METADATA_CACHE:
case Type::DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE:
case Type::RESET_COVERAGE:
case Type::RESTART_REPLICAS:
case Type::JEMALLOC_PURGE:
Expand Down
1 change: 1 addition & 0 deletions src/Parsers/ASTSystemQuery.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class ASTSystemQuery : public IAST, public ASTQueryWithOnCluster
DROP_SCHEMA_CACHE,
DROP_FORMAT_SCHEMA_CACHE,
DROP_S3_CLIENT_CACHE,
DROP_OBJECT_STORAGE_LIST_OBJECTS_CACHE,
STOP_LISTEN,
START_LISTEN,
RESTART_REPLICAS,
Expand Down
210 changes: 210 additions & 0 deletions src/Storages/Cache/ObjectStorageListObjectsCache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
#include <Storages/Cache/ObjectStorageListObjectsCache.h>
#include <Common/TTLCachePolicy.h>
#include <Common/ProfileEvents.h>
#include <boost/functional/hash.hpp>

namespace ProfileEvents
{
extern const Event ObjectStorageListObjectsCacheHits;
extern const Event ObjectStorageListObjectsCacheMisses;
extern const Event ObjectStorageListObjectsCacheExactMatchHits;
extern const Event ObjectStorageListObjectsCachePrefixMatchHits;
}

namespace DB
{

template <typename Key, typename Mapped, typename HashFunction, typename WeightFunction, typename IsStaleFunction>
class ObjectStorageListObjectsCachePolicy : public TTLCachePolicy<Key, Mapped, HashFunction, WeightFunction, IsStaleFunction>
{
public:
using BasePolicy = TTLCachePolicy<Key, Mapped, HashFunction, WeightFunction, IsStaleFunction>;
using typename BasePolicy::MappedPtr;
using typename BasePolicy::KeyMapped;
using BasePolicy::cache;

ObjectStorageListObjectsCachePolicy()
: BasePolicy(CurrentMetrics::end(), CurrentMetrics::end(), std::make_unique<NoCachePolicyUserQuota>())
{
}

std::optional<KeyMapped> getWithKey(const Key & key) override
{
if (const auto it = cache.find(key); it != cache.end())
{
if (!IsStaleFunction()(it->first))
{
return std::make_optional<KeyMapped>({it->first, it->second});
}
// found a stale entry, remove it but don't return. We still want to perform the prefix matching search
BasePolicy::remove(it->first);
}

if (const auto it = findBestMatchingPrefixAndRemoveExpiredEntries(key); it != cache.end())
{
return std::make_optional<KeyMapped>({it->first, it->second});
}

return std::nullopt;
}

private:
auto findBestMatchingPrefixAndRemoveExpiredEntries(Key key)
{
while (!key.prefix.empty())
{
if (const auto it = cache.find(key); it != cache.end())
{
if (IsStaleFunction()(it->first))
{
BasePolicy::remove(it->first);
}
else
{
return it;
}
}

key.prefix.pop_back();
}

return cache.end();
}
};

ObjectStorageListObjectsCache::Key::Key(
const String & storage_description_,
const String & bucket_,
const String & prefix_,
const std::chrono::steady_clock::time_point & expires_at_,
std::optional<UUID> user_id_)
: storage_description(storage_description_), bucket(bucket_), prefix(prefix_), expires_at(expires_at_), user_id(user_id_) {}

bool ObjectStorageListObjectsCache::Key::operator==(const Key & other) const
{
return storage_description == other.storage_description && bucket == other.bucket && prefix == other.prefix;
}

size_t ObjectStorageListObjectsCache::KeyHasher::operator()(const Key & key) const
{
std::size_t seed = 0;

boost::hash_combine(seed, key.storage_description);
boost::hash_combine(seed, key.bucket);
boost::hash_combine(seed, key.prefix);

return seed;
}

bool ObjectStorageListObjectsCache::IsStale::operator()(const Key & key) const
{
return key.expires_at < std::chrono::steady_clock::now();
}

size_t ObjectStorageListObjectsCache::WeightFunction::operator()(const Value & value) const
{
std::size_t weight = 0;

for (const auto & object : value)
{
const auto object_metadata = object->metadata;
weight += object->relative_path.capacity() + sizeof(object_metadata);

// variable size
if (object_metadata)
{
weight += object_metadata->etag.capacity();
weight += object_metadata->attributes.size() * (sizeof(std::string) * 2);

for (const auto & [k, v] : object_metadata->attributes)
{
weight += k.capacity() + v.capacity();
}
}
}

return weight;
}

ObjectStorageListObjectsCache::ObjectStorageListObjectsCache()
: cache(std::make_unique<ObjectStorageListObjectsCachePolicy<Key, Value, KeyHasher, WeightFunction, IsStale>>())
{
}

void ObjectStorageListObjectsCache::set(
const Key & key,
const std::shared_ptr<Value> & value)
{
auto key_with_ttl = key;
key_with_ttl.expires_at = std::chrono::steady_clock::now() + std::chrono::seconds(ttl_in_seconds);

cache.set(key_with_ttl, value);
}

void ObjectStorageListObjectsCache::clear()
{
cache.clear();
}

std::optional<ObjectStorageListObjectsCache::Value> ObjectStorageListObjectsCache::get(const Key & key, bool filter_by_prefix)
{
const auto pair = cache.getWithKey(key);

if (!pair)
{
ProfileEvents::increment(ProfileEvents::ObjectStorageListObjectsCacheMisses);
return {};
}

ProfileEvents::increment(ProfileEvents::ObjectStorageListObjectsCacheHits);

if (pair->key == key)
{
ProfileEvents::increment(ProfileEvents::ObjectStorageListObjectsCacheExactMatchHits);
return *pair->mapped;
}

ProfileEvents::increment(ProfileEvents::ObjectStorageListObjectsCachePrefixMatchHits);

if (!filter_by_prefix)
{
return *pair->mapped;
}

Value filtered_objects;

filtered_objects.reserve(pair->mapped->size());

for (const auto & object : *pair->mapped)
{
if (object->relative_path.starts_with(key.prefix))
{
filtered_objects.push_back(object);
}
}

return filtered_objects;
}

void ObjectStorageListObjectsCache::setMaxSizeInBytes(std::size_t size_in_bytes_)
{
cache.setMaxSizeInBytes(size_in_bytes_);
}

void ObjectStorageListObjectsCache::setMaxCount(std::size_t count)
{
cache.setMaxCount(count);
}

void ObjectStorageListObjectsCache::setTTL(std::size_t ttl_in_seconds_)
{
ttl_in_seconds = ttl_in_seconds_;
}

ObjectStorageListObjectsCache & ObjectStorageListObjectsCache::instance()
{
static ObjectStorageListObjectsCache instance;
return instance;
}

}
Loading
Loading