Skip to content
Merged
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
50 changes: 50 additions & 0 deletions src/impl/utils/CacheConfig.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "milvus/utils/CacheConfig.h"

#include <mutex>

#include "./cache/CollectionTsCache.h"
#include "./cache/SchemaCache.h"

namespace milvus {

namespace {

std::mutex capacity_mutex;

} // namespace

Status
CacheConfig::SetCapacity(size_t capacity) {
if (capacity == 0) {
return {StatusCode::INVALID_ARGUMENT, "Cache capacity must be greater than zero"};
}
std::lock_guard<std::mutex> lock(capacity_mutex);
SchemaCache::GetInstance().SetCapacity(capacity);
Comment thread
yhmo marked this conversation as resolved.
Resolved
CollectionTsCache::GetInstance().SetCapacity(capacity);
return Status::OK();
Comment thread
yhmo marked this conversation as resolved.
Resolved
}

size_t
CacheConfig::GetCapacity() {
// Reads only SchemaCache's capacity, which is internally protected by its
// own lock and returned as a single size_t; no outer lock is needed.
return SchemaCache::GetInstance().Capacity();
}

Comment thread
yhmo marked this conversation as resolved.
Resolved
} // namespace milvus
71 changes: 64 additions & 7 deletions src/impl/utils/cache/CollectionTsCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,34 @@
#include "./CollectionTsCache.h"

#include <algorithm>
#include <mutex>

namespace milvus {

CollectionTsCache::CollectionTsCache(size_t capacity) : capacity_(capacity) {
}

CollectionTsCache&
CollectionTsCache::GetInstance() {
static CollectionTsCache instance;
return instance;
}

void
CollectionTsCache::SetCapacity(size_t capacity) {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
capacity_ = capacity;
while (cache_.size() > capacity_) {
evictIfNeededLocked();
Comment thread
yhmo marked this conversation as resolved.
Resolved
}
}

size_t
CollectionTsCache::Capacity() const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
return capacity_;
}

uint64_t
CollectionTsCache::Get(const std::string& endpoint, const std::string& db_name, const std::string& collection_name) {
const auto key = CollectionCacheKey::Create(endpoint, db_name, collection_name);
Expand All @@ -34,7 +53,8 @@ CollectionTsCache::Get(const std::string& endpoint, const std::string& db_name,
if (it == cache_.end()) {
return 0;
}
return it->second;
touch(it->second);
Comment thread
yhmo marked this conversation as resolved.
Resolved
return it->second->ts_;
}

void
Expand All @@ -48,13 +68,15 @@ CollectionTsCache::Set(const std::string& endpoint, const std::string& db_name,
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end()) {
if (ts > it->second) {
it->second = ts;
if (ts > it->second->ts_) {
it->second->ts_ = ts;
}
touch(it->second);
Comment thread
yhmo marked this conversation as resolved.
Resolved
return;
}

cache_.emplace(key, ts);
cache_.emplace(key, std::make_shared<Entry>(ts, nextAccess()));
evictIfNeededLocked();
}

void
Expand Down Expand Up @@ -106,19 +128,25 @@ CollectionTsCache::transfer(const CollectionCacheKey& source_key, const Collecti
uint64_t latest_ts = 0;
auto source_it = cache_.find(source_key);
if (source_it != cache_.end()) {
latest_ts = source_it->second;
latest_ts = source_it->second->ts_;
}
auto target_it = cache_.find(target_key);
if (target_it != cache_.end()) {
latest_ts = std::max(latest_ts, target_it->second);
latest_ts = std::max(latest_ts, target_it->second->ts_);
}

if (drop_source) {
cache_.erase(source_key);
} else if (source_it != cache_.end()) {
// A copy keeps the source; refresh its recency so it is not evicted by
// its own copy, which would silently drop the source collection's SESSION
// timestamp (mirrors the Java SDK's transfer()).
touch(source_it->second);
}
cache_.erase(target_key);
if (latest_ts != 0) {
cache_.emplace(target_key, latest_ts);
cache_.emplace(target_key, std::make_shared<Entry>(latest_ts, nextAccess()));
evictIfNeededLocked();
Comment thread
yhmo marked this conversation as resolved.
Resolved
Comment thread
yhmo marked this conversation as resolved.
Resolved
}
}

Expand All @@ -134,4 +162,33 @@ CollectionTsCache::Size() const {
return cache_.size();
}

uint64_t
CollectionTsCache::nextAccess() {
return access_sequence_.fetch_add(1, std::memory_order_relaxed) + 1;
}

void
CollectionTsCache::touch(const EntryPtr& entry) {
Comment thread
yhmo marked this conversation as resolved.
Resolved
const auto access = nextAccess();
auto previous = entry->last_access_.load(std::memory_order_relaxed);
while (previous < access && !entry->last_access_.compare_exchange_weak(previous, access, std::memory_order_relaxed,
std::memory_order_relaxed)) {
}
}

void
CollectionTsCache::evictIfNeededLocked() {
if (cache_.size() <= capacity_) {
return;
}

const auto oldest = std::min_element(cache_.begin(), cache_.end(), [](const auto& left, const auto& right) {
Comment thread
yhmo marked this conversation as resolved.
Resolved
return left.second->last_access_.load(std::memory_order_relaxed) <
right.second->last_access_.load(std::memory_order_relaxed);
});
if (oldest != cache_.end()) {
cache_.erase(oldest);
}
}

} // namespace milvus
35 changes: 33 additions & 2 deletions src/impl/utils/cache/CollectionTsCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,32 @@

#pragma once

#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <memory>
#include <shared_mutex>
#include <string>
#include <unordered_map>

#include "./CollectionCacheKey.h"
#include "milvus/utils/CacheConfig.h"

namespace milvus {

class CollectionTsCache {
public:
explicit CollectionTsCache(size_t capacity = DEFAULT_CAPACITY);

static CollectionTsCache&
GetInstance();

void
SetCapacity(size_t capacity);

size_t
Capacity() const;

uint64_t
Get(const std::string& endpoint, const std::string& db_name, const std::string& collection_name);

Expand Down Expand Up @@ -62,11 +72,32 @@ class CollectionTsCache {
Size() const;

private:
struct Entry {
Entry(uint64_t ts, uint64_t last_access) : ts_(ts), last_access_(last_access) {
}

uint64_t ts_;
std::atomic<uint64_t> last_access_;
};

using EntryPtr = std::shared_ptr<Entry>;

void
transfer(const CollectionCacheKey& source_key, const CollectionCacheKey& target_key, bool drop_source);

uint64_t
nextAccess();

void
touch(const EntryPtr& entry);

void
evictIfNeededLocked();

size_t capacity_;
mutable std::shared_timed_mutex mutex_;
std::unordered_map<CollectionCacheKey, uint64_t, CollectionCacheKeyHash> cache_;
std::atomic<uint64_t> access_sequence_{0};
std::unordered_map<CollectionCacheKey, EntryPtr, CollectionCacheKeyHash> cache_;
};

} // namespace milvus
15 changes: 15 additions & 0 deletions src/impl/utils/cache/SchemaCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@ SchemaCache::GetInstance() {
return instance;
}

void
SchemaCache::SetCapacity(size_t capacity) {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
capacity_ = capacity;
while (cache_.size() > capacity_) {
evictIfNeededLocked();
}
}

size_t
SchemaCache::Capacity() const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
return capacity_;
}

Status
SchemaCache::GetOrLoad(const std::string& endpoint, const std::string& db_name, const std::string& collection_name,
bool force_update, const void* load_scope, const Loader& loader, CollectionDescPtr& desc) {
Expand Down
10 changes: 8 additions & 2 deletions src/impl/utils/cache/SchemaCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,25 @@
#include "./CollectionCacheKey.h"
#include "milvus/Status.h"
#include "milvus/types/CollectionDesc.h"
#include "milvus/utils/CacheConfig.h"

namespace milvus {

class SchemaCache {
public:
static constexpr size_t default_capacity = 4096;
using Loader = std::function<Status(CollectionDescPtr&)>;

explicit SchemaCache(size_t capacity = default_capacity);
explicit SchemaCache(size_t capacity = DEFAULT_CAPACITY);

static SchemaCache&
GetInstance();

void
SetCapacity(size_t capacity);

size_t
Capacity() const;

// Completed schemas are shared by collection key. Concurrent loads are coalesced only when
// load_scope is the same stable per-client identity, so one client's RPC deadline, credentials,
// or connection state cannot control another client's schema load.
Expand Down
2 changes: 2 additions & 0 deletions src/include/milvus/MilvusClientV2.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
#include "Status.h"
#include "milvus/BulkImport.h"
#include "milvus/Export.h"
#include "milvus/utils/CacheConfig.h"
#include "milvus/utils/FP16.h"
Comment thread
yhmo marked this conversation as resolved.
Resolved
#include "request/alias/AlterAliasRequest.h"
#include "request/alias/CreateAliasRequest.h"
#include "request/alias/DescribeAliasRequest.h"
Expand Down
74 changes: 74 additions & 0 deletions src/include/milvus/utils/CacheConfig.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include <cstddef>

#include "milvus/Export.h"
#include "milvus/Status.h"

namespace milvus {

/**
* @brief Default LRU entry bound shared by the schema and collection-timestamp caches.
*/
constexpr size_t DEFAULT_CAPACITY = 4096;

/**
* @brief Static entry points to tune the in-process SDK caches.
*
* The schema and collection-timestamp caches are process-wide singletons that
* keep a bounded LRU of per-collection entries. Both default to 4096 entries
* and evict the least recently used entry once the configured capacity is
* exceeded. Call SetCapacity before heavy workloads to raise or lower the
* bound; shrinking below the current size evicts entries immediately.
*
* Note: the collection-timestamp cache backs the SESSION consistency level.
* Once a client tracks more than the configured number of collections, the
* least recently used timestamps are evicted and SESSION reads for those
* collections fall back to eventual consistency until a later mutation stores
* a fresh timestamp. This mirrors pymilvus, which bounds both caches at 4096.
*
* The two caches are sized by one shared capacity on purpose (matching
* pymilvus' single-knob default), even though a schema entry is far heavier
* than a timestamp entry. Growing the capacity raises SESSION coverage and
* schema retention together; callers needing very large SESSION working sets
* should weigh the additional schema memory against their collection count.
*/
class MILVUS_SDK_API CacheConfig {
Comment thread
yhmo marked this conversation as resolved.
Resolved
Comment thread
yhmo marked this conversation as resolved.
Resolved
Comment thread
yhmo marked this conversation as resolved.
Resolved
public:
Comment thread
yhmo marked this conversation as resolved.
Resolved
/**
* @brief Set the maximum number of cached collection schemas and timestamps.
* @param [in] capacity the new capacity for both caches; must be greater than zero.
* @return a Status indicating success or an invalid argument.
*/
static Status
SetCapacity(size_t capacity);
Comment thread
yhmo marked this conversation as resolved.
Resolved

/**
* @brief Get the current maximum number of cached collection schemas and timestamps.
*
* Returns the schema cache capacity. Both caches share the same value when
* configured through SetCapacity; callers who resized a cache directly
* should read that cache's own Capacity() instead.
* @return the current schema cache capacity.
*/
static size_t
GetCapacity();
};

} // namespace milvus
Loading
Loading