Skip to content

Antalya: Cache the list objects operation on object storage using a TTL + prefix matching cache implementation #743

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

Merged
merged 55 commits into from
May 9, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
3dc33f3
draft immpl
arthurpassos Apr 17, 2025
7e182c7
remove garbage
arthurpassos Apr 17, 2025
ef985c9
use starts_with
arthurpassos Apr 17, 2025
43c1383
fix a few obvious bugs
arthurpassos Apr 17, 2025
989cfe0
some other fixes
arthurpassos Apr 17, 2025
157450d
another fix
arthurpassos Apr 17, 2025
d4af4ae
Merge branch 'antalya' into list_objects_cache
arthurpassos Apr 18, 2025
727b64d
remove unused method
arthurpassos Apr 18, 2025
68cbad7
some other fixes
arthurpassos Apr 18, 2025
00f58b3
some other fixes
arthurpassos Apr 18, 2025
67ccaf0
use steady_clock instead of system_clock
arthurpassos Apr 18, 2025
2b37e0c
small fixes
arthurpassos Apr 18, 2025
0d6e343
Dont return null in case of exact match with stale entry, perform lin…
arthurpassos Apr 18, 2025
0f605c4
add some metrics
arthurpassos Apr 18, 2025
3ed2349
implement cache clear command
arthurpassos Apr 18, 2025
f345b33
remove ifdef from parquet
arthurpassos Apr 18, 2025
9242843
add stateless tests
arthurpassos Apr 20, 2025
4e19b09
add unit tests
arthurpassos Apr 20, 2025
7a6eaec
Merge branch 'antalya' into list_objects_cache
arthurpassos Apr 20, 2025
8c4ea48
rename ttl argument and member variable
arthurpassos Apr 20, 2025
74b980c
new settings history
arthurpassos Apr 20, 2025
4f55a75
make the setting false by default so other tests are not affected
arthurpassos Apr 21, 2025
303ee27
add ref file
arthurpassos Apr 21, 2025
e6b379e
remove cachedglobiterator in favor of expensive copy. I think I'll re…
arthurpassos Apr 21, 2025
d7b50f4
simplify things a bit
arthurpassos Apr 21, 2025
6cfa510
add some more tests
arthurpassos Apr 22, 2025
be8c6a1
make cache return a copy instead of a pointer, we don't want modifica…
arthurpassos Apr 22, 2025
b60cb95
update ut
arthurpassos Apr 22, 2025
d91bf00
improve prefix matching by implementing search with time complexity o…
arthurpassos Apr 22, 2025
c6e53a1
Merge branch 'antalya' into list_objects_cache
arthurpassos Apr 29, 2025
f1c3591
Merge branch 'antalya' into list_objects_cache
arthurpassos Apr 29, 2025
14973d2
Merge branch 'antalya' into list_objects_cache
arthurpassos Apr 29, 2025
55ac0bc
Merge branch 'antalya' into list_objects_cache
arthurpassos May 1, 2025
e0e19a2
idraft impl of authorization aware cache
arthurpassos May 2, 2025
45af8a5
rename setting
arthurpassos May 2, 2025
7266d92
delete copy/move constructors and assignment operators
arthurpassos May 2, 2025
8e78b28
azure impl and fix aws
arthurpassos May 5, 2025
2ed102d
docs
arthurpassos May 5, 2025
28bfcfb
fix tests
arthurpassos May 5, 2025
aab089c
Merge branch 'antalya' into list_objects_cache
arthurpassos May 5, 2025
dd5934e
incorporate comments on tests
arthurpassos May 5, 2025
0f5057e
remove unused code
arthurpassos May 5, 2025
27c4dea
Revert "remove unused code"
arthurpassos May 6, 2025
d789d1e
Revert "incorporate comments on tests"
arthurpassos May 6, 2025
fef71c0
Revert "docs"
arthurpassos May 6, 2025
6bfcb86
Revert "azure impl and fix aws"
arthurpassos May 6, 2025
f68725a
Revert "idraft impl of authorization aware cache"
arthurpassos May 6, 2025
7597da0
Merge branch 'antalya' into list_objects_cache
arthurpassos May 6, 2025
e7940af
Merge branch 'antalya' into list_objects_cache
arthurpassos May 6, 2025
f863a6e
use description as part of the key
arthurpassos May 6, 2025
cbfe36d
Reapply "incorporate comments on tests"
arthurpassos May 6, 2025
9092aba
remove unused code
arthurpassos May 6, 2025
057b0b5
add supportsListObjectsCache to enable this cache for s3-like (minio,…
arthurpassos May 7, 2025
49748c9
increase default cache size
arthurpassos May 7, 2025
96cf2d2
fix weight funciton
arthurpassos May 8, 2025
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
8 changes: 8 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/attachInformationSchemaTables.h>
#include <Storages/Cache/ExternalDataSourceCache.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 @@ -318,6 +319,9 @@ namespace ServerSetting
extern const ServerSettingsUInt64 max_prefixes_deserialization_thread_pool_free_size;
extern const ServerSettingsUInt64 prefixes_deserialization_thread_pool_thread_pool_queue_size;
extern const ServerSettingsUInt64 input_format_parquet_metadata_cache_max_size;
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;
}

}
Expand Down Expand Up @@ -2327,6 +2331,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);
ParquetFileMetaDataCache::instance()->setMaxSizeInBytes(server_settings[ServerSetting::input_format_parquet_metadata_cache_max_size]);

Expand Down
4 changes: 2 additions & 2 deletions src/Common/TTLCachePolicy.h
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,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
6 changes: 4 additions & 2 deletions src/Core/ServerSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1004,8 +1004,10 @@ namespace DB
```
)", 0) \
DECLARE(Bool, storage_shared_set_join_use_inner_uuid, false, "If enabled, an inner UUID is generated during the creation of SharedSet and SharedJoin. ClickHouse Cloud only", 0) \
DECLARE(UInt64, input_format_parquet_metadata_cache_max_size, 500000000, "Maximum size of parquet file metadata cache", 0) \

DECLARE(UInt64, input_format_parquet_metadata_cache_max_size, 500000000, "Maximum size of parquet file metadata cache", 0) \
DECLARE(UInt64, object_storage_list_objects_cache_size, 5000000, "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 @@ -6108,6 +6108,9 @@ Limit for hosts used for request in object storage cluster table functions - azu
Possible values:
- Positive integer.
- 0 — All hosts in cluster.
)", EXPERIMENTAL) \
DECLARE(Bool, use_object_storage_list_objects_cache, true, R"(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add it to the src/Core/SettingsChangesHistory.cpp

Cache the list of objects returned by list objects calls in object storage
)", EXPERIMENTAL) \
\
/* ####################################################### */ \
Expand Down
213 changes: 213 additions & 0 deletions src/Storages/Cache/ObjectStorageListObjectsCache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
#include <Storages/Cache/ObjectStorageListObjectsCache.h>
#include <boost/functional/hash.hpp>

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(std::make_unique<NoCachePolicyUserQuota>())
{
}

MappedPtr get(const Key & key) override
{
if (const auto it = cache.find(key); it != cache.end())
{
if (IsStaleFunction()(it->first))
{
BasePolicy::remove(it->first);
return {};
}
return it->second;
}

if (const auto it = findBestMatchingPrefix(key); it != cache.end())
{
if (IsStaleFunction()(it->first))
{
BasePolicy::remove(it->first);
return {};
}
return it->second;
}

return {};
}

std::optional<KeyMapped> getWithKey(const Key & key) override
{
if (const auto it = cache.find(key); it != cache.end())
{
if (IsStaleFunction()(it->first))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case is interesting. In case we find an exact match, but it has expired. Should we try to find a prefix match or simply update the entry?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, there can be a more up-to-date prefix entry, so why not try to reuse it

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only reason is that this entry would cease to exist. It would never be cached again. And it would become a linear search forever.

Actually, not forever, if the more up-to-date prefix entry gets evicted and this query is performed again, it would re-appear.

But I think you are right.

{
BasePolicy::remove(it->first);
return std::nullopt;
}
return std::make_optional<KeyMapped>({it->first, it->second});
}

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

return std::nullopt;
}

private:
auto findBestMatchingPrefix(const Key & key)
{
const auto & prefix = key.prefix;

auto best_match = cache.end();
size_t best_length = 0;

std::vector<Key> to_remove;

for (auto it = cache.begin(); it != cache.end(); ++it)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this cycle.
In my opinion better something like (in pseudocode)

while (!key.prefix.empty())
{
  if (auto res = cache.getWithKey(key))
  {  // should not be more than one passed key, if key '/foo/bar' exists, key '/foo' can't be in cache
    if (IsStaleFunction(res))
    {
      BasePolicy::remove(res);
      return std::nullopt;
    }
    else
      return res;
  }
  key.prefix.pop_back();
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain why it is better?

And why do you assume the below?

{ // should not be more than one passed key, if key '/foo/bar' exists, key '/foo' can't be in cache

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, assuming this version you suggested works, the time complexity goes to O(key_path_size). Which should probably be better than O(N).

But it won't find "the best match", tho.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just implemented it, can you please have a look?

Btw, thanks for the suggestion, it's a great one.

{
const auto & candidate_bucket = it->first.bucket;
const auto & candidate_prefix = it->first.prefix;

if (candidate_bucket == key.bucket && prefix.starts_with(candidate_prefix))
{
if (IsStaleFunction()(it->first))
{
to_remove.push_back(it->first);
continue;
}

if (candidate_prefix.size() > best_length)
{
best_match = it;
best_length = candidate_prefix.size();
}
}
}

for (const auto & k : to_remove)
BasePolicy::remove(k);

return best_match;
}
};

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

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

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

boost::hash_combine(seed, std::hash<String>()(key.bucket));
boost::hash_combine(seed, std::hash<String>()(key.prefix));

return seed;
}

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

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

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

return weight;
}

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

void ObjectStorageListObjectsCache::set(
const std::string & bucket,
const std::string & prefix,
const std::shared_ptr<Value> & value)
{
const auto key = Key{bucket, prefix, std::chrono::system_clock::now() + std::chrono::seconds(ttl)};

cache.set(key, value);
}

ObjectStorageListObjectsCache::Cache::MappedPtr ObjectStorageListObjectsCache::get(const String & bucket, const String & prefix, bool filter_by_prefix)
{
const auto input_key = Key{bucket, prefix};
auto pair = cache.getWithKey(input_key);

if (!pair)
{
return {};
}

if (pair->key == input_key || filter_by_prefix)
{
return pair->mapped;
}

auto filtered_objects = std::make_shared<std::vector<ObjectInfoPtr>>();
filtered_objects->reserve(pair->mapped->size());

for (const auto & object : *pair->mapped)
{
if (object->relative_path.starts_with(input_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_)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it in seconds/miliseconds/minutes/hours?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In seconds, will modify the argument name

{
ttl = ttl_;
}

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

}
69 changes: 69 additions & 0 deletions src/Storages/Cache/ObjectStorageListObjectsCache.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#pragma once

#include <chrono>
#include <Disks/ObjectStorages/IObjectStorage.h>
#include <Storages/ObjectStorage/StorageObjectStorage.h>
#include <Common/TTLCachePolicy.h>
#include <Common/CacheBase.h>

namespace DB
{

class ObjectStorageListObjectsCache
{
public:
static ObjectStorageListObjectsCache & instance();

struct Key
{
Key(
const String & bucket_,
const String & prefix_,
const std::chrono::system_clock::time_point & expires_at_ = std::chrono::system_clock::now(),
std::optional<UUID> user_id_ = std::nullopt);

std::string bucket;
std::string prefix;
std::chrono::system_clock::time_point expires_at;
std::optional<UUID> user_id;

bool operator==(const Key & other) const;
};

using Value = StorageObjectStorage::ObjectInfos;
struct KeyHasher
{
size_t operator()(const Key & key) const;
};

struct IsStale
{
bool operator()(const Key & key) const;
};

struct WeightFunction
{
size_t operator()(const Value & value) const;
};

using Cache = CacheBase<Key, Value, KeyHasher, WeightFunction>;

void set(
const std::string & bucket,
const std::string & prefix,
const std::shared_ptr<Value> & value);

Cache::MappedPtr get(const String & bucket, const String & prefix, bool filter_by_prefix = true);

void setMaxSizeInBytes(std::size_t size_in_bytes_);
void setMaxCount(std::size_t count);
void setTTL(std::size_t ttl_);

private:
ObjectStorageListObjectsCache();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just as a precaution, please declare copy and move constructors/assignment operators as deleted here, so there is not way to accidentally make a copy like that:

ObjectStorageListObjectsCache copy_of_a_cache = ObjectStorageListObjectsCache::instance();


Cache cache;
size_t ttl;
};

}
Loading
Loading